@datalayer/agent-runtimes 1.5.80 → 1.5.82
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.
- package/dist-embed/chunks/ChatView-uYgfl4KN.js +32 -0
- package/dist-embed/chunks/{DeckComponent-Cd1sbs9L.js → DeckComponent-DS42k_Ud.js} +2 -2
- package/dist-embed/chunks/{DocumentView-ssQ835Wa.js → DocumentView-DTZjQfu5.js} +1 -1
- package/dist-embed/chunks/{EphemeralDocument-DNziilOG.js → EphemeralDocument-BcxH847U.js} +1 -1
- package/dist-embed/chunks/{ExcalidrawComponent-CQ4BeoQt.js → ExcalidrawComponent-D-DdWmbS.js} +1 -1
- package/dist-embed/chunks/{ExcalidrawModal-8W-b1OmA.js → ExcalidrawModal-Bgdc7pqI.js} +1 -1
- package/dist-embed/chunks/{JupyterLexicalExtension-BLYM-DTn.js → JupyterLexicalExtension-2cZTnnOv.js} +6 -6
- package/dist-embed/chunks/{YouTubePlugin-BgZG6fCA.js → YouTubePlugin-CcQPagoa.js} +1 -1
- package/dist-embed/chunks/{abnfDiagram-VCTEODGH-CHerLzZ0.js → abnfDiagram-VCTEODGH-BHwrDUSK.js} +1 -1
- package/dist-embed/chunks/{abnfDiagram-VCTEODGH-BdOOK2nG.js → abnfDiagram-VCTEODGH-BlJ0uJzg.js} +1 -1
- package/dist-embed/chunks/{abnfDiagram-VCTEODGH-CsKFU4Ej.js → abnfDiagram-VCTEODGH-BnGI-UIs.js} +1 -1
- package/dist-embed/chunks/{ar-SA-G6X2FPQ2-Bcy9b6jn.js → ar-SA-G6X2FPQ2-CqfmhD9l.js} +1 -1
- package/dist-embed/chunks/{architectureDiagram-5GKGNRK7-C8jjE2mY.js → architectureDiagram-5GKGNRK7-BAJb7Shu.js} +1 -1
- package/dist-embed/chunks/{architectureDiagram-5GKGNRK7-iDgRBR0a.js → architectureDiagram-5GKGNRK7-CuAYWP6N.js} +1 -1
- package/dist-embed/chunks/{architectureDiagram-5GKGNRK7-GukKr_g1.js → architectureDiagram-5GKGNRK7-DLWJva8u.js} +1 -1
- package/dist-embed/chunks/{az-AZ-76LH7QW2-Bzy5rt95.js → az-AZ-76LH7QW2-mjoZR4wa.js} +1 -1
- package/dist-embed/chunks/{bg-BG-XCXSNQG7-C3mQkAoD.js → bg-BG-XCXSNQG7-DU3y3x4T.js} +1 -1
- package/dist-embed/chunks/{blockDiagram-868be97b-D3BurtSN.js → blockDiagram-868be97b-DRJ_ofQv.js} +1 -1
- package/dist-embed/chunks/{blockDiagram-I7D4REHJ-DH6ta7S_.js → blockDiagram-I7D4REHJ-BZLSOJfR.js} +1 -1
- package/dist-embed/chunks/{blockDiagram-I7D4REHJ-oDRNhSU2.js → blockDiagram-I7D4REHJ-DO_8w9-1.js} +1 -1
- package/dist-embed/chunks/{blockDiagram-I7D4REHJ-edfypROz.js → blockDiagram-I7D4REHJ-XN1bU5Ii.js} +1 -1
- package/dist-embed/chunks/{bn-BD-2XOGV67Q-DHwDUFeg.js → bn-BD-2XOGV67Q-C4V6q1wT.js} +1 -1
- package/dist-embed/chunks/{c4Diagram-3f4bdde3-Dmbl9p6m.js → c4Diagram-3f4bdde3-B-w3s9rx.js} +1 -1
- package/dist-embed/chunks/{c4Diagram-7LVT6UL2-B6NHHf7w.js → c4Diagram-7LVT6UL2-B28HS4IQ.js} +1 -1
- package/dist-embed/chunks/{c4Diagram-7LVT6UL2-CR3iQQ6O.js → c4Diagram-7LVT6UL2-BACgR0fs.js} +1 -1
- package/dist-embed/chunks/{c4Diagram-7LVT6UL2-BD3Ld97M.js → c4Diagram-7LVT6UL2-DwLtBd8O.js} +1 -1
- package/dist-embed/chunks/{ca-ES-6MX7JW3Y-CWMZCfjI.js → ca-ES-6MX7JW3Y-DzJcx7TI.js} +1 -1
- package/dist-embed/chunks/{chunk-2Q5K7J3B-9xCosPaH.js → chunk-2Q5K7J3B-BqK0jhMM.js} +1 -1
- package/dist-embed/chunks/{chunk-2Q5K7J3B-ZWnuQ6M2.js → chunk-2Q5K7J3B-Cv2QB080.js} +1 -1
- package/dist-embed/chunks/{chunk-2Q5K7J3B-H_DA_jTG.js → chunk-2Q5K7J3B-Pu-PawH9.js} +1 -1
- package/dist-embed/chunks/{chunk-5VM5RSS4-BhWUyelG.js → chunk-5VM5RSS4-BIWdC4YC.js} +1 -1
- package/dist-embed/chunks/{chunk-5VM5RSS4-7q2jPq-I.js → chunk-5VM5RSS4-DI3POCyE.js} +1 -1
- package/dist-embed/chunks/{chunk-5VM5RSS4-C2EZUNrH.js → chunk-5VM5RSS4-DthkbWcR.js} +1 -1
- package/dist-embed/chunks/{chunk-F27PBJKO-B9wgW70d.js → chunk-F27PBJKO-BY-_X1Ii.js} +1 -1
- package/dist-embed/chunks/{chunk-F27PBJKO-hasZYXJc.js → chunk-F27PBJKO-DcCqnHNB.js} +1 -1
- package/dist-embed/chunks/{chunk-F27PBJKO-iAw_9Xtd.js → chunk-F27PBJKO-dSqM-5aG.js} +1 -1
- package/dist-embed/chunks/{chunk-IMKFNOWR-CU661Hle.js → chunk-IMKFNOWR-BYkz40H8.js} +1 -1
- package/dist-embed/chunks/{chunk-IMKFNOWR-CR2LIHPi.js → chunk-IMKFNOWR-DPv-w5lK.js} +1 -1
- package/dist-embed/chunks/{chunk-IMKFNOWR-DhXkXQPV.js → chunk-IMKFNOWR-O7b2kauh.js} +1 -1
- package/dist-embed/chunks/{chunk-JWPE2WC7-B40RAhYQ.js → chunk-JWPE2WC7-779bmDSv.js} +1 -1
- package/dist-embed/chunks/{chunk-JWPE2WC7-DaBG37yC.js → chunk-JWPE2WC7-Be4x4L6B.js} +1 -1
- package/dist-embed/chunks/{chunk-JWPE2WC7-D4pNFsZF.js → chunk-JWPE2WC7-th9umQbo.js} +1 -1
- package/dist-embed/chunks/{chunk-POPQ4Y6H-CNc-_UkX.js → chunk-POPQ4Y6H-B097KlFr.js} +1 -1
- package/dist-embed/chunks/{chunk-POPQ4Y6H-PC7NS4ab.js → chunk-POPQ4Y6H-CYXeyiko.js} +1 -1
- package/dist-embed/chunks/{chunk-POPQ4Y6H-WjTzJISs.js → chunk-POPQ4Y6H-C_fIQaTN.js} +1 -1
- package/dist-embed/chunks/{chunk-SVP7TREG-BgVpHjUA.js → chunk-SVP7TREG-BZUv4JX-.js} +1 -1
- package/dist-embed/chunks/{chunk-SVP7TREG-bq0J6tH_.js → chunk-SVP7TREG-YgahXZy2.js} +1 -1
- package/dist-embed/chunks/{chunk-SVP7TREG-B-LR0OEY.js → chunk-SVP7TREG-dXH2Z6GR.js} +1 -1
- package/dist-embed/chunks/{chunk-TICWLB2K-D0mlrZUj.js → chunk-TICWLB2K-C54VOu9Q.js} +1 -1
- package/dist-embed/chunks/{chunk-TICWLB2K-BKUWUi4x.js → chunk-TICWLB2K-DIe5qIoj.js} +1 -1
- package/dist-embed/chunks/{chunk-TICWLB2K-BV_9f6ak.js → chunk-TICWLB2K-YWBHGfC8.js} +1 -1
- package/dist-embed/chunks/{chunk-XXDRQBXY-fV8doVJJ.js → chunk-XXDRQBXY-B1faoehH.js} +1 -1
- package/dist-embed/chunks/{chunk-XXDRQBXY-CFD4Agg8.js → chunk-XXDRQBXY-CNEiTt6v.js} +1 -1
- package/dist-embed/chunks/{chunk-XXDRQBXY-DF8wFPCi.js → chunk-XXDRQBXY-f3FbRmyb.js} +1 -1
- package/dist-embed/chunks/{classDiagram-ZZMXUADV-B2RPE1Bl.js → classDiagram-ZZMXUADV-Cd7eEzi4.js} +1 -1
- package/dist-embed/chunks/{classDiagram-ZZMXUADV-B0pbDswj.js → classDiagram-ZZMXUADV-DuuqqgIP.js} +1 -1
- package/dist-embed/chunks/{classDiagram-ZZMXUADV-BSdRgwsr.js → classDiagram-ZZMXUADV-q1xSQX4O.js} +1 -1
- package/dist-embed/chunks/{classDiagram-f62afe4f-tD890DEl.js → classDiagram-f62afe4f-ByEt3lSF.js} +1 -1
- package/dist-embed/chunks/{classDiagram-v2-604399ef-DReIuoeI.js → classDiagram-v2-604399ef-NBzfAORG.js} +1 -1
- package/dist-embed/chunks/{classDiagram-v2-VYDZK3BY-B2RPE1Bl.js → classDiagram-v2-VYDZK3BY-Cd7eEzi4.js} +1 -1
- package/dist-embed/chunks/{classDiagram-v2-VYDZK3BY-B0pbDswj.js → classDiagram-v2-VYDZK3BY-DuuqqgIP.js} +1 -1
- package/dist-embed/chunks/{classDiagram-v2-VYDZK3BY-BSdRgwsr.js → classDiagram-v2-VYDZK3BY-q1xSQX4O.js} +1 -1
- package/dist-embed/chunks/{cose-bilkent-JH36ORCC-CGF9N16A.js → cose-bilkent-JH36ORCC-BiEPnrEj.js} +1 -1
- package/dist-embed/chunks/{cose-bilkent-JH36ORCC-D976z1sp.js → cose-bilkent-JH36ORCC-DfR5QnyH.js} +1 -1
- package/dist-embed/chunks/{cose-bilkent-JH36ORCC-BS_pJML-.js → cose-bilkent-JH36ORCC-DzJSYCRG.js} +1 -1
- package/dist-embed/chunks/{createText-aed3d8b3-1eVJ8jxH.js → createText-aed3d8b3-6mXespHo.js} +1 -1
- package/dist-embed/chunks/{cs-CZ-2BRQDIVT-B_pe2qj9.js → cs-CZ-2BRQDIVT-BKep5hDJ.js} +1 -1
- package/dist-embed/chunks/{cynefinDiagram-5FMLGOSQ-Cil4cm66.js → cynefinDiagram-5FMLGOSQ-B7qhaV93.js} +1 -1
- package/dist-embed/chunks/{cynefinDiagram-5FMLGOSQ-AxJwZ7KT.js → cynefinDiagram-5FMLGOSQ-DwHfF9hE.js} +1 -1
- package/dist-embed/chunks/{cynefinDiagram-5FMLGOSQ-D7ioXav_.js → cynefinDiagram-5FMLGOSQ-_vxJMyqw.js} +1 -1
- package/dist-embed/chunks/{da-DK-5WZEPLOC-CGWCNcJj.js → da-DK-5WZEPLOC-DlOP6lOL.js} +1 -1
- package/dist-embed/chunks/{dagre-GXQ25YYZ-DauBFK-x.js → dagre-GXQ25YYZ-Bjepw68A.js} +1 -1
- package/dist-embed/chunks/{dagre-GXQ25YYZ-B8Ip03td.js → dagre-GXQ25YYZ-DFR_CaEv.js} +1 -1
- package/dist-embed/chunks/{dagre-GXQ25YYZ-Cp78_L9l.js → dagre-GXQ25YYZ-Ds0JPzDS.js} +1 -1
- package/dist-embed/chunks/{de-DE-XR44H4JA-DTdq2h_G.js → de-DE-XR44H4JA-BRk2-hl3.js} +1 -1
- package/dist-embed/chunks/{diagram-S7CK7UJ4-LsSU5PzE.js → diagram-S7CK7UJ4-BwwRJlNT.js} +1 -1
- package/dist-embed/chunks/{diagram-S7CK7UJ4-BxRBCYVP.js → diagram-S7CK7UJ4-DIMHIP_O.js} +1 -1
- package/dist-embed/chunks/{diagram-S7CK7UJ4-cLOCifii.js → diagram-S7CK7UJ4-DjMCZvT1.js} +1 -1
- package/dist-embed/chunks/{diagram-UQ7AKVKN-BvgP6_rf.js → diagram-UQ7AKVKN-BqqL4ZW6.js} +1 -1
- package/dist-embed/chunks/{diagram-UQ7AKVKN-BK4qe_eB.js → diagram-UQ7AKVKN-COGYRNFS.js} +1 -1
- package/dist-embed/chunks/{diagram-UQ7AKVKN-CoIPlGw-.js → diagram-UQ7AKVKN-D0P7rl1p.js} +1 -1
- package/dist-embed/chunks/{diagram-VSXAHHWV-Cy8iWh4H.js → diagram-VSXAHHWV-ChB-FOnw.js} +1 -1
- package/dist-embed/chunks/{diagram-VSXAHHWV-CIhWkrRX.js → diagram-VSXAHHWV-DsMS8foW.js} +1 -1
- package/dist-embed/chunks/{diagram-VSXAHHWV-DWWQ-Ga9.js → diagram-VSXAHHWV-DvxkVQ-E.js} +1 -1
- package/dist-embed/chunks/{diagram-VX7I27RA-43SwkivD.js → diagram-VX7I27RA-BIxeQH4u.js} +1 -1
- package/dist-embed/chunks/{diagram-VX7I27RA-CQM8aGRO.js → diagram-VX7I27RA-Cg10qtez.js} +1 -1
- package/dist-embed/chunks/{diagram-VX7I27RA-CCx8R8FK.js → diagram-VX7I27RA-Cuf1tsVI.js} +1 -1
- package/dist-embed/chunks/{diagram-Z3DM3KII-Da75Rc5Q.js → diagram-Z3DM3KII-B22XcXbf.js} +1 -1
- package/dist-embed/chunks/{diagram-Z3DM3KII-DrILxydN.js → diagram-Z3DM3KII-CNWiLQR4.js} +1 -1
- package/dist-embed/chunks/{diagram-Z3DM3KII-Dqcrl8-1.js → diagram-Z3DM3KII-DsRXBtfM.js} +1 -1
- package/dist-embed/chunks/{ebnfDiagram-PWID7BFC-CwBVaHP2.js → ebnfDiagram-PWID7BFC-81p8Ls5M.js} +1 -1
- package/dist-embed/chunks/{ebnfDiagram-PWID7BFC-DC-Zam6d.js → ebnfDiagram-PWID7BFC-BiAjk2HF.js} +1 -1
- package/dist-embed/chunks/{ebnfDiagram-PWID7BFC-Klx1dPe6.js → ebnfDiagram-PWID7BFC-C31mpWW_.js} +1 -1
- package/dist-embed/chunks/{edges-b2856ca0-B3ybuHDU.js → edges-b2856ca0-Bup5nxkN.js} +1 -1
- package/dist-embed/chunks/{el-GR-BZB4AONW-qdInZt55.js → el-GR-BZB4AONW-BwGTv3Ip.js} +1 -1
- package/dist-embed/chunks/{erDiagram-5d81789a-HZ-VLc2f.js → erDiagram-5d81789a-DFzRdHol.js} +1 -1
- package/dist-embed/chunks/{erDiagram-RLTQ6QDP-DmlOR1VA.js → erDiagram-RLTQ6QDP-BdoySyRQ.js} +1 -1
- package/dist-embed/chunks/{erDiagram-RLTQ6QDP-6YXMuidI.js → erDiagram-RLTQ6QDP-BrpNZMOa.js} +1 -1
- package/dist-embed/chunks/{erDiagram-RLTQ6QDP-CNO4pVhU.js → erDiagram-RLTQ6QDP-OQO_sYyP.js} +1 -1
- package/dist-embed/chunks/{es-ES-U4NZUMDT-CbVgghD5.js → es-ES-U4NZUMDT-tz36zNcB.js} +1 -1
- package/dist-embed/chunks/{eu-ES-A7QVB2H4-Cfyi4-QV.js → eu-ES-A7QVB2H4-CGBVWQ14.js} +1 -1
- package/dist-embed/chunks/{fa-IR-HGAKTJCU-Bpz9Yk2c.js → fa-IR-HGAKTJCU-CoO7_ncQ.js} +1 -1
- package/dist-embed/chunks/{fi-FI-Z5N7JZ37-CnNP_ASI.js → fi-FI-Z5N7JZ37-DPjdvbO9.js} +1 -1
- package/dist-embed/chunks/{flowDb-185abca5-7Nn2obHG.js → flowDb-185abca5-au1lLLx1.js} +1 -1
- package/dist-embed/chunks/{flowDiagram-1629c991-CnvM_psw.js → flowDiagram-1629c991-BeGPcZ6y.js} +1 -1
- package/dist-embed/chunks/{flowDiagram-HODETNUW-Bsl5oOFb.js → flowDiagram-HODETNUW-CYTfSgr_.js} +1 -1
- package/dist-embed/chunks/{flowDiagram-HODETNUW-DpJLPDJS.js → flowDiagram-HODETNUW-D1SiifhW.js} +1 -1
- package/dist-embed/chunks/{flowDiagram-HODETNUW-_PPo6xx4.js → flowDiagram-HODETNUW-ZrGwOdyu.js} +1 -1
- package/dist-embed/chunks/{flowDiagram-v2-1d953310-TkF25UVC.js → flowDiagram-v2-1d953310-DjmvuK3n.js} +1 -1
- package/dist-embed/chunks/{flowchart-elk-definition-6df44142-CwiGfEuJ.js → flowchart-elk-definition-6df44142-vDckeTZu.js} +1 -1
- package/dist-embed/chunks/{fr-FR-RHASNOE6-CXIU81zC.js → fr-FR-RHASNOE6-Cmv7wG_0.js} +1 -1
- package/dist-embed/chunks/{ganttDiagram-3b0b3873-DeouFDZE.js → ganttDiagram-3b0b3873-DVQKpltu.js} +1 -1
- package/dist-embed/chunks/{ganttDiagram-EL5Y4UJY-BeK3rGHM.js → ganttDiagram-EL5Y4UJY-BORJG_RB.js} +1 -1
- package/dist-embed/chunks/{ganttDiagram-EL5Y4UJY-B3ddBLm-.js → ganttDiagram-EL5Y4UJY-BqzFsgGN.js} +1 -1
- package/dist-embed/chunks/{ganttDiagram-EL5Y4UJY-DnJUq63S.js → ganttDiagram-EL5Y4UJY-YQkzQd01.js} +1 -1
- package/dist-embed/chunks/{gitGraphDiagram-WWUBYQGX-CKVR9Ajq.js → gitGraphDiagram-WWUBYQGX-AAVjuV14.js} +1 -1
- package/dist-embed/chunks/{gitGraphDiagram-WWUBYQGX-u7eHxrMk.js → gitGraphDiagram-WWUBYQGX-BKLKcFoS.js} +1 -1
- package/dist-embed/chunks/{gitGraphDiagram-WWUBYQGX-DkYi8eWr.js → gitGraphDiagram-WWUBYQGX-D1o9osXz.js} +1 -1
- package/dist-embed/chunks/{gitGraphDiagram-f01e8bc2-mCCRVzIs.js → gitGraphDiagram-f01e8bc2-CJSbiZjx.js} +1 -1
- package/dist-embed/chunks/{gl-ES-HMX3MZ6V-Do1RdVfG.js → gl-ES-HMX3MZ6V-CRdkmw5y.js} +1 -1
- package/dist-embed/chunks/{he-IL-6SHJWFNN-NcTscmv6.js → he-IL-6SHJWFNN-DvMw5Cul.js} +1 -1
- package/dist-embed/chunks/{hi-IN-IWLTKZ5I-CyNpoQ12.js → hi-IN-IWLTKZ5I-DJlp0nwg.js} +1 -1
- package/dist-embed/chunks/{hu-HU-A5ZG7DT2-Bzge2Fdz.js → hu-HU-A5ZG7DT2-CzRriMFn.js} +1 -1
- package/dist-embed/chunks/{id-ID-SAP4L64H-DaNcoDhl.js → id-ID-SAP4L64H-DIWyOwkf.js} +1 -1
- package/dist-embed/chunks/{index-9bae90f3-CzUk5Hhq.js → index-9bae90f3-CSxqLQwc.js} +1 -1
- package/dist-embed/chunks/{index-Cx_cIRez.js → index-B8BulvHI.js} +1 -1
- package/dist-embed/chunks/{index-CLdL3h_Z.js → index-BCGvaYVt.js} +1 -1
- package/dist-embed/chunks/{index-BQdtKMKk.js → index-CbnU-kk0.js} +4 -4
- package/dist-embed/chunks/index-CeTMYE1j.js +1 -0
- package/dist-embed/chunks/{index-lOJZWhTu.js → index-DY5U0msZ.js} +4 -4
- package/dist-embed/chunks/{index-D_vehxcD.js → index-DxN3ZybZ.js} +1 -1
- package/dist-embed/chunks/{infoDiagram-27XIBGKW-CrHEoNfn.js → infoDiagram-27XIBGKW-BnxVO2UJ.js} +1 -1
- package/dist-embed/chunks/{infoDiagram-27XIBGKW-DiC5_yjB.js → infoDiagram-27XIBGKW-COSYMCha.js} +1 -1
- package/dist-embed/chunks/{infoDiagram-27XIBGKW-C3YByzAX.js → infoDiagram-27XIBGKW-CrDC6noC.js} +1 -1
- package/dist-embed/chunks/{infoDiagram-a29d40f1-DRVyx4Bf.js → infoDiagram-a29d40f1-oSOWBNcS.js} +1 -1
- package/dist-embed/chunks/{ishikawaDiagram-5VMMS53U-B87JmQRn.js → ishikawaDiagram-5VMMS53U-Cabl3zHc.js} +1 -1
- package/dist-embed/chunks/{ishikawaDiagram-5VMMS53U-DkW3YLz9.js → ishikawaDiagram-5VMMS53U-Dy7sKgzH.js} +1 -1
- package/dist-embed/chunks/{ishikawaDiagram-5VMMS53U-3WGbru46.js → ishikawaDiagram-5VMMS53U-orLa617t.js} +1 -1
- package/dist-embed/chunks/{it-IT-JPQ66NNP-6fWP-4Pk.js → it-IT-JPQ66NNP--0R7ykIn.js} +1 -1
- package/dist-embed/chunks/{ja-JP-DBVTYXUO-TOPcUfq8.js → ja-JP-DBVTYXUO-BceLsdOT.js} +1 -1
- package/dist-embed/chunks/{journeyDiagram-3NMN7TZE-BZWmkUfk.js → journeyDiagram-3NMN7TZE-CFX02NzG.js} +1 -1
- package/dist-embed/chunks/{journeyDiagram-3NMN7TZE-BcfZXfHF.js → journeyDiagram-3NMN7TZE-DK2YyxiL.js} +1 -1
- package/dist-embed/chunks/{journeyDiagram-3NMN7TZE-BjO5pIr-.js → journeyDiagram-3NMN7TZE-YkKUQWKF.js} +1 -1
- package/dist-embed/chunks/{journeyDiagram-95396277-D_QLiVq4.js → journeyDiagram-95396277-CU6tIrkG.js} +1 -1
- package/dist-embed/chunks/{kaa-6HZHGXH3-WPmptgZr.js → kaa-6HZHGXH3-DmBIoS2A.js} +1 -1
- package/dist-embed/chunks/{kab-KAB-ZGHBKWFO-CMOAXrZA.js → kab-KAB-ZGHBKWFO-FOhJJBEr.js} +1 -1
- package/dist-embed/chunks/{kanban-definition-UXKFOSKX-D9d45rsU.js → kanban-definition-UXKFOSKX-BluwjAGS.js} +1 -1
- package/dist-embed/chunks/{kanban-definition-UXKFOSKX-B84ZaZEy.js → kanban-definition-UXKFOSKX-C14qnrHj.js} +1 -1
- package/dist-embed/chunks/{kanban-definition-UXKFOSKX-DKCJ8_n0.js → kanban-definition-UXKFOSKX-C4dKZPut.js} +1 -1
- package/dist-embed/chunks/{kk-KZ-P5N5QNE5-B6ezOPzr.js → kk-KZ-P5N5QNE5-Cfl-4Zso.js} +1 -1
- package/dist-embed/chunks/{km-KH-HSX4SM5Z-C84QUPbc.js → km-KH-HSX4SM5Z-CkPlUErW.js} +1 -1
- package/dist-embed/chunks/{ko-KR-MTYHY66A-cuBEuTL_.js → ko-KR-MTYHY66A-ClNehjJR.js} +1 -1
- package/dist-embed/chunks/{ku-TR-6OUDTVRD-B9KdlCAR.js → ku-TR-6OUDTVRD-BWAQD572.js} +1 -1
- package/dist-embed/chunks/{layout-Do3wJC1j.js → layout-BJZx1DET.js} +1 -1
- package/dist-embed/chunks/{layout-Dx5Hzkor.js → layout-Cj2S0_6r.js} +1 -1
- package/dist-embed/chunks/{layout-C6Twj1mW.js → layout-CrZLRdHC.js} +1 -1
- package/dist-embed/chunks/{lt-LT-XHIRWOB4-B39JwBGi.js → lt-LT-XHIRWOB4-CdVgmT3F.js} +1 -1
- package/dist-embed/chunks/{lv-LV-5QDEKY6T-8WReOaa7.js → lv-LV-5QDEKY6T-DhvrkAd6.js} +1 -1
- package/dist-embed/chunks/{mermaid.core-D0955PCw.js → mermaid.core-CN-kUGXQ.js} +4 -4
- package/dist-embed/chunks/{mermaid.core-D98kc0OO.js → mermaid.core-Cb8_A6yp.js} +3 -3
- package/dist-embed/chunks/{mindmap-definition-YA3MSWOX-D86IPkt3.js → mindmap-definition-YA3MSWOX-BI8iAkoX.js} +1 -1
- package/dist-embed/chunks/{mindmap-definition-YA3MSWOX-5wZuXgB8.js → mindmap-definition-YA3MSWOX-C3PLDJT4.js} +1 -1
- package/dist-embed/chunks/{mindmap-definition-YA3MSWOX-BURkGTKI.js → mindmap-definition-YA3MSWOX-CLcKjJkV.js} +1 -1
- package/dist-embed/chunks/{mindmap-definition-e4c1d938-UbbfpF-a.js → mindmap-definition-e4c1d938-BR3XAv_v.js} +1 -1
- package/dist-embed/chunks/{mr-IN-CRQNXWMA-DUaS8VWx.js → mr-IN-CRQNXWMA-EGNXrciM.js} +1 -1
- package/dist-embed/chunks/{my-MM-5M5IBNSE-BdJYwQXg.js → my-MM-5M5IBNSE-B-8cjGNb.js} +1 -1
- package/dist-embed/chunks/{nb-NO-T6EIAALU-C_p5yu1z.js → nb-NO-T6EIAALU-C49vGMvQ.js} +1 -1
- package/dist-embed/chunks/{nl-NL-IS3SIHDZ-DM5qgcCp.js → nl-NL-IS3SIHDZ-Bop5b6pF.js} +1 -1
- package/dist-embed/chunks/{nn-NO-6E72VCQL-BuX1DqI5.js → nn-NO-6E72VCQL-CztS-gYX.js} +1 -1
- package/dist-embed/chunks/{oc-FR-POXYY2M6-BAWljcaf.js → oc-FR-POXYY2M6-D5wo47w8.js} +1 -1
- package/dist-embed/chunks/{pa-IN-N4M65BXN-2iyq8qxX.js → pa-IN-N4M65BXN-USnnio2R.js} +1 -1
- package/dist-embed/chunks/{pegDiagram-XKGWAZYB-BjrOX_Ki.js → pegDiagram-XKGWAZYB-BHSFNuDr.js} +1 -1
- package/dist-embed/chunks/{pegDiagram-XKGWAZYB-BJAdJVqh.js → pegDiagram-XKGWAZYB-CxqsEvHB.js} +1 -1
- package/dist-embed/chunks/{pegDiagram-XKGWAZYB-CyuSADYr.js → pegDiagram-XKGWAZYB-D_KkFB8O.js} +1 -1
- package/dist-embed/chunks/{percentages-BXMCSKIN-C9b5dzpq.js → percentages-BXMCSKIN-Qs237i5f.js} +5 -5
- package/dist-embed/chunks/{pieDiagram-E7YTZNPT-C55wHgO0.js → pieDiagram-E7YTZNPT-C01d4vFA.js} +1 -1
- package/dist-embed/chunks/{pieDiagram-E7YTZNPT-ni9UMEzV.js → pieDiagram-E7YTZNPT-DrPlYr3y.js} +1 -1
- package/dist-embed/chunks/{pieDiagram-E7YTZNPT-GvxNnk0x.js → pieDiagram-E7YTZNPT-XvKrNQIe.js} +1 -1
- package/dist-embed/chunks/{pieDiagram-c941bede-DTmViAsB.js → pieDiagram-c941bede-5Q4eh0ys.js} +1 -1
- package/dist-embed/chunks/{pl-PL-T2D74RX3-C6nLJHhB.js → pl-PL-T2D74RX3-BzossiHE.js} +1 -1
- package/dist-embed/chunks/{pt-BR-5N22H2LF-B1adz-DU.js → pt-BR-5N22H2LF-DqZAv4oC.js} +1 -1
- package/dist-embed/chunks/{pt-PT-UZXXM6DQ-BCZpI4LV.js → pt-PT-UZXXM6DQ-CfFta-9l.js} +1 -1
- package/dist-embed/chunks/{quadrantDiagram-AXDQQJYC-CufBEqrC.js → quadrantDiagram-AXDQQJYC-Ba9Uoul2.js} +1 -1
- package/dist-embed/chunks/{quadrantDiagram-AXDQQJYC-BCeMrGXB.js → quadrantDiagram-AXDQQJYC-Cayreizb.js} +1 -1
- package/dist-embed/chunks/{quadrantDiagram-AXDQQJYC-Yg2WGHWh.js → quadrantDiagram-AXDQQJYC-qHBK2GfL.js} +1 -1
- package/dist-embed/chunks/{quadrantDiagram-cf8b8fe0-BZAbhmbg.js → quadrantDiagram-cf8b8fe0-baOXG64t.js} +1 -1
- package/dist-embed/chunks/{railroadDiagram-O6MQD6OU-BAXhb26s.js → railroadDiagram-O6MQD6OU-BoiPFsc0.js} +1 -1
- package/dist-embed/chunks/{railroadDiagram-O6MQD6OU-6tStysfX.js → railroadDiagram-O6MQD6OU-Ck3rOcDX.js} +1 -1
- package/dist-embed/chunks/{railroadDiagram-O6MQD6OU-Df7m1mT4.js → railroadDiagram-O6MQD6OU-DPbTwglx.js} +1 -1
- package/dist-embed/chunks/{requirementDiagram-53bda41b-DNqx3JRF.js → requirementDiagram-53bda41b--Vif0cFL.js} +1 -1
- package/dist-embed/chunks/{requirementDiagram-BXWQKSXE-CmXBYo40.js → requirementDiagram-BXWQKSXE-BU62-ZX8.js} +1 -1
- package/dist-embed/chunks/{requirementDiagram-BXWQKSXE-0AqPqv7a.js → requirementDiagram-BXWQKSXE-BnpFahSo.js} +1 -1
- package/dist-embed/chunks/{requirementDiagram-BXWQKSXE-B0SL6Gqb.js → requirementDiagram-BXWQKSXE-TxEizGOu.js} +1 -1
- package/dist-embed/chunks/{ro-RO-JPDTUUEW-BPM7y_F2.js → ro-RO-JPDTUUEW-DeKMiDGM.js} +1 -1
- package/dist-embed/chunks/{ru-RU-B4JR7IUQ-UViKo8dy.js → ru-RU-B4JR7IUQ-DwcP27bd.js} +1 -1
- package/dist-embed/chunks/{sankeyDiagram-P5KCCOFB-rQsp_j9w.js → sankeyDiagram-P5KCCOFB-BZdt2wZF.js} +1 -1
- package/dist-embed/chunks/{sankeyDiagram-P5KCCOFB-CktuQIU1.js → sankeyDiagram-P5KCCOFB-Be7ybx8L.js} +1 -1
- package/dist-embed/chunks/{sankeyDiagram-P5KCCOFB-CqcWOAyy.js → sankeyDiagram-P5KCCOFB-BvBkWEs8.js} +1 -1
- package/dist-embed/chunks/{sankeyDiagram-c3ef121a-4-5C_fXA.js → sankeyDiagram-c3ef121a-DG1UM3l4.js} +1 -1
- package/dist-embed/chunks/{sequenceDiagram-82a5b84f-DedJ5qnD.js → sequenceDiagram-82a5b84f-UdVxURsq.js} +1 -1
- package/dist-embed/chunks/{sequenceDiagram-WJ2MYXX4-Br4F1sd7.js → sequenceDiagram-WJ2MYXX4-BCfarclu.js} +1 -1
- package/dist-embed/chunks/{sequenceDiagram-WJ2MYXX4-BBGHED3s.js → sequenceDiagram-WJ2MYXX4-D7c_CoMJ.js} +1 -1
- package/dist-embed/chunks/{sequenceDiagram-WJ2MYXX4-GMFparx1.js → sequenceDiagram-WJ2MYXX4-Dg0wfvkN.js} +1 -1
- package/dist-embed/chunks/{si-LK-N5RQ5JYF-D7TIYEDr.js → si-LK-N5RQ5JYF-d-F0Cewp.js} +1 -1
- package/dist-embed/chunks/{sizeCapture-INFHLROL-8qFOiWrK.js → sizeCapture-INFHLROL-DMANNAaY.js} +1 -1
- package/dist-embed/chunks/{sizeCapture-INFHLROL-C_M5Nl06.js → sizeCapture-INFHLROL-Dj0ydwKk.js} +1 -1
- package/dist-embed/chunks/{sizeCapture-INFHLROL-BNuVN7vX.js → sizeCapture-INFHLROL-DlIgxaWS.js} +1 -1
- package/dist-embed/chunks/{sk-SK-C5VTKIMK-CQedcNlJ.js → sk-SK-C5VTKIMK-BgobCs_4.js} +1 -1
- package/dist-embed/chunks/{sl-SI-NN7IZMDC-BX1W51zJ.js → sl-SI-NN7IZMDC-BLiLsQKQ.js} +1 -1
- package/dist-embed/chunks/{stateDiagram-43e79a5f-C-TVhCrM.js → stateDiagram-43e79a5f-CNvh6hi1.js} +1 -1
- package/dist-embed/chunks/{stateDiagram-D77RDMKH-tqnmMQUf.js → stateDiagram-D77RDMKH-B57tGlQp.js} +1 -1
- package/dist-embed/chunks/{stateDiagram-D77RDMKH-CWrs6KzY.js → stateDiagram-D77RDMKH-D0LWS8oe.js} +1 -1
- package/dist-embed/chunks/{stateDiagram-D77RDMKH-XK76naDS.js → stateDiagram-D77RDMKH-DxKAfNML.js} +1 -1
- package/dist-embed/chunks/{stateDiagram-v2-2041ed4f-TVcKzajK.js → stateDiagram-v2-2041ed4f-BJpoWqKy.js} +1 -1
- package/dist-embed/chunks/{stateDiagram-v2-MP3YSRHH-D3ZN_IoS.js → stateDiagram-v2-MP3YSRHH-CouGWb0D.js} +1 -1
- package/dist-embed/chunks/{stateDiagram-v2-MP3YSRHH-lpluVNfO.js → stateDiagram-v2-MP3YSRHH-DAJ3mmV7.js} +1 -1
- package/dist-embed/chunks/{stateDiagram-v2-MP3YSRHH-C3MNIg5B.js → stateDiagram-v2-MP3YSRHH-DWVb2don.js} +1 -1
- package/dist-embed/chunks/{styles-455b33cd-CIILXOoF.js → styles-455b33cd--c-Q4lAI.js} +1 -1
- package/dist-embed/chunks/{styles-f932cba9-CVBMDsh6.js → styles-f932cba9-D41PptLO.js} +1 -1
- package/dist-embed/chunks/{styles-fcc2142b-CTOmFTKK.js → styles-fcc2142b-DO_mbuzb.js} +1 -1
- package/dist-embed/chunks/{subset-shared.chunk-PVguOYyR.js → subset-shared.chunk-KMJoi0ES.js} +1 -1
- package/dist-embed/chunks/{subset-worker.chunk-iWGyr_E5.js → subset-worker.chunk-D4fLKx8W.js} +1 -1
- package/dist-embed/chunks/{sv-SE-XGPEYMSR-DI7YcqUR.js → sv-SE-XGPEYMSR-BG1QXCvW.js} +1 -1
- package/dist-embed/chunks/{svgDrawCommon-148a3cd9-BCgvh5nL.js → svgDrawCommon-148a3cd9-_sy1MPqQ.js} +1 -1
- package/dist-embed/chunks/{swimlanes-42K2YHIH-B9qJ99nD.js → swimlanes-42K2YHIH-DFY4MLTT.js} +1 -1
- package/dist-embed/chunks/{swimlanes-42K2YHIH-Ca0PhRmf.js → swimlanes-42K2YHIH-DFhNG700.js} +1 -1
- package/dist-embed/chunks/{swimlanes-42K2YHIH-DHcV40DB.js → swimlanes-42K2YHIH-qHdPIKqR.js} +1 -1
- package/dist-embed/chunks/{swimlanesDiagram-VR7AAH4N-BEQKTD21.js → swimlanesDiagram-VR7AAH4N-DLu8qxW1.js} +1 -1
- package/dist-embed/chunks/{swimlanesDiagram-VR7AAH4N-CQ7d-sbG.js → swimlanesDiagram-VR7AAH4N-DfJlYoc0.js} +1 -1
- package/dist-embed/chunks/{swimlanesDiagram-VR7AAH4N-D-2e4UFJ.js → swimlanesDiagram-VR7AAH4N-Di8ZW7vB.js} +1 -1
- package/dist-embed/chunks/{ta-IN-2NMHFXQM-OZH5xroe.js → ta-IN-2NMHFXQM-Cwf7MXhM.js} +1 -1
- package/dist-embed/chunks/{th-TH-HPSO5L25-gAuWhBpT.js → th-TH-HPSO5L25-BgFIeFdc.js} +1 -1
- package/dist-embed/chunks/{timeline-definition-24CTP7MA-CtZZro9U.js → timeline-definition-24CTP7MA-CSnCQHgO.js} +1 -1
- package/dist-embed/chunks/{timeline-definition-24CTP7MA-DJcFE1jT.js → timeline-definition-24CTP7MA-EjGuok3K.js} +1 -1
- package/dist-embed/chunks/{timeline-definition-24CTP7MA-B8lxEouP.js → timeline-definition-24CTP7MA-jNu4kA6-.js} +1 -1
- package/dist-embed/chunks/{timeline-definition-7545f45a-CLycxRtq.js → timeline-definition-7545f45a-DKVkx2iN.js} +1 -1
- package/dist-embed/chunks/{tr-TR-DEFEU3FU-DQ0SDuS6.js → tr-TR-DEFEU3FU-B36BzndK.js} +1 -1
- package/dist-embed/chunks/{uk-UA-QMV73CPH-7J4e2jng.js → uk-UA-QMV73CPH-BIdgdufZ.js} +1 -1
- package/dist-embed/chunks/{vennDiagram-4TSXK5OY-zaNGkt8b.js → vennDiagram-4TSXK5OY-BwJIpWTX.js} +1 -1
- package/dist-embed/chunks/{vennDiagram-4TSXK5OY-Ca7szyFH.js → vennDiagram-4TSXK5OY-Ct92LUy3.js} +1 -1
- package/dist-embed/chunks/{vennDiagram-4TSXK5OY-BMmQ-DIV.js → vennDiagram-4TSXK5OY-sTUDzxoI.js} +1 -1
- package/dist-embed/chunks/{vi-VN-M7AON7JQ-dNpZ5DZ5.js → vi-VN-M7AON7JQ-C_vYqSDJ.js} +1 -1
- package/dist-embed/chunks/{wardleyDiagram-VM6X3IG4-C1VKw6YX.js → wardleyDiagram-VM6X3IG4-CmL9UVda.js} +1 -1
- package/dist-embed/chunks/{wardleyDiagram-VM6X3IG4-Dh0UOrRp.js → wardleyDiagram-VM6X3IG4-D19vZyCA.js} +1 -1
- package/dist-embed/chunks/{wardleyDiagram-VM6X3IG4-D_Q6gtp2.js → wardleyDiagram-VM6X3IG4-pjFMZv0g.js} +1 -1
- package/dist-embed/chunks/{xychartDiagram-3f383b91-B-BTwetN.js → xychartDiagram-3f383b91-C9v4_Sav.js} +1 -1
- package/dist-embed/chunks/{xychartDiagram-S5SC5T6Z-D_TaZM0k.js → xychartDiagram-S5SC5T6Z-BR0Sc17V.js} +1 -1
- package/dist-embed/chunks/{xychartDiagram-S5SC5T6Z-4OhI4XQl.js → xychartDiagram-S5SC5T6Z-CVSyvraK.js} +1 -1
- package/dist-embed/chunks/{xychartDiagram-S5SC5T6Z-BQHFHk-x.js → xychartDiagram-S5SC5T6Z-DlWO5eFt.js} +1 -1
- package/dist-embed/chunks/{zh-CN-LNUGB5OW-CZSp2g8b.js → zh-CN-LNUGB5OW-yOtUN9v4.js} +1 -1
- package/dist-embed/chunks/{zh-HK-E62DVLB3-DUqVOyB_.js → zh-HK-E62DVLB3-Drd2m3yL.js} +1 -1
- package/dist-embed/chunks/{zh-TW-RAJ6MFWO-U-TalxxN.js → zh-TW-RAJ6MFWO-CqJCCTAz.js} +1 -1
- package/dist-embed/datalayer-app-main.js +13 -13
- package/lib/AgentNode.js +9 -9
- package/lib/agents/AgentRuntimeChat.js +1 -1
- package/lib/api/agents.js +3 -3
- package/lib/api/context.js +3 -3
- package/lib/api/evals.js +3 -3
- package/lib/api/events.js +3 -3
- package/lib/api/index.js +2 -2
- package/lib/api/notifications.js +3 -3
- package/lib/api/output.js +3 -3
- package/lib/api/runtimes/checkpoints.js +3 -3
- package/lib/api/runtimes/environments.js +3 -3
- package/lib/api/runtimes/healthz.js +2 -2
- package/lib/api/runtimes/runtimes.js +3 -3
- package/lib/api/runtimes/snapshots.js +3 -3
- package/lib/api/scheduler/schedules.js +2 -2
- package/lib/api/spacer/documents.js +2 -2
- package/lib/api/spacer/healthz.js +2 -2
- package/lib/api/spacer/items.js +2 -2
- package/lib/api/spacer/lexicals.js +2 -2
- package/lib/api/spacer/notebooks.js +2 -2
- package/lib/api/spacer/spaces.js +3 -3
- package/lib/api/spacer/users.js +3 -3
- package/lib/apps/core/index.d.ts +12 -0
- package/lib/apps/embed/AppEmbed.js +2 -2
- package/lib/apps/embed/element.js +1 -1
- package/lib/apps/plugins/agents/AnonymousKeyBadge.js +1 -1
- package/lib/apps/plugins/app-activity/AppActivity.js +2 -2
- package/lib/apps/plugins/app-computer/AppComputer.js +1 -1
- package/lib/apps/plugins/app-page/AppPage.js +1 -1
- package/lib/apps/plugins/app-rules/AppRulesCard.js +1 -1
- package/lib/apps/plugins/app-rules/sessionRulesAction.d.ts +17 -0
- package/lib/apps/plugins/app-rules/sessionRulesAction.js +30 -0
- package/lib/apps/plugins/assistant/index.js +2 -2
- package/lib/apps/plugins/chat/ChatView.js +1 -1
- package/lib/apps/plugins/chat/SessionActionsMenu.js +13 -8
- package/lib/apps/plugins/chat/sessionActions.js +4 -0
- package/lib/apps/plugins/commands/index.js +1 -1
- package/lib/apps/plugins/document/openingDocument.js +1 -1
- package/lib/apps/plugins/page-layout/TurnPanel.js +1 -1
- package/lib/apps/plugins/page-layout/index.js +2 -2
- package/lib/apps/presets.js +1 -1
- package/lib/chat/ChatFloating.js +1 -1
- package/lib/chat/ChatPopupStandalone.js +1 -1
- package/lib/chat/ChatSidebar.js +1 -1
- package/lib/chat/ChatStandalone.js +1 -1
- package/lib/chat/assistant/characters.js +1 -1
- package/lib/chat/base/ChatBase.js +1 -1
- package/lib/chat/presence/Presence.js +1 -1
- package/lib/client/AgentRuntimesClient.js +1 -1
- package/lib/client/AgentsMixin.js +1 -1
- package/lib/client/mixins/RuntimesMixin.js +1 -1
- package/lib/client/mixins/SpacerMixin.js +2 -2
- package/lib/client/utils/spacerUtils.js +1 -1
- package/lib/components/agents/AgentSummary.js +1 -1
- package/lib/components/cards/NotificationEventCard.js +1 -1
- package/lib/components/cards/OutputCard.js +1 -1
- package/lib/components/cards/ToolApprovalCard.js +1 -1
- package/lib/components/code-sandboxes/CodeSandboxLauncher.js +6 -6
- package/lib/components/code-sandboxes/CodeSandboxPickerCell.js +1 -1
- package/lib/components/context/SpaceSelect.js +1 -1
- package/lib/components/flashes/FlashDisclaimer.js +1 -1
- package/lib/components/inspector/AgentInspector.js +1 -1
- package/lib/components/inspector/agentSpans.js +1 -1
- package/lib/components/progress/CreditsIndicator.js +2 -2
- package/lib/components/progress/index.js +1 -1
- package/lib/components/scheduler/ScheduleMenu.js +1 -1
- package/lib/components/snapshots/SandboxSnapshotMenu.js +2 -2
- package/lib/components/snippets/SnippetDialog.js +1 -1
- package/lib/components/teams/SceneTranscript.js +1 -1
- package/lib/context/CostUsageChart.js +1 -1
- package/lib/context/TokenUsageChart.js +1 -1
- package/lib/context/TurnGraphChart.js +1 -1
- package/lib/examples/AgentA2ATeamExample.js +2 -2
- package/lib/examples/AgentCheckpointsExample.js +1 -1
- package/lib/examples/AgentCodemodeExample.js +1 -1
- package/lib/examples/AgentEvalsExample.js +1 -1
- package/lib/examples/AgentGuardrailsExample.js +2 -2
- package/lib/examples/AgentInferenceProviderExample.js +1 -1
- package/lib/examples/AgentMCPExample.js +1 -1
- package/lib/examples/AgentMemoryExample.js +1 -1
- package/lib/examples/AgentMonitoringExample.js +1 -1
- package/lib/examples/AgentNotificationsExample.js +1 -1
- package/lib/examples/AgentOtelExample.js +1 -1
- package/lib/examples/AgentOutputsExample.js +1 -1
- package/lib/examples/AgentSkillsExample.js +1 -1
- package/lib/examples/AgentToolApprovalsExample.js +1 -1
- package/lib/examples/AgentTriggersExample.js +1 -1
- package/lib/examples/AgentspecsExample.js +1 -1
- package/lib/examples/LoopWorkspaceEmbed.js +1 -1
- package/lib/examples/ScenesExample.js +2 -2
- package/lib/examples/VoiceChatExample.js +1 -1
- package/lib/examples/components/AuthRequiredView.js +2 -2
- package/lib/examples/components/HeaderControls.js +1 -1
- package/lib/examples/main.js +4 -4
- package/lib/examples2/main.js +1 -1
- package/lib/hooks/index.js +1 -1
- package/lib/hooks/useAIAgentsWebSocket.js +2 -2
- package/lib/hooks/useAgentRuntimes.js +3 -3
- package/lib/hooks/useCellOutputshot.js +1 -1
- package/lib/hooks/useCheckpoints.js +6 -6
- package/lib/hooks/useMonitoring.js +1 -1
- package/lib/hooks/useNotifications.js +2 -2
- package/lib/hooks/useProjects.js +1 -1
- package/lib/jupyter/serverExecution.js +2 -2
- package/lib/mocks/models/CourseMock.js +2 -2
- package/lib/mocks/models/SpaceMock.js +2 -2
- package/lib/models/CodeSandboxSnapshotDTO.js +1 -1
- package/lib/models/EnvironmentDTO.js +1 -1
- package/lib/models/LexicalDTO.js +2 -2
- package/lib/models/NotebookDTO.js +2 -2
- package/lib/models/Page.js +1 -1
- package/lib/models/RuntimeDTO.js +1 -1
- package/lib/models/Space.js +2 -2
- package/lib/models/SpaceDTO.js +2 -2
- package/lib/models/index.js +1 -1
- package/lib/portable/sessions.d.ts +4 -0
- package/lib/portable/sessions.js +4 -0
- package/lib/runtimes/actions.js +1 -1
- package/lib/services/DatalayerServiceManager.js +2 -2
- package/lib/state/index.js +3 -3
- package/lib/state/substates/RuntimesState.js +2 -2
- package/lib/state/substates/index.js +1 -1
- package/lib/stores/agentRuntimeStore.js +1 -1
- package/lib/types/mcp.js +1 -1
- package/lib/types/sandbox.js +1 -1
- package/package.json +1 -1
- package/scripts/check-npm-pack.mjs +22 -3
- package/scripts/esm-specifiers.mjs +71 -1
- package/scripts/fully-specify-lib.mjs +17 -2
- package/dist-embed/chunks/ChatView-LzqHHAEe.js +0 -32
- package/dist-embed/chunks/index-D8x0MQWQ.js +0 -1
|
@@ -120,7 +120,7 @@ ${Au}
|
|
|
120
120
|
:scope strong {
|
|
121
121
|
font-weight: var(--base-text-weight-semibold);
|
|
122
122
|
}
|
|
123
|
-
`,loopThemeStyles=buildThemeStyles(loopLight,loopDark,{fontFamily:loopFontFamily,css:loopOwnCss,shape:{radiusControl:loopShapeVars["--loop-radius-control"],radiusTable:loopShapeVars["--borderRadius-medium"],radiusOverlay:loopShapeVars["--loop-radius-card"],radiusCard:loopShapeVars["--loop-radius-card"],radiusBubble:loopShapeVars["--loop-radius-bubble"],radiusFrame:loopShapeVars["--loop-radius-frame"],shadow:loopShapeVars["--loop-shadow-frame"],motionStatus:loopMotionVars["--loop-motion-status"],motionMessage:loopMotionVars["--loop-motion-message"],motionPane:loopMotionVars["--loop-motion-pane"],motionEasing:loopMotionVars["--loop-motion-easing"],messageLink:"currentColor"},variables:{light:{...loopShapeVars,...loopTints("light"),...loopMotionVars,...loopShadows.light,...loopTypeVars(loopFontFamily),"--loop-hairline":loopHairline.light,"--borderColor-default":loopHairline.light,"--focus-outlineColor":loopFocusRing.light,"--underlineNav-borderColor-active":themeAccents.green.accent},dark:{...loopShapeVars,...loopTints("dark"),...loopMotionVars,...loopShadows.dark,...loopTypeVars(loopFontFamily),"--loop-hairline":loopHairline.dark,"--borderColor-default":loopHairline.dark,"--focus-outlineColor":loopFocusRing.dark,"--underlineNav-borderColor-active":themeAccents.green.accent}}});loopThemeStyles.css;const loopTheme={...theme$1,fontWeights:{light:loopFontWeights.regular,normal:loopFontWeights.regular,semibold:loopFontWeights.semibold,bold:loopFontWeights.semibold}},themeTokens={datalayer:{label:"Datalayer",description:"Default green palette — the classic Datalayer look.",brandColor:datalayerColors.greenBrand,defaultColorMode:"auto",themeStyles:datalayerThemeStyles,cardGradient:{light:{from:datalayerColors.greenBrand,to:datalayerColors.greenText},dark:{from:datalayerColors.greenAccent,to:datalayerColors.greenBrand}},brightPalette:{glow:datalayerColors.brightGlow,onGlow:"#1b1f24",pop:datalayerColors.brightPop,spark:datalayerColors.brightSpark,blaze:datalayerColors.brightBlaze,surge:datalayerColors.brightSurge,flame:datalayerColors.brightFlame,gold:datalayerColors.brightGold},brightPaletteLight:{glow:datalayerColors.brightLightGlow,onGlow:"#1b1f24",pop:datalayerColors.brightLightPop,spark:datalayerColors.brightLightSpark,blaze:datalayerColors.brightLightBlaze,surge:datalayerColors.brightLightSurge,flame:datalayerColors.brightLightFlame,gold:datalayerColors.brightLightGold}},spatial:{label:"Spatial",description:"Cosmic indigo & deep blues — inspired by space.",brandColor:spatialColors.indigoBrand,defaultColorMode:"auto",themeStyles:spatialThemeStyles,cardGradient:{light:{from:spatialColors.indigoBrand,to:spatialColors.indigoText},dark:{from:spatialColors.indigoAccent,to:spatialColors.indigoBrand}},brightPalette:{glow:spatialColors.brightGlow,onGlow:"#ffffff",pop:spatialColors.brightPop,spark:spatialColors.brightSpark,blaze:spatialColors.brightBlaze,surge:spatialColors.brightSurge,flame:spatialColors.brightFlame,gold:spatialColors.brightGold},brightPaletteLight:{glow:spatialColors.brightLightGlow,onGlow:"#ffffff",pop:spatialColors.brightLightPop,spark:spatialColors.brightLightSpark,blaze:spatialColors.brightLightBlaze,surge:spatialColors.brightLightSurge,flame:spatialColors.brightLightFlame,gold:spatialColors.brightLightGold}},lovely:{label:"Lovely",description:"Warm rose & magenta — soft and inviting.",brandColor:lovelyColors.roseBrand,defaultColorMode:"auto",themeStyles:lovelyThemeStyles,cardGradient:{light:{from:lovelyColors.roseBrand,to:lovelyColors.roseText},dark:{from:lovelyColors.roseAccent,to:lovelyColors.roseBrand}},brightPalette:{glow:lovelyColors.brightGlow,onGlow:"#ffffff",pop:lovelyColors.brightPop,spark:lovelyColors.brightSpark,blaze:lovelyColors.brightBlaze,surge:lovelyColors.brightSurge,flame:lovelyColors.brightFlame,gold:lovelyColors.brightGold},brightPaletteLight:{glow:lovelyColors.brightLightGlow,onGlow:"#ffffff",pop:lovelyColors.brightLightPop,spark:lovelyColors.brightLightSpark,blaze:lovelyColors.brightLightBlaze,surge:lovelyColors.brightLightSurge,flame:lovelyColors.brightLightFlame,gold:lovelyColors.brightLightGold}},matrix:{label:"Matrix",description:"Phosphor green on black — CRT terminal aesthetic.",brandColor:matrixColors.greenPhosphor,defaultColorMode:"dark",themeStyles:matrixThemeStyles,cardGradient:{light:{from:matrixColors.greenBrand,to:matrixColors.greenText},dark:{from:matrixColors.greenGlow,to:matrixColors.greenHover}},brightPalette:{glow:matrixColors.brightGlow,onGlow:"#1b1f24",pop:matrixColors.brightPop,spark:matrixColors.brightSpark,blaze:matrixColors.brightBlaze,surge:matrixColors.brightSurge,flame:matrixColors.brightFlame,gold:matrixColors.brightGold},brightPaletteLight:{glow:matrixColors.brightLightGlow,onGlow:"#1b1f24",pop:matrixColors.brightLightPop,spark:matrixColors.brightLightSpark,blaze:matrixColors.brightLightBlaze,surge:matrixColors.brightLightSurge,flame:matrixColors.brightLightFlame,gold:matrixColors.brightLightGold}},earth:{label:"Earth",description:"Ocean blues, forest greens & golden sun — the Blue Planet.",brandColor:earthColors.oceanBrand,defaultColorMode:"auto",themeStyles:earthThemeStyles,cardGradient:{light:{from:earthColors.oceanBrand,to:earthColors.oceanText},dark:{from:earthColors.oceanAccent,to:earthColors.oceanBrand}},brightPalette:{glow:earthColors.brightGlow,onGlow:"#ffffff",pop:earthColors.brightPop,spark:earthColors.brightSpark,blaze:earthColors.brightBlaze,surge:earthColors.brightSurge,flame:earthColors.brightFlame,gold:earthColors.brightGold},brightPaletteLight:{glow:earthColors.brightLightGlow,onGlow:"#ffffff",pop:earthColors.brightLightPop,spark:earthColors.brightLightSpark,blaze:earthColors.brightLightBlaze,surge:earthColors.brightLightSurge,flame:earthColors.brightLightFlame,gold:earthColors.brightLightGold}},sand:{label:"Sand",description:"Warm, pale desert neutrals with a golden accent — calm & editorial.",brandColor:sandColors.sandBrand,defaultColorMode:"light",themeStyles:sandThemeStyles,cardGradient:{light:{from:sandColors.sandBrand,to:sandColors.sandText},dark:{from:sandColors.sandAccent,to:sandColors.sandBrand}},brightPalette:{glow:sandColors.brightGlow,onGlow:"#211A12",pop:sandColors.brightPop,spark:sandColors.brightSpark,blaze:sandColors.brightBlaze,surge:sandColors.brightSurge,flame:sandColors.brightFlame,gold:sandColors.brightGold},brightPaletteLight:{glow:sandColors.brightLightGlow,onGlow:"#ffffff",pop:sandColors.brightLightPop,spark:sandColors.brightLightSpark,blaze:sandColors.brightLightBlaze,surge:sandColors.brightLightSurge,flame:sandColors.brightLightFlame,gold:sandColors.brightLightGold}},ivory:{label:"Ivory",description:"Soft, warm off-white that creates a calm, refined, and welcoming feeling.",brandColor:ivoryColors.ivoryBrand,defaultColorMode:"light",themeStyles:ivoryThemeStyles,cardGradient:{light:{from:ivoryColors.ivoryBrand,to:ivoryColors.ivoryText},dark:{from:ivoryColors.ivoryAccent,to:ivoryColors.ivoryBrand}},brightPalette:{glow:ivoryColors.brightGlow,onGlow:"#211A12",pop:ivoryColors.brightPop,spark:ivoryColors.brightSpark,blaze:ivoryColors.brightBlaze,surge:ivoryColors.brightSurge,flame:ivoryColors.brightFlame,gold:ivoryColors.brightGold},brightPaletteLight:{glow:ivoryColors.brightLightGlow,onGlow:"#ffffff",pop:ivoryColors.brightLightPop,spark:ivoryColors.brightLightSpark,blaze:ivoryColors.brightLightBlaze,surge:ivoryColors.brightLightSurge,flame:ivoryColors.brightLightFlame,gold:ivoryColors.brightLightGold}},sun:{label:"Sun",description:"Warm, radiant theme inspired by golden light, bringing energy, optimism, and a welcoming atmosphere.",brandColor:sunColors.sunBrand,defaultColorMode:"light",themeStyles:sunThemeStyles,cardGradient:{light:{from:sunColors.sunBrand,to:sunColors.sunText},dark:{from:sunColors.sunAccent,to:sunColors.sunBrand}},brightPalette:{glow:sunColors.brightGlow,onGlow:"#211A08",pop:sunColors.brightPop,spark:sunColors.brightSpark,blaze:sunColors.brightBlaze,surge:sunColors.brightSurge,flame:sunColors.brightFlame,gold:sunColors.brightGold},brightPaletteLight:{glow:sunColors.brightLightGlow,onGlow:"#ffffff",pop:sunColors.brightLightPop,spark:sunColors.brightLightSpark,blaze:sunColors.brightLightBlaze,surge:sunColors.brightLightSurge,flame:sunColors.brightLightFlame,gold:sunColors.brightLightGold}},loop:{label:"Loop",description:"Very clean: one soft accent, neutral everything else. The look of an application built in LOOP.",brandColor:loopColors.loopBrand,defaultColorMode:"light",themeStyles:loopThemeStyles,cardGradient:{light:{from:loopColors.loopBrand,to:loopColors.loopBrand},dark:{from:loopColors.loopBrand,to:loopColors.loopBrand}},brightPalette:{glow:loopColors.brightGlow,onGlow:loopColors.loopOn,pop:loopColors.brightPop,spark:loopColors.brightSpark,blaze:loopColors.brightBlaze,surge:loopColors.brightSurge,flame:loopColors.brightFlame,gold:loopColors.brightGold},brightPaletteLight:{glow:loopColors.brightLightGlow,onGlow:"#ffffff",pop:loopColors.brightLightPop,spark:loopColors.brightLightSpark,blaze:loopColors.brightLightBlaze,surge:loopColors.brightLightSurge,flame:loopColors.brightLightFlame,gold:loopColors.brightLightGold}}};function brightPaletteOf(Au,lo){const $u=themeTokens[Au]??themeTokens.datalayer;return lo==="light"?$u.brightPaletteLight??$u.brightPalette:$u.brightPalette}const primerThemes={datalayer:datalayerTheme,spatial:spatialTheme,lovely:lovelyTheme,matrix:matrixTheme,earth:earthTheme,sand:sandTheme,ivory:ivoryTheme,sun:sunTheme,loop:loopTheme},themeConfigs=Object.fromEntries(Object.keys(themeTokens).map(Au=>[Au,{...themeTokens[Au],primerTheme:primerThemes[Au]}]));function getThemeConfig(Au){return themeConfigs[Au]}const osMode=()=>typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";function getBrightPalette(Au="datalayer",lo){const $u=lo==="auto"?osMode():lo==="light"?"light":"dark";return brightPaletteOf(Au,$u)}const createStoreImpl$2=Au=>{let lo;const $u=new Set,Ru=(Lu,Bu)=>{const ju=typeof Lu=="function"?Lu(lo):Lu;if(!Object.is(ju,lo)){const Fu=lo;lo=Bu??(typeof ju!="object"||ju===null)?ju:Object.assign({},lo,ju),$u.forEach(zu=>zu(lo,Fu))}},Iu=()=>lo,Mu={setState:Ru,getState:Iu,getInitialState:()=>Du,subscribe:Lu=>($u.add(Lu),()=>$u.delete(Lu))},Du=lo=Au(Ru,Iu,Mu);return Mu},createStore$2=(Au=>Au?createStoreImpl$2(Au):createStoreImpl$2),identity$2=Au=>Au;function useStore$2(Au,lo=identity$2){const $u=vM.useSyncExternalStore(Au.subscribe,vM.useCallback(()=>lo(Au.getState()),[Au,lo]),vM.useCallback(()=>lo(Au.getInitialState()),[Au,lo]));return vM.useDebugValue($u),$u}const createImpl$2=Au=>{const lo=createStore$2(Au),$u=Ru=>useStore$2(lo,Ru);return Object.assign($u,lo),$u},create$h=(Au=>Au?createImpl$2(Au):createImpl$2);function createJSONStorage$1(Au,lo){let $u;try{$u=Au()}catch{return}return{getItem:Iu=>{var Pu;const Ou=Du=>Du===null?null:JSON.parse(Du,void 0),Mu=(Pu=$u.getItem(Iu))!=null?Pu:null;return Mu instanceof Promise?Mu.then(Ou):Ou(Mu)},setItem:(Iu,Pu)=>$u.setItem(Iu,JSON.stringify(Pu,void 0)),removeItem:Iu=>$u.removeItem(Iu)}}const toThenable$1=Au=>lo=>{try{const $u=Au(lo);return $u instanceof Promise?$u:{then(Ru){return toThenable$1(Ru)($u)},catch(Ru){return this}}}catch($u){return{then(Ru){return this},catch(Ru){return toThenable$1(Ru)($u)}}}},persistImpl$1=(Au,lo)=>($u,Ru,Iu)=>{let Pu={storage:createJSONStorage$1(()=>window.localStorage),partialize:Vu=>Vu,version:0,merge:(Vu,Gu)=>({...Gu,...Vu}),...lo},Ou=!1,Mu=0;const Du=new Set,Lu=new Set;let Bu=Pu.storage;if(!Bu)return Au((...Vu)=>{console.warn(`[zustand persist middleware] Unable to update item '${Pu.name}', the given storage is currently unavailable.`),$u(...Vu)},Ru,Iu);const ju=()=>{const Vu=Pu.partialize({...Ru()});return Bu.setItem(Pu.name,{state:Vu,version:Pu.version})},Fu=Iu.setState;Iu.setState=(Vu,Gu)=>(Fu(Vu,Gu),ju());const zu=Au((...Vu)=>($u(...Vu),ju()),Ru,Iu);Iu.getInitialState=()=>zu;let Uu;const Hu=()=>{var Vu,Gu;if(!Bu)return;const Wu=++Mu;Ou=!1,Du.forEach(Ju=>{var Yu;return Ju((Yu=Ru())!=null?Yu:zu)});const Ku=((Gu=Pu.onRehydrateStorage)==null?void 0:Gu.call(Pu,(Vu=Ru())!=null?Vu:zu))||void 0;return toThenable$1(Bu.getItem.bind(Bu))(Pu.name).then(Ju=>{if(Ju)if(typeof Ju.version=="number"&&Ju.version!==Pu.version){if(Pu.migrate){const Yu=Pu.migrate(Ju.state,Ju.version);return Yu instanceof Promise?Yu.then(Xu=>[!0,Xu]):[!0,Yu]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,Ju.state];return[!1,void 0]}).then(Ju=>{var Yu;if(Wu!==Mu)return;const[Xu,ed]=Ju;if(Uu=Pu.merge(ed,(Yu=Ru())!=null?Yu:zu),$u(Uu,!0),Xu)return ju()}).then(()=>{Wu===Mu&&(Ku?.(Ru(),void 0),Uu=Ru(),Ou=!0,Lu.forEach(Ju=>Ju(Uu)))}).catch(Ju=>{Wu===Mu&&Ku?.(void 0,Ju)})};return Iu.persist={setOptions:Vu=>{Pu={...Pu,...Vu},Vu.storage&&(Bu=Vu.storage)},clearStorage:()=>{++Mu,Bu?.removeItem(Pu.name)},getOptions:()=>Pu,rehydrate:()=>Hu(),hasHydrated:()=>Ou,onHydrate:Vu=>(Du.add(Vu),()=>{Du.delete(Vu)}),onFinishHydration:Vu=>(Lu.add(Vu),()=>{Lu.delete(Vu)})},Pu.skipHydration||Hu(),Uu||zu},persist$2=persistImpl$1,VARIANT_SCHEMA_VERSION=1;function normalizeVariantPreference(Au){return{theme:Au.theme,colorMode:Au.colorMode,version:typeof Au.version=="number"?Au.version:VARIANT_SCHEMA_VERSION}}function normalizeVariants(Au){if(!Au)return{};const lo={};for(const[$u,Ru]of Object.entries(Au))!Ru||typeof Ru!="object"||!("theme"in Ru)||!("colorMode"in Ru)||(lo[$u]=normalizeVariantPreference(Ru));return lo}function hasMissingVariantVersion(Au){return!Au||Object.keys(Au).length===0?!1:Object.values(Au).some(lo=>typeof lo?.version!="number")}const colorModeCycle={light:"dark",dark:"auto",auto:"light"};function createThemeStore(Au,lo){return create$h()(persist$2($u=>({colorMode:lo?.colorMode,theme:lo?.theme,activeVariant:null,variants:normalizeVariants(lo?.variants),toggleColorMode:()=>$u(Ru=>{const Iu=colorModeCycle[Ru.colorMode];return Ru.activeVariant&&Ru.variants[Ru.activeVariant]?{colorMode:Iu,variants:{...Ru.variants,[Ru.activeVariant]:{...Ru.variants[Ru.activeVariant],colorMode:Iu,version:VARIANT_SCHEMA_VERSION}}}:{colorMode:Iu}}),setColorMode:Ru=>$u(Iu=>Iu.activeVariant&&Iu.variants[Iu.activeVariant]?{colorMode:Ru,variants:{...Iu.variants,[Iu.activeVariant]:{...Iu.variants[Iu.activeVariant],colorMode:Ru,version:VARIANT_SCHEMA_VERSION}}}:{colorMode:Ru}),setTheme:(Ru,Iu=!0)=>$u(Pu=>{const Ou=Iu?themeConfigs[Ru].defaultColorMode:Pu.colorMode;return Pu.activeVariant&&Pu.variants[Pu.activeVariant]?{theme:Ru,colorMode:Ou,variants:{...Pu.variants,[Pu.activeVariant]:{theme:Ru,colorMode:Ou,version:VARIANT_SCHEMA_VERSION}}}:{theme:Ru,colorMode:Ou}}),registerVariants:Ru=>$u(Iu=>{const Pu={...Iu.variants};for(const[Ou,Mu]of Object.entries(Ru))Pu[Ou]?Pu[Ou]=normalizeVariantPreference({...Pu[Ou],version:Pu[Ou].version??VARIANT_SCHEMA_VERSION}):Pu[Ou]=normalizeVariantPreference(Mu);return{variants:Pu}}),setVariant:Ru=>$u(Iu=>{const Pu=Iu.variants[Ru];return Pu?{activeVariant:Ru,theme:Pu.theme,colorMode:Pu.colorMode}:{activeVariant:Ru}})}),{name:Au,version:3,storage:createJSONStorage$1(()=>localStorage),partialize:$u=>({colorMode:$u.colorMode,theme:$u.theme,activeVariant:$u.activeVariant,variants:$u.variants}),migrate:$u=>{const Ru=$u??{},Iu=Ru.variants,Pu=hasMissingVariantVersion(Iu),Ou=normalizeVariants(Iu);return Pu&&(Ou["agent-anonymous"]={theme:"matrix",colorMode:"dark",version:VARIANT_SCHEMA_VERSION}),{...Ru,variants:Ou,...Pu?{theme:Ru.activeVariant==="agent-anonymous"?"matrix":Ru.theme,colorMode:Ru.activeVariant==="agent-anonymous"?"dark":Ru.colorMode}:{}}},merge:($u,Ru)=>{const Iu=$u??{},Pu=normalizeVariants(Ru.variants);if(Iu.variants)for(const[Ou,Mu]of Object.entries(Iu.variants))Mu&&typeof Mu=="object"&&"theme"in Mu&&(Pu[Ou]=normalizeVariantPreference(Mu));return{...Ru,...Iu,variants:Pu}}}))}const useThemeStore=createThemeStore("datalayer-theme",{colorMode:"dark",theme:"matrix"}),dlBrightDark=getBrightPalette("datalayer"),dlBrightLight=getBrightPalette("datalayer","light"),spBrightDark=getBrightPalette("spatial"),spBrightLight=getBrightPalette("spatial","light"),lvBrightDark=getBrightPalette("lovely"),lvBrightLight=getBrightPalette("lovely","light"),mxBrightDark=getBrightPalette("matrix"),mxBrightLight=getBrightPalette("matrix","light"),eaBrightDark=getBrightPalette("earth"),eaBrightLight=getBrightPalette("earth","light"),saBrightDark=getBrightPalette("sand"),saBrightLight=getBrightPalette("sand","light"),ivBrightDark=getBrightPalette("ivory"),ivBrightLight=getBrightPalette("ivory","light"),suBrightDark=getBrightPalette("sun"),suBrightLight=getBrightPalette("sun","light"),loBrightDark=getBrightPalette("loop"),loBrightLight=getBrightPalette("loop","light"),palettes={datalayer:{light:{bg:"#f6f8fa",bgPanel:"#ffffff",bgAlt:"#f0f3f6",primary:datalayerColors.greenBrand,secondary:datalayerColors.greenText,accent:datalayerColors.greenBright,glow:dlBrightLight.glow,pop:dlBrightLight.pop,spark:dlBrightLight.spark,blaze:dlBrightLight.blaze,surge:dlBrightLight.surge,flame:dlBrightLight.flame,gold:dlBrightLight.gold,textLight:"#1f2328",textMuted:"#656d76",isLight:!0},dark:{bg:"#0d1117",bgPanel:"#161b22",bgAlt:"#1c2128",primary:datalayerColors.greenAccent,secondary:datalayerColors.greenBrand,accent:datalayerColors.greenBright,glow:dlBrightDark.glow,pop:dlBrightDark.pop,spark:dlBrightDark.spark,blaze:dlBrightDark.blaze,surge:dlBrightDark.surge,flame:dlBrightDark.flame,gold:dlBrightDark.gold,textLight:"#f0f6fc",textMuted:"#8b949e",isLight:!1}},spatial:{light:{bg:"#f0f2ff",bgPanel:"#ffffff",bgAlt:"#eef2ff",primary:spatialColors.indigoBrand,secondary:spatialColors.indigoText,accent:spatialColors.indigoBright,glow:spBrightLight.glow,pop:spBrightLight.pop,spark:spBrightLight.spark,blaze:spBrightLight.blaze,surge:spBrightLight.surge,flame:spBrightLight.flame,gold:spBrightLight.gold,textLight:"#1E1E3F",textMuted:spatialColors.gray,isLight:!0},dark:{bg:spatialColors.black,bgPanel:"#111827",bgAlt:"#1E293B",primary:spatialColors.indigoAccent,secondary:spatialColors.indigoBrand,accent:spatialColors.indigoBright,glow:spBrightDark.glow,pop:spBrightDark.pop,spark:spBrightDark.spark,blaze:spBrightDark.blaze,surge:spBrightDark.surge,flame:spBrightDark.flame,gold:spBrightDark.gold,textLight:"#E0E7FF",textMuted:"#94A3B8",isLight:!1}},lovely:{light:{bg:"#fff5f7",bgPanel:"#ffffff",bgAlt:lovelyColors.roseTint,primary:lovelyColors.roseBrand,secondary:lovelyColors.roseText,accent:lovelyColors.roseBright,glow:lvBrightLight.glow,pop:lvBrightLight.pop,spark:lvBrightLight.spark,blaze:lvBrightLight.blaze,surge:lvBrightLight.surge,flame:lvBrightLight.flame,gold:lvBrightLight.gold,textLight:"#2D1B28",textMuted:lovelyColors.gray,isLight:!0},dark:{bg:lovelyColors.black,bgPanel:"#250E1D",bgAlt:"#3D1530",primary:lovelyColors.roseAccent,secondary:lovelyColors.roseBrand,accent:lovelyColors.roseBright,glow:lvBrightDark.glow,pop:lvBrightDark.pop,spark:lvBrightDark.spark,blaze:lvBrightDark.blaze,surge:lvBrightDark.surge,flame:lvBrightDark.flame,gold:lvBrightDark.gold,textLight:"#FCE7F3",textMuted:"#D4A5BD",isLight:!1}},matrix:{light:{bg:"#f0fff0",bgPanel:"#ffffff",bgAlt:matrixColors.greenTint,primary:matrixColors.greenBrand,secondary:matrixColors.greenText,accent:matrixColors.greenAccent,glow:mxBrightLight.glow,pop:mxBrightLight.pop,spark:mxBrightLight.spark,blaze:mxBrightLight.blaze,surge:mxBrightLight.surge,flame:mxBrightLight.flame,gold:mxBrightLight.gold,textLight:"#0A2E1A",textMuted:matrixColors.gray,isLight:!0},dark:{bg:matrixColors.black,bgPanel:"#0A1F0A",bgAlt:"#122812",primary:matrixColors.greenPhosphor,secondary:matrixColors.greenGlow,accent:matrixColors.greenGlow,glow:mxBrightDark.glow,pop:mxBrightDark.pop,spark:mxBrightDark.spark,blaze:mxBrightDark.blaze,surge:mxBrightDark.surge,flame:mxBrightDark.flame,gold:mxBrightDark.gold,textLight:"#C8E6C9",textMuted:"#66BB6A",isLight:!1}},earth:{light:{bg:"#F0F5FA",bgPanel:"#ffffff",bgAlt:earthColors.oceanTint,primary:earthColors.oceanBrand,secondary:earthColors.oceanText,accent:earthColors.oceanAccent,glow:eaBrightLight.glow,pop:eaBrightLight.pop,spark:eaBrightLight.spark,blaze:eaBrightLight.blaze,surge:eaBrightLight.surge,flame:eaBrightLight.flame,gold:eaBrightLight.gold,textLight:"#1A2332",textMuted:earthColors.gray,isLight:!0},dark:{bg:earthColors.black,bgPanel:"#0E1D30",bgAlt:"#132840",primary:earthColors.oceanAccent,secondary:earthColors.oceanBrand,accent:earthColors.oceanBright,glow:eaBrightDark.glow,pop:eaBrightDark.pop,spark:eaBrightDark.spark,blaze:eaBrightDark.blaze,surge:eaBrightDark.surge,flame:eaBrightDark.flame,gold:eaBrightDark.gold,textLight:"#D4E4DC",textMuted:"#8A9BA8",isLight:!1}},sand:{light:{bg:"#FBF7EF",bgPanel:"#ffffff",bgAlt:sandColors.sandTint,primary:sandColors.sandBrand,secondary:sandColors.sandText,accent:sandColors.sandAccent,glow:saBrightLight.glow,pop:saBrightLight.pop,spark:saBrightLight.spark,blaze:saBrightLight.blaze,surge:saBrightLight.surge,flame:saBrightLight.flame,gold:saBrightLight.gold,textLight:"#2B2118",textMuted:sandColors.gray,isLight:!0},dark:{bg:sandColors.black,bgPanel:"#2A2118",bgAlt:"#33281A",primary:sandColors.sandAccent,secondary:sandColors.sandBrand,accent:sandColors.sandBright,glow:saBrightDark.glow,pop:saBrightDark.pop,spark:saBrightDark.spark,blaze:saBrightDark.blaze,surge:saBrightDark.surge,flame:saBrightDark.flame,gold:saBrightDark.gold,textLight:"#EDE3D3",textMuted:"#B7A793",isLight:!1}},ivory:{light:{bg:"#FBF6EC",bgPanel:"#ffffff",bgAlt:ivoryColors.ivoryTint,primary:ivoryColors.ivoryBrand,secondary:ivoryColors.ivoryText,accent:ivoryColors.ivoryAccent,glow:ivBrightLight.glow,pop:ivBrightLight.pop,spark:ivBrightLight.spark,blaze:ivBrightLight.blaze,surge:ivBrightLight.surge,flame:ivBrightLight.flame,gold:ivBrightLight.gold,textLight:"#2C2318",textMuted:ivoryColors.gray,isLight:!0},dark:{bg:ivoryColors.black,bgPanel:"#2A2219",bgAlt:"#33291B",primary:ivoryColors.ivoryAccent,secondary:ivoryColors.ivoryBrand,accent:ivoryColors.ivoryBright,glow:ivBrightDark.glow,pop:ivBrightDark.pop,spark:ivBrightDark.spark,blaze:ivBrightDark.blaze,surge:ivBrightDark.surge,flame:ivBrightDark.flame,gold:ivBrightDark.gold,textLight:"#EFE6D6",textMuted:"#BBAC97",isLight:!1}},sun:{light:{bg:"#FFF9EC",bgPanel:"#ffffff",bgAlt:sunColors.sunTint,primary:sunColors.sunBrand,secondary:sunColors.sunText,accent:sunColors.sunAccent,glow:suBrightLight.glow,pop:suBrightLight.pop,spark:suBrightLight.spark,blaze:suBrightLight.blaze,surge:suBrightLight.surge,flame:suBrightLight.flame,gold:suBrightLight.gold,textLight:"#2A2210",textMuted:sunColors.gray,isLight:!0},dark:{bg:sunColors.black,bgPanel:"#2A2109",bgAlt:"#33290C",primary:sunColors.sunAccent,secondary:sunColors.sunBrand,accent:sunColors.sunBright,glow:suBrightDark.glow,pop:suBrightDark.pop,spark:suBrightDark.spark,blaze:suBrightDark.blaze,surge:suBrightDark.surge,flame:suBrightDark.flame,gold:suBrightDark.gold,textLight:"#F3E9CF",textMuted:"#BEAC82",isLight:!1}},loop:{light:{bg:loopColors.white,bgPanel:"#ffffff",bgAlt:loopColors.subtle,primary:loopColors.loopBrand,secondary:loopColors.loopText,accent:loopColors.loopAccent,glow:loBrightLight.glow,pop:loBrightLight.pop,spark:loBrightLight.spark,blaze:loBrightLight.blaze,surge:loBrightLight.surge,flame:loBrightLight.flame,gold:loBrightLight.gold,textLight:loopColors.ink,textMuted:loopColors.gray,isLight:!0},dark:{bg:loopColors.black,bgPanel:"#19191B",bgAlt:loopColors.subtleDark,primary:loopColors.loopBrand,secondary:loopColors.loopBright,accent:loopColors.loopAccent,glow:loBrightDark.glow,pop:loBrightDark.pop,spark:loBrightDark.spark,blaze:loBrightDark.blaze,surge:loBrightDark.surge,flame:loBrightDark.flame,gold:loBrightDark.gold,textLight:loopColors.inkDark,textMuted:loopColors.grayDark,isLight:!1}}};function getColorPalette(Au="datalayer",lo="auto"){const $u=lo==="auto"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":lo;return palettes[Au]?.[$u]??palettes.datalayer.dark}function useColorPalette(){const{colorMode:Au,theme:lo}=useThemeStore();return getColorPalette(lo,Au)}const SHEET_SHADOW="0 1px 2px rgba(0,0,0,0.06), 0 24px 48px -28px rgba(0,0,0,0.35)";function Sheet(Au){return jsxRuntimeExports.jsx(Box,{bg:"canvas.default",border:"1px solid",borderColor:"border.default",borderRadius:"card",boxShadow:SHEET_SHADOW,...Au})}const sizeMap$2={small:16,medium:32,large:64};function _DlIconInverseColormode$2({mode:Au,children:lo}){const $u=reactExports.useRef(null),[Ru,Iu]=reactExports.useState({mode:typeof Au=="string"?Au:null,lightTheme:null,darkTheme:null});return reactExports.useLayoutEffect(()=>{if(typeof document>"u")return;let Pu=null,Ou=null,Mu=null,Du=$u.current&&$u.current.parentElement;for(;Du&&(!Pu||!Ou||!Mu);)Du.getAttribute&&(Pu=Pu||Du.getAttribute("data-color-mode"),Ou=Ou||Du.getAttribute("data-light-theme"),Mu=Mu||Du.getAttribute("data-dark-theme")),Du=Du.parentElement;(!Pu||Pu==="auto")&&(Pu=typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),Iu({mode:typeof Au=="string"?Au:Pu==="dark"?"light":"dark",lightTheme:Ou,darkTheme:Mu})},[Au]),reactExports.createElement("span",{ref:$u,"data-color-mode":Ru.mode||"light","data-light-theme":Ru.lightTheme||void 0,"data-dark-theme":Ru.darkTheme||void 0,style:{display:"inline-flex",lineHeight:0,color:"var(--fgColor-default, var(--color-fg-default, currentColor))"}},lo)}function AiAgentIcon({title:Au,titleId:lo,size:$u,colored:Ru,themed:Iu,colormode:Pu,...Ou},Mu){const Du=reactExports.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",fill:Iu?"var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor))":"var(--datalayer-icon-color, currentColor)",width:$u?typeof $u=="string"?sizeMap$2[$u]:$u:"16px","aria-hidden":"true",ref:Mu,"aria-labelledby":lo},Ou,{"data-datalayer-icon":"",style:Ou&&Ou.color!=null?Object.assign({},Ou.style,{"--datalayer-icon-color":Ou.color,color:Ou.color}):Ou&&Ou.style}),reactExports.createElement("style",null,'[data-color-mode="light"]{--datalayer-icon-color-scheme:light}[data-color-mode="dark"]{--datalayer-icon-color-scheme:dark}svg[data-datalayer-icon]{color-scheme:var(--datalayer-icon-color-scheme, light dark)}'),Au?reactExports.createElement("title",{id:lo},Au):null,reactExports.createElement("path",{d:"M5.75 7.5a.75.75 0 01.75.75v1.5a.75.75 0 01-1.5 0v-1.5a.75.75 0 01.75-.75zm5.25.75a.75.75 0 00-1.5 0v1.5a.75.75 0 001.5 0v-1.5z"}),reactExports.createElement("path",{d:"M6.25 0h2A.75.75 0 019 .75V3.5h3.25a2.25 2.25 0 012.25 2.25V8h.75a.75.75 0 010 1.5h-.75v2.75a2.25 2.25 0 01-2.25 2.25h-8.5a2.25 2.25 0 01-2.25-2.25V9.5H.75a.75.75 0 010-1.5h.75V5.75A2.25 2.25 0 013.75 3.5H7.5v-2H6.25a.75.75 0 010-1.5zM3 5.75v6.5c0 .414.336.75.75.75h8.5a.75.75 0 00.75-.75v-6.5a.75.75 0 00-.75-.75h-8.5a.75.75 0 00-.75.75z"}));return Pu?reactExports.createElement(_DlIconInverseColormode$2,{mode:typeof Pu=="string"?Pu:void 0},Du):Du}const ForwardRef$2=reactExports.forwardRef(AiAgentIcon),sizeMap$1={small:16,medium:32,large:64};function _DlIconInverseColormode$1({mode:Au,children:lo}){const $u=reactExports.useRef(null),[Ru,Iu]=reactExports.useState({mode:typeof Au=="string"?Au:null,lightTheme:null,darkTheme:null});return reactExports.useLayoutEffect(()=>{if(typeof document>"u")return;let Pu=null,Ou=null,Mu=null,Du=$u.current&&$u.current.parentElement;for(;Du&&(!Pu||!Ou||!Mu);)Du.getAttribute&&(Pu=Pu||Du.getAttribute("data-color-mode"),Ou=Ou||Du.getAttribute("data-light-theme"),Mu=Mu||Du.getAttribute("data-dark-theme")),Du=Du.parentElement;(!Pu||Pu==="auto")&&(Pu=typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),Iu({mode:typeof Au=="string"?Au:Pu==="dark"?"light":"dark",lightTheme:Ou,darkTheme:Mu})},[Au]),reactExports.createElement("span",{ref:$u,"data-color-mode":Ru.mode||"light","data-light-theme":Ru.lightTheme||void 0,"data-dark-theme":Ru.darkTheme||void 0,style:{display:"inline-flex",lineHeight:0,color:"var(--fgColor-default, var(--color-fg-default, currentColor))"}},lo)}function MicrophoneIcon({title:Au,titleId:lo,size:$u,colored:Ru,themed:Iu,colormode:Pu,...Ou},Mu){const Du=reactExports.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 72 72",fill:Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 72%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 62%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 72%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 62%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 72%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",width:$u?typeof $u=="string"?sizeMap$1[$u]:$u:"16px","aria-hidden":"true",ref:Mu,"aria-labelledby":lo},Ou,{"data-datalayer-icon":"",style:Ou&&Ou.color!=null?Object.assign({},Ou.style,{"--datalayer-icon-color":Ou.color,color:Ou.color}):Ou&&Ou.style}),reactExports.createElement("style",null,'[data-color-mode="light"]{--datalayer-icon-color-scheme:light}[data-color-mode="dark"]{--datalayer-icon-color-scheme:dark}svg[data-datalayer-icon]{color-scheme:var(--datalayer-icon-color-scheme, light dark)}'),Au?reactExports.createElement("title",{id:lo},Au):null,reactExports.createElement("path",{fill:Ru?"#3F3F3F":Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 41%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 93%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 41%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 93%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 41%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",d:"M39.4 29.52c-2.636-2.216-2.553-3.52-2.55-3.523-.109-.127-1.758-1.676-1.777-2.156l-.009-.082-2.556 3.283c.324-.446-6.322 10.406-6.322 10.406L14.393 53.686l3.373 3.372S42.18 35.781 41.828 36.161l3.403-3.356c-.107.004-3.193-1.068-5.83-3.284z"}),reactExports.createElement("path",{fill:Ru?"#D0CFCE":Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 71%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 63%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 71%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 63%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 71%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",d:"M54.62 30.18a.998.998 0 01-1.411.093l-16.62-14.58a1 1 0 01-.099-1.4c-.003.003-.007.004-.01.008l-.654.786a1 1 0 00.11 1.391L52.554 31.06a1 1 0 001.427-.113l.655-.787c.04-.047.055-.105.084-.157-.033.06-.054.123-.1.177z"}),reactExports.createElement("path",{fill:Ru?"#3F3F3F":Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 41%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 93%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 41%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 93%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 41%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",d:"M55.258 25.541c-1.162 3.4-5.283 5.562-5.283 5.562-1.926 1.097-4.032 1.62-6.038 1.52 0 0-.347-.081-.913-.272-1.828-.634-5.85-2.485-7.25-6.88-.377-2.002-.159-4.185.646-6.277 1.023-4.264 4.995-6.256 4.995-6.256 1.41-.956 2.94-1.59 4.479-1.871 2.82-.533 5.66.08 7.775 1.972 3.327 2.947 3.844 8.086 1.59 12.502z"}),reactExports.createElement("path",{fill:Ru?"#9B9B9A":Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 55%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 79%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 55%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 79%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 55%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",d:"M51.475 25.541c-1.172 3.4-5.283 5.562-5.283 5.562a12.08 12.08 0 01-3.168 1.247c-1.828-.633-5.85-2.484-7.25-6.88-.377-2.001-.159-4.184.646-6.276 1.022-4.264 4.995-6.256 4.995-6.256 1.41-.956 2.94-1.59 4.479-1.871 1.46.292 2.83.946 3.992 1.972 3.317 2.947 3.833 8.086 1.589 12.502z"}),reactExports.createElement("path",{d:"M30.75 38.941l4.02-4.619m14.744-3.892c-1.804 1.014-3.774 1.495-5.65 1.404m-2.36-18.184c3.737-2.497 8.405-2.591 11.465.093 3.108 2.727 3.59 7.471 1.489 11.545m-18.223-.065c-.354-1.844-.152-3.862.602-5.789m-3.52 8.196L14.393 53.686l3.373 3.373 23.34-21.572M15.497 56.001l-3.046 3.074m41.417-29.554L37.249 14.94",fill:"none",stroke:Ru?"#000":Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 38%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 96%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 38%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 96%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 38%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",strokeLinecap:"round",strokeLinejoin:"round",strokeMiterlimit:10,strokeWidth:2}));return Pu?reactExports.createElement(_DlIconInverseColormode$1,{mode:typeof Pu=="string"?Pu:void 0},Du):Du}const ForwardRef$1=reactExports.forwardRef(MicrophoneIcon),sizeMap={small:16,medium:32,large:64};function _DlIconInverseColormode({mode:Au,children:lo}){const $u=reactExports.useRef(null),[Ru,Iu]=reactExports.useState({mode:typeof Au=="string"?Au:null,lightTheme:null,darkTheme:null});return reactExports.useLayoutEffect(()=>{if(typeof document>"u")return;let Pu=null,Ou=null,Mu=null,Du=$u.current&&$u.current.parentElement;for(;Du&&(!Pu||!Ou||!Mu);)Du.getAttribute&&(Pu=Pu||Du.getAttribute("data-color-mode"),Ou=Ou||Du.getAttribute("data-light-theme"),Mu=Mu||Du.getAttribute("data-dark-theme")),Du=Du.parentElement;(!Pu||Pu==="auto")&&(Pu=typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),Iu({mode:typeof Au=="string"?Au:Pu==="dark"?"light":"dark",lightTheme:Ou,darkTheme:Mu})},[Au]),reactExports.createElement("span",{ref:$u,"data-color-mode":Ru.mode||"light","data-light-theme":Ru.lightTheme||void 0,"data-dark-theme":Ru.darkTheme||void 0,style:{display:"inline-flex",lineHeight:0,color:"var(--fgColor-default, var(--color-fg-default, currentColor))"}},lo)}function PlusCircleIcon({title:Au,titleId:lo,size:$u,colored:Ru,themed:Iu,colormode:Pu,...Ou},Mu){const Du=reactExports.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fillRule:"evenodd",clipRule:"evenodd",width:$u?typeof $u=="string"?sizeMap[$u]:$u:"16px",viewBox:"0 0 24 24",fill:Iu?"var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor))":"var(--datalayer-icon-color, currentColor)","aria-hidden":"true",ref:Mu,"aria-labelledby":lo},Ou,{"data-datalayer-icon":"",style:Ou&&Ou.color!=null?Object.assign({},Ou.style,{"--datalayer-icon-color":Ou.color,color:Ou.color}):Ou&&Ou.style}),reactExports.createElement("style",null,'[data-color-mode="light"]{--datalayer-icon-color-scheme:light}[data-color-mode="dark"]{--datalayer-icon-color-scheme:dark}svg[data-datalayer-icon]{color-scheme:var(--datalayer-icon-color-scheme, light dark)}'),Au?reactExports.createElement("title",{id:lo},Au):null,reactExports.createElement("path",{d:"M11.5 0C17.847 0 23 5.153 23 11.5S17.847 23 11.5 23 0 17.847 0 11.5 5.153 0 11.5 0zm0 1C17.295 1 22 5.705 22 11.5S17.295 22 11.5 22 1 17.295 1 11.5 5.705 1 11.5 1zm.5 10h6v1h-6v6h-1v-6H5v-1h6V5h1v6z"}));return Pu?reactExports.createElement(_DlIconInverseColormode,{mode:typeof Pu=="string"?Pu:void 0},Du):Du}const ForwardRef=reactExports.forwardRef(PlusCircleIcon),__vite_import_meta_env__$2={},createStoreImpl$1=Au=>{let lo;const $u=new Set,Ru=(Bu,ju)=>{const Fu=typeof Bu=="function"?Bu(lo):Bu;if(!Object.is(Fu,lo)){const zu=lo;lo=ju??(typeof Fu!="object"||Fu===null)?Fu:Object.assign({},lo,Fu),$u.forEach(Uu=>Uu(lo,zu))}},Iu=()=>lo,Du={setState:Ru,getState:Iu,getInitialState:()=>Lu,subscribe:Bu=>($u.add(Bu),()=>$u.delete(Bu)),destroy:()=>{(__vite_import_meta_env__$2?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),$u.clear()}},Lu=lo=Au(Ru,Iu,Du);return Du},createStore$1=Au=>Au?createStoreImpl$1(Au):createStoreImpl$1;var withSelector={exports:{}},withSelector_production={},shim={exports:{}},useSyncExternalStoreShim_production={};var hasRequiredUseSyncExternalStoreShim_production;function requireUseSyncExternalStoreShim_production(){if(hasRequiredUseSyncExternalStoreShim_production)return useSyncExternalStoreShim_production;hasRequiredUseSyncExternalStoreShim_production=1;var Au=requireReact();function lo(ju,Fu){return ju===Fu&&(ju!==0||1/ju===1/Fu)||ju!==ju&&Fu!==Fu}var $u=typeof Object.is=="function"?Object.is:lo,Ru=Au.useState,Iu=Au.useEffect,Pu=Au.useLayoutEffect,Ou=Au.useDebugValue;function Mu(ju,Fu){var zu=Fu(),Uu=Ru({inst:{value:zu,getSnapshot:Fu}}),Hu=Uu[0].inst,Vu=Uu[1];return Pu(function(){Hu.value=zu,Hu.getSnapshot=Fu,Du(Hu)&&Vu({inst:Hu})},[ju,zu,Fu]),Iu(function(){return Du(Hu)&&Vu({inst:Hu}),ju(function(){Du(Hu)&&Vu({inst:Hu})})},[ju]),Ou(zu),zu}function Du(ju){var Fu=ju.getSnapshot;ju=ju.value;try{var zu=Fu();return!$u(ju,zu)}catch{return!0}}function Lu(ju,Fu){return Fu()}var Bu=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Lu:Mu;return useSyncExternalStoreShim_production.useSyncExternalStore=Au.useSyncExternalStore!==void 0?Au.useSyncExternalStore:Bu,useSyncExternalStoreShim_production}var hasRequiredShim;function requireShim(){return hasRequiredShim||(hasRequiredShim=1,shim.exports=requireUseSyncExternalStoreShim_production()),shim.exports}var hasRequiredWithSelector_production;function requireWithSelector_production(){if(hasRequiredWithSelector_production)return withSelector_production;hasRequiredWithSelector_production=1;var Au=requireReact(),lo=requireShim();function $u(Lu,Bu){return Lu===Bu&&(Lu!==0||1/Lu===1/Bu)||Lu!==Lu&&Bu!==Bu}var Ru=typeof Object.is=="function"?Object.is:$u,Iu=lo.useSyncExternalStore,Pu=Au.useRef,Ou=Au.useEffect,Mu=Au.useMemo,Du=Au.useDebugValue;return withSelector_production.useSyncExternalStoreWithSelector=function(Lu,Bu,ju,Fu,zu){var Uu=Pu(null);if(Uu.current===null){var Hu={hasValue:!1,value:null};Uu.current=Hu}else Hu=Uu.current;Uu=Mu(function(){function Gu(Xu){if(!Wu){if(Wu=!0,Ku=Xu,Xu=Fu(Xu),zu!==void 0&&Hu.hasValue){var ed=Hu.value;if(zu(ed,Xu))return Ju=ed}return Ju=Xu}if(ed=Ju,Ru(Ku,Xu))return ed;var td=Fu(Xu);return zu!==void 0&&zu(ed,td)?(Ku=Xu,ed):(Ku=Xu,Ju=td)}var Wu=!1,Ku,Ju,Yu=ju===void 0?null:ju;return[function(){return Gu(Bu())},Yu===null?void 0:function(){return Gu(Yu())}]},[Bu,ju,Fu,zu]);var Vu=Iu(Lu,Uu[0],Uu[1]);return Ou(function(){Hu.hasValue=!0,Hu.value=Vu},[Vu]),Du(Vu),Vu},withSelector_production}var hasRequiredWithSelector;function requireWithSelector(){return hasRequiredWithSelector||(hasRequiredWithSelector=1,withSelector.exports=requireWithSelector_production()),withSelector.exports}var withSelectorExports=requireWithSelector();const useSyncExternalStoreExports=getDefaultExportFromCjs(withSelectorExports),__vite_import_meta_env__$1={},{useDebugValue}=vM,{useSyncExternalStoreWithSelector}=useSyncExternalStoreExports;let didWarnAboutEqualityFn=!1;const identity$1=Au=>Au;function useStore$1(Au,lo=identity$1,$u){(__vite_import_meta_env__$1?"production":void 0)!=="production"&&$u&&!didWarnAboutEqualityFn&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),didWarnAboutEqualityFn=!0);const Ru=useSyncExternalStoreWithSelector(Au.subscribe,Au.getState,Au.getServerState||Au.getInitialState,lo,$u);return useDebugValue(Ru),Ru}const createImpl$1=Au=>{(__vite_import_meta_env__$1?"production":void 0)!=="production"&&typeof Au!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const lo=typeof Au=="function"?createStore$1(Au):Au,$u=(Ru,Iu)=>useStore$1(lo,Ru,Iu);return Object.assign($u,lo),$u},create$g=Au=>Au?createImpl$1(Au):createImpl$1,CONTROL_PLANE_URL="https://prod1.datalayer.run",RUNTIMES_PLANE_URL="https://r1.datalayer.run",MCP_SERVER_URL="https://mcp.datalayer.run/mcp",DEFAULT_PLANE_URLS={iamUrl:CONTROL_PLANE_URL,managerUrl:CONTROL_PLANE_URL,libraryUrl:CONTROL_PLANE_URL,spacerUrl:CONTROL_PLANE_URL,otelUrl:CONTROL_PLANE_URL,growthUrl:CONTROL_PLANE_URL,inboundsUrl:CONTROL_PLANE_URL,successUrl:CONTROL_PLANE_URL,supportUrl:CONTROL_PLANE_URL,contentsUrl:RUNTIMES_PLANE_URL,runtimesUrl:RUNTIMES_PLANE_URL,schedulerUrl:RUNTIMES_PLANE_URL,aiAgentsUrl:RUNTIMES_PLANE_URL,aiInferenceUrl:RUNTIMES_PLANE_URL,datalayerMcpServerUrl:MCP_SERVER_URL};class Logger{scope;isDevelopment;constructor(lo){this.scope=lo,this.isDevelopment=!1}log(lo,$u,...Ru){if(!this.isDevelopment&&lo==="debug")return;const Pu=`[${new Date().toISOString()}] [${this.scope}] [${lo.toUpperCase()}]`;switch(lo){case"debug":console.debug(Pu,$u,...Ru);break;case"info":console.info(Pu,$u,...Ru);break;case"warn":console.warn(Pu,$u,...Ru);break;case"error":console.error(Pu,$u,...Ru);break}}debug(lo,...$u){this.log("debug",lo,...$u)}info(lo,...$u){this.log("info",lo,...$u)}warn(lo,...$u){this.log("warn",lo,...$u)}error(lo,...$u){this.log("error",lo,...$u)}}function createLogger(Au){return new Logger(Au)}const configLogger=createLogger("config");let loadConfigurationFromServer=!0,initialConfiguration={token:"",credits:0,cpuEnvironment:'ai-agents-env"',gpuEnvironment:"ai-env",useMock:!1,whiteLabel:!0,loadConfigurationFromServer:!0,jupyterServerless:!1,...DEFAULT_PLANE_URLS,launcher:{category:"Datalayer",name:"Datalayer",icon:null,rank:1},brand:{name:"Datalayer",about:"AI Agents for Data Analysis",logoUrl:"https://assets.datalayer.tech/datalayer-25.svg",logoSquareUrl:"https://assets.datalayer.tech/datalayer-square.png",copyright:"© 2025 Datalayer, Inc",docsUrl:"https://datalayer.ai/docs",supportUrl:"https://datalayer.ai/support",termsUrl:"https://datalayer.ai/terms",pricingUrl:"https://datalayer.ai/pricing",privacyUrl:"https://datalayer.ai/privacy"}};const pageConfiguration={};try{if(typeof document<"u"){const Au=document.getElementById("datalayer-config-data");if(Au?.innerText){const lo=JSON.parse(Au?.innerText||"{}");Object.assign(pageConfiguration,lo),lo.loadConfigurationFromServer!=null&&(loadConfigurationFromServer=lo.loadConfigurationFromServer),initialConfiguration={...initialConfiguration,...lo},configLogger.info("Datalayer configuration loaded from HTML page",initialConfiguration),window.document.title=`${initialConfiguration.brand.name} ☰ ${initialConfiguration.brand.about}`}}}catch(Au){configLogger.debug("No valid configuration found in the webpage.",Au)}const coreStore=createStore$1((Au,lo)=>({tab:0,getIntTab:()=>Math.floor(lo().tab),setTab:$u=>Au(Ru=>({tab:$u})),configuration:initialConfiguration,setConfiguration:$u=>{configLogger.debug("Setting Datalayer configuration",$u),Au(Ru=>({configuration:{...Ru.configuration,...$u}}))},version:"",setVersion:$u=>{$u&&!lo().version&&Au(Ru=>({version:$u}))},loadConfigurationFromServer,setLoadConfigurationFromServer:$u=>{Au(Ru=>({loadConfigurationFromServer:$u}))}}));function useCoreStore(Au){return useStore$1(coreStore,Au)}const getOtelConsumeUrl=()=>coreStore.getState().configuration.otelUrl,BACKEND_TOOL_ACTIONS={"create-plan":["read"],"current-time":["read"],decide:["read"],"display-recipe":["read"],"example-create-plan":["read"],"example-current-time":["read"],"example-display-recipe":["read"],"example-generate-haiku":["read"],"example-generate-task-steps":["read"],"example-get-weather":["read"],"example-render-a2ui-surface":["read"],"example-update-plan-step":["read"],"generate-haiku":["read"],"generate-task-steps":["read"],"get-weather":["read"],"runtime-echo":["read"],"runtime-send-mail":["send"],"runtime-sensitive-echo":["read"],"update-plan-step":["read"]},SERVER_ACTIONS={alphavantage:{default:[],tools:{},conditions:{},signs:{}},chart:{checked:"2026-10-02",default:[],tools:{generate_area_chart:["read"],generate_bar_chart:["read"],generate_boxplot_chart:["read"],generate_column_chart:["read"],generate_district_map:["read"],generate_dual_axes_chart:["read"],generate_fishbone_diagram:["read"],generate_flow_diagram:["read"],generate_funnel_chart:["read"],generate_histogram_chart:["read"],generate_line_chart:["read"],generate_liquid_chart:["read"],generate_mind_map:["read"],generate_network_graph:["read"],generate_organization_chart:["read"],generate_path_map:["read"],generate_pie_chart:["read"],generate_pin_map:["read"],generate_radar_chart:["read"],generate_sankey_chart:["read"],generate_scatter_chart:["read"],generate_treemap_chart:["read"],generate_venn_chart:["read"],generate_violin_chart:["read"],generate_waterfall_chart:["read"],generate_word_cloud_chart:["read"],generate_spreadsheet:["read"]},conditions:{},signs:{}},datalayer:{checked:"2026-10-05",default:[],tools:{read_notebook:["read"],read_cell:["read"],download_notebook:["read"],list_notebooks:["read"],list_spaces:["read"],list_space_notebooks:["read"],find_notebook:["read"],list_notebook_versions:["read"],list_kernels:["read"],list_files:["read"],list_sandboxes:["read"],list_toolsets:["read"],search_library:["read"],get_library_artifact:["read"],read_library_artifact:["read"],search_earth_datasets:["read"],search_earth_datagranules:["read"],download_earth_data_granules:["read"],odoo_get_context:["read"],odoo_get_account:["read"],odoo_get_settings:["read"],odoo_list_companies:["read"],odoo_set_company:["write"],odoo_list_models:["read"],odoo_get_fields:["read"],odoo_search_records:["read"],odoo_read_records:["read"],odoo_group_records:["read"],odoo_create_record:["write"],odoo_update_records:["write"],odoo_delete_records:["delete"],odoo_accounting_list_invoices:["read"],odoo_accounting_get_invoice:["read"],odoo_accounting_list_journal_entries:["read"],odoo_accounting_list_open_balances:["read"],odoo_accounting_list_accounts:["read"],odoo_accounting_list_journals:["read"],odoo_accounting_get_journal_entry:["read"],odoo_accounting_trial_balance:["read"],odoo_accounting_general_ledger:["read"],odoo_winauditor_preview_balance:["read"],odoo_winauditor_preview_general_journal:["read"],odoo_winauditor_preview_general_ledger:["read"],odoo_accounting_create_draft_invoice:["write"],odoo_accounting_post_invoice:["write"],odoo_accounting_create_draft_journal_entry:["write"],odoo_accounting_post_journal_entry:["write"],odoo_winauditor_import_balance:["write"],odoo_winauditor_import_general_journal:["write"],odoo_winauditor_import_general_ledger:["write"],odoo_winauditor_preview_import_file:["read"],odoo_winauditor_migration_status:["read"],odoo_winauditor_import_partners:["write"],odoo_winauditor_import_chart_of_accounts:["write"],odoo_winauditor_ensure_journals:["write"],odoo_winauditor_import_journal_items:["write"],odoo_winauditor_post_migration_entries:["write"],odoo_winauditor_reconcile_journal_items:["write"],odoo_winauditor_import_assets:["write"],odoo_winauditor_validate_assets:["write"],odoo_winauditor_rollback_migration:["delete"],odoo_winauditor_attach_document:["write"],odoo_winauditor_list_attachments:["read"],odoo_winauditor_validate_migration:["read"],odoo_accounting_list_partners:["read"],odoo_accounting_partner_ledger:["read"],odoo_accounting_aged_balance:["read"],odoo_accounting_list_taxes:["read"],odoo_accounting_list_assets:["read"],odoo_accounting_get_asset:["read"],odoo_accounting_reconcile_lines:["write"],odoo_accounting_unreconcile_lines:["write"],odoo_accounting_bank_status:["read"],odoo_accounting_list_bank_lines:["read"],odoo_accounting_get_bank_line:["read"],odoo_accounting_suggest_bank_matches:["read"],odoo_accounting_suggest_reconciliations:["read"],odoo_accounting_explain_account_balance:["read"],odoo_accounting_list_bank_feeds:["read"],odoo_accounting_list_currency_rates:["read"],odoo_accounting_get_lock_dates:["read"],odoo_accounting_book_bank_line:["write"],odoo_accounting_match_bank_line:["write"],odoo_accounting_reset_bank_line:["write"],odoo_accounting_remove_duplicate_bank_lines:["delete"],odoo_accounting_link_bank_feed:["write"],odoo_accounting_create_vendor_bill:["write"],odoo_accounting_create_customer_invoice:["write"],odoo_accounting_set_currency_rates:["write"],odoo_accounting_set_lock_date:["write"],odoo_accounting_create_matching_model:["write"],odoo_accounting_get_tax_settings:["read"],odoo_accounting_list_tax_returns:["read"],odoo_accounting_get_tax_return:["read"],odoo_accounting_tax_grids:["read"],odoo_accounting_list_tax_grid_lines:["read"],odoo_accounting_check_tax_period:["read"],odoo_accounting_list_untagged_tax_lines:["read"],odoo_accounting_set_tax_periodicity:["write"],odoo_accounting_set_tax_grids:["write"],read_benchmark:["read"],read_benchmark_task:["read"],read_benchmark_task_trajectory:["read"],list_benchmark_task_files:["read"],list_content_sources:["read"],describe_content_source:["read"],list_content_attachments:["read"],list_dataset_revisions:["read"],query_status:["read"],list_secrets:["read"],use_notebook:["read"],unuse_notebook:["read"],connect_to_jupyter:["read"],insert_cell:["write"],delete_cell:["delete"],move_cell:["write"],edit_cell_source:["write"],snapshot_notebook:["write"],restore_notebook:["write"],overwrite_cell_source:["write"],clear_cell_output:["write"],execute_cell:["write"],execute_code:["write"],restart_notebook:["write"],insert_execute_code_cell:["write"],launch_sandbox:["buy"],use_sandbox:["write"],terminate_sandbox:["delete"],snapshot_sandbox:["write","buy"],share_sandbox:["publish"],unshare_sandbox:["write"],marimo_run_cell:["write"],marimo_run_code:["write"],marimo_remove_cell:["delete"],marimo_plan:["read"],marimo_graph:["read"],enable_toolset:["write"],disable_toolset:["write"],attach_content:["write"],detach_content:["write"],query_source:["read"],cancel_query:["write"],save_query_as_revision:["write"],mount_local_folder:["read"]},conditions:{},signs:{}},earthdata:{checked:"2026-10-07",default:[],tools:{search_earth_datasets:["read"],search_earth_datagranules:["read"],download_earth_data_granules:["write"]},conditions:{},signs:{}},eurus:{default:[],tools:{},conditions:{},signs:{}},filesystem:{checked:"2026-10-02",default:[],tools:{read_file:["read"],read_text_file:["read"],read_media_file:["read"],read_multiple_files:["read"],write_file:["write"],edit_file:["write"],create_directory:["write"],list_directory:["read"],list_directory_with_sizes:["read"],directory_tree:["read"],move_file:["write","delete"],search_files:["read"],get_file_info:["read"],list_allowed_directories:["read"]},conditions:{},signs:{}},github:{default:[],tools:{},conditions:{},signs:{}},"google-workspace":{checked:"2026-10-02",default:[],tools:{start_google_auth:["write"],search_gmail_messages:["read"],get_gmail_message_content:["read"],get_gmail_messages_content_batch:["read"],get_gmail_attachment_content:["read","write"],send_gmail_message:["send"],draft_gmail_message:["write"],get_gmail_thread_content:["read"],get_gmail_threads_content_batch:["read"],list_gmail_labels:["read"],manage_gmail_label:["write"],list_gmail_filters:["read"],manage_gmail_filter:["write","send"],modify_gmail_message_labels:["write"],batch_modify_gmail_message_labels:["write"],search_drive_files:["read"],get_drive_file_content:["read"],get_drive_file_download_url:["read"],list_drive_items:["read"],create_drive_folder:["write"],create_drive_file:["write"],import_to_google_doc:["write"],import_to_google_slides:["write"],import_to_google_sheets:["write"],get_drive_file_permissions:["read"],check_drive_file_public_access:["read"],update_drive_file:["write"],get_drive_shareable_link:["read"],manage_drive_access:["publish","send","delete"],copy_drive_file:["write"],set_drive_file_permissions:["publish","write"],list_calendars:["read"],get_events:["read"],manage_event:["write","send"],manage_out_of_office:["write","send"],manage_focus_time:["write","send"],query_freebusy:["read"],create_calendar:["write"],search_docs:["read"],get_doc_content:["read"],list_docs_in_folder:["read"],create_doc:["write"],modify_doc_text:["write"],find_and_replace_doc:["write"],insert_doc_elements:["write"],insert_doc_image:["write"],update_doc_headers_footers:["write"],batch_update_doc:["write","delete"],inspect_doc_structure:["read"],debug_docs_runtime_info:["read"],create_table_with_data:["write"],debug_table_structure:["read"],export_doc_to_pdf:["write"],update_paragraph_style:["write"],get_doc_as_markdown:["read"],manage_doc_tab:["write"],list_document_comments:["read"],manage_document_comment:["write","send"],list_spreadsheets:["read"],get_spreadsheet_info:["read"],read_sheet_values:["read"],modify_sheet_values:["write"],format_sheet_range:["write"],manage_conditional_formatting:["write"],create_spreadsheet:["write"],create_sheet:["write"],list_sheet_tables:["read"],append_table_rows:["write"],manage_sheet_tab:["write"],resize_sheet_dimensions:["write","delete"],move_sheet_rows:["write","delete"],manage_named_range:["write"],list_spreadsheet_comments:["read"],manage_spreadsheet_comment:["write","send"],list_spaces:["read"],get_messages:["read"],send_message:["send","write"],search_messages:["read"],create_reaction:["send"],download_chat_attachment:["read","write"],create_form:["write"],get_form:["read"],set_publish_settings:["publish"],get_form_response:["read"],list_form_responses:["read"],batch_update_form:["write","delete"],create_presentation:["write"],get_presentation:["read"],batch_update_presentation:["write","delete"],get_page:["read"],get_page_thumbnail:["read"],list_presentation_comments:["read"],manage_presentation_comment:["write","send"],list_task_lists:["read"],get_task_list:["read"],manage_task_list:["write"],list_tasks:["read"],get_task:["read"],manage_task:["write"],list_contacts:["read"],get_contact:["read"],search_contacts:["read"],manage_contact:["write"],list_contact_groups:["read"],get_contact_group:["read"],manage_contacts_batch:["write"],manage_contact_group:["write"],search_custom:["read"],get_search_engine_info:["read"],get_script_project:["read"],manage_script_content:["write","delete"],run_script_function:["write","send","delete","publish"],manage_deployment:["publish"],list_script_deployments:["read"],manage_script_project:["write"],manage_script_version:["write"],get_script_version:["read"],get_script_activity:["read"],generate_trigger_code:["read"],manage_script_trigger:["write"]},conditions:{manage_gmail_label:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_gmail_filter:[{argument:"action",classes:["delete"],equals:["delete","update"]}],modify_gmail_message_labels:[{argument:"add_label_ids",classes:["delete"],includes:["TRASH","SPAM"]}],batch_modify_gmail_message_labels:[{argument:"add_label_ids",classes:["delete"],includes:["TRASH","SPAM"]}],update_drive_file:[{argument:"trashed",classes:["delete"],equals:[!0]}],manage_event:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_out_of_office:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_focus_time:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_doc_tab:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_conditional_formatting:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_sheet_tab:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_named_range:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_task_list:[{argument:"action",classes:["delete"],equals:["delete","clear_completed"]}],manage_task:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_contact:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_contacts_batch:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_contact_group:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_deployment:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_script_project:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_script_trigger:[{argument:"action",classes:["delete"],equals:["delete"]}]},signs:{send_gmail_message:"body",draft_gmail_message:"body",send_message:"message_text"}},huggingface:{default:[],tools:{},conditions:{},signs:{}},kaggle:{default:[],tools:{},conditions:{},signs:{}},odoo:{default:[],tools:{},conditions:{},signs:{}},"odoo-accounting":{checked:"2026-10-05",default:[],tools:{odoo_accounting_list_invoices:["read"],odoo_accounting_get_invoice:["read"],odoo_accounting_list_journal_entries:["read"],odoo_accounting_list_open_balances:["read"],odoo_accounting_list_accounts:["read"],odoo_accounting_list_journals:["read"],odoo_accounting_get_journal_entry:["read"],odoo_accounting_trial_balance:["read"],odoo_accounting_general_ledger:["read"],odoo_accounting_create_draft_invoice:["write"],odoo_accounting_post_invoice:["write"],odoo_accounting_create_draft_journal_entry:["write"],odoo_accounting_post_journal_entry:["write"],odoo_accounting_list_partners:["read"],odoo_accounting_partner_ledger:["read"],odoo_accounting_aged_balance:["read"],odoo_accounting_list_taxes:["read"],odoo_accounting_list_assets:["read"],odoo_accounting_get_asset:["read"],odoo_accounting_reconcile_lines:["write"],odoo_accounting_unreconcile_lines:["write"],odoo_accounting_bank_status:["read"],odoo_accounting_list_bank_lines:["read"],odoo_accounting_get_bank_line:["read"],odoo_accounting_suggest_bank_matches:["read"],odoo_accounting_suggest_reconciliations:["read"],odoo_accounting_explain_account_balance:["read"],odoo_accounting_list_bank_feeds:["read"],odoo_accounting_list_currency_rates:["read"],odoo_accounting_get_lock_dates:["read"],odoo_accounting_book_bank_line:["write"],odoo_accounting_match_bank_line:["write"],odoo_accounting_reset_bank_line:["write"],odoo_accounting_remove_duplicate_bank_lines:["delete"],odoo_accounting_link_bank_feed:["write"],odoo_accounting_create_vendor_bill:["write"],odoo_accounting_create_customer_invoice:["write"],odoo_accounting_set_currency_rates:["write"],odoo_accounting_set_lock_date:["write"],odoo_accounting_create_matching_model:["write"],odoo_accounting_get_tax_settings:["read"],odoo_accounting_list_tax_returns:["read"],odoo_accounting_get_tax_return:["read"],odoo_accounting_tax_grids:["read"],odoo_accounting_list_tax_grid_lines:["read"],odoo_accounting_check_tax_period:["read"],odoo_accounting_list_untagged_tax_lines:["read"],odoo_accounting_set_tax_periodicity:["write"],odoo_accounting_set_tax_grids:["write"]},conditions:{},signs:{}},salesforce:{default:[],tools:{},conditions:{},signs:{}},slack:{checked:"2026-10-02",default:[],tools:{slack_list_channels:["read"],slack_post_message:["send"],slack_reply_to_thread:["send"],slack_add_reaction:["send"],slack_get_channel_history:["read"],slack_get_thread_replies:["read"],slack_get_users:["read"],slack_get_user_profile:["read"]},conditions:{},signs:{slack_post_message:"text",slack_reply_to_thread:"text"}},tavily:{checked:"2026-10-02",default:[],tools:{tavily_search:["read"],tavily_extract:["read"],tavily_crawl:["read"],tavily_map:["read"],tavily_research:["read"]},conditions:{},signs:{}}},BEHAVIOURS=["do_it","if_asked","ask_first","leave_to_me"],DEFAULT_BEHAVIOURS={read:"do_it",write:"ask_first",send:"ask_first",buy:"ask_first",delete:"ask_first",publish:"ask_first"},SERVER_TOOL=/^([A-Za-z0-9_-]+)(?::\d+(?:\.\d+)*)?\.([A-Za-z_][A-Za-z0-9_-]*)$/,own$a=(Au,lo)=>Object.prototype.hasOwnProperty.call(Au,lo)?Au[lo]:void 0,idOf=Au=>{const lo=Au.lastIndexOf(":");return lo>0&&Au.slice(lo+1).includes(".")?Au.slice(0,lo):Au};function splitRef(Au){const lo=SERVER_TOOL.exec(Au);return lo?[lo[1],lo[2]]:[void 0,idOf(Au)]}const isPattern=Au=>/[*?]/.test(Au);function matchesPattern(Au,lo){const $u=Array.from(lo,Ru=>Ru==="*"?"[\\s\\S]*":Ru==="?"?"[\\s\\S]":Ru.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("");return new RegExp(`^${$u}$`).test(Au)}const isComparable=Au=>typeof Au=="string"||typeof Au=="boolean"||typeof Au=="number"&&Number.isFinite(Au)&&(!Number.isInteger(Au)||Number.isSafeInteger(Au)),same=(Au,lo)=>typeof Au=="string"&&typeof lo=="string"?Au.trim().toLowerCase()===lo.trim().toLowerCase():isComparable(Au)&&isComparable(lo)&&Au===lo;function conditionHolds(Au,lo){if(!Object.prototype.hasOwnProperty.call(lo,Au.argument))return!1;const $u=lo[Au.argument];return Au.equals?.some(Ru=>same($u,Ru))?!0:Au.includes?.length?(Array.isArray($u)?$u:[$u]).some(Iu=>Au.includes.some(Pu=>same(Iu,Pu))):!1}function entryOf$1(Au,lo){const $u=own$a(SERVER_ACTIONS,Au);if(!$u)return[[],[]];const Ru=own$a($u.tools,lo);if(Ru)return[[...Ru],own$a($u.conditions,lo)??[]];for(const[Iu,Pu]of Object.entries($u.tools))if(isPattern(Iu)&&matchesPattern(lo,Iu))return[[...Pu],own$a($u.conditions,Iu)??[]];return[[...$u.default],[]]}const FORWARDING={"google-workspace.send_gmail_message":{message:"forward_message_id",mailbox:"user_google_email",recipients:["to","cc","bcc"]}};function addresses(Au){return(Array.isArray(Au)?Au:[Au]).filter($u=>typeof $u=="string").flatMap($u=>$u.split(",")).map($u=>{const Ru=/<([^>]*)>/.exec($u);return(Ru?Ru[1]:$u).trim().toLowerCase()}).filter($u=>$u.includes("@"))}const domainOf=Au=>Au.slice(Au.lastIndexOf("@")+1).trim();function forwardsOutside(Au,lo,$u){const Ru=own$a(FORWARDING,`${Au}.${lo}`),Iu=Ru?$u[Ru.message]:void 0;if(!Ru||typeof Iu!="string"||!Iu.trim())return!1;const[Pu]=addresses($u[Ru.mailbox]);return Pu?Ru.recipients.flatMap(Ou=>addresses($u[Ou])).some(Ou=>domainOf(Ou)!==domainOf(Pu)):!0}function classesOf(Au,lo){const[$u,Ru]=splitRef(Au);if($u===void 0)return[...own$a(BACKEND_TOOL_ACTIONS,Ru)??[]];const[Iu,Pu]=entryOf$1($u,Ru);for(const Ou of Pu)if(lo===void 0||conditionHolds(Ou,lo))for(const Mu of Ou.classes)Iu.includes(Mu)||Iu.push(Mu);return lo!==void 0&&Iu.length>0&&!Iu.includes("publish")&&forwardsOutside($u,Ru,lo)&&Iu.push("publish"),Iu}const strictest=Au=>Au.reduce((lo,$u)=>BEHAVIOURS.indexOf($u)>BEHAVIOURS.indexOf(lo)?$u:lo),connectionTo=(Au,lo)=>Au.connections.find($u=>idOf($u.server)===lo),reaches=(Au,lo)=>Au.only.length===0||Au.only.some($u=>matchesPattern(lo,$u)),isClass$1=Au=>Object.prototype.hasOwnProperty.call(DEFAULT_BEHAVIOURS,Au),normal=Au=>{if(isClass$1(Au))return Au;const[lo,$u]=splitRef(Au);return lo!==void 0?`${lo}.${$u}`:$u},byClasses=(Au,lo)=>{const $u={};for(const Ru of Au.rules)for(const Iu of Ru.appliesTo)isClass$1(Iu)&&($u[Iu]=Ru.behaviour);return lo.map(Ru=>$u[Ru]??DEFAULT_BEHAVIOURS[Ru])};function behaviourFor(Au,lo,$u={}){const[Ru,Iu]=splitRef(lo);let Pu,Ou=[],Mu;if($u.classes?Pu=Mu=[...$u.classes]:(Mu=classesOf(lo),Pu=classesOf(lo,{}),Ou=($u.arguments===void 0?Mu:classesOf(lo,$u.arguments)).filter(Bu=>!Pu.includes(Bu))),Ru!==void 0){const Lu=connectionTo(Au,Ru);if(!Lu||!reaches(Lu,Iu)||Lu.access==="read"&&Mu.some(Bu=>Bu!=="read"))return"leave_to_me"}const Du=Ru!==void 0?`${Ru}.${Iu}`:Iu;for(const Lu of Au.rules)if(Lu.appliesTo.some(Bu=>!isClass$1(Bu)&&normal(Bu)===Du))return strictest([Lu.behaviour,...byClasses(Au,Ou)]);return Pu.length===0&&Ou.length===0?"leave_to_me":strictest(byClasses(Au,[...Pu,...Ou]))}const BEHAVIOUR_WORDS={do_it:{says:"Do it",means:"It does it without asking."},if_asked:{says:"Do it if I asked",means:"Only what you approved in advance."},ask_first:{says:"Ask me first",means:"It waits for your yes."},leave_to_me:{says:"Leave it to me",means:"It never does it, and hands it to you."}},ACTION_WORDS={read:"Read",write:"Create or change",send:"Send",buy:"Buy",delete:"Delete",publish:"Share or publish"};function coverOf(Au){const lo=own$a(ACTION_WORDS,Au);if(lo)return lo;const[$u,Ru]=splitRef(Au);return $u?`${Ru} (${$u})`:Ru}const A2A_PROTOCOL_0_0_1={id:"a2a",version:"0.0.1",name:"Agent2Agent",description:"How agents talk to agents: teams and scenes talk over it, an application's route serves it, and its Agent Card advertises its extensions.",publisher:"Google, now the Linux Foundation",layer:"transport",specUrl:"https://a2a-protocol.org",specVersion:"1.0",status:"shipped",connects:"Other agents, each at its address with its Agent Card",packages:{python:["fasta2a","a2a-sdk"],typescript:["@a2a-js/sdk"]},protocolTools:[],appspecBlock:"a2a"},A2UI_PROTOCOL_0_0_1={id:"a2ui",version:"0.0.1",name:"A2UI",description:"How an agent's answer becomes an interface: components the host renders from a declarative surface.",publisher:"Google",layer:"ui",specUrl:"https://a2ui.org",specVersion:"0.9",status:"shipped",connects:"The person, through components an answer draws",packages:{python:["agent-runtimes"],typescript:["@a2ui/react","@a2ui/web_core"]},protocolTools:[]},ACP_PROTOCOL_0_0_1={id:"acp",version:"0.0.1",name:"Agentic Commerce Protocol",description:"Checkout sessions at a seller, completed with a payment the model never sees. In applications at test merchants only, with no real payment token (decided 2026-10-13): each purchase asked of the person first, made at most once.",publisher:"OpenAI, Stripe",layer:"commerce",specUrl:"https://github.com/agentic-commerce-protocol/agentic-commerce-protocol",specVersion:"2026-04-17",status:"shipped",connects:"Sellers, to check out with a delegated payment",packages:{python:["agent-runtimes"],typescript:["@datalayer/agent-runtimes"]},protocolTools:["agentic-commerce"]},AG_UI_PROTOCOL_0_0_1={id:"ag-ui",version:"0.0.1",name:"AG-UI",description:"How an agent streams its run to a page: messages, tool calls and state as events.",publisher:"CopilotKit",layer:"ui",specUrl:"https://docs.ag-ui.com",specVersion:"0.0.57 (@ag-ui/core)",status:"shipped",connects:"The page a person talks to the agent on",packages:{python:["ag-ui-protocol"],typescript:["@ag-ui/client","@ag-ui/core"]},protocolTools:[]},MCP_PROTOCOL_0_0_1={id:"mcp",version:"0.0.1",name:"Model Context Protocol",description:"How an agent calls tools and reads resources: clients and servers in both languages, and the MCP gateway every connection goes through.",publisher:"Anthropic",layer:"transport",specUrl:"https://modelcontextprotocol.io/specification",specVersion:"2026-07-28 (Python), 2025-11-25 (TypeScript)",status:"shipped",connects:"Tools, resources and prompts served by MCP servers",packages:{python:["mcp"],typescript:["@modelcontextprotocol/sdk","@mcp-ui/client"]},protocolTools:[]},PACT_PROTOCOL_0_0_1={id:"pact",version:"0.0.1",name:"Personal Agent Consent & Trust",description:"A personal agent asking a business's agent over A2A, first as itself, then for a person who delegated some of their permissions.",publisher:"Decagon, Instinct",layer:"consent",specUrl:"https://openpactprotocol.org",specVersion:"1.0",status:"shipped",connects:"Businesses' agents, asked for a person with their delegation",packages:{python:["agent-runtimes"],typescript:["@datalayer/agent-runtimes"]},protocolTools:["pact"],appspecBlock:"pact"},PAP_PROTOCOL_0_0_1={id:"pap",version:"0.0.1",name:"Personal Agent Protocol",description:"A person's agent working with a company for them — signed out, then signed in at the company, its changes confirmed by the person — and an application being a company personal agents reach.",publisher:"Sierra, Meta",layer:"consent",specUrl:"https://personalagentprotocol.org",specVersion:"draft 0.2",status:"shipped",connects:"Companies, as a person's agent there, or being one",packages:{python:["personal-agent-protocol"],typescript:["@datalayer/personal-agent-protocol"]},protocolTools:["pap"],appspecBlock:"pap"},TAP_PROTOCOL_0_0_1={id:"tap",version:"0.0.1",name:"Trusted Agent Protocol",description:"An agent-recognition profile over Web Bot Auth for merchants: a signature tagged agent-browser-auth to browse or agent-payer-auth to pay. Still a draft profile, built from Visa's public Merchant Specifications (2026-10-13) until Visa confirms it. In applications at test merchants only (decided 2026-10-14): the MCP gateway signs each UCP or ACP purchase with agent-payer-auth under the application's own key, and the test merchants verify it; browsing stays Web Bot Auth.",publisher:"Visa",layer:"identity",specUrl:"https://developer.visa.com/capabilities/trusted-agent-protocol/trusted-agent-protocol-specifications",specVersion:"draft (Merchant Specifications, read 2026-10-13)",status:"shipped",connects:"Merchants that recognise an agent by its signature",packages:{python:["agent-runtimes"],typescript:["@datalayer/agent-runtimes","http-message-sig"]},protocolTools:[]},UCP_PROTOCOL_0_0_1={id:"ucp",version:"0.0.1",name:"Universal Commerce Protocol",description:"Shopping at a merchant: catalogue, checkout and orders, every purchase an exact proposal the person approves. In applications at test merchants only, with no real payment (decided 2026-10-13): each purchase asked of the person first, made at most once.",publisher:"Google, with Shopify and retailers",layer:"commerce",specUrl:"https://github.com/Universal-Commerce-Protocol/ucp",specVersion:"2026-08-25",status:"shipped",connects:"Merchants, to search, check out and follow orders",packages:{python:["ucp-sdk","agent-runtimes"],typescript:["@ucp-js/sdk","@datalayer/agent-runtimes"]},protocolTools:["ucp"]},WEB_BOT_AUTH_PROTOCOL_0_0_1={id:"web-bot-auth",version:"0.0.1",name:"Web Bot Auth",description:"Signed outbound requests (RFC 9421) and the key directory a website checks them against. In applications, every request to a company, business or merchant is signed, and a signed fetch reads pages at the sites an application names, GET only (decided 2026-10-13).",publisher:"Cloudflare (IETF draft)",layer:"identity",specUrl:"https://datatracker.ietf.org/doc/draft-ietf-webbotauth-httpsig-protocol/",specVersion:"draft-ietf-webbotauth-httpsig-protocol-00",status:"shipped",connects:"Websites, which can tell the application's requests from someone pretending",packages:{python:["agent-runtimes"],typescript:["@datalayer/agent-runtimes","web-bot-auth"]},protocolTools:["signed-fetch"],appspecBlock:"signed_fetch"},PROTOCOL_CATALOGUE={a2a:A2A_PROTOCOL_0_0_1,a2ui:A2UI_PROTOCOL_0_0_1,acp:ACP_PROTOCOL_0_0_1,"ag-ui":AG_UI_PROTOCOL_0_0_1,mcp:MCP_PROTOCOL_0_0_1,pact:PACT_PROTOCOL_0_0_1,pap:PAP_PROTOCOL_0_0_1,tap:TAP_PROTOCOL_0_0_1,ucp:UCP_PROTOCOL_0_0_1,"web-bot-auth":WEB_BOT_AUTH_PROTOCOL_0_0_1},A2UI_SURFACE_UI_0_0_1={id:"a2ui-surface",version:"0.0.1",name:"Surfaces in the conversation",description:"Forms, tables and cards the agent draws in the conversation; what you fill in goes back to it.",emoji:"🪟",octicon:"browser",plugin:"@datalayer/loop-plugin-a2ui-surface",folder:"a2ui-surface",contributions:{slots:["loop.chatHeader"],points:["reactor.ui.renderer","reactor.ui.toolBinding"],commands:[]},contributionPoints:[],settings:{},renderers:["a2ui"],catalog:"a2ui/v0.9",components:[{id:"Text",name:"Text",category:"text",emoji:"🔤",description:"Words on the page: a heading, a paragraph, the answer — plain or Markdown.",version:"0.9.0",standard:!0,properties:{type:"object",required:["text"],properties:{text:{type:"string",title:"Words",description:"What it says, plain or in simple Markdown."},variant:{type:"string",title:"Style",description:"A heading of a level, a caption, or body text.",enum:["h1","h2","h3","h4","h5","caption","body"],default:"body"}}},events:[]},{id:"Image",name:"Image",category:"media",emoji:"🖼️",description:"A picture: a chart rendered elsewhere, a logo, a photo.",version:"0.9.0",standard:!0,properties:{type:"object",required:["url"],properties:{url:{type:"string",title:"Address",description:"Where the picture is."},description:{type:"string",title:"Description",description:"What it shows, for those who cannot see it."},fit:{type:"string",title:"Fit",description:"How it is resized to its place.",enum:["contain","cover","fill","none","scaleDown"],default:"fill"},variant:{type:"string",title:"Size",description:"An icon, an avatar, a feature or a header.",enum:["icon","avatar","smallFeature","mediumFeature","largeFeature","header"],default:"mediumFeature"}}},events:[]},{id:"Icon",name:"Icon",category:"media",emoji:"🔣",description:"A small drawing that says what something is: a check, a warning, a link.",version:"0.9.0",standard:!0,properties:{type:"object",required:["name"],properties:{name:{type:"string",title:"Icon",description:"Which drawing, by its name.",enum:["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"]}}},events:[]},{id:"Video",name:"Video",category:"media",emoji:"🎬",description:"A film played in place.",version:"0.9.0",standard:!0,properties:{type:"object",required:["url"],properties:{url:{type:"string",title:"Address",description:"Where the film is."}}},events:[]},{id:"AudioPlayer",name:"Audio",category:"media",emoji:"🔊",description:"A sound played in place: a recording, a summary read aloud.",version:"0.9.0",standard:!0,properties:{type:"object",required:["url"],properties:{url:{type:"string",title:"Address",description:"Where the sound is."},description:{type:"string",title:"Description",description:"What it is: a title or a summary."}}},events:[]},{id:"Row",name:"Row",category:"layout",emoji:"➡️",description:"Children side by side, left to right.",version:"0.9.0",standard:!0,properties:{type:"object",required:["children"],properties:{children:{type:"array",title:"Blocks",description:"The blocks inside it, by id, left to right.",items:{type:"string"}},justify:{type:"string",title:"Spacing",description:"How the blocks share the width.",enum:["center","end","spaceAround","spaceBetween","spaceEvenly","start","stretch"],default:"start"},align:{type:"string",title:"Alignment",description:"How the blocks line up top to bottom.",enum:["start","center","end","stretch"],default:"stretch"}}},events:[]},{id:"Column",name:"Column",category:"layout",emoji:"⬇️",description:"Children one under the other.",version:"0.9.0",standard:!0,properties:{type:"object",required:["children"],properties:{children:{type:"array",title:"Blocks",description:"The blocks inside it, by id, top to bottom.",items:{type:"string"}},justify:{type:"string",title:"Spacing",description:"How the blocks share the height.",enum:["start","center","end","spaceBetween","spaceAround","spaceEvenly","stretch"],default:"start"},align:{type:"string",title:"Alignment",description:"How the blocks line up left to right.",enum:["center","end","start","stretch"],default:"stretch"}}},events:[]},{id:"List",name:"List",category:"layout",emoji:"📃",description:"Items one after the other, each drawn by the same children: results, alternatives, steps.",version:"0.9.0",standard:!0,properties:{type:"object",required:["children"],properties:{children:{type:"array",title:"Blocks",description:"The blocks inside it, by id, or the template repeated over a list.",items:{type:"string"}},direction:{type:"string",title:"Direction",description:"One under the other, or side by side.",enum:["vertical","horizontal"],default:"vertical"},align:{type:"string",title:"Alignment",description:"How the items line up across.",enum:["start","center","end","stretch"],default:"stretch"}}},events:[]},{id:"Card",name:"Card",category:"layout",emoji:"🗂️",description:"A framed group: what belongs together, set apart.",version:"0.9.0",standard:!0,properties:{type:"object",required:["child"],properties:{child:{type:"string",title:"Block",description:"The one block inside it, by id; a Row or Column for several."}}},events:[]},{id:"Tabs",name:"Tabs",category:"layout",emoji:"📑",description:"Several views of one place, one shown at a time.",version:"0.9.0",standard:!0,properties:{type:"object",required:["tabs"],properties:{tabs:{type:"array",title:"Tabs",description:"Each tab's title and the block it shows, by id.",minItems:1,items:{type:"object",required:["title","child"],properties:{title:{type:"string"},child:{type:"string"}}}}}},events:[]},{id:"Divider",name:"Divider",category:"layout",emoji:"➖",description:"A line between what comes before and after.",version:"0.9.0",standard:!0,properties:{type:"object",properties:{axis:{type:"string",title:"Direction",description:"Across or up and down.",enum:["horizontal","vertical"],default:"horizontal"}}},events:[]},{id:"Modal",name:"Modal",category:"layout",emoji:"🪟",description:"A window over the page, opened by a trigger: details, a confirmation.",version:"0.9.0",standard:!0,properties:{type:"object",required:["trigger","content"],properties:{trigger:{type:"string",title:"Opened by",description:"The block that opens it, by id: a button."},content:{type:"string",title:"Shows",description:"The block shown inside it, by id."}}},events:[]},{id:"Button",name:"Button",category:"action",emoji:"🔘",description:"An action the person takes: send, run, approve. One filled button per screen.",version:"0.9.0",standard:!0,properties:{type:"object",required:["child","action"],properties:{child:{type:"string",title:"Label",description:"The block on it, by id: a Text for its words."},variant:{type:"string",title:"Style",description:"Primary for the one main action, borderless for a link.",enum:["default","primary","borderless"],default:"default"},action:{type:"object",title:"Does",description:"What pressing it sends, by name, with what it reads."}}},events:[]},{id:"TextField",name:"Input",category:"input",emoji:"⌨️",description:"A field the person types in: a word, a sentence, a number, a date.",version:"0.9.0",standard:!0,properties:{type:"object",required:["label"],properties:{label:{type:"string",title:"Label",description:"What the person reads beside it."},value:{type:"string",title:"Value",description:"What is typed in it."},variant:{type:"string",title:"Kind",description:"A short or long text, a number, or hidden as typed.",enum:["longText","number","shortText","obscured"],default:"shortText"},validationRegexp:{type:"string",title:"Pattern",description:"A regular expression what is typed must match."}}},events:[]},{id:"CheckBox",name:"Checkbox",category:"input",emoji:"☑️",description:"Yes or no: an option on or off, a consent given.",version:"0.9.0",standard:!0,properties:{type:"object",required:["label","value"],properties:{label:{type:"string",title:"Label",description:"What the person reads beside it."},value:{type:"boolean",title:"Value",description:"Whether it is ticked."}}},events:[]},{id:"ChoicePicker",name:"Select",category:"input",emoji:"🔽",description:"One choice, or several, among options the builder lists or the data gives.",version:"0.9.0",standard:!0,properties:{type:"object",required:["options","value"],properties:{label:{type:"string",title:"Label",description:"What the person reads above the options."},variant:{type:"string",title:"Choice",description:"One of the options, or several.",enum:["multipleSelection","mutuallyExclusive"],default:"mutuallyExclusive"},options:{type:"array",title:"Options",description:"What may be chosen: the words read and the value sent.",items:{type:"object",required:["label","value"],properties:{label:{type:"string"},value:{type:"string"}}}},value:{type:"array",title:"Value",description:"The values chosen.",items:{type:"string"}},displayStyle:{type:"string",title:"Shown as",description:"Checkboxes or chips.",enum:["checkbox","chips"],default:"checkbox"},filterable:{type:"boolean",title:"Searchable",description:"A search field above the options.",default:!1}}},events:[]},{id:"Slider",name:"Slider",category:"input",emoji:"🎚️",description:"A number chosen along a range: a weight, a budget, a threshold.",version:"0.9.0",standard:!0,properties:{type:"object",required:["value","max"],properties:{label:{type:"string",title:"Label",description:"What the person reads beside it."},min:{type:"number",title:"Least",description:"The smallest value.",default:0},max:{type:"number",title:"Most",description:"The largest value."},value:{type:"number",title:"Value",description:"The value chosen."}}},events:[]},{id:"DateTimeInput",name:"Date and time",category:"input",emoji:"📅",description:"A date, a time, or both, chosen from a calendar.",version:"0.9.0",standard:!0,properties:{type:"object",required:["value"],properties:{value:{type:"string",title:"Value",description:"The date or time chosen, in ISO 8601."},enableDate:{type:"boolean",title:"Date",description:"A date may be chosen.",default:!1},enableTime:{type:"boolean",title:"Time",description:"A time may be chosen.",default:!1},min:{type:"string",title:"Earliest",description:"The earliest that may be chosen, in ISO 8601."},max:{type:"string",title:"Latest",description:"The latest that may be chosen, in ISO 8601."},label:{type:"string",title:"Label",description:"What the person reads beside it."}}},events:[]},{id:"Table",name:"Table",category:"data",emoji:"📋",description:"Rows the application found or keeps, with the columns the builder chooses.",version:"1.0.0",standard:!1,properties:{type:"object",required:["columns"],properties:{title:{type:"string",title:"Title",description:"What the table is, above it."},columns:{type:"array",title:"Columns",description:"The columns, in order.",minItems:1,items:{type:"string"}},page_size:{type:"integer",title:"Rows per page",description:"How many rows show at once.",minimum:1,maximum:500,default:20},selectable:{type:"boolean",title:"Selectable",description:"A row may be chosen, and its choice sent.",default:!1}}},bindings:{shows:["rows"],sends:["selected"]},events:["select"],example:{title:"Runs",columns:["model","pass rate","cost"]}},{id:"Chart",name:"Chart",category:"data",emoji:"📊",description:"Numbers drawn: a bar, a line, a scatter of what the application measured.",version:"1.0.0",standard:!1,properties:{type:"object",required:["kind","x","y"],properties:{title:{type:"string",title:"Title",description:"What the chart shows, above it."},kind:{type:"string",title:"Kind",description:"How the numbers are drawn.",enum:["bar","line","scatter","area"],default:"bar"},x:{type:"string",title:"Across",description:"The field along the bottom."},y:{type:"string",title:"Up",description:"The field measured."},series:{type:"string",title:"Series",description:"A field whose values are drawn apart."}}},bindings:{shows:["points"],sends:[]},events:[],example:{kind:"bar",x:"model",y:"pass rate"}},{id:"FileUpload",name:"File upload",category:"input",emoji:"📎",description:"A file the person gives the application: a document to read, a sheet to check.",version:"1.0.0",standard:!1,properties:{type:"object",required:["label"],properties:{label:{type:"string",title:"Label",description:"What the person reads beside it."},accept:{type:"array",title:"Accepts",description:"The kinds of file it takes, by extension.",items:{type:"string",pattern:"^\\.[a-z0-9]+$"}},multiple:{type:"boolean",title:"Several",description:"More than one file at once.",default:!1},max_mb:{type:"integer",title:"Largest (MB)",description:"The largest file it takes.",minimum:1,maximum:500,default:25}}},bindings:{shows:[],sends:["files"]},events:["upload"],example:{label:"The contract",accept:[".pdf",".docx"]}},{id:"Chat",name:"Chat",category:"conversation",emoji:"💬",description:"The conversation with the application: its welcome, its starters, the composer.",version:"1.0.0",standard:!1,properties:{type:"object",properties:{welcome:{type:"string",title:"Welcome",description:"What it says before anyone writes."},placeholder:{type:"string",title:"Composer hint",description:"Shown in the composer while it is empty.",default:"Ask anything"},starters:{type:"array",title:"Starters",description:"Questions offered before the first message.",maxItems:6,items:{type:"string"}},show_tools:{type:"boolean",title:"Shows its tools",description:"The tool calls are shown as they happen.",default:!0}}},bindings:{shows:["messages"],sends:["message"]},events:["send"],example:{welcome:"Ask me to research anything.",starters:["What changed in Python 3.13?"]}},{id:"Evidence",name:"Evidence",category:"data",emoji:"🔎",description:"What an answer rests on: the sources opened, the passages cited, each with its link.",version:"1.0.0",standard:!1,properties:{type:"object",properties:{title:{type:"string",title:"Title",description:"Above the sources.",default:"Sources"},show_passages:{type:"boolean",title:"Shows passages",description:"Each source with the passage cited from it.",default:!0},max_items:{type:"integer",title:"Most shown",description:"How many sources show before *more*.",minimum:1,maximum:50,default:5}}},bindings:{shows:["sources"],sends:[]},events:["open"],example:{title:"What this rests on"}},{id:"Form",name:"Form",category:"input",emoji:"🧾",description:"Several fields asked at once, from a JSON Schema, checked as they are filled and again when they arrive (drawn with @datalayer/primer-rjsf).",version:"1.1.0",standard:!1,properties:{type:"object",required:["schema"],properties:{title:{type:"string",title:"Title",description:"What the form is for, above it."},schema:{type:"object",title:"Fields",description:"The JSON Schema of what is asked: its fields, their types, what is required."},ui:{type:"object",title:"How its fields are drawn",description:"By field name, the ui: options @datalayer/primer-rjsf reads (a uiSchema): ui:widget one of select, radio, range, updown, switch, checkbox, text, textarea, date, checkboxes, tags; each field's own widget when unsaid."},submit_label:{type:"string",title:"Send button",description:"The words on its button.",default:"Send"}}},bindings:{shows:["values"],sends:["values"]},events:["submit"],example:{title:"The quote",schema:{type:"object",required:["seats"],properties:{seats:{type:"integer",minimum:1,title:"Seats"}}}}},{id:"Download",name:"File to download",category:"data",emoji:"📄",description:"A file the application gives, to save: a report, a sheet, an export — by its link, or the file itself as a data: URL.",version:"1.0.0",standard:!1,properties:{type:"object",required:["name","url"],properties:{name:{type:"string",title:"File name",description:"What the file is saved as, with its extension.",minLength:1},url:{type:"string",title:"Link",description:"Where the file is: an http(s) link, or the file itself as a data: URL.",pattern:"^(https?://|data:)"},media_type:{type:"string",title:"Kind",description:"Its media type (text/csv, application/pdf…), said beside its name."},size:{type:"integer",title:"Size (bytes)",description:"How large it is, said beside its name.",minimum:0},description:{type:"string",title:"Description",description:"A line under its name."}}},bindings:{shows:[],sends:[]},events:["download"],example:{name:"totals.csv",url:"data:text/csv;base64,bW9udGgsdG90YWwKSmFuLDEyMDAK",media_type:"text/csv",size:21,description:"The month's totals."}}]},A2UI_VIEW_UI_0_0_1={id:"a2ui-view",version:"0.0.1",name:"Surface view",description:"The last result of the code, shown as a page you can use rather than as raw output.",emoji:"🖼",octicon:"browser",plugin:"@datalayer/loop-plugin-a2ui",folder:"a2ui",contributions:{slots:[],points:["loop.command","loop.viewType"],commands:["a2ui"]},contributionPoints:[],settings:{},renderers:["a2ui"],catalog:"",components:[]},AGENTSPECS_UI_0_0_1={id:"agentspecs",version:"0.0.1",name:"Agent picker",description:"Choose which agent answers in this conversation.",emoji:"🤖",octicon:"people",plugin:"@datalayer/loop-plugin-agentspecs",folder:"agentspecs",contributions:{slots:["loop.header"],points:["loop.command"],commands:["agents"]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},APP_ACTIVITY_UI_0_0_1={id:"app-activity",version:"0.0.1",name:"Activity",description:"What your application did, is doing, and is about to do, beside its page.",emoji:"🕘",octicon:"pulse",plugin:"@datalayer/loop-plugin-app-activity",folder:"app-activity",per:"application",contributions:{slots:["loop.sidebar"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},APP_COMPONENTS_UI_0_0_1={id:"app-components",version:"0.0.1",name:"Your own components",description:"The components your application's developer wrote, on its page and in its answers.",emoji:"🧩",octicon:"apps",plugin:"@datalayer/loop-plugin-app-components",folder:"app-components",per:"application",contributions:{slots:[],points:["loop.a2ui.component","loop.canvas.block"],commands:[]},contributionPoints:[],settings:{},renderers:["a2ui"],catalog:"",components:[]},APP_COMPUTER_UI_0_0_1={id:"app-computer",version:"0.0.1",name:"Computer",description:"The computer your application works on: what ran there, its files, and taking it over.",emoji:"🖥️",octicon:"device-desktop",plugin:"@datalayer/loop-plugin-app-computer",folder:"app-computer",per:"application",contributions:{slots:["loop.sidebar"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},APP_ELEMENTS_UI_0_0_1={id:"app-elements",version:"0.0.1",name:"Side panel and pages",description:"What your application opens beside the conversation: a side panel, a page of its own, a question for you.",emoji:"🗂️",octicon:"sidebar-expand",plugin:"@datalayer/loop-plugin-app-elements",folder:"app-elements",contributions:{slots:["root"],points:["reactor.ui.renderer"],commands:[]},contributionPoints:[],settings:{},renderers:["a2ui"],catalog:"",components:[]},APP_PAGE_UI_0_0_1={id:"app-page",version:"0.0.1",name:"Application page",description:"Your application's page, drawn beside its conversation.",emoji:"📈",octicon:"browser",plugin:"@datalayer/loop-plugin-app-page",folder:"app-page",per:"application",contributions:{slots:[],points:["loop.chat.surface"],commands:[]},contributionPoints:[],settings:{},renderers:["a2ui","mcp-apps"],catalog:"",components:[]},APP_RULES_UI_0_0_1={id:"app-rules",version:"0.0.1",name:"Rules and approvals",description:"When your application acts alone, when it asks you, and the approvals waiting for your yes.",emoji:"🛡️",octicon:"shield-check",plugin:"@datalayer/loop-plugin-app-rules",folder:"app-rules",per:"application",contributions:{slots:["loop.sidebar"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CANVAS_BLOCKS_UI_0_0_1={id:"canvas-blocks",version:"0.0.1",name:"Blocks",description:"The blocks you place on your application's page in the visual editor, one set for each part that draws them.",emoji:"🧱",octicon:"apps",plugin:"@datalayer/loop-plugin-ui",folder:"canvas-blocks",per:"ui",contributions:{slots:[],points:["loop.canvas.block"],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CANVAS_PARTS_UI_0_0_1={id:"canvas-parts",version:"0.0.1",name:"Parts",description:"What you drop on your agent in the visual editor: connections, skills, models, rules, tests and events.",emoji:"🧰",octicon:"package",plugin:"@datalayer/loop-plugin-parts",folder:"canvas-parts",per:"source",contributions:{slots:[],points:["loop.canvas.part"],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CHAT_EXTRAS_UI_0_0_1={id:"chat-extras",version:"0.0.1",name:"Banner and status",description:"A live banner over the conversation and a status line under it, set by the page around it.",emoji:"📣",octicon:"megaphone",plugin:"@datalayer/loop-plugin-chat-extras",folder:"chat-extras",contributions:{slots:[],points:["loop.chat.extras"],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CHAT_HEADER_UI_0_0_1={id:"chat-header",version:"0.0.1",name:"Chat title bar",description:"The conversation's title bar: who answers, what it runs on, and its actions.",emoji:"🏷️",octicon:"rows",plugin:"@datalayer/loop-plugin-chat-header",folder:"chat-header",contributions:{slots:[],points:["loop.chat.header"],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CHAT_VIEW_UI_0_0_1={id:"chat-view",version:"0.0.1",name:"Chat button",description:"Back to the conversation alone, from under the composer.",emoji:"💬",octicon:"comment-discussion",plugin:"@datalayer/loop-plugin-chat-view",folder:"chat-view",contributions:{slots:["loop.promptAction"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CHAT_UI_0_0_1={id:"chat",version:"0.0.1",name:"Chat",description:"The conversation: what you ask, what it answers, and the work it opens beside it.",emoji:"💬",octicon:"comment-discussion",plugin:"@datalayer/loop-plugin-chat",folder:"chat",contributions:{slots:[],points:["loop.chat.turn","loop.command","loop.document.toolbar.item","loop.notebook.toolbar.item","loop.viewType"],commands:["chat"]},contributionPoints:["loop.agent.available","loop.chat.composer","loop.chat.extras","loop.chat.header","loop.chat.suggestion","loop.chat.turn","loop.frontendTool"],settings:{type:"object",properties:{placeholder:{type:"string",title:"Composer hint",description:"Shown in the composer while it is empty; the agent's own when unsaid.",default:""},defaultSurface:{type:"string",title:"Opens beside it",description:"What opens beside the conversation: notebook, document, a page, or none.",default:"notebook"},showSurfaceSelector:{type:"boolean",title:"Offers the switcher",description:"The strip that switches what is open beside the conversation.",default:!0},hideHeader:{type:"boolean",title:"Hides its title bar",description:"The conversation without its own title bar.",default:!1},headerButtons:{type:"object",title:"Title bar buttons",description:"Whether the title bar offers a new chat and clearing this one.",properties:{newChat:{type:"boolean",title:"New chat",description:"Start another conversation."},clear:{type:"boolean",title:"Clear",description:"Clear this conversation."}},default:{newChat:!1,clear:!1}},hidePrompt:{type:"boolean",title:"Hides the composer",description:"The conversation read without being written to.",default:!1},promptPlacement:{type:"string",title:"Composer place",description:"Where the composer sits.",enum:["top","bottom","bottom-chat","floating"],default:"bottom"},autoFocusPrompt:{type:"boolean",title:"Composer takes the caret",description:"The composer is ready to type in when the page opens.",default:!0},suggestionLabels:{type:"boolean",title:"Openers by the composer",description:"The openers shown as labels by the composer, not only in its menu.",default:!0},fullScreenTopOffset:{type:["number","string"],title:"Room kept at the top",description:"What full screen leaves at the top for the page's own header.",default:0}}},renderers:[],catalog:"",components:[]},COMMANDS_UI_0_0_1={id:"commands",version:"0.0.1",name:"Command palette",description:"Every command at hand, with Ctrl-K.",emoji:"⌘",octicon:"command-palette",plugin:"@datalayer/loop-plugin-commands",folder:"commands",contributions:{slots:["loop.status"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},DOCUMENT_TOOLBAR_UI_0_0_1={id:"document-toolbar",version:"0.0.1",name:"Document toolbar",description:"Shows what the document's code blocks run on.",emoji:"🔵",octicon:"circle",plugin:"@datalayer/loop-plugin-document-toolbar",folder:"document-toolbar",contributions:{slots:[],points:["loop.document.toolbar"],commands:[]},contributionPoints:["loop.document.toolbar.item"],settings:{},renderers:[],catalog:"",components:[]},DOCUMENT_VIEW_UI_0_0_1={id:"document-view",version:"0.0.1",name:"Document button",description:"The document beside the conversation, from under the composer.",emoji:"📄",octicon:"file",plugin:"@datalayer/loop-plugin-document-view",folder:"document-view",contributions:{slots:["loop.promptAction"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},DOCUMENT_UI_0_0_1={id:"document",version:"0.0.1",name:"Document",description:"A document beside the conversation, written with the agent.",emoji:"📄",octicon:"file",plugin:"@datalayer/loop-plugin-document",folder:"document",contributions:{slots:[],points:["loop.chat.surface","loop.command"],commands:["document"]},contributionPoints:["loop.document.opening","loop.document.toolbar"],settings:{},renderers:[],catalog:"",components:[]},INPUT_PROMPT_UI_0_0_1={id:"input-prompt",version:"0.0.1",name:"Composer",description:"Where you write to the agent, under or over the conversation.",emoji:"✏️",octicon:"pencil",plugin:"@datalayer/loop-plugin-input-prompt",folder:"input-prompt",contributions:{slots:[],points:["loop.chat.composer"],commands:[]},contributionPoints:["loop.prompt.panel"],settings:{},renderers:[],catalog:"",components:[]},MODELS_UI_0_0_1={id:"models",version:"0.0.1",name:"Models",description:"Which model answers, and the models you may choose from.",emoji:"🧠",octicon:"cpu",plugin:"@datalayer/loop-plugin-models",folder:"models",contributions:{slots:[],points:["loop.command"],commands:["models"]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},NOTEBOOK_TOOLBAR_UI_0_0_1={id:"notebook-toolbar",version:"0.0.1",name:"Notebook toolbar",description:"Shows what the notebook is running on.",emoji:"🟢",octicon:"circle",plugin:"@datalayer/loop-plugin-notebook-toolbar",folder:"notebook-toolbar",contributions:{slots:[],points:["loop.notebook.toolbar"],commands:[]},contributionPoints:["loop.notebook.toolbar.item"],settings:{},renderers:[],catalog:"",components:[]},NOTEBOOK_VIEW_UI_0_0_1={id:"notebook-view",version:"0.0.1",name:"Notebook button",description:"The notebook beside the conversation, from under the composer.",emoji:"📓",octicon:"rows",plugin:"@datalayer/loop-plugin-notebook-view",folder:"notebook-view",contributions:{slots:["loop.promptAction"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},NOTEBOOK_UI_0_0_1={id:"notebook",version:"0.0.1",name:"Notebook",description:"A notebook beside the conversation, its code run as you go.",emoji:"📓",octicon:"rows",plugin:"@datalayer/loop-plugin-notebook",folder:"notebook",contributions:{slots:[],points:["loop.chat.surface","loop.command"],commands:["notebook"]},contributionPoints:["loop.notebook.opening","loop.notebook.toolbar"],settings:{},renderers:[],catalog:"",components:[]},PAGE_LAYOUT_UI_0_0_1={id:"page-layout",version:"0.0.1",name:"Page layout",description:"The work on a centred sheet like a document, the composer above it and the conversation in a panel beside it; or the conversation and the work side by side.",emoji:"📄",octicon:"file",plugin:"@datalayer/loop-plugin-page-layout",folder:"page-layout",contributions:{slots:["loop.header"],points:["loop.chat.layout","loop.prompt.panel"],commands:[]},contributionPoints:[],settings:{type:"object",properties:{arrangement:{type:"string",title:"Arrangement",description:"The work on a sheet with the conversation in a panel, or both side by side.",enum:["page","split"],default:"page"},turnPanel:{type:"string",title:"Current turn",description:"Where the current turn hangs on the composer.",enum:["below","above","none"],default:"below"},turnPanelFooter:{type:"string",title:"Under the reply",description:"What is drawn under the reply: everything, its actions, or nothing.",enum:["full","actions","none"],default:"full"},prompt:{type:"string",title:"Composer",description:"Docked above the sheet, or floating over it.",enum:["docked","floating"],default:"docked"},promptAnchor:{type:"string",title:"Floating composer starts",description:"The edge a floating composer starts at.",enum:["top","bottom"],default:"top"},pageSize:{type:"object",title:"Sheet",description:"The sheet: free at its reading width when unsaid, or a paper (letter, a4) whose width it takes, with a width or a height of its own over either.",properties:{format:{type:"string",title:"Paper",description:"The paper the sheet is.",enum:["free","letter","a4"]},width:{type:"number",title:"Width",description:"The sheet's width in pixels; over a paper, it replaces the paper's."},height:{type:"number",title:"Height",description:"The sheet's least height in pixels; what is past it grows the sheet."}}}}},renderers:[],catalog:"",components:[]},PAP_SIGN_IN_UI_0_0_1={id:"pap-sign-in",version:"0.0.1",name:"Sign in at a company",description:"Where your agent asks you to sign in at a company: its page, the code, and until when.",emoji:"🔑",octicon:"sign-in",plugin:"@datalayer/loop-plugin-pap-sign-in",folder:"pap-sign-in",contributions:{slots:["loop.chatHeader"],points:["reactor.ui.renderer","reactor.ui.toolBinding"],commands:[]},contributionPoints:[],settings:{},renderers:["mcp-ui"],catalog:"",components:[]},PROMPT_UI_0_0_1={id:"prompt",version:"0.0.1",name:"Floating composer",description:"The composer in a card you move over the page, and the commands that bring it back or start over.",emoji:"🪶",octicon:"paper-airplane",plugin:"@datalayer/loop-plugin-prompt",folder:"prompt",contributions:{slots:["loop.promptAction"],points:["loop.command"],commands:["new","prompt"]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},SUBAGENT_ACTIVITY_UI_0_0_1={id:"subagent-activity",version:"0.0.1",name:"Delegated work",description:"The face of an agent yours handed work to, pulsing while it works.",emoji:"👥",octicon:"people",plugin:"@datalayer/loop-plugin-subagent-activity",folder:"subagent-activity",contributions:{slots:["loop.inpromptMenu"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},WINDOW_FRAME_UI_0_0_1={id:"window-frame",version:"0.0.1",name:"Window",description:"Draws the editor as a window, with room in its title bar for controls and actions.",emoji:"🪟",octicon:"browser",plugin:"@datalayer/loop-plugin-window-frame",folder:"window-frame",contributions:{slots:["loop.header","loop.window.controls"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},UI_CATALOGUE={"a2ui-surface":A2UI_SURFACE_UI_0_0_1,"a2ui-view":A2UI_VIEW_UI_0_0_1,agentspecs:AGENTSPECS_UI_0_0_1,"app-activity":APP_ACTIVITY_UI_0_0_1,"app-components":APP_COMPONENTS_UI_0_0_1,"app-computer":APP_COMPUTER_UI_0_0_1,"app-elements":APP_ELEMENTS_UI_0_0_1,"app-page":APP_PAGE_UI_0_0_1,"app-rules":APP_RULES_UI_0_0_1,"canvas-blocks":CANVAS_BLOCKS_UI_0_0_1,"canvas-parts":CANVAS_PARTS_UI_0_0_1,"chat-extras":CHAT_EXTRAS_UI_0_0_1,"chat-header":CHAT_HEADER_UI_0_0_1,"chat-view":CHAT_VIEW_UI_0_0_1,chat:CHAT_UI_0_0_1,commands:COMMANDS_UI_0_0_1,"document-toolbar":DOCUMENT_TOOLBAR_UI_0_0_1,"document-view":DOCUMENT_VIEW_UI_0_0_1,document:DOCUMENT_UI_0_0_1,"input-prompt":INPUT_PROMPT_UI_0_0_1,models:MODELS_UI_0_0_1,"notebook-toolbar":NOTEBOOK_TOOLBAR_UI_0_0_1,"notebook-view":NOTEBOOK_VIEW_UI_0_0_1,notebook:NOTEBOOK_UI_0_0_1,"page-layout":PAGE_LAYOUT_UI_0_0_1,"pap-sign-in":PAP_SIGN_IN_UI_0_0_1,prompt:PROMPT_UI_0_0_1,"subagent-activity":SUBAGENT_ACTIVITY_UI_0_0_1,"window-frame":WINDOW_FRAME_UI_0_0_1};function listUI(){return Object.values(UI_CATALOGUE)}const COMPONENT_CATALOGUE=Object.fromEntries(Object.values(UI_CATALOGUE).flatMap(Au=>Au.components.map(lo=>[lo.id,lo]))),A2UI_UI_RENDERER_0_0_1={id:"a2ui",version:"0.0.1",name:"A2UI",description:"An agent describes an interface — a form, a table, a card — as a tree of components from a catalogue the host allows, and the host renders it; what the user does in it comes back to the agent as an action.",docsUrl:"https://a2ui.org/",enabled:!0},MCP_APPS_UI_RENDERER_0_0_1={id:"mcp-apps",version:"0.0.1",name:"MCP Apps",description:"An MCP server ships an interactive app with a tool: the host renders it in a sandboxed frame beside the conversation, and the app calls the server's tools through the host.",docsUrl:"https://modelcontextprotocol.io/docs/extensions/apps",enabled:!1},MCP_UI_UI_RENDERER_0_0_1={id:"mcp-ui",version:"0.0.1",name:"MCP UI",description:"An MCP tool answers with a UI resource — HTML, a remote page or a component — that the host renders in place of plain text.",docsUrl:"https://mcpui.dev/",enabled:!1},UI_RENDERER_CATALOGUE={a2ui:A2UI_UI_RENDERER_0_0_1,"mcp-apps":MCP_APPS_UI_RENDERER_0_0_1,"mcp-ui":MCP_UI_UI_RENDERER_0_0_1},DEFAULT_UPLOAD_MB=10,DEFAULT_MAX_FILES=5;function kindTakes(Au,lo){const $u=Au.trim().toLowerCase();if($u.startsWith("."))return lo.name.toLowerCase().endsWith($u);const Ru=(lo.type||"").split(";",1)[0].trim().toLowerCase();return $u.endsWith("/*")?Ru.startsWith($u.slice(0,-1)):Ru===$u}const acceptsFile=(Au,lo)=>!Au?.length||Au.some($u=>kindTakes($u,lo)),megabytes=Au=>`${(Au/(1024*1024)).toFixed(1)} MB`,uploadsAccept=Au=>Au.kinds.map(lo=>lo.type).join(",");function uploadsRefusal(Au,lo){if(lo.length===0)return null;const $u=Au.interface.uploads;if(!$u)return`${Au.name} takes no file sent with a message: its Appspec names none it takes (interface.uploads).`;if(lo.length>$u.maxFiles)return`${lo.length} files were sent at once: ${Au.name} takes at most ${$u.maxFiles}.`;for(const Ru of lo){const Iu=$u.kinds.find(Pu=>kindTakes(Pu.type,Ru));if(!Iu){const Pu=$u.kinds.map(Ou=>Ou.type).join(", ");return`${Ru.name} is not a kind of file ${Au.name} takes: it takes ${Pu}.`}if(Ru.size>Iu.maxMb*1024*1024)return`${Ru.name} is ${megabytes(Ru.size)}: ${Au.name} takes ${Iu.type} of at most ${Iu.maxMb} MB.`}return null}function uploadsInWords(Au){return`Takes ${Au.kinds.map($u=>`${$u.type} up to ${$u.maxMb} MB`).join(", ")}; ${Au.maxFiles} at most at once.`}const APP_SCHEMA="loop.app/v1",DEFAULT_LANGUAGE="en",DEFAULT_EMOJI="👀",APP_KINDS=["chat","widget","decision","worker"],APP_ACCENTS=["green","rose","sky","lime","sun","violet"],APP_THEME_VARIANTS=["datalayer","spatial","lovely","matrix","earth","sand","ivory","sun","loop"],APP_THEME_MODES=["light","dark","auto"],APP_EMBED_MODES=["inline","bubble","panel","assistant"],APP_ASSISTANT_AVATAR_ID=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function isAvatarId(Au){return typeof Au=="string"&&Au.length<=64&&APP_ASSISTANT_AVATAR_ID.test(Au)}const AVATAR_MODEL_URL=/^https:\/\/\S+\.(?:glb|gltf)(?:[?#]\S*)?$/;function isAvatarModel3D(Au){if(typeof Au!="object"||Au===null||Array.isArray(Au))return!1;const{kind:lo,url:$u,...Ru}=Au;return lo==="model3d"&&Object.keys(Ru).length===0&&($u===void 0||$u===""||typeof $u=="string"&&AVATAR_MODEL_URL.test($u))}const ACTION_CLASS_NAMES=["read","write","send","buy","delete","publish"],DEFAULT_LAYOUTS={chat:"chat",widget:"page",decision:"page",worker:"split"},A2UI_OUTPUT="application/json+a2ui";function uiFor(Au,lo={}){if(Au==="decision")return[{plugin:"app-page"}];const $u=[{plugin:"chat"}];return lo.outputs?.includes(A2UI_OUTPUT)&&$u.push({plugin:"a2ui-surface",renderer:"a2ui"}),lo.signsIn&&$u.push({plugin:"pap-sign-in"}),(lo.layout??DEFAULT_LAYOUTS[Au])!=="chat"&&$u.push({plugin:"page-layout"},{plugin:"app-page"},{plugin:"canvas-blocks"}),lo.ownComponents&&$u.push({plugin:"app-components"}),$u}const DEFAULT_RECORD_INCLUDE=["conversations","actions","approvals"],DEFAULT_KEEP_FOR="1_years",DEFAULT_READY_AT=.8,DEFAULT_PROTOCOL="a2ui/v0.9",DEFAULT_ICON="apps",DEFAULT_VERSION="0.0.1",NO_HOST_PARAMETERS={type:"object",properties:{}},isData=Au=>!!Au&&typeof Au=="object"&&!Array.isArray(Au),text$k=(Au,lo="")=>typeof Au=="string"?Au:lo,flag=(Au,lo)=>typeof Au=="boolean"?Au:lo,numberOf=(Au,lo)=>typeof Au=="number"&&Number.isFinite(Au)?Au:lo,texts=Au=>Array.isArray(Au)?Au.filter(lo=>typeof lo=="string"):[],records$1=Au=>Array.isArray(Au)?Au.filter(isData):[],uiChoices=Au=>Array.isArray(Au)?Au.filter(isData).map(lo=>({plugin:text$k(lo.plugin),...text$k(lo.renderer)?{renderer:text$k(lo.renderer)}:{}})):[],uiShapeProblems=Au=>Array.isArray(Au)?Au.filter(lo=>!isData(lo)).map(lo=>`\`ui\` lists UI plugins, each as \`{plugin, renderer}\`: ${JSON.stringify(lo)} is not one`+(typeof lo=="string"&&UI_RENDERER_CATALOGUE[lo]?` (${JSON.stringify(lo)} is a UI renderer: name the plugin it renders, and say it as its \`renderer\`).`:".")):[];function parseTestTurn(Au){return{...text$k(Au.say)?{say:text$k(Au.say)}:{},...text$k(Au.choose)?{choose:text$k(Au.choose)}:{},...text$k(Au.press)?{press:text$k(Au.press)}:{},...isData(Au.payload)&&Object.keys(Au.payload).length?{payload:{...Au.payload}}:{}}}const oneOf$3=(Au,lo,$u)=>lo.includes(Au)?Au:$u,RETENTION$1=/^([1-9]\d*)_(day|days|month|months|year|years)$/,DAYS={day:1,month:30,year:365};function retentionDays(Au){const lo=RETENTION$1.exec(Au.trim());return lo?Number(lo[1])*DAYS[lo[2].replace(/s$/,"")]:0}function emptyAppspec(Au="chat"){return{schema:APP_SCHEMA,id:"",version:DEFAULT_VERSION,name:"",kind:Au,description:"",owner:"",agent:"",team:"",instructions:"",model:"",skills:[],backendTools:[],context:[],contents:[],connections:[],protocols:[],ui:uiFor(Au),rules:[],permissions:{spaces:[],computer:{browse:!1,files:!1,shell:!1}},interface:{layout:DEFAULT_LAYOUTS[Au],welcome:"",starters:[],commands:[],modes:[],actions:[],profiles:[],language:DEFAULT_LANGUAGE,translations:{},components:[],outputs:[]},tests:{readyAt:DEFAULT_READY_AT,evalset:"",cases:[],verified:{live:[],recorded:[],unverified:[]}},record:{keepFor:DEFAULT_KEEP_FOR,retentionDays:retentionDays(DEFAULT_KEEP_FOR),include:[...DEFAULT_RECORD_INCLUDE],suggestTests:!1},checks:{guards:[],gates:[],track:""},deployment:{},goal:"",triggers:[],memory:"",notifications:[],samples:{documents:[],alternatives:[]},setup:[],enabled:!0,unavailable_because:"",tags:[],icon:DEFAULT_ICON,emoji:DEFAULT_EMOJI,avatar:"",banner:""}}const KNOWN_KEYS=["schema","id","version","name","kind","description","owner","agent","team","instructions","model","skills","backend_tools","tools","context","contents","connections","protocols","ui","pap","pact","commerce","signed_fetch","pair","a2a","rules","permissions","interface","tests","record","checks","deployment","goal","triggers","memory","notifications","decision","samples","enabled","unavailable_because","tags","icon","emoji","avatar","banner"],CHECK_STAGES=["answer","tool_call"];function parseTool(Au){return{name:text$k(Au.name),description:text$k(Au.description),parameters:isData(Au.parameters)?Au.parameters:{...NO_HOST_PARAMETERS},does:texts(Au.does)}}function parseConnection(Au){return{server:text$k(Au.server),access:oneOf$3(Au.access,["read","write"],"read"),as:oneOf$3(Au.as,["owner","user"],"owner"),only:texts(Au.only)}}const PAP_PROFILES=["draft-01"],PAP_PROFILE=PAP_PROFILES[PAP_PROFILES.length-1];function papProfileProblem(Au){if(Au==null||Au==="")return`Its \`pap\` block names no Personal Agent Protocol profile: add \`profile: ${PAP_PROFILE}\`.`;if(!PAP_PROFILES.includes(Au))return`This application asks for Personal Agent Protocol profile “${String(Au)}”; Datalayer speaks ${PAP_PROFILES.join(" or ")}.`}const PAP_INTERFACES=["agent","openapi","mcp","web"],PAP_SIGN_IN=["direct","device","mediated"],PAP_DEFAULT_INTERFACES=["agent"],PAP_DEFAULT_SIGN_IN=["direct","device"],enumsOf=(Au,lo,$u)=>Array.isArray(Au)?Au.filter(Ru=>lo.includes(Ru)):[...$u];function parsePap(Au){const lo=isData(Au.company)?Au.company:{};return{profile:Au.profile,connections:records$1(Au.connections).map($u=>({id:text$k($u.id),company:text$k($u.company),access:oneOf$3($u.access,["read","write"],"read"),as:oneOf$3($u.as,["owner","user"],"user"),scopes:texts($u.scopes),interfaces:enumsOf($u.interfaces,PAP_INTERFACES,PAP_DEFAULT_INTERFACES),signIn:enumsOf($u.sign_in,PAP_SIGN_IN,PAP_DEFAULT_SIGN_IN),extensions:texts($u.extensions)})),company:{enabled:flag(lo.enabled,!1),signedOut:flag(lo.signed_out,!0),interfaces:enumsOf(lo.interfaces,PAP_INTERFACES,PAP_DEFAULT_INTERFACES),scopes:texts(lo.scopes),extensions:texts(lo.extensions),personalAgents:oneOf$3(lo.personal_agents,["any","registered"],"any"),registeredAgents:texts(lo.registered_agents),operations:records$1(lo.operations).map($u=>({action:text$k($u.action),tool:text$k($u.tool),...isData($u.allows)?{allows:parsePapStanding($u.allows)}:{},summary:text$k($u.summary),userApprovalRequired:flag($u.user_approval_required,!0)}))}}}function parsePapStanding(Au){return{connection:text$k(Au.connection),action:oneOf$3(Au.action,["write","buy"],"buy"),limits:records$1(Au.limits).map(lo=>({path:text$k(lo.path),...typeof lo.maximum=="string"?{maximum:text$k(lo.maximum)}:{},...typeof lo.allowed=="string"?{allowed:text$k(lo.allowed)}:{}})),uses:text$k(Au.uses),days:text$k(Au.days)}}function dumpPapStanding(Au){return{connection:Au.connection,action:Au.action,limits:Au.limits.map(lo=>({path:lo.path,...lo.maximum!==void 0?{maximum:lo.maximum}:{},...lo.allowed!==void 0?{allowed:lo.allowed}:{}})),uses:Au.uses,days:Au.days}}function dumpPap(Au){return Au?new Writer().text("profile",Au.profile,"\0").list("connections",Au.connections.map(lo=>new Writer().text("id",lo.id,"\0").text("company",lo.company,"\0").value("access",lo.access,"read").value("as",lo.as,"user").list("scopes",lo.scopes).list("interfaces",lo.interfaces,[...PAP_DEFAULT_INTERFACES]).list("sign_in",lo.signIn,[...PAP_DEFAULT_SIGN_IN]).list("extensions",lo.extensions).data)).part("company",new Writer().value("enabled",Au.company.enabled,!1).value("signed_out",Au.company.signedOut,!0).list("interfaces",Au.company.interfaces,[...PAP_DEFAULT_INTERFACES]).list("scopes",Au.company.scopes).list("extensions",Au.company.extensions).value("personal_agents",Au.company.personalAgents,"any").list("registered_agents",Au.company.registeredAgents).list("operations",Au.company.operations.map(lo=>new Writer().text("action",lo.action,"\0").text("tool",lo.tool,lo.allows?"":"\0").present("allows",lo.allows?dumpPapStanding(lo.allows):void 0).text("summary",lo.summary,"\0").value("user_approval_required",lo.userApprovalRequired,!0).data)).data).data:{}}function parsePact(Au){const lo=isData(Au.business)?Au.business:{},$u={};if(isData(lo.scopes))for(const[Ru,Iu]of Object.entries(lo.scopes))$u[Ru]=text$k(Iu);return{connections:records$1(Au.connections).map(Ru=>({id:text$k(Ru.id),brand:text$k(Ru.brand),audience:text$k(Ru.audience),access:oneOf$3(Ru.access,["read","write"],"read"),scopes:texts(Ru.scopes)})),business:{enabled:flag(lo.enabled,!1),brand:text$k(lo.brand),scopes:$u,registeredAgents:records$1(lo.registered_agents).map(Ru=>({issuer:text$k(Ru.issuer),jwksUri:text$k(Ru.jwks_uri)}))}}}function parseCommerce(Au){return{merchants:records$1(Au.merchants).map(lo=>({id:text$k(lo.id),protocol:oneOf$3(lo.protocol,["ucp","acp"],"ucp"),merchant:text$k(lo.merchant),access:oneOf$3(lo.access,["read","write"],"read"),...isData(lo.limit)?{limit:{amount:text$k(lo.limit.amount),currency:text$k(lo.limit.currency)}}:{}}))}}function dumpCommerce(Au){return Au?new Writer().list("merchants",Au.merchants.map(lo=>new Writer().text("id",lo.id,"\0").text("protocol",lo.protocol,"\0").text("merchant",lo.merchant,"\0").value("access",lo.access,"read").part("limit",lo.limit?{amount:lo.limit.amount,currency:lo.limit.currency}:{}).data)).data:{}}function parseSignedFetch(Au){return{sites:records$1(Au.sites).map(lo=>({id:text$k(lo.id),site:text$k(lo.site)}))}}function dumpSignedFetch(Au){return Au?new Writer().list("sites",Au.sites.map(lo=>new Writer().text("id",lo.id,"\0").text("site",lo.site,"\0").data)).data:{}}function parsePair(Au){const lo=text$k(Au.id),$u=text$k(Au.role);return/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(lo)?$u!=="business"&&$u!=="personal_agent"?`One of a pair is its business or its personal_agent, not ${JSON.stringify($u)}.`:{id:lo,role:$u}:`A pair's id is lower-case letters, digits and hyphens: ${JSON.stringify(lo)}.`}function dumpPact(Au){if(!Au)return{};const lo=Au.business??{enabled:!1,brand:"",scopes:{},registeredAgents:[]};return new Writer().list("connections",Au.connections.map($u=>new Writer().text("id",$u.id,"\0").text("brand",$u.brand,"\0").text("audience",$u.audience,"\0").value("access",$u.access,"read").list("scopes",$u.scopes).data)).part("business",new Writer().value("enabled",lo.enabled,!1).text("brand",lo.brand).part("scopes",{...lo.scopes}).list("registered_agents",lo.registeredAgents.map($u=>new Writer().text("issuer",$u.issuer,"\0").text("jwks_uri",$u.jwksUri,"\0").data)).data).data}function parseA2A(Au){return{extensions:records$1(Au.extensions).map(lo=>({uri:text$k(lo.uri),description:text$k(lo.description),required:flag(lo.required,!1),params:isData(lo.params)?{...lo.params}:{}}))}}function dumpA2A(Au){return Au?new Writer().list("extensions",Au.extensions.map(lo=>new Writer().text("uri",lo.uri,"\0").text("description",lo.description).value("required",lo.required,!1).part("params",lo.params).data)).data:{}}function parseRule$1(Au){return{action:text$k(Au.action),appliesTo:typeof Au.applies_to=="string"?[Au.applies_to]:texts(Au.applies_to),behaviour:oneOf$3(Au.behaviour,BEHAVIOURS,"ask_first")}}function parseAction(Au){const lo={name:text$k(Au.name)};return text$k(Au.description)&&(lo.description=text$k(Au.description)),isData(Au.payload)&&(lo.payload=JSON.parse(JSON.stringify(Au.payload))),lo}function parseCommand$1(Au){return{name:text$k(Au.name),description:text$k(Au.description),prompt:text$k(Au.prompt)}}function parseModeOption(Au){const lo={id:text$k(Au.id),label:text$k(Au.label)};for(const $u of["description","instructions","model"])typeof Au[$u]=="string"&&Au[$u]&&(lo[$u]=Au[$u]);return lo}function parseMode(Au){const lo={id:text$k(Au.id),label:text$k(Au.label),options:records$1(Au.options).map(parseModeOption)};return typeof Au.default=="string"&&Au.default&&(lo.default=Au.default),lo}function parseStarter(Au){const lo={label:text$k(Au.label),message:text$k(Au.message)};return typeof Au.category=="string"&&Au.category&&(lo.category=Au.category),lo}function parseProfile(Au){return{id:text$k(Au.id),label:text$k(Au.label),description:text$k(Au.description),instructions:text$k(Au.instructions),model:typeof Au.model=="string"&&Au.model?Au.model:null,starters:records$1(Au.starters).map(parseStarter)}}function wordsBy(Au){return Object.fromEntries(Object.entries(isData(Au)?Au:{}).filter(lo=>typeof lo[1]=="string"))}function recordsBy(Au){return Object.fromEntries(Object.entries(isData(Au)?Au:{}).filter(lo=>isData(lo[1])))}const mapValues=(Au,lo)=>Object.fromEntries(Object.entries(Au).map(([$u,Ru])=>[$u,lo(Ru)]));function parseTranslation(Au){return{name:text$k(Au.name),description:text$k(Au.description),welcome:text$k(Au.welcome),starters:mapValues(recordsBy(Au.starters),lo=>({label:text$k(lo.label),message:text$k(lo.message)})),categories:wordsBy(Au.categories),settings:mapValues(recordsBy(Au.settings),lo=>({title:text$k(lo.title),description:text$k(lo.description),options:wordsBy(lo.options)})),commands:wordsBy(Au.commands),modes:mapValues(recordsBy(Au.modes),lo=>({label:text$k(lo.label),options:mapValues(recordsBy(lo.options),$u=>({label:text$k($u.label),description:text$k($u.description)}))})),profiles:mapValues(recordsBy(Au.profiles),lo=>({label:text$k(lo.label),description:text$k(lo.description)}))}}function parseSurface(Au){return{protocol:text$k(Au.protocol,DEFAULT_PROTOCOL),components:records$1(Au.components).filter(lo=>typeof lo.id=="string"&&typeof lo.component=="string"),composedBy:text$k(Au.composed_by),composedAt:text$k(Au.composed_at)}}const DEFAULT_VOICE={enabled:!1,input:"push_to_talk",output:"on_request",where:"auto"};function parseVoice(Au){const lo=isData(Au)?Au:{};return{enabled:lo.enabled===!0,input:oneOf$3(lo.input,["off","push_to_talk","hands_free"],DEFAULT_VOICE.input),output:oneOf$3(lo.output,["off","on_request","always"],DEFAULT_VOICE.output),voice:text$k(lo.voice),language:text$k(lo.language),where:oneOf$3(lo.where,["auto","device","server"],DEFAULT_VOICE.where)}}function parseUploads(Au){return{kinds:records$1(Au.kinds).map(lo=>({type:text$k(lo.type),maxMb:numberOf(lo.max_mb,DEFAULT_UPLOAD_MB)})),maxFiles:numberOf(Au.max_files,DEFAULT_MAX_FILES)}}const PAGE_OUTPUT_SHOWS={Text:"text",Image:"url",Table:"rows",Chart:"points"},DEFAULT_CUSTOM_HEIGHT=240;function parseCustomComponent(Au){const lo={name:text$k(Au.name),description:text$k(Au.description),props:isData(Au.props)?JSON.parse(JSON.stringify(Au.props)):{type:"object",properties:{}},shows:texts(Au.shows),sends:texts(Au.sends),source:text$k(Au.source),integrity:text$k(Au.integrity),height:numberOf(Au.height,DEFAULT_CUSTOM_HEIGHT)};return isData(Au.example)&&(lo.example=JSON.parse(JSON.stringify(Au.example))),lo}function dumpCustomComponent(Au){const lo=new Writer().text("name",Au.name,"\0").text("description",Au.description,"\0");return lo.data.props=JSON.parse(JSON.stringify(Au.props)),lo.list("shows",Au.shows).list("sends",Au.sends).text("source",Au.source,"\0").text("integrity",Au.integrity).value("height",Au.height,DEFAULT_CUSTOM_HEIGHT),Au.example&&(lo.data.example=JSON.parse(JSON.stringify(Au.example))),lo.data}function pageOutputShows(Au,lo=[]){return Au in PAGE_OUTPUT_SHOWS?PAGE_OUTPUT_SHOWS[Au]:lo.find($u=>$u.name===Au)?.shows[0]}function parsePage(Au){const lo={function:text$k(Au.function),inputs:isData(Au.inputs)?JSON.parse(JSON.stringify(Au.inputs)):{},outputs:records$1(Au.outputs).map($u=>({name:text$k($u.name),title:text$k($u.title),component:text$k($u.component,"Text"),props:isData($u.props)?JSON.parse(JSON.stringify($u.props)):{}})),live:Au.live!==!1};return isData(Au.inputs_ui)&&(lo.inputsUi=JSON.parse(JSON.stringify(Au.inputs_ui))),lo}function dumpPage(Au){const lo=new Writer().text("function",Au.function,"\0");return lo.data.inputs=JSON.parse(JSON.stringify(Au.inputs)),Au.inputsUi&&(lo.data.inputs_ui={...Au.inputsUi}),lo.list("outputs",Au.outputs.map($u=>new Writer().text("name",$u.name,"\0").text("title",$u.title).text("component",$u.component,"Text").part("props",{...$u.props}).data)),lo.value("live",Au.live,!0).data}function parseInterface(Au,lo){const $u={layout:oneOf$3(Au.layout,["chat","page","split"],DEFAULT_LAYOUTS[lo]),accent:APP_ACCENTS.includes(Au.accent)?Au.accent:void 0,welcome:text$k(Au.welcome),starters:records$1(Au.starters).map(parseStarter),commands:records$1(Au.commands).map(parseCommand$1),modes:records$1(Au.modes).map(parseMode),actions:records$1(Au.actions).map(parseAction),profiles:records$1(Au.profiles).map(parseProfile),language:text$k(Au.language,DEFAULT_LANGUAGE),translations:mapValues(recordsBy(Au.translations),parseTranslation),components:texts(Au.components),voice:parseVoice(Au.voice),outputs:texts(Au.outputs)};return isData(Au.settings)&&($u.settings=JSON.parse(JSON.stringify(Au.settings))),isData(Au.settings_ui)&&($u.settingsUi=JSON.parse(JSON.stringify(Au.settings_ui))),isData(Au.uploads)&&($u.uploads=parseUploads(Au.uploads)),Array.isArray(Au.custom_components)&&($u.customComponents=records$1(Au.custom_components).map(parseCustomComponent)),isData(Au.surface)&&($u.surface=parseSurface(Au.surface)),isData(Au.page)&&($u.page=parsePage(Au.page)),isAvatarId(Au.avatar)?$u.avatar=Au.avatar:isAvatarModel3D(Au.avatar)&&($u.avatar=Au.avatar.url?{kind:"model3d",url:Au.avatar.url}:{kind:"model3d"}),(Au.balloon==="history"||Au.balloon==="current")&&($u.balloon=Au.balloon),isData(Au.theme)&&APP_THEME_VARIANTS.includes(Au.theme.variant)&&($u.theme={variant:Au.theme.variant},APP_THEME_MODES.includes(Au.theme.mode)&&($u.theme.mode=Au.theme.mode)),$u}function parseCriterion(Au){return{name:text$k(Au.name),kind:oneOf$3(Au.kind,["metric","noul","choice","score"],"metric"),weight:Math.max(0,numberOf(Au.weight,1)),instructions:text$k(Au.instructions),options:texts(Au.options),direction:Au.direction==="lower"?"lower":"higher",measure:oneOf$3(Au.measure,["","pass_rate","cost_per_task","seconds_per_task"],"")}}function parseDecision(Au){return{question:text$k(Au.question),alternatives:texts(Au.alternatives),criteria:records$1(Au.criteria).map(parseCriterion),minConfidence:Math.min(1,Math.max(0,numberOf(Au.min_confidence,0))),scenarios:records$1(Au.scenarios).map(lo=>({name:text$k(lo.name),weights:Object.fromEntries(Object.entries(isData(lo.weights)?lo.weights:{}).filter($u=>typeof $u[1]=="number"))})),decisionModel:text$k(Au.decision_model)}}function parseSamples(Au){return{documents:records$1(Au.documents).map(lo=>({name:text$k(lo.name),file:text$k(lo.file),text:text$k(lo.text)})),alternatives:records$1(Au.alternatives).map(lo=>({name:text$k(lo.name),evidence:text$k(lo.evidence),metrics:Object.fromEntries(Object.entries(isData(lo.metrics)?lo.metrics:{}).filter($u=>typeof $u[1]=="number"))}))}}function parseDeployment(Au){const lo={};return isData(Au.hosted)&&(lo.hosted={visibility:oneOf$3(Au.hosted.visibility,["private","invited","organization","link","public"],"private"),slug:text$k(Au.hosted.slug),...Au.hosted.avatar_alone===!0?{avatarAlone:!0}:{}}),isData(Au.embedded)&&(lo.embedded={mode:oneOf$3(Au.embedded.mode,APP_EMBED_MODES,"inline"),origins:texts(Au.embedded.origins),...isData(Au.embedded.host)?{host:{context:texts(Au.embedded.host.context),...Au.embedded.host.user!==void 0?{user:text$k(Au.embedded.host.user)}:{},functions:records$1(Au.embedded.host.functions).map($u=>({name:text$k($u.name),description:text$k($u.description),parameters:isData($u.parameters)?$u.parameters:{...NO_HOST_PARAMETERS}}))}}:{}}),lo}function parseTrigger(Au){return{type:oneOf$3(Au.type,["schedule","event","once"],"schedule"),cron:text$k(Au.cron),event:text$k(Au.event),at:text$k(Au.at),description:text$k(Au.description),prompt:text$k(Au.prompt)}}function parseAppspec(Au){const lo=[];if(!isData(Au))return{app:emptyAppspec(),problems:["The document is not an application."]};const $u=Au;for(const Uu of Object.keys($u))KNOWN_KEYS.includes(Uu)||lo.push(`\`${Uu}\` is not a field of the spec.`);lo.push(...uiShapeProblems($u.ui));const Ru=text$k($u.schema,APP_SCHEMA);Ru!==APP_SCHEMA&&lo.push(`This reads ${APP_SCHEMA}; the application is written in ${Ru}.`),APP_KINDS.includes($u.kind)||lo.push($u.kind===void 0?"The application does not say its `kind`.":`\`${String($u.kind)}\` is not a kind: chat, widget, decision or worker.`);const Iu=oneOf$3($u.kind,APP_KINDS,"chat"),Pu=emptyAppspec(Iu),Ou=isData($u.permissions)?$u.permissions:{},Mu=isData(Ou.computer)?Ou.computer:{},Du=isData($u.tests)?$u.tests:{},Lu=isData(Du.verified)?Du.verified:{},Bu=isData($u.record)?$u.record:{},ju=isData($u.checks)?$u.checks:{};for(const Uu of records$1(ju.code))CHECK_STAGES.includes(Uu.on)||lo.push(`The check \`${text$k(Uu.name)}\` of its code runs on answer or tool_call, not \`${String(Uu.on)}\`.`);const Fu=text$k(Bu.keep_for,DEFAULT_KEEP_FOR);retentionDays(Fu)===0&&lo.push(`Cannot read the retention \`${Fu}\`: write 90_days, 18_months or 1_years.`);const zu={...Pu,schema:APP_SCHEMA,id:text$k($u.id),version:text$k($u.version,DEFAULT_VERSION),name:text$k($u.name),kind:Iu,description:text$k($u.description),owner:text$k($u.owner),agent:text$k($u.agent),team:text$k($u.team),instructions:text$k($u.instructions),model:text$k($u.model),skills:texts($u.skills),backendTools:texts($u.backend_tools),tools:records$1($u.tools).map(parseTool),context:texts($u.context),contents:texts($u.contents),connections:records$1($u.connections).map(parseConnection),protocols:texts($u.protocols),ui:uiChoices($u.ui),rules:records$1($u.rules).map(parseRule$1),permissions:{spaces:records$1(Ou.spaces).map(Uu=>({space:text$k(Uu.space),access:oneOf$3(Uu.access,["read","write"],"read")})),computer:{browse:flag(Mu.browse,!1),files:flag(Mu.files,!1),shell:flag(Mu.shell,!1)}},interface:parseInterface(isData($u.interface)?$u.interface:{},Iu),tests:{readyAt:Math.min(1,Math.max(0,numberOf(Du.ready_at,DEFAULT_READY_AT))),evalset:text$k(Du.evalset),cases:records$1(Du.cases).map(Uu=>({ask:text$k(Uu.ask),...records$1(Uu.turns).length?{turns:records$1(Uu.turns).map(parseTestTurn)}:{},expect:text$k(Uu.expect),...text$k(Uu.code)?{code:text$k(Uu.code)}:{},...records$1(Uu.files).length?{files:records$1(Uu.files).map(Hu=>({name:text$k(Hu.name),text:text$k(Hu.text)}))}:{}})),verified:{live:texts(Lu.live),recorded:texts(Lu.recorded),unverified:texts(Lu.unverified)}},record:{keepFor:Fu,retentionDays:retentionDays(Fu),include:Array.isArray(Bu.include)?texts(Bu.include):[...DEFAULT_RECORD_INCLUDE],suggestTests:Bu.suggest_tests===!0},checks:{guards:texts(ju.guards),gates:texts(ju.gates),track:text$k(ju.track),code:records$1(ju.code).map(Uu=>({name:text$k(Uu.name),on:oneOf$3(Uu.on,CHECK_STAGES,"answer"),description:text$k(Uu.description)}))},deployment:parseDeployment(isData($u.deployment)?$u.deployment:{}),goal:text$k($u.goal),triggers:records$1($u.triggers).map(parseTrigger),memory:text$k($u.memory),notifications:texts($u.notifications),samples:parseSamples(isData($u.samples)?$u.samples:{}),enabled:flag($u.enabled,!0),unavailable_because:text$k($u.unavailable_because),tags:texts($u.tags),icon:text$k($u.icon,DEFAULT_ICON),emoji:text$k($u.emoji,DEFAULT_EMOJI)||DEFAULT_EMOJI,avatar:text$k($u.avatar).trim(),banner:text$k($u.banner).trim()};if(isData($u.decision)&&(zu.decision=parseDecision($u.decision)),isData($u.pap)&&Object.keys($u.pap).length>0){const Uu=papProfileProblem($u.pap.profile);Uu?lo.push(Uu):zu.pap=parsePap($u.pap)}if(isData($u.pact)&&(zu.pact=parsePact($u.pact)),isData($u.commerce)&&(zu.commerce=parseCommerce($u.commerce)),isData($u.signed_fetch)&&(zu.signed_fetch=parseSignedFetch($u.signed_fetch)),isData($u.pair)){const Uu=parsePair($u.pair);typeof Uu=="string"?lo.push(Uu):zu.pair=Uu}return isData($u.a2a)&&(zu.a2a=parseA2A($u.a2a)),lo.push(...protocolsProblems(zu),...uiProblems(zu)),{app:zu,problems:lo}}function uiProblems(Au){const lo=[],$u=[];for(const Ru of Au.ui){const Iu=Ru.plugin;if($u.includes(Iu)){lo.push(`It lists the UI plugin '${Iu}' twice.`);continue}$u.push(Iu);const Pu=UI_CATALOGUE[Iu];if(!Pu){lo.push(`There is no UI plugin named '${Iu}': one of ${Object.keys(UI_CATALOGUE).sort().join(", ")}.`+(UI_RENDERER_CATALOGUE[Iu]?` '${Iu}' is a UI renderer: say it as a plugin's \`renderer\`.`:""));continue}if(Ru.renderer===void 0)continue;const Ou=UI_RENDERER_CATALOGUE[Ru.renderer];Ou?Pu.renderers.includes(Ou.id)?Au.enabled&&!Ou.enabled&&lo.push(`The UI renderer ${Ou.name} ('${Ou.id}') is not enabled: an application cannot be exposed through it yet.`):lo.push(`The UI plugin ${Pu.name} ('${Iu}') is not exposed through ${Ou.name}: `+(Pu.renderers.length>0?`through ${Pu.renderers.join(", ")} only.`:"through no renderer.")):lo.push(`There is no UI renderer named '${Ru.renderer}': one of ${Object.keys(UI_RENDERER_CATALOGUE).sort().join(", ")}.`)}return lo}function protocolsProblems(Au){const lo=[],$u=[];for(const Iu of Au.protocols){if($u.includes(Iu)){lo.push(`It lists the protocol '${Iu}' twice.`);continue}$u.push(Iu);const Pu=PROTOCOL_CATALOGUE[Iu];Pu?Au.enabled&&Pu.status==="planned"&&lo.push(`${Pu.name} ('${Iu}') is planned, not shipped: an application cannot speak it yet.`):lo.push(`There is no protocol named '${Iu}': one of ${Object.keys(PROTOCOL_CATALOGUE).sort().join(", ")}.`)}const Ru={pap:!!(Au.pap&&(Au.pap.connections.length>0||Au.pap.company.enabled)),pact:!!(Au.pact&&(Au.pact.connections.length>0||Au.pact.business?.enabled)),a2a:!!(Au.a2a&&Au.a2a.extensions.length>0),signed_fetch:!!(Au.signed_fetch&&Au.signed_fetch.sites.length>0)};for(const Iu of Object.values(PROTOCOL_CATALOGUE)){const Pu=Iu.appspecBlock;Pu&&Ru[Pu]&&!Au.protocols.includes(Iu.id)&&lo.push(`Its \`${Pu}\` block configures ${Iu.name}, which it does not list: add '${Iu.id}' to \`protocols\`.`)}for(const Iu of new Set((Au.commerce?.merchants??[]).map(Pu=>Pu.protocol)))Au.protocols.includes(Iu)||lo.push(`Its \`commerce\` block shops over ${Iu.toUpperCase()}, which it does not list: add '${Iu}' to \`protocols\`.`);return lo}const sameList=(Au,lo)=>Au.length===lo.length&&Au.every(($u,Ru)=>$u===lo[Ru]);class Writer{data={};text(lo,$u,Ru=""){return $u!==Ru&&(this.data[lo]=$u),this}value(lo,$u,Ru){return $u!==Ru&&(this.data[lo]=$u),this}list(lo,$u,Ru=[]){return sameList($u,Ru)||(this.data[lo]=$u),this}part(lo,$u){return Object.keys($u).length>0&&(this.data[lo]=$u),this}present(lo,$u){return $u!==void 0&&(this.data[lo]=$u),this}}function sorted(Au){return Array.isArray(Au)?Au.map(sorted):isData(Au)?Object.fromEntries(Object.keys(Au).sort((lo,$u)=>lo<$u?-1:lo>$u?1:0).map(lo=>[lo,sorted(Au[lo])])):Au}function dumpComponent(Au){const{id:lo,component:$u,...Ru}=Au;return{id:lo,component:$u,...sorted(Ru)}}function dumpSurface(Au){return new Writer().text("protocol",Au.protocol,DEFAULT_PROTOCOL).list("components",Au.components.map(dumpComponent)).text("composed_by",Au.composedBy).text("composed_at",Au.composedAt).data}function dumpStarter(Au){return new Writer().text("label",Au.label,"\0").text("message",Au.message,"\0").text("category",Au.category??"").data}const saidWords=Au=>Object.fromEntries(Object.entries(Au).filter(([,lo])=>lo!==""));function dumpTranslation(Au){const lo=($u,Ru)=>Object.fromEntries(Object.entries($u).map(([Iu,Pu])=>[Iu,Ru(Pu)]));return new Writer().text("name",Au.name).text("description",Au.description).text("welcome",Au.welcome).part("starters",lo(Au.starters,$u=>new Writer().text("label",$u.label).text("message",$u.message).data)).part("categories",saidWords(Au.categories)).part("settings",lo(Au.settings,$u=>new Writer().text("title",$u.title).text("description",$u.description).part("options",saidWords($u.options)).data)).part("commands",saidWords(Au.commands)).part("modes",lo(Au.modes,$u=>new Writer().text("label",$u.label).part("options",lo($u.options,Ru=>new Writer().text("label",Ru.label).text("description",Ru.description).data)).data)).part("profiles",lo(Au.profiles,$u=>new Writer().text("label",$u.label).text("description",$u.description).data)).data}function dumpInterface(Au,lo){const $u=new Writer().value("layout",Au.layout,DEFAULT_LAYOUTS[lo]).value("accent",Au.accent,void 0).text("welcome",Au.welcome).list("starters",Au.starters.map(dumpStarter)).list("commands",Au.commands.map(Ru=>({name:Ru.name,description:Ru.description,prompt:Ru.prompt}))).list("modes",Au.modes.map(Ru=>{const Iu=new Writer().text("id",Ru.id,"\0").text("label",Ru.label,"\0").list("options",Ru.options.map(Pu=>new Writer().text("id",Pu.id,"\0").text("label",Pu.label,"\0").text("description",Pu.description??"").text("instructions",Pu.instructions??"").text("model",Pu.model??"").data));return Ru.default&&(Iu.data.default=Ru.default),Iu.data})).list("actions",(Au.actions??[]).map(Ru=>{const Iu=new Writer().text("name",Ru.name,"\0").text("description",Ru.description??"");return Ru.payload&&(Iu.data.payload={...Ru.payload}),Iu.data})).list("profiles",(Au.profiles??[]).map(Ru=>new Writer().text("id",Ru.id,"\0").text("label",Ru.label,"\0").text("description",Ru.description).text("instructions",Ru.instructions).text("model",Ru.model??"").list("starters",Ru.starters.map(dumpStarter)).data)).part("settings",Au.settings?{...Au.settings}:{});return Au.settingsUi&&($u.data.settings_ui={...Au.settingsUi}),$u.text("language",Au.language??DEFAULT_LANGUAGE,DEFAULT_LANGUAGE).part("translations",mapValues(Au.translations??{},dumpTranslation)),Au.uploads&&($u.data.uploads=new Writer().list("kinds",Au.uploads.kinds.map(Ru=>new Writer().text("type",Ru.type,"\0").value("max_mb",Ru.maxMb,DEFAULT_UPLOAD_MB).data)).value("max_files",Au.uploads.maxFiles,DEFAULT_MAX_FILES).data),$u.list("components",Au.components),$u.list("custom_components",(Au.customComponents??[]).map(dumpCustomComponent)),Au.surface&&($u.data.surface=dumpSurface(Au.surface)),Au.page&&($u.data.page=dumpPage(Au.page)),Au.avatar&&($u.data.avatar=typeof Au.avatar=="string"?Au.avatar:{...Au.avatar}),Au.balloon&&($u.data.balloon=Au.balloon),Au.theme&&($u.data.theme=Au.theme.mode?{variant:Au.theme.variant,mode:Au.theme.mode}:{variant:Au.theme.variant}),Au.voice&&$u.part("voice",new Writer().value("enabled",Au.voice.enabled,DEFAULT_VOICE.enabled).value("input",Au.voice.input,DEFAULT_VOICE.input).value("output",Au.voice.output,DEFAULT_VOICE.output).text("voice",Au.voice.voice).text("language",Au.voice.language).value("where",Au.voice.where,DEFAULT_VOICE.where).data),$u.list("outputs",Au.outputs??[]),$u.data}function dumpDecision(Au){return new Writer().text("question",Au.question,"\0").list("alternatives",Au.alternatives).list("criteria",Au.criteria.map(lo=>new Writer().text("name",lo.name,"\0").value("kind",lo.kind,"metric").value("weight",lo.weight,1).text("instructions",lo.instructions).list("options",lo.options).value("direction",lo.direction,"higher").value("measure",lo.measure,"").data)).value("min_confidence",Au.minConfidence,0).list("scenarios",Au.scenarios.map(lo=>new Writer().text("name",lo.name,"\0").part("weights",sorted(lo.weights)).data)).text("decision_model",Au.decisionModel).data}function dumpSamples(Au){return new Writer().list("documents",Au.documents.map(lo=>new Writer().text("name",lo.name,"\0").text("file",lo.file,"\0").text("text",lo.text,"\0").data)).list("alternatives",Au.alternatives.map(lo=>new Writer().text("name",lo.name,"\0").text("evidence",lo.evidence,"\0").part("metrics",{...lo.metrics}).data)).data}function dumpAppspec(Au){const lo=new Writer().value("browse",Au.permissions.computer.browse,!1).value("files",Au.permissions.computer.files,!1).value("shell",Au.permissions.computer.shell,!1).data,$u=new Writer;return $u.data.schema=APP_SCHEMA,$u.text("id",Au.id,"\0").text("version",Au.version,DEFAULT_VERSION).text("name",Au.name,"\0").text("kind",Au.kind,"\0").text("description",Au.description).text("owner",Au.owner).text("agent",Au.agent).text("team",Au.team).text("instructions",Au.instructions).text("model",Au.model).list("skills",Au.skills).list("backend_tools",Au.backendTools).list("tools",(Au.tools??[]).map(Ru=>({name:Ru.name,description:Ru.description,...JSON.stringify(Ru.parameters)===JSON.stringify(NO_HOST_PARAMETERS)?{}:{parameters:Ru.parameters},does:Ru.does}))).list("context",Au.context).list("contents",Au.contents).list("connections",Au.connections.map(Ru=>new Writer().text("server",Ru.server,"\0").value("access",Ru.access,"read").value("as",Ru.as,"owner").list("only",Ru.only).data)).list("protocols",Au.protocols).list("ui",Au.ui.map(Ru=>Ru.renderer?{plugin:Ru.plugin,renderer:Ru.renderer}:{plugin:Ru.plugin})).part("pap",dumpPap(Au.pap)).part("pact",dumpPact(Au.pact)).part("commerce",dumpCommerce(Au.commerce)).part("signed_fetch",dumpSignedFetch(Au.signed_fetch)).part("pair",Au.pair?{id:Au.pair.id,role:Au.pair.role}:{}).part("a2a",dumpA2A(Au.a2a)).list("rules",Au.rules.map(Ru=>({action:Ru.action,applies_to:Ru.appliesTo.length===1&&ACTION_CLASS_NAMES.includes(Ru.appliesTo[0])?Ru.appliesTo[0]:Ru.appliesTo,behaviour:Ru.behaviour}))).part("permissions",new Writer().list("spaces",Au.permissions.spaces.map(Ru=>new Writer().text("space",Ru.space,"\0").value("access",Ru.access,"read").data)).part("computer",lo).data).part("interface",dumpInterface(Au.interface,Au.kind)).part("tests",new Writer().value("ready_at",Au.tests.readyAt,DEFAULT_READY_AT).text("evalset",Au.tests.evalset).list("cases",Au.tests.cases.map(Ru=>({...Ru.turns?.length?{turns:Ru.turns.map(Iu=>parseTestTurn({...Iu}))}:{ask:Ru.ask},expect:Ru.expect,...Ru.code?{code:Ru.code}:{},...Ru.files?.length?{files:Ru.files.map(Iu=>({name:Iu.name,text:Iu.text}))}:{}}))).part("verified",new Writer().list("live",Au.tests.verified.live).list("recorded",Au.tests.verified.recorded).list("unverified",Au.tests.verified.unverified).data).data).part("record",new Writer().text("keep_for",Au.record.keepFor,DEFAULT_KEEP_FOR).list("include",Au.record.include,DEFAULT_RECORD_INCLUDE).value("suggest_tests",Au.record.suggestTests,!1).data).part("checks",new Writer().list("guards",Au.checks.guards).list("gates",Au.checks.gates).text("track",Au.checks.track).list("code",(Au.checks.code??[]).map(Ru=>({name:Ru.name,on:Ru.on,description:Ru.description}))).data).part("deployment",new Writer().present("hosted",Au.deployment.hosted&&new Writer().value("visibility",Au.deployment.hosted.visibility,"private").text("slug",Au.deployment.hosted.slug).value("avatar_alone",Au.deployment.hosted.avatarAlone===!0,!1).data).present("embedded",Au.deployment.embedded&&new Writer().value("mode",Au.deployment.embedded.mode,"inline").list("origins",Au.deployment.embedded.origins).present("host",Au.deployment.embedded.host&&new Writer().list("context",Au.deployment.embedded.host.context).list("functions",Au.deployment.embedded.host.functions.map(Ru=>({name:Ru.name,description:Ru.description,...JSON.stringify(Ru.parameters)===JSON.stringify(NO_HOST_PARAMETERS)?{}:{parameters:Ru.parameters}}))).value("user",Au.deployment.embedded.host.user??"claimed","claimed").data).data).data).text("goal",Au.goal).list("triggers",Au.triggers.map(Ru=>new Writer().text("type",Ru.type,"\0").text("cron",Ru.cron).text("event",Ru.event).text("at",Ru.at).text("description",Ru.description).text("prompt",Ru.prompt).data)).text("memory",Au.memory).list("notifications",Au.notifications),Au.decision&&($u.data.decision=dumpDecision(Au.decision)),$u.part("samples",dumpSamples(Au.samples)).value("enabled",Au.enabled,!0).text("unavailable_because",Au.unavailable_because).list("tags",Au.tags).text("icon",Au.icon??DEFAULT_ICON,DEFAULT_ICON).text("emoji",Au.emoji,DEFAULT_EMOJI).text("avatar",Au.avatar??"","").text("banner",Au.banner??"",""),$u.data}const ALIAS=Symbol.for("yaml.alias"),DOC=Symbol.for("yaml.document"),MAP$1=Symbol.for("yaml.map"),PAIR=Symbol.for("yaml.pair"),SCALAR$1=Symbol.for("yaml.scalar"),SEQ=Symbol.for("yaml.seq"),NODE_TYPE$1=Symbol.for("yaml.node.type"),isAlias=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===ALIAS,isDocument=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===DOC,isMap=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===MAP$1,isPair=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===PAIR,isScalar=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===SCALAR$1,isSeq$1=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===SEQ;function isCollection(Au){if(Au&&typeof Au=="object")switch(Au[NODE_TYPE$1]){case MAP$1:case SEQ:return!0}return!1}function isNode$1(Au){if(Au&&typeof Au=="object")switch(Au[NODE_TYPE$1]){case ALIAS:case MAP$1:case SCALAR$1:case SEQ:return!0}return!1}const hasAnchor=Au=>(isScalar(Au)||isCollection(Au))&&!!Au.anchor,BREAK=Symbol("break visit"),SKIP$1=Symbol("skip children"),REMOVE=Symbol("remove node");function visit$4(Au,lo){const $u=initVisitor(lo);isDocument(Au)?visit_(null,Au.contents,$u,Object.freeze([Au]))===REMOVE&&(Au.contents=null):visit_(null,Au,$u,Object.freeze([]))}visit$4.BREAK=BREAK;visit$4.SKIP=SKIP$1;visit$4.REMOVE=REMOVE;function visit_(Au,lo,$u,Ru){const Iu=callVisitor(Au,lo,$u,Ru);if(isNode$1(Iu)||isPair(Iu))return replaceNode(Au,Ru,Iu),visit_(Au,Iu,$u,Ru);if(typeof Iu!="symbol"){if(isCollection(lo)){Ru=Object.freeze(Ru.concat(lo));for(let Pu=0;Pu<lo.items.length;++Pu){const Ou=visit_(Pu,lo.items[Pu],$u,Ru);if(typeof Ou=="number")Pu=Ou-1;else{if(Ou===BREAK)return BREAK;Ou===REMOVE&&(lo.items.splice(Pu,1),Pu-=1)}}}else if(isPair(lo)){Ru=Object.freeze(Ru.concat(lo));const Pu=visit_("key",lo.key,$u,Ru);if(Pu===BREAK)return BREAK;Pu===REMOVE&&(lo.key=null);const Ou=visit_("value",lo.value,$u,Ru);if(Ou===BREAK)return BREAK;Ou===REMOVE&&(lo.value=null)}}return Iu}function initVisitor(Au){return typeof Au=="object"&&(Au.Collection||Au.Node||Au.Value)?Object.assign({Alias:Au.Node,Map:Au.Node,Scalar:Au.Node,Seq:Au.Node},Au.Value&&{Map:Au.Value,Scalar:Au.Value,Seq:Au.Value},Au.Collection&&{Map:Au.Collection,Seq:Au.Collection},Au):Au}function callVisitor(Au,lo,$u,Ru){if(typeof $u=="function")return $u(Au,lo,Ru);if(isMap(lo))return $u.Map?.(Au,lo,Ru);if(isSeq$1(lo))return $u.Seq?.(Au,lo,Ru);if(isPair(lo))return $u.Pair?.(Au,lo,Ru);if(isScalar(lo))return $u.Scalar?.(Au,lo,Ru);if(isAlias(lo))return $u.Alias?.(Au,lo,Ru)}function replaceNode(Au,lo,$u){const Ru=lo[lo.length-1];if(isCollection(Ru))Ru.items[Au]=$u;else if(isPair(Ru))Au==="key"?Ru.key=$u:Ru.value=$u;else if(isDocument(Ru))Ru.contents=$u;else{const Iu=isAlias(Ru)?"alias":"scalar";throw new Error(`Cannot replace node with ${Iu} parent`)}}const escapeChars={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},escapeTagName=Au=>Au.replace(/[!,[\]{}]/g,lo=>escapeChars[lo]);class Directives{constructor(lo,$u){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Directives.defaultYaml,lo),this.tags=Object.assign({},Directives.defaultTags,$u)}clone(){const lo=new Directives(this.yaml,this.tags);return lo.docStart=this.docStart,lo}atDocument(){const lo=new Directives(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Directives.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Directives.defaultTags);break}return lo}add(lo,$u){this.atNextDocument&&(this.yaml={explicit:Directives.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Directives.defaultTags),this.atNextDocument=!1);const Ru=lo.trim().split(/[ \t]+/),Iu=Ru.shift();switch(Iu){case"%TAG":{if(Ru.length!==2&&($u(0,"%TAG directive should contain exactly two parts"),Ru.length<2))return!1;const[Pu,Ou]=Ru;return this.tags[Pu]=Ou,!0}case"%YAML":{if(this.yaml.explicit=!0,Ru.length!==1)return $u(0,"%YAML directive should contain exactly one part"),!1;const[Pu]=Ru;if(Pu==="1.1"||Pu==="1.2")return this.yaml.version=Pu,!0;{const Ou=/^\d+\.\d+$/.test(Pu);return $u(6,`Unsupported YAML version ${Pu}`,Ou),!1}}default:return $u(0,`Unknown directive ${Iu}`,!0),!1}}tagName(lo,$u){if(lo==="!")return"!";if(lo[0]!=="!")return $u(`Not a valid tag: ${lo}`),null;if(lo[1]==="<"){const Ou=lo.slice(2,-1);return Ou==="!"||Ou==="!!"?($u(`Verbatim tags aren't resolved, so ${lo} is invalid.`),null):(lo[lo.length-1]!==">"&&$u("Verbatim tags must end with a >"),Ou)}const[,Ru,Iu]=lo.match(/^(.*!)([^!]*)$/s);Iu||$u(`The ${lo} tag has no suffix`);const Pu=this.tags[Ru];if(Pu)try{return Pu+decodeURIComponent(Iu)}catch(Ou){return $u(String(Ou)),null}return Ru==="!"?lo:($u(`Could not resolve tag: ${lo}`),null)}tagString(lo){for(const[$u,Ru]of Object.entries(this.tags))if(lo.startsWith(Ru))return $u+escapeTagName(lo.substring(Ru.length));return lo[0]==="!"?lo:`!<${lo}>`}toString(lo){const $u=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],Ru=Object.entries(this.tags);let Iu;if(lo&&Ru.length>0&&isNode$1(lo.contents)){const Pu={};visit$4(lo.contents,(Ou,Mu)=>{isNode$1(Mu)&&Mu.tag&&(Pu[Mu.tag]=!0)}),Iu=Object.keys(Pu)}else Iu=[];for(const[Pu,Ou]of Ru)Pu==="!!"&&Ou==="tag:yaml.org,2002:"||(!lo||Iu.some(Mu=>Mu.startsWith(Ou)))&&$u.push(`%TAG ${Pu} ${Ou}`);return $u.join(`
|
|
123
|
+
`,loopThemeStyles=buildThemeStyles(loopLight,loopDark,{fontFamily:loopFontFamily,css:loopOwnCss,shape:{radiusControl:loopShapeVars["--loop-radius-control"],radiusTable:loopShapeVars["--borderRadius-medium"],radiusOverlay:loopShapeVars["--loop-radius-card"],radiusCard:loopShapeVars["--loop-radius-card"],radiusBubble:loopShapeVars["--loop-radius-bubble"],radiusFrame:loopShapeVars["--loop-radius-frame"],shadow:loopShapeVars["--loop-shadow-frame"],motionStatus:loopMotionVars["--loop-motion-status"],motionMessage:loopMotionVars["--loop-motion-message"],motionPane:loopMotionVars["--loop-motion-pane"],motionEasing:loopMotionVars["--loop-motion-easing"],messageLink:"currentColor"},variables:{light:{...loopShapeVars,...loopTints("light"),...loopMotionVars,...loopShadows.light,...loopTypeVars(loopFontFamily),"--loop-hairline":loopHairline.light,"--borderColor-default":loopHairline.light,"--focus-outlineColor":loopFocusRing.light,"--underlineNav-borderColor-active":themeAccents.green.accent},dark:{...loopShapeVars,...loopTints("dark"),...loopMotionVars,...loopShadows.dark,...loopTypeVars(loopFontFamily),"--loop-hairline":loopHairline.dark,"--borderColor-default":loopHairline.dark,"--focus-outlineColor":loopFocusRing.dark,"--underlineNav-borderColor-active":themeAccents.green.accent}}});loopThemeStyles.css;const loopTheme={...theme$1,fontWeights:{light:loopFontWeights.regular,normal:loopFontWeights.regular,semibold:loopFontWeights.semibold,bold:loopFontWeights.semibold}},themeTokens={datalayer:{label:"Datalayer",description:"Default green palette — the classic Datalayer look.",brandColor:datalayerColors.greenBrand,defaultColorMode:"auto",themeStyles:datalayerThemeStyles,cardGradient:{light:{from:datalayerColors.greenBrand,to:datalayerColors.greenText},dark:{from:datalayerColors.greenAccent,to:datalayerColors.greenBrand}},brightPalette:{glow:datalayerColors.brightGlow,onGlow:"#1b1f24",pop:datalayerColors.brightPop,spark:datalayerColors.brightSpark,blaze:datalayerColors.brightBlaze,surge:datalayerColors.brightSurge,flame:datalayerColors.brightFlame,gold:datalayerColors.brightGold},brightPaletteLight:{glow:datalayerColors.brightLightGlow,onGlow:"#1b1f24",pop:datalayerColors.brightLightPop,spark:datalayerColors.brightLightSpark,blaze:datalayerColors.brightLightBlaze,surge:datalayerColors.brightLightSurge,flame:datalayerColors.brightLightFlame,gold:datalayerColors.brightLightGold}},spatial:{label:"Spatial",description:"Cosmic indigo & deep blues — inspired by space.",brandColor:spatialColors.indigoBrand,defaultColorMode:"auto",themeStyles:spatialThemeStyles,cardGradient:{light:{from:spatialColors.indigoBrand,to:spatialColors.indigoText},dark:{from:spatialColors.indigoAccent,to:spatialColors.indigoBrand}},brightPalette:{glow:spatialColors.brightGlow,onGlow:"#ffffff",pop:spatialColors.brightPop,spark:spatialColors.brightSpark,blaze:spatialColors.brightBlaze,surge:spatialColors.brightSurge,flame:spatialColors.brightFlame,gold:spatialColors.brightGold},brightPaletteLight:{glow:spatialColors.brightLightGlow,onGlow:"#ffffff",pop:spatialColors.brightLightPop,spark:spatialColors.brightLightSpark,blaze:spatialColors.brightLightBlaze,surge:spatialColors.brightLightSurge,flame:spatialColors.brightLightFlame,gold:spatialColors.brightLightGold}},lovely:{label:"Lovely",description:"Warm rose & magenta — soft and inviting.",brandColor:lovelyColors.roseBrand,defaultColorMode:"auto",themeStyles:lovelyThemeStyles,cardGradient:{light:{from:lovelyColors.roseBrand,to:lovelyColors.roseText},dark:{from:lovelyColors.roseAccent,to:lovelyColors.roseBrand}},brightPalette:{glow:lovelyColors.brightGlow,onGlow:"#ffffff",pop:lovelyColors.brightPop,spark:lovelyColors.brightSpark,blaze:lovelyColors.brightBlaze,surge:lovelyColors.brightSurge,flame:lovelyColors.brightFlame,gold:lovelyColors.brightGold},brightPaletteLight:{glow:lovelyColors.brightLightGlow,onGlow:"#ffffff",pop:lovelyColors.brightLightPop,spark:lovelyColors.brightLightSpark,blaze:lovelyColors.brightLightBlaze,surge:lovelyColors.brightLightSurge,flame:lovelyColors.brightLightFlame,gold:lovelyColors.brightLightGold}},matrix:{label:"Matrix",description:"Phosphor green on black — CRT terminal aesthetic.",brandColor:matrixColors.greenPhosphor,defaultColorMode:"dark",themeStyles:matrixThemeStyles,cardGradient:{light:{from:matrixColors.greenBrand,to:matrixColors.greenText},dark:{from:matrixColors.greenGlow,to:matrixColors.greenHover}},brightPalette:{glow:matrixColors.brightGlow,onGlow:"#1b1f24",pop:matrixColors.brightPop,spark:matrixColors.brightSpark,blaze:matrixColors.brightBlaze,surge:matrixColors.brightSurge,flame:matrixColors.brightFlame,gold:matrixColors.brightGold},brightPaletteLight:{glow:matrixColors.brightLightGlow,onGlow:"#1b1f24",pop:matrixColors.brightLightPop,spark:matrixColors.brightLightSpark,blaze:matrixColors.brightLightBlaze,surge:matrixColors.brightLightSurge,flame:matrixColors.brightLightFlame,gold:matrixColors.brightLightGold}},earth:{label:"Earth",description:"Ocean blues, forest greens & golden sun — the Blue Planet.",brandColor:earthColors.oceanBrand,defaultColorMode:"auto",themeStyles:earthThemeStyles,cardGradient:{light:{from:earthColors.oceanBrand,to:earthColors.oceanText},dark:{from:earthColors.oceanAccent,to:earthColors.oceanBrand}},brightPalette:{glow:earthColors.brightGlow,onGlow:"#ffffff",pop:earthColors.brightPop,spark:earthColors.brightSpark,blaze:earthColors.brightBlaze,surge:earthColors.brightSurge,flame:earthColors.brightFlame,gold:earthColors.brightGold},brightPaletteLight:{glow:earthColors.brightLightGlow,onGlow:"#ffffff",pop:earthColors.brightLightPop,spark:earthColors.brightLightSpark,blaze:earthColors.brightLightBlaze,surge:earthColors.brightLightSurge,flame:earthColors.brightLightFlame,gold:earthColors.brightLightGold}},sand:{label:"Sand",description:"Warm, pale desert neutrals with a golden accent — calm & editorial.",brandColor:sandColors.sandBrand,defaultColorMode:"light",themeStyles:sandThemeStyles,cardGradient:{light:{from:sandColors.sandBrand,to:sandColors.sandText},dark:{from:sandColors.sandAccent,to:sandColors.sandBrand}},brightPalette:{glow:sandColors.brightGlow,onGlow:"#211A12",pop:sandColors.brightPop,spark:sandColors.brightSpark,blaze:sandColors.brightBlaze,surge:sandColors.brightSurge,flame:sandColors.brightFlame,gold:sandColors.brightGold},brightPaletteLight:{glow:sandColors.brightLightGlow,onGlow:"#ffffff",pop:sandColors.brightLightPop,spark:sandColors.brightLightSpark,blaze:sandColors.brightLightBlaze,surge:sandColors.brightLightSurge,flame:sandColors.brightLightFlame,gold:sandColors.brightLightGold}},ivory:{label:"Ivory",description:"Soft, warm off-white that creates a calm, refined, and welcoming feeling.",brandColor:ivoryColors.ivoryBrand,defaultColorMode:"light",themeStyles:ivoryThemeStyles,cardGradient:{light:{from:ivoryColors.ivoryBrand,to:ivoryColors.ivoryText},dark:{from:ivoryColors.ivoryAccent,to:ivoryColors.ivoryBrand}},brightPalette:{glow:ivoryColors.brightGlow,onGlow:"#211A12",pop:ivoryColors.brightPop,spark:ivoryColors.brightSpark,blaze:ivoryColors.brightBlaze,surge:ivoryColors.brightSurge,flame:ivoryColors.brightFlame,gold:ivoryColors.brightGold},brightPaletteLight:{glow:ivoryColors.brightLightGlow,onGlow:"#ffffff",pop:ivoryColors.brightLightPop,spark:ivoryColors.brightLightSpark,blaze:ivoryColors.brightLightBlaze,surge:ivoryColors.brightLightSurge,flame:ivoryColors.brightLightFlame,gold:ivoryColors.brightLightGold}},sun:{label:"Sun",description:"Warm, radiant theme inspired by golden light, bringing energy, optimism, and a welcoming atmosphere.",brandColor:sunColors.sunBrand,defaultColorMode:"light",themeStyles:sunThemeStyles,cardGradient:{light:{from:sunColors.sunBrand,to:sunColors.sunText},dark:{from:sunColors.sunAccent,to:sunColors.sunBrand}},brightPalette:{glow:sunColors.brightGlow,onGlow:"#211A08",pop:sunColors.brightPop,spark:sunColors.brightSpark,blaze:sunColors.brightBlaze,surge:sunColors.brightSurge,flame:sunColors.brightFlame,gold:sunColors.brightGold},brightPaletteLight:{glow:sunColors.brightLightGlow,onGlow:"#ffffff",pop:sunColors.brightLightPop,spark:sunColors.brightLightSpark,blaze:sunColors.brightLightBlaze,surge:sunColors.brightLightSurge,flame:sunColors.brightLightFlame,gold:sunColors.brightLightGold}},loop:{label:"Loop",description:"Very clean: one soft accent, neutral everything else. The look of an application built in LOOP.",brandColor:loopColors.loopBrand,defaultColorMode:"light",themeStyles:loopThemeStyles,cardGradient:{light:{from:loopColors.loopBrand,to:loopColors.loopBrand},dark:{from:loopColors.loopBrand,to:loopColors.loopBrand}},brightPalette:{glow:loopColors.brightGlow,onGlow:loopColors.loopOn,pop:loopColors.brightPop,spark:loopColors.brightSpark,blaze:loopColors.brightBlaze,surge:loopColors.brightSurge,flame:loopColors.brightFlame,gold:loopColors.brightGold},brightPaletteLight:{glow:loopColors.brightLightGlow,onGlow:"#ffffff",pop:loopColors.brightLightPop,spark:loopColors.brightLightSpark,blaze:loopColors.brightLightBlaze,surge:loopColors.brightLightSurge,flame:loopColors.brightLightFlame,gold:loopColors.brightLightGold}}};function brightPaletteOf(Au,lo){const $u=themeTokens[Au]??themeTokens.datalayer;return lo==="light"?$u.brightPaletteLight??$u.brightPalette:$u.brightPalette}const primerThemes={datalayer:datalayerTheme,spatial:spatialTheme,lovely:lovelyTheme,matrix:matrixTheme,earth:earthTheme,sand:sandTheme,ivory:ivoryTheme,sun:sunTheme,loop:loopTheme},themeConfigs=Object.fromEntries(Object.keys(themeTokens).map(Au=>[Au,{...themeTokens[Au],primerTheme:primerThemes[Au]}]));function getThemeConfig(Au){return themeConfigs[Au]}const osMode=()=>typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";function getBrightPalette(Au="datalayer",lo){const $u=lo==="auto"?osMode():lo==="light"?"light":"dark";return brightPaletteOf(Au,$u)}const createStoreImpl$2=Au=>{let lo;const $u=new Set,Ru=(Lu,Bu)=>{const ju=typeof Lu=="function"?Lu(lo):Lu;if(!Object.is(ju,lo)){const Fu=lo;lo=Bu??(typeof ju!="object"||ju===null)?ju:Object.assign({},lo,ju),$u.forEach(zu=>zu(lo,Fu))}},Iu=()=>lo,Mu={setState:Ru,getState:Iu,getInitialState:()=>Du,subscribe:Lu=>($u.add(Lu),()=>$u.delete(Lu))},Du=lo=Au(Ru,Iu,Mu);return Mu},createStore$2=(Au=>Au?createStoreImpl$2(Au):createStoreImpl$2),identity$2=Au=>Au;function useStore$2(Au,lo=identity$2){const $u=vM.useSyncExternalStore(Au.subscribe,vM.useCallback(()=>lo(Au.getState()),[Au,lo]),()=>lo(Au.getInitialState()));return vM.useDebugValue($u),$u}const createImpl$2=Au=>{const lo=createStore$2(Au),$u=Ru=>useStore$2(lo,Ru);return Object.assign($u,lo),$u},create$h=(Au=>Au?createImpl$2(Au):createImpl$2);function createJSONStorage$1(Au,lo){let $u;try{$u=Au()}catch{return}return{getItem:Iu=>{var Pu;const Ou=Du=>Du===null?null:JSON.parse(Du,void 0),Mu=(Pu=$u.getItem(Iu))!=null?Pu:null;return Mu instanceof Promise?Mu.then(Ou):Ou(Mu)},setItem:(Iu,Pu)=>$u.setItem(Iu,JSON.stringify(Pu,void 0)),removeItem:Iu=>$u.removeItem(Iu)}}const toThenable$1=Au=>lo=>{try{const $u=Au(lo);return $u instanceof Promise?$u:{then(Ru){return toThenable$1(Ru)($u)},catch(Ru){return this}}}catch($u){return{then(Ru){return this},catch(Ru){return toThenable$1(Ru)($u)}}}},persistImpl$1=(Au,lo)=>($u,Ru,Iu)=>{let Pu={storage:createJSONStorage$1(()=>window.localStorage),partialize:Vu=>Vu,version:0,merge:(Vu,Gu)=>({...Gu,...Vu}),...lo},Ou=!1,Mu=0;const Du=new Set,Lu=new Set;let Bu=Pu.storage;if(!Bu)return Au((...Vu)=>{console.warn(`[zustand persist middleware] Unable to update item '${Pu.name}', the given storage is currently unavailable.`),$u(...Vu)},Ru,Iu);const ju=()=>{const Vu=Pu.partialize({...Ru()});return Bu.setItem(Pu.name,{state:Vu,version:Pu.version})},Fu=Iu.setState;Iu.setState=(...Vu)=>(Fu(...Vu),ju());const zu=Au((...Vu)=>($u(...Vu),ju()),Ru,Iu);Iu.getInitialState=()=>zu;let Uu;const Hu=()=>{var Vu,Gu;if(!Bu)return;const Wu=++Mu;Ou=!1,Du.forEach(Ju=>{var Yu;return Ju((Yu=Ru())!=null?Yu:zu)});const Ku=((Gu=Pu.onRehydrateStorage)==null?void 0:Gu.call(Pu,(Vu=Ru())!=null?Vu:zu))||void 0;return toThenable$1(Bu.getItem.bind(Bu))(Pu.name).then(Ju=>{if(Ju)if(typeof Ju.version=="number"&&Ju.version!==Pu.version){if(Pu.migrate){const Yu=Pu.migrate(Ju.state,Ju.version);return Yu instanceof Promise?Yu.then(Xu=>[!0,Xu]):[!0,Yu]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,Ju.state];return[!1,void 0]}).then(Ju=>{var Yu;if(Wu!==Mu)return;const[Xu,ed]=Ju;if(Uu=Pu.merge(ed,(Yu=Ru())!=null?Yu:zu),$u(Uu,!0),Xu)return ju()}).then(()=>{Wu===Mu&&(Ku?.(Ru(),void 0),Uu=Ru(),Ou=!0,Lu.forEach(Ju=>Ju(Uu)))}).catch(Ju=>{Wu===Mu&&Ku?.(void 0,Ju)})};return Iu.persist={setOptions:Vu=>{Pu={...Pu,...Vu},Vu.storage&&(Bu=Vu.storage)},clearStorage:()=>{++Mu,Bu?.removeItem(Pu.name)},getOptions:()=>Pu,rehydrate:()=>Hu(),hasHydrated:()=>Ou,onHydrate:Vu=>(Du.add(Vu),()=>{Du.delete(Vu)}),onFinishHydration:Vu=>(Lu.add(Vu),()=>{Lu.delete(Vu)})},Pu.skipHydration||Hu(),Uu||zu},persist$2=persistImpl$1,VARIANT_SCHEMA_VERSION=1;function normalizeVariantPreference(Au){return{theme:Au.theme,colorMode:Au.colorMode,version:typeof Au.version=="number"?Au.version:VARIANT_SCHEMA_VERSION}}function normalizeVariants(Au){if(!Au)return{};const lo={};for(const[$u,Ru]of Object.entries(Au))!Ru||typeof Ru!="object"||!("theme"in Ru)||!("colorMode"in Ru)||(lo[$u]=normalizeVariantPreference(Ru));return lo}function hasMissingVariantVersion(Au){return!Au||Object.keys(Au).length===0?!1:Object.values(Au).some(lo=>typeof lo?.version!="number")}const colorModeCycle={light:"dark",dark:"auto",auto:"light"};function createThemeStore(Au,lo){return create$h()(persist$2($u=>({colorMode:lo?.colorMode,theme:lo?.theme,activeVariant:null,variants:normalizeVariants(lo?.variants),toggleColorMode:()=>$u(Ru=>{const Iu=colorModeCycle[Ru.colorMode];return Ru.activeVariant&&Ru.variants[Ru.activeVariant]?{colorMode:Iu,variants:{...Ru.variants,[Ru.activeVariant]:{...Ru.variants[Ru.activeVariant],colorMode:Iu,version:VARIANT_SCHEMA_VERSION}}}:{colorMode:Iu}}),setColorMode:Ru=>$u(Iu=>Iu.activeVariant&&Iu.variants[Iu.activeVariant]?{colorMode:Ru,variants:{...Iu.variants,[Iu.activeVariant]:{...Iu.variants[Iu.activeVariant],colorMode:Ru,version:VARIANT_SCHEMA_VERSION}}}:{colorMode:Ru}),setTheme:(Ru,Iu=!0)=>$u(Pu=>{const Ou=Iu?themeConfigs[Ru].defaultColorMode:Pu.colorMode;return Pu.activeVariant&&Pu.variants[Pu.activeVariant]?{theme:Ru,colorMode:Ou,variants:{...Pu.variants,[Pu.activeVariant]:{theme:Ru,colorMode:Ou,version:VARIANT_SCHEMA_VERSION}}}:{theme:Ru,colorMode:Ou}}),registerVariants:Ru=>$u(Iu=>{const Pu={...Iu.variants};for(const[Ou,Mu]of Object.entries(Ru))Pu[Ou]?Pu[Ou]=normalizeVariantPreference({...Pu[Ou],version:Pu[Ou].version??VARIANT_SCHEMA_VERSION}):Pu[Ou]=normalizeVariantPreference(Mu);return{variants:Pu}}),setVariant:Ru=>$u(Iu=>{const Pu=Iu.variants[Ru];return Pu?{activeVariant:Ru,theme:Pu.theme,colorMode:Pu.colorMode}:{activeVariant:Ru}})}),{name:Au,version:3,storage:createJSONStorage$1(()=>localStorage),partialize:$u=>({colorMode:$u.colorMode,theme:$u.theme,activeVariant:$u.activeVariant,variants:$u.variants}),migrate:$u=>{const Ru=$u??{},Iu=Ru.variants,Pu=hasMissingVariantVersion(Iu),Ou=normalizeVariants(Iu);return Pu&&(Ou["agent-anonymous"]={theme:"matrix",colorMode:"dark",version:VARIANT_SCHEMA_VERSION}),{...Ru,variants:Ou,...Pu?{theme:Ru.activeVariant==="agent-anonymous"?"matrix":Ru.theme,colorMode:Ru.activeVariant==="agent-anonymous"?"dark":Ru.colorMode}:{}}},merge:($u,Ru)=>{const Iu=$u??{},Pu=normalizeVariants(Ru.variants);if(Iu.variants)for(const[Ou,Mu]of Object.entries(Iu.variants))Mu&&typeof Mu=="object"&&"theme"in Mu&&(Pu[Ou]=normalizeVariantPreference(Mu));return{...Ru,...Iu,variants:Pu}}}))}const useThemeStore=createThemeStore("datalayer-theme",{colorMode:"dark",theme:"matrix"}),dlBrightDark=getBrightPalette("datalayer"),dlBrightLight=getBrightPalette("datalayer","light"),spBrightDark=getBrightPalette("spatial"),spBrightLight=getBrightPalette("spatial","light"),lvBrightDark=getBrightPalette("lovely"),lvBrightLight=getBrightPalette("lovely","light"),mxBrightDark=getBrightPalette("matrix"),mxBrightLight=getBrightPalette("matrix","light"),eaBrightDark=getBrightPalette("earth"),eaBrightLight=getBrightPalette("earth","light"),saBrightDark=getBrightPalette("sand"),saBrightLight=getBrightPalette("sand","light"),ivBrightDark=getBrightPalette("ivory"),ivBrightLight=getBrightPalette("ivory","light"),suBrightDark=getBrightPalette("sun"),suBrightLight=getBrightPalette("sun","light"),loBrightDark=getBrightPalette("loop"),loBrightLight=getBrightPalette("loop","light"),palettes={datalayer:{light:{bg:"#f6f8fa",bgPanel:"#ffffff",bgAlt:"#f0f3f6",primary:datalayerColors.greenBrand,secondary:datalayerColors.greenText,accent:datalayerColors.greenBright,glow:dlBrightLight.glow,pop:dlBrightLight.pop,spark:dlBrightLight.spark,blaze:dlBrightLight.blaze,surge:dlBrightLight.surge,flame:dlBrightLight.flame,gold:dlBrightLight.gold,textLight:"#1f2328",textMuted:"#656d76",isLight:!0},dark:{bg:"#0d1117",bgPanel:"#161b22",bgAlt:"#1c2128",primary:datalayerColors.greenAccent,secondary:datalayerColors.greenBrand,accent:datalayerColors.greenBright,glow:dlBrightDark.glow,pop:dlBrightDark.pop,spark:dlBrightDark.spark,blaze:dlBrightDark.blaze,surge:dlBrightDark.surge,flame:dlBrightDark.flame,gold:dlBrightDark.gold,textLight:"#f0f6fc",textMuted:"#8b949e",isLight:!1}},spatial:{light:{bg:"#f0f2ff",bgPanel:"#ffffff",bgAlt:"#eef2ff",primary:spatialColors.indigoBrand,secondary:spatialColors.indigoText,accent:spatialColors.indigoBright,glow:spBrightLight.glow,pop:spBrightLight.pop,spark:spBrightLight.spark,blaze:spBrightLight.blaze,surge:spBrightLight.surge,flame:spBrightLight.flame,gold:spBrightLight.gold,textLight:"#1E1E3F",textMuted:spatialColors.gray,isLight:!0},dark:{bg:spatialColors.black,bgPanel:"#111827",bgAlt:"#1E293B",primary:spatialColors.indigoAccent,secondary:spatialColors.indigoBrand,accent:spatialColors.indigoBright,glow:spBrightDark.glow,pop:spBrightDark.pop,spark:spBrightDark.spark,blaze:spBrightDark.blaze,surge:spBrightDark.surge,flame:spBrightDark.flame,gold:spBrightDark.gold,textLight:"#E0E7FF",textMuted:"#94A3B8",isLight:!1}},lovely:{light:{bg:"#fff5f7",bgPanel:"#ffffff",bgAlt:lovelyColors.roseTint,primary:lovelyColors.roseBrand,secondary:lovelyColors.roseText,accent:lovelyColors.roseBright,glow:lvBrightLight.glow,pop:lvBrightLight.pop,spark:lvBrightLight.spark,blaze:lvBrightLight.blaze,surge:lvBrightLight.surge,flame:lvBrightLight.flame,gold:lvBrightLight.gold,textLight:"#2D1B28",textMuted:lovelyColors.gray,isLight:!0},dark:{bg:lovelyColors.black,bgPanel:"#250E1D",bgAlt:"#3D1530",primary:lovelyColors.roseAccent,secondary:lovelyColors.roseBrand,accent:lovelyColors.roseBright,glow:lvBrightDark.glow,pop:lvBrightDark.pop,spark:lvBrightDark.spark,blaze:lvBrightDark.blaze,surge:lvBrightDark.surge,flame:lvBrightDark.flame,gold:lvBrightDark.gold,textLight:"#FCE7F3",textMuted:"#D4A5BD",isLight:!1}},matrix:{light:{bg:"#f0fff0",bgPanel:"#ffffff",bgAlt:matrixColors.greenTint,primary:matrixColors.greenBrand,secondary:matrixColors.greenText,accent:matrixColors.greenAccent,glow:mxBrightLight.glow,pop:mxBrightLight.pop,spark:mxBrightLight.spark,blaze:mxBrightLight.blaze,surge:mxBrightLight.surge,flame:mxBrightLight.flame,gold:mxBrightLight.gold,textLight:"#0A2E1A",textMuted:matrixColors.gray,isLight:!0},dark:{bg:matrixColors.black,bgPanel:"#0A1F0A",bgAlt:"#122812",primary:matrixColors.greenPhosphor,secondary:matrixColors.greenGlow,accent:matrixColors.greenGlow,glow:mxBrightDark.glow,pop:mxBrightDark.pop,spark:mxBrightDark.spark,blaze:mxBrightDark.blaze,surge:mxBrightDark.surge,flame:mxBrightDark.flame,gold:mxBrightDark.gold,textLight:"#C8E6C9",textMuted:"#66BB6A",isLight:!1}},earth:{light:{bg:"#F0F5FA",bgPanel:"#ffffff",bgAlt:earthColors.oceanTint,primary:earthColors.oceanBrand,secondary:earthColors.oceanText,accent:earthColors.oceanAccent,glow:eaBrightLight.glow,pop:eaBrightLight.pop,spark:eaBrightLight.spark,blaze:eaBrightLight.blaze,surge:eaBrightLight.surge,flame:eaBrightLight.flame,gold:eaBrightLight.gold,textLight:"#1A2332",textMuted:earthColors.gray,isLight:!0},dark:{bg:earthColors.black,bgPanel:"#0E1D30",bgAlt:"#132840",primary:earthColors.oceanAccent,secondary:earthColors.oceanBrand,accent:earthColors.oceanBright,glow:eaBrightDark.glow,pop:eaBrightDark.pop,spark:eaBrightDark.spark,blaze:eaBrightDark.blaze,surge:eaBrightDark.surge,flame:eaBrightDark.flame,gold:eaBrightDark.gold,textLight:"#D4E4DC",textMuted:"#8A9BA8",isLight:!1}},sand:{light:{bg:"#FBF7EF",bgPanel:"#ffffff",bgAlt:sandColors.sandTint,primary:sandColors.sandBrand,secondary:sandColors.sandText,accent:sandColors.sandAccent,glow:saBrightLight.glow,pop:saBrightLight.pop,spark:saBrightLight.spark,blaze:saBrightLight.blaze,surge:saBrightLight.surge,flame:saBrightLight.flame,gold:saBrightLight.gold,textLight:"#2B2118",textMuted:sandColors.gray,isLight:!0},dark:{bg:sandColors.black,bgPanel:"#2A2118",bgAlt:"#33281A",primary:sandColors.sandAccent,secondary:sandColors.sandBrand,accent:sandColors.sandBright,glow:saBrightDark.glow,pop:saBrightDark.pop,spark:saBrightDark.spark,blaze:saBrightDark.blaze,surge:saBrightDark.surge,flame:saBrightDark.flame,gold:saBrightDark.gold,textLight:"#EDE3D3",textMuted:"#B7A793",isLight:!1}},ivory:{light:{bg:"#FBF6EC",bgPanel:"#ffffff",bgAlt:ivoryColors.ivoryTint,primary:ivoryColors.ivoryBrand,secondary:ivoryColors.ivoryText,accent:ivoryColors.ivoryAccent,glow:ivBrightLight.glow,pop:ivBrightLight.pop,spark:ivBrightLight.spark,blaze:ivBrightLight.blaze,surge:ivBrightLight.surge,flame:ivBrightLight.flame,gold:ivBrightLight.gold,textLight:"#2C2318",textMuted:ivoryColors.gray,isLight:!0},dark:{bg:ivoryColors.black,bgPanel:"#2A2219",bgAlt:"#33291B",primary:ivoryColors.ivoryAccent,secondary:ivoryColors.ivoryBrand,accent:ivoryColors.ivoryBright,glow:ivBrightDark.glow,pop:ivBrightDark.pop,spark:ivBrightDark.spark,blaze:ivBrightDark.blaze,surge:ivBrightDark.surge,flame:ivBrightDark.flame,gold:ivBrightDark.gold,textLight:"#EFE6D6",textMuted:"#BBAC97",isLight:!1}},sun:{light:{bg:"#FFF9EC",bgPanel:"#ffffff",bgAlt:sunColors.sunTint,primary:sunColors.sunBrand,secondary:sunColors.sunText,accent:sunColors.sunAccent,glow:suBrightLight.glow,pop:suBrightLight.pop,spark:suBrightLight.spark,blaze:suBrightLight.blaze,surge:suBrightLight.surge,flame:suBrightLight.flame,gold:suBrightLight.gold,textLight:"#2A2210",textMuted:sunColors.gray,isLight:!0},dark:{bg:sunColors.black,bgPanel:"#2A2109",bgAlt:"#33290C",primary:sunColors.sunAccent,secondary:sunColors.sunBrand,accent:sunColors.sunBright,glow:suBrightDark.glow,pop:suBrightDark.pop,spark:suBrightDark.spark,blaze:suBrightDark.blaze,surge:suBrightDark.surge,flame:suBrightDark.flame,gold:suBrightDark.gold,textLight:"#F3E9CF",textMuted:"#BEAC82",isLight:!1}},loop:{light:{bg:loopColors.white,bgPanel:"#ffffff",bgAlt:loopColors.subtle,primary:loopColors.loopBrand,secondary:loopColors.loopText,accent:loopColors.loopAccent,glow:loBrightLight.glow,pop:loBrightLight.pop,spark:loBrightLight.spark,blaze:loBrightLight.blaze,surge:loBrightLight.surge,flame:loBrightLight.flame,gold:loBrightLight.gold,textLight:loopColors.ink,textMuted:loopColors.gray,isLight:!0},dark:{bg:loopColors.black,bgPanel:"#19191B",bgAlt:loopColors.subtleDark,primary:loopColors.loopBrand,secondary:loopColors.loopBright,accent:loopColors.loopAccent,glow:loBrightDark.glow,pop:loBrightDark.pop,spark:loBrightDark.spark,blaze:loBrightDark.blaze,surge:loBrightDark.surge,flame:loBrightDark.flame,gold:loBrightDark.gold,textLight:loopColors.inkDark,textMuted:loopColors.grayDark,isLight:!1}}};function getColorPalette(Au="datalayer",lo="auto"){const $u=lo==="auto"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":lo;return palettes[Au]?.[$u]??palettes.datalayer.dark}function useColorPalette(){const{colorMode:Au,theme:lo}=useThemeStore();return getColorPalette(lo,Au)}const SHEET_SHADOW="0 1px 2px rgba(0,0,0,0.06), 0 24px 48px -28px rgba(0,0,0,0.35)";function Sheet(Au){return jsxRuntimeExports.jsx(Box,{bg:"canvas.default",border:"1px solid",borderColor:"border.default",borderRadius:"card",boxShadow:SHEET_SHADOW,...Au})}const sizeMap$2={small:16,medium:32,large:64};function _DlIconInverseColormode$2({mode:Au,children:lo}){const $u=reactExports.useRef(null),[Ru,Iu]=reactExports.useState({mode:typeof Au=="string"?Au:null,lightTheme:null,darkTheme:null});return reactExports.useLayoutEffect(()=>{if(typeof document>"u")return;let Pu=null,Ou=null,Mu=null,Du=$u.current&&$u.current.parentElement;for(;Du&&(!Pu||!Ou||!Mu);)Du.getAttribute&&(Pu=Pu||Du.getAttribute("data-color-mode"),Ou=Ou||Du.getAttribute("data-light-theme"),Mu=Mu||Du.getAttribute("data-dark-theme")),Du=Du.parentElement;(!Pu||Pu==="auto")&&(Pu=typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),Iu({mode:typeof Au=="string"?Au:Pu==="dark"?"light":"dark",lightTheme:Ou,darkTheme:Mu})},[Au]),reactExports.createElement("span",{ref:$u,"data-color-mode":Ru.mode||"light","data-light-theme":Ru.lightTheme||void 0,"data-dark-theme":Ru.darkTheme||void 0,style:{display:"inline-flex",lineHeight:0,color:"var(--fgColor-default, var(--color-fg-default, currentColor))"}},lo)}function AiAgentIcon({title:Au,titleId:lo,size:$u,colored:Ru,themed:Iu,colormode:Pu,...Ou},Mu){const Du=reactExports.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",fill:Iu?"var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor))":"var(--datalayer-icon-color, currentColor)",width:$u?typeof $u=="string"?sizeMap$2[$u]:$u:"16px","aria-hidden":"true",ref:Mu,"aria-labelledby":lo},Ou,{"data-datalayer-icon":"",style:Ou&&Ou.color!=null?Object.assign({},Ou.style,{"--datalayer-icon-color":Ou.color,color:Ou.color}):Ou&&Ou.style}),reactExports.createElement("style",null,'[data-color-mode="light"]{--datalayer-icon-color-scheme:light}[data-color-mode="dark"]{--datalayer-icon-color-scheme:dark}svg[data-datalayer-icon]{color-scheme:var(--datalayer-icon-color-scheme, light dark)}'),Au?reactExports.createElement("title",{id:lo},Au):null,reactExports.createElement("path",{d:"M5.75 7.5a.75.75 0 01.75.75v1.5a.75.75 0 01-1.5 0v-1.5a.75.75 0 01.75-.75zm5.25.75a.75.75 0 00-1.5 0v1.5a.75.75 0 001.5 0v-1.5z"}),reactExports.createElement("path",{d:"M6.25 0h2A.75.75 0 019 .75V3.5h3.25a2.25 2.25 0 012.25 2.25V8h.75a.75.75 0 010 1.5h-.75v2.75a2.25 2.25 0 01-2.25 2.25h-8.5a2.25 2.25 0 01-2.25-2.25V9.5H.75a.75.75 0 010-1.5h.75V5.75A2.25 2.25 0 013.75 3.5H7.5v-2H6.25a.75.75 0 010-1.5zM3 5.75v6.5c0 .414.336.75.75.75h8.5a.75.75 0 00.75-.75v-6.5a.75.75 0 00-.75-.75h-8.5a.75.75 0 00-.75.75z"}));return Pu?reactExports.createElement(_DlIconInverseColormode$2,{mode:typeof Pu=="string"?Pu:void 0},Du):Du}const ForwardRef$2=reactExports.forwardRef(AiAgentIcon),sizeMap$1={small:16,medium:32,large:64};function _DlIconInverseColormode$1({mode:Au,children:lo}){const $u=reactExports.useRef(null),[Ru,Iu]=reactExports.useState({mode:typeof Au=="string"?Au:null,lightTheme:null,darkTheme:null});return reactExports.useLayoutEffect(()=>{if(typeof document>"u")return;let Pu=null,Ou=null,Mu=null,Du=$u.current&&$u.current.parentElement;for(;Du&&(!Pu||!Ou||!Mu);)Du.getAttribute&&(Pu=Pu||Du.getAttribute("data-color-mode"),Ou=Ou||Du.getAttribute("data-light-theme"),Mu=Mu||Du.getAttribute("data-dark-theme")),Du=Du.parentElement;(!Pu||Pu==="auto")&&(Pu=typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),Iu({mode:typeof Au=="string"?Au:Pu==="dark"?"light":"dark",lightTheme:Ou,darkTheme:Mu})},[Au]),reactExports.createElement("span",{ref:$u,"data-color-mode":Ru.mode||"light","data-light-theme":Ru.lightTheme||void 0,"data-dark-theme":Ru.darkTheme||void 0,style:{display:"inline-flex",lineHeight:0,color:"var(--fgColor-default, var(--color-fg-default, currentColor))"}},lo)}function MicrophoneIcon({title:Au,titleId:lo,size:$u,colored:Ru,themed:Iu,colormode:Pu,...Ou},Mu){const Du=reactExports.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 72 72",fill:Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 72%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 62%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 72%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 62%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 72%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",width:$u?typeof $u=="string"?sizeMap$1[$u]:$u:"16px","aria-hidden":"true",ref:Mu,"aria-labelledby":lo},Ou,{"data-datalayer-icon":"",style:Ou&&Ou.color!=null?Object.assign({},Ou.style,{"--datalayer-icon-color":Ou.color,color:Ou.color}):Ou&&Ou.style}),reactExports.createElement("style",null,'[data-color-mode="light"]{--datalayer-icon-color-scheme:light}[data-color-mode="dark"]{--datalayer-icon-color-scheme:dark}svg[data-datalayer-icon]{color-scheme:var(--datalayer-icon-color-scheme, light dark)}'),Au?reactExports.createElement("title",{id:lo},Au):null,reactExports.createElement("path",{fill:Ru?"#3F3F3F":Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 41%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 93%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 41%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 93%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 41%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",d:"M39.4 29.52c-2.636-2.216-2.553-3.52-2.55-3.523-.109-.127-1.758-1.676-1.777-2.156l-.009-.082-2.556 3.283c.324-.446-6.322 10.406-6.322 10.406L14.393 53.686l3.373 3.372S42.18 35.781 41.828 36.161l3.403-3.356c-.107.004-3.193-1.068-5.83-3.284z"}),reactExports.createElement("path",{fill:Ru?"#D0CFCE":Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 71%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 63%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 71%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 63%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 71%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",d:"M54.62 30.18a.998.998 0 01-1.411.093l-16.62-14.58a1 1 0 01-.099-1.4c-.003.003-.007.004-.01.008l-.654.786a1 1 0 00.11 1.391L52.554 31.06a1 1 0 001.427-.113l.655-.787c.04-.047.055-.105.084-.157-.033.06-.054.123-.1.177z"}),reactExports.createElement("path",{fill:Ru?"#3F3F3F":Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 41%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 93%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 41%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 93%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 41%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",d:"M55.258 25.541c-1.162 3.4-5.283 5.562-5.283 5.562-1.926 1.097-4.032 1.62-6.038 1.52 0 0-.347-.081-.913-.272-1.828-.634-5.85-2.485-7.25-6.88-.377-2.002-.159-4.185.646-6.277 1.023-4.264 4.995-6.256 4.995-6.256 1.41-.956 2.94-1.59 4.479-1.871 2.82-.533 5.66.08 7.775 1.972 3.327 2.947 3.844 8.086 1.59 12.502z"}),reactExports.createElement("path",{fill:Ru?"#9B9B9A":Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 55%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 79%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 55%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 79%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 55%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",d:"M51.475 25.541c-1.172 3.4-5.283 5.562-5.283 5.562a12.08 12.08 0 01-3.168 1.247c-1.828-.633-5.85-2.484-7.25-6.88-.377-2.001-.159-4.184.646-6.276 1.022-4.264 4.995-6.256 4.995-6.256 1.41-.956 2.94-1.59 4.479-1.871 1.46.292 2.83.946 3.992 1.972 3.317 2.947 3.833 8.086 1.589 12.502z"}),reactExports.createElement("path",{d:"M30.75 38.941l4.02-4.619m14.744-3.892c-1.804 1.014-3.774 1.495-5.65 1.404m-2.36-18.184c3.737-2.497 8.405-2.591 11.465.093 3.108 2.727 3.59 7.471 1.489 11.545m-18.223-.065c-.354-1.844-.152-3.862.602-5.789m-3.52 8.196L14.393 53.686l3.373 3.373 23.34-21.572M15.497 56.001l-3.046 3.074m41.417-29.554L37.249 14.94",fill:"none",stroke:Ru?"#000":Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 38%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 96%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 38%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 96%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 38%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",strokeLinecap:"round",strokeLinejoin:"round",strokeMiterlimit:10,strokeWidth:2}));return Pu?reactExports.createElement(_DlIconInverseColormode$1,{mode:typeof Pu=="string"?Pu:void 0},Du):Du}const ForwardRef$1=reactExports.forwardRef(MicrophoneIcon),sizeMap={small:16,medium:32,large:64};function _DlIconInverseColormode({mode:Au,children:lo}){const $u=reactExports.useRef(null),[Ru,Iu]=reactExports.useState({mode:typeof Au=="string"?Au:null,lightTheme:null,darkTheme:null});return reactExports.useLayoutEffect(()=>{if(typeof document>"u")return;let Pu=null,Ou=null,Mu=null,Du=$u.current&&$u.current.parentElement;for(;Du&&(!Pu||!Ou||!Mu);)Du.getAttribute&&(Pu=Pu||Du.getAttribute("data-color-mode"),Ou=Ou||Du.getAttribute("data-light-theme"),Mu=Mu||Du.getAttribute("data-dark-theme")),Du=Du.parentElement;(!Pu||Pu==="auto")&&(Pu=typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),Iu({mode:typeof Au=="string"?Au:Pu==="dark"?"light":"dark",lightTheme:Ou,darkTheme:Mu})},[Au]),reactExports.createElement("span",{ref:$u,"data-color-mode":Ru.mode||"light","data-light-theme":Ru.lightTheme||void 0,"data-dark-theme":Ru.darkTheme||void 0,style:{display:"inline-flex",lineHeight:0,color:"var(--fgColor-default, var(--color-fg-default, currentColor))"}},lo)}function PlusCircleIcon({title:Au,titleId:lo,size:$u,colored:Ru,themed:Iu,colormode:Pu,...Ou},Mu){const Du=reactExports.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fillRule:"evenodd",clipRule:"evenodd",width:$u?typeof $u=="string"?sizeMap[$u]:$u:"16px",viewBox:"0 0 24 24",fill:Iu?"var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor))":"var(--datalayer-icon-color, currentColor)","aria-hidden":"true",ref:Mu,"aria-labelledby":lo},Ou,{"data-datalayer-icon":"",style:Ou&&Ou.color!=null?Object.assign({},Ou.style,{"--datalayer-icon-color":Ou.color,color:Ou.color}):Ou&&Ou.style}),reactExports.createElement("style",null,'[data-color-mode="light"]{--datalayer-icon-color-scheme:light}[data-color-mode="dark"]{--datalayer-icon-color-scheme:dark}svg[data-datalayer-icon]{color-scheme:var(--datalayer-icon-color-scheme, light dark)}'),Au?reactExports.createElement("title",{id:lo},Au):null,reactExports.createElement("path",{d:"M11.5 0C17.847 0 23 5.153 23 11.5S17.847 23 11.5 23 0 17.847 0 11.5 5.153 0 11.5 0zm0 1C17.295 1 22 5.705 22 11.5S17.295 22 11.5 22 1 17.295 1 11.5 5.705 1 11.5 1zm.5 10h6v1h-6v6h-1v-6H5v-1h6V5h1v6z"}));return Pu?reactExports.createElement(_DlIconInverseColormode,{mode:typeof Pu=="string"?Pu:void 0},Du):Du}const ForwardRef=reactExports.forwardRef(PlusCircleIcon),__vite_import_meta_env__$2={},createStoreImpl$1=Au=>{let lo;const $u=new Set,Ru=(Bu,ju)=>{const Fu=typeof Bu=="function"?Bu(lo):Bu;if(!Object.is(Fu,lo)){const zu=lo;lo=ju??(typeof Fu!="object"||Fu===null)?Fu:Object.assign({},lo,Fu),$u.forEach(Uu=>Uu(lo,zu))}},Iu=()=>lo,Du={setState:Ru,getState:Iu,getInitialState:()=>Lu,subscribe:Bu=>($u.add(Bu),()=>$u.delete(Bu)),destroy:()=>{(__vite_import_meta_env__$2?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),$u.clear()}},Lu=lo=Au(Ru,Iu,Du);return Du},createStore$1=Au=>Au?createStoreImpl$1(Au):createStoreImpl$1;var withSelector={exports:{}},withSelector_production={},shim={exports:{}},useSyncExternalStoreShim_production={};var hasRequiredUseSyncExternalStoreShim_production;function requireUseSyncExternalStoreShim_production(){if(hasRequiredUseSyncExternalStoreShim_production)return useSyncExternalStoreShim_production;hasRequiredUseSyncExternalStoreShim_production=1;var Au=requireReact();function lo(ju,Fu){return ju===Fu&&(ju!==0||1/ju===1/Fu)||ju!==ju&&Fu!==Fu}var $u=typeof Object.is=="function"?Object.is:lo,Ru=Au.useState,Iu=Au.useEffect,Pu=Au.useLayoutEffect,Ou=Au.useDebugValue;function Mu(ju,Fu){var zu=Fu(),Uu=Ru({inst:{value:zu,getSnapshot:Fu}}),Hu=Uu[0].inst,Vu=Uu[1];return Pu(function(){Hu.value=zu,Hu.getSnapshot=Fu,Du(Hu)&&Vu({inst:Hu})},[ju,zu,Fu]),Iu(function(){return Du(Hu)&&Vu({inst:Hu}),ju(function(){Du(Hu)&&Vu({inst:Hu})})},[ju]),Ou(zu),zu}function Du(ju){var Fu=ju.getSnapshot;ju=ju.value;try{var zu=Fu();return!$u(ju,zu)}catch{return!0}}function Lu(ju,Fu){return Fu()}var Bu=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Lu:Mu;return useSyncExternalStoreShim_production.useSyncExternalStore=Au.useSyncExternalStore!==void 0?Au.useSyncExternalStore:Bu,useSyncExternalStoreShim_production}var hasRequiredShim;function requireShim(){return hasRequiredShim||(hasRequiredShim=1,shim.exports=requireUseSyncExternalStoreShim_production()),shim.exports}var hasRequiredWithSelector_production;function requireWithSelector_production(){if(hasRequiredWithSelector_production)return withSelector_production;hasRequiredWithSelector_production=1;var Au=requireReact(),lo=requireShim();function $u(Lu,Bu){return Lu===Bu&&(Lu!==0||1/Lu===1/Bu)||Lu!==Lu&&Bu!==Bu}var Ru=typeof Object.is=="function"?Object.is:$u,Iu=lo.useSyncExternalStore,Pu=Au.useRef,Ou=Au.useEffect,Mu=Au.useMemo,Du=Au.useDebugValue;return withSelector_production.useSyncExternalStoreWithSelector=function(Lu,Bu,ju,Fu,zu){var Uu=Pu(null);if(Uu.current===null){var Hu={hasValue:!1,value:null};Uu.current=Hu}else Hu=Uu.current;Uu=Mu(function(){function Gu(Xu){if(!Wu){if(Wu=!0,Ku=Xu,Xu=Fu(Xu),zu!==void 0&&Hu.hasValue){var ed=Hu.value;if(zu(ed,Xu))return Ju=ed}return Ju=Xu}if(ed=Ju,Ru(Ku,Xu))return ed;var td=Fu(Xu);return zu!==void 0&&zu(ed,td)?(Ku=Xu,ed):(Ku=Xu,Ju=td)}var Wu=!1,Ku,Ju,Yu=ju===void 0?null:ju;return[function(){return Gu(Bu())},Yu===null?void 0:function(){return Gu(Yu())}]},[Bu,ju,Fu,zu]);var Vu=Iu(Lu,Uu[0],Uu[1]);return Ou(function(){Hu.hasValue=!0,Hu.value=Vu},[Vu]),Du(Vu),Vu},withSelector_production}var hasRequiredWithSelector;function requireWithSelector(){return hasRequiredWithSelector||(hasRequiredWithSelector=1,withSelector.exports=requireWithSelector_production()),withSelector.exports}var withSelectorExports=requireWithSelector();const useSyncExternalStoreExports=getDefaultExportFromCjs(withSelectorExports),__vite_import_meta_env__$1={},{useDebugValue}=vM,{useSyncExternalStoreWithSelector}=useSyncExternalStoreExports;let didWarnAboutEqualityFn=!1;const identity$1=Au=>Au;function useStore$1(Au,lo=identity$1,$u){(__vite_import_meta_env__$1?"production":void 0)!=="production"&&$u&&!didWarnAboutEqualityFn&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),didWarnAboutEqualityFn=!0);const Ru=useSyncExternalStoreWithSelector(Au.subscribe,Au.getState,Au.getServerState||Au.getInitialState,lo,$u);return useDebugValue(Ru),Ru}const createImpl$1=Au=>{(__vite_import_meta_env__$1?"production":void 0)!=="production"&&typeof Au!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const lo=typeof Au=="function"?createStore$1(Au):Au,$u=(Ru,Iu)=>useStore$1(lo,Ru,Iu);return Object.assign($u,lo),$u},create$g=Au=>Au?createImpl$1(Au):createImpl$1,CONTROL_PLANE_URL="https://prod1.datalayer.run",RUNTIMES_PLANE_URL="https://r1.datalayer.run",MCP_SERVER_URL="https://mcp.datalayer.run/mcp",DEFAULT_PLANE_URLS={iamUrl:CONTROL_PLANE_URL,managerUrl:CONTROL_PLANE_URL,libraryUrl:CONTROL_PLANE_URL,spacerUrl:CONTROL_PLANE_URL,otelUrl:CONTROL_PLANE_URL,growthUrl:CONTROL_PLANE_URL,inboundsUrl:CONTROL_PLANE_URL,successUrl:CONTROL_PLANE_URL,supportUrl:CONTROL_PLANE_URL,contentsUrl:RUNTIMES_PLANE_URL,runtimesUrl:RUNTIMES_PLANE_URL,schedulerUrl:RUNTIMES_PLANE_URL,aiAgentsUrl:RUNTIMES_PLANE_URL,aiInferenceUrl:RUNTIMES_PLANE_URL,datalayerMcpServerUrl:MCP_SERVER_URL};class Logger{scope;isDevelopment;constructor(lo){this.scope=lo,this.isDevelopment=!1}log(lo,$u,...Ru){if(!this.isDevelopment&&lo==="debug")return;const Pu=`[${new Date().toISOString()}] [${this.scope}] [${lo.toUpperCase()}]`;switch(lo){case"debug":console.debug(Pu,$u,...Ru);break;case"info":console.info(Pu,$u,...Ru);break;case"warn":console.warn(Pu,$u,...Ru);break;case"error":console.error(Pu,$u,...Ru);break}}debug(lo,...$u){this.log("debug",lo,...$u)}info(lo,...$u){this.log("info",lo,...$u)}warn(lo,...$u){this.log("warn",lo,...$u)}error(lo,...$u){this.log("error",lo,...$u)}}function createLogger(Au){return new Logger(Au)}const configLogger=createLogger("config");let loadConfigurationFromServer=!0,initialConfiguration={token:"",credits:0,cpuEnvironment:'ai-agents-env"',gpuEnvironment:"ai-env",useMock:!1,whiteLabel:!0,loadConfigurationFromServer:!0,jupyterServerless:!1,...DEFAULT_PLANE_URLS,launcher:{category:"Datalayer",name:"Datalayer",icon:null,rank:1},brand:{name:"Datalayer",about:"AI Agents for Data Analysis",logoUrl:"https://assets.datalayer.tech/datalayer-25.svg",logoSquareUrl:"https://assets.datalayer.tech/datalayer-square.png",copyright:"© 2025 Datalayer, Inc",docsUrl:"https://datalayer.ai/docs",supportUrl:"https://datalayer.ai/support",termsUrl:"https://datalayer.ai/terms",pricingUrl:"https://datalayer.ai/pricing",privacyUrl:"https://datalayer.ai/privacy"}};const pageConfiguration={};try{if(typeof document<"u"){const Au=document.getElementById("datalayer-config-data");if(Au?.innerText){const lo=JSON.parse(Au?.innerText||"{}");Object.assign(pageConfiguration,lo),lo.loadConfigurationFromServer!=null&&(loadConfigurationFromServer=lo.loadConfigurationFromServer),initialConfiguration={...initialConfiguration,...lo},configLogger.info("Datalayer configuration loaded from HTML page",initialConfiguration),window.document.title=`${initialConfiguration.brand.name} ☰ ${initialConfiguration.brand.about}`}}}catch(Au){configLogger.debug("No valid configuration found in the webpage.",Au)}const coreStore=createStore$1((Au,lo)=>({tab:0,getIntTab:()=>Math.floor(lo().tab),setTab:$u=>Au(Ru=>({tab:$u})),configuration:initialConfiguration,setConfiguration:$u=>{configLogger.debug("Setting Datalayer configuration",$u),Au(Ru=>({configuration:{...Ru.configuration,...$u}}))},version:"",setVersion:$u=>{$u&&!lo().version&&Au(Ru=>({version:$u}))},loadConfigurationFromServer,setLoadConfigurationFromServer:$u=>{Au(Ru=>({loadConfigurationFromServer:$u}))}}));function useCoreStore(Au){return useStore$1(coreStore,Au)}const getOtelConsumeUrl=()=>coreStore.getState().configuration.otelUrl,BACKEND_TOOL_ACTIONS={"create-plan":["read"],"current-time":["read"],decide:["read"],"display-recipe":["read"],"example-create-plan":["read"],"example-current-time":["read"],"example-display-recipe":["read"],"example-generate-haiku":["read"],"example-generate-task-steps":["read"],"example-get-weather":["read"],"example-render-a2ui-surface":["read"],"example-update-plan-step":["read"],"generate-haiku":["read"],"generate-task-steps":["read"],"get-weather":["read"],"runtime-echo":["read"],"runtime-send-mail":["send"],"runtime-sensitive-echo":["read"],"update-plan-step":["read"]},SERVER_ACTIONS={alphavantage:{default:[],tools:{},conditions:{},signs:{}},chart:{checked:"2026-10-02",default:[],tools:{generate_area_chart:["read"],generate_bar_chart:["read"],generate_boxplot_chart:["read"],generate_column_chart:["read"],generate_district_map:["read"],generate_dual_axes_chart:["read"],generate_fishbone_diagram:["read"],generate_flow_diagram:["read"],generate_funnel_chart:["read"],generate_histogram_chart:["read"],generate_line_chart:["read"],generate_liquid_chart:["read"],generate_mind_map:["read"],generate_network_graph:["read"],generate_organization_chart:["read"],generate_path_map:["read"],generate_pie_chart:["read"],generate_pin_map:["read"],generate_radar_chart:["read"],generate_sankey_chart:["read"],generate_scatter_chart:["read"],generate_treemap_chart:["read"],generate_venn_chart:["read"],generate_violin_chart:["read"],generate_waterfall_chart:["read"],generate_word_cloud_chart:["read"],generate_spreadsheet:["read"]},conditions:{},signs:{}},datalayer:{checked:"2026-10-05",default:[],tools:{read_notebook:["read"],read_cell:["read"],download_notebook:["read"],list_notebooks:["read"],list_spaces:["read"],list_space_notebooks:["read"],find_notebook:["read"],list_notebook_versions:["read"],list_kernels:["read"],list_files:["read"],list_sandboxes:["read"],list_toolsets:["read"],search_library:["read"],get_library_artifact:["read"],read_library_artifact:["read"],search_earth_datasets:["read"],search_earth_datagranules:["read"],download_earth_data_granules:["read"],odoo_get_context:["read"],odoo_get_account:["read"],odoo_get_settings:["read"],odoo_list_companies:["read"],odoo_set_company:["write"],odoo_list_models:["read"],odoo_get_fields:["read"],odoo_search_records:["read"],odoo_read_records:["read"],odoo_group_records:["read"],odoo_create_record:["write"],odoo_update_records:["write"],odoo_delete_records:["delete"],odoo_accounting_list_invoices:["read"],odoo_accounting_get_invoice:["read"],odoo_accounting_list_journal_entries:["read"],odoo_accounting_list_open_balances:["read"],odoo_accounting_list_accounts:["read"],odoo_accounting_list_journals:["read"],odoo_accounting_get_journal_entry:["read"],odoo_accounting_trial_balance:["read"],odoo_accounting_general_ledger:["read"],odoo_winauditor_preview_balance:["read"],odoo_winauditor_preview_general_journal:["read"],odoo_winauditor_preview_general_ledger:["read"],odoo_accounting_create_draft_invoice:["write"],odoo_accounting_post_invoice:["write"],odoo_accounting_create_draft_journal_entry:["write"],odoo_accounting_post_journal_entry:["write"],odoo_winauditor_import_balance:["write"],odoo_winauditor_import_general_journal:["write"],odoo_winauditor_import_general_ledger:["write"],odoo_winauditor_preview_import_file:["read"],odoo_winauditor_migration_status:["read"],odoo_winauditor_import_partners:["write"],odoo_winauditor_import_chart_of_accounts:["write"],odoo_winauditor_ensure_journals:["write"],odoo_winauditor_import_journal_items:["write"],odoo_winauditor_post_migration_entries:["write"],odoo_winauditor_reconcile_journal_items:["write"],odoo_winauditor_import_assets:["write"],odoo_winauditor_validate_assets:["write"],odoo_winauditor_rollback_migration:["delete"],odoo_winauditor_attach_document:["write"],odoo_winauditor_list_attachments:["read"],odoo_winauditor_validate_migration:["read"],odoo_accounting_list_partners:["read"],odoo_accounting_partner_ledger:["read"],odoo_accounting_aged_balance:["read"],odoo_accounting_list_taxes:["read"],odoo_accounting_list_assets:["read"],odoo_accounting_get_asset:["read"],odoo_accounting_reconcile_lines:["write"],odoo_accounting_unreconcile_lines:["write"],odoo_accounting_bank_status:["read"],odoo_accounting_list_bank_lines:["read"],odoo_accounting_get_bank_line:["read"],odoo_accounting_suggest_bank_matches:["read"],odoo_accounting_suggest_reconciliations:["read"],odoo_accounting_explain_account_balance:["read"],odoo_accounting_list_bank_feeds:["read"],odoo_accounting_list_currency_rates:["read"],odoo_accounting_get_lock_dates:["read"],odoo_accounting_book_bank_line:["write"],odoo_accounting_match_bank_line:["write"],odoo_accounting_reset_bank_line:["write"],odoo_accounting_remove_duplicate_bank_lines:["delete"],odoo_accounting_link_bank_feed:["write"],odoo_accounting_create_vendor_bill:["write"],odoo_accounting_create_customer_invoice:["write"],odoo_accounting_set_currency_rates:["write"],odoo_accounting_set_lock_date:["write"],odoo_accounting_create_matching_model:["write"],odoo_accounting_get_tax_settings:["read"],odoo_accounting_list_tax_returns:["read"],odoo_accounting_get_tax_return:["read"],odoo_accounting_tax_grids:["read"],odoo_accounting_list_tax_grid_lines:["read"],odoo_accounting_check_tax_period:["read"],odoo_accounting_list_untagged_tax_lines:["read"],odoo_accounting_set_tax_periodicity:["write"],odoo_accounting_set_tax_grids:["write"],read_benchmark:["read"],read_benchmark_task:["read"],read_benchmark_task_trajectory:["read"],list_benchmark_task_files:["read"],list_content_sources:["read"],describe_content_source:["read"],list_content_attachments:["read"],list_dataset_revisions:["read"],query_status:["read"],list_secrets:["read"],use_notebook:["read"],unuse_notebook:["read"],connect_to_jupyter:["read"],insert_cell:["write"],delete_cell:["delete"],move_cell:["write"],edit_cell_source:["write"],snapshot_notebook:["write"],restore_notebook:["write"],overwrite_cell_source:["write"],clear_cell_output:["write"],execute_cell:["write"],execute_code:["write"],restart_notebook:["write"],insert_execute_code_cell:["write"],launch_sandbox:["buy"],use_sandbox:["write"],terminate_sandbox:["delete"],snapshot_sandbox:["write","buy"],share_sandbox:["publish"],unshare_sandbox:["write"],marimo_run_cell:["write"],marimo_run_code:["write"],marimo_remove_cell:["delete"],marimo_plan:["read"],marimo_graph:["read"],enable_toolset:["write"],disable_toolset:["write"],attach_content:["write"],detach_content:["write"],query_source:["read"],cancel_query:["write"],save_query_as_revision:["write"],mount_local_folder:["read"]},conditions:{},signs:{}},earthdata:{checked:"2026-10-07",default:[],tools:{search_earth_datasets:["read"],search_earth_datagranules:["read"],download_earth_data_granules:["write"]},conditions:{},signs:{}},eurus:{default:[],tools:{},conditions:{},signs:{}},filesystem:{checked:"2026-10-02",default:[],tools:{read_file:["read"],read_text_file:["read"],read_media_file:["read"],read_multiple_files:["read"],write_file:["write"],edit_file:["write"],create_directory:["write"],list_directory:["read"],list_directory_with_sizes:["read"],directory_tree:["read"],move_file:["write","delete"],search_files:["read"],get_file_info:["read"],list_allowed_directories:["read"]},conditions:{},signs:{}},github:{default:[],tools:{},conditions:{},signs:{}},"google-workspace":{checked:"2026-10-02",default:[],tools:{start_google_auth:["write"],search_gmail_messages:["read"],get_gmail_message_content:["read"],get_gmail_messages_content_batch:["read"],get_gmail_attachment_content:["read","write"],send_gmail_message:["send"],draft_gmail_message:["write"],get_gmail_thread_content:["read"],get_gmail_threads_content_batch:["read"],list_gmail_labels:["read"],manage_gmail_label:["write"],list_gmail_filters:["read"],manage_gmail_filter:["write","send"],modify_gmail_message_labels:["write"],batch_modify_gmail_message_labels:["write"],search_drive_files:["read"],get_drive_file_content:["read"],get_drive_file_download_url:["read"],list_drive_items:["read"],create_drive_folder:["write"],create_drive_file:["write"],import_to_google_doc:["write"],import_to_google_slides:["write"],import_to_google_sheets:["write"],get_drive_file_permissions:["read"],check_drive_file_public_access:["read"],update_drive_file:["write"],get_drive_shareable_link:["read"],manage_drive_access:["publish","send","delete"],copy_drive_file:["write"],set_drive_file_permissions:["publish","write"],list_calendars:["read"],get_events:["read"],manage_event:["write","send"],manage_out_of_office:["write","send"],manage_focus_time:["write","send"],query_freebusy:["read"],create_calendar:["write"],search_docs:["read"],get_doc_content:["read"],list_docs_in_folder:["read"],create_doc:["write"],modify_doc_text:["write"],find_and_replace_doc:["write"],insert_doc_elements:["write"],insert_doc_image:["write"],update_doc_headers_footers:["write"],batch_update_doc:["write","delete"],inspect_doc_structure:["read"],debug_docs_runtime_info:["read"],create_table_with_data:["write"],debug_table_structure:["read"],export_doc_to_pdf:["write"],update_paragraph_style:["write"],get_doc_as_markdown:["read"],manage_doc_tab:["write"],list_document_comments:["read"],manage_document_comment:["write","send"],list_spreadsheets:["read"],get_spreadsheet_info:["read"],read_sheet_values:["read"],modify_sheet_values:["write"],format_sheet_range:["write"],manage_conditional_formatting:["write"],create_spreadsheet:["write"],create_sheet:["write"],list_sheet_tables:["read"],append_table_rows:["write"],manage_sheet_tab:["write"],resize_sheet_dimensions:["write","delete"],move_sheet_rows:["write","delete"],manage_named_range:["write"],list_spreadsheet_comments:["read"],manage_spreadsheet_comment:["write","send"],list_spaces:["read"],get_messages:["read"],send_message:["send","write"],search_messages:["read"],create_reaction:["send"],download_chat_attachment:["read","write"],create_form:["write"],get_form:["read"],set_publish_settings:["publish"],get_form_response:["read"],list_form_responses:["read"],batch_update_form:["write","delete"],create_presentation:["write"],get_presentation:["read"],batch_update_presentation:["write","delete"],get_page:["read"],get_page_thumbnail:["read"],list_presentation_comments:["read"],manage_presentation_comment:["write","send"],list_task_lists:["read"],get_task_list:["read"],manage_task_list:["write"],list_tasks:["read"],get_task:["read"],manage_task:["write"],list_contacts:["read"],get_contact:["read"],search_contacts:["read"],manage_contact:["write"],list_contact_groups:["read"],get_contact_group:["read"],manage_contacts_batch:["write"],manage_contact_group:["write"],search_custom:["read"],get_search_engine_info:["read"],get_script_project:["read"],manage_script_content:["write","delete"],run_script_function:["write","send","delete","publish"],manage_deployment:["publish"],list_script_deployments:["read"],manage_script_project:["write"],manage_script_version:["write"],get_script_version:["read"],get_script_activity:["read"],generate_trigger_code:["read"],manage_script_trigger:["write"]},conditions:{manage_gmail_label:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_gmail_filter:[{argument:"action",classes:["delete"],equals:["delete","update"]}],modify_gmail_message_labels:[{argument:"add_label_ids",classes:["delete"],includes:["TRASH","SPAM"]}],batch_modify_gmail_message_labels:[{argument:"add_label_ids",classes:["delete"],includes:["TRASH","SPAM"]}],update_drive_file:[{argument:"trashed",classes:["delete"],equals:[!0]}],manage_event:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_out_of_office:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_focus_time:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_doc_tab:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_conditional_formatting:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_sheet_tab:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_named_range:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_task_list:[{argument:"action",classes:["delete"],equals:["delete","clear_completed"]}],manage_task:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_contact:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_contacts_batch:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_contact_group:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_deployment:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_script_project:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_script_trigger:[{argument:"action",classes:["delete"],equals:["delete"]}]},signs:{send_gmail_message:"body",draft_gmail_message:"body",send_message:"message_text"}},huggingface:{default:[],tools:{},conditions:{},signs:{}},kaggle:{default:[],tools:{},conditions:{},signs:{}},odoo:{default:[],tools:{},conditions:{},signs:{}},"odoo-accounting":{checked:"2026-10-05",default:[],tools:{odoo_accounting_list_invoices:["read"],odoo_accounting_get_invoice:["read"],odoo_accounting_list_journal_entries:["read"],odoo_accounting_list_open_balances:["read"],odoo_accounting_list_accounts:["read"],odoo_accounting_list_journals:["read"],odoo_accounting_get_journal_entry:["read"],odoo_accounting_trial_balance:["read"],odoo_accounting_general_ledger:["read"],odoo_accounting_create_draft_invoice:["write"],odoo_accounting_post_invoice:["write"],odoo_accounting_create_draft_journal_entry:["write"],odoo_accounting_post_journal_entry:["write"],odoo_accounting_list_partners:["read"],odoo_accounting_partner_ledger:["read"],odoo_accounting_aged_balance:["read"],odoo_accounting_list_taxes:["read"],odoo_accounting_list_assets:["read"],odoo_accounting_get_asset:["read"],odoo_accounting_reconcile_lines:["write"],odoo_accounting_unreconcile_lines:["write"],odoo_accounting_bank_status:["read"],odoo_accounting_list_bank_lines:["read"],odoo_accounting_get_bank_line:["read"],odoo_accounting_suggest_bank_matches:["read"],odoo_accounting_suggest_reconciliations:["read"],odoo_accounting_explain_account_balance:["read"],odoo_accounting_list_bank_feeds:["read"],odoo_accounting_list_currency_rates:["read"],odoo_accounting_get_lock_dates:["read"],odoo_accounting_book_bank_line:["write"],odoo_accounting_match_bank_line:["write"],odoo_accounting_reset_bank_line:["write"],odoo_accounting_remove_duplicate_bank_lines:["delete"],odoo_accounting_link_bank_feed:["write"],odoo_accounting_create_vendor_bill:["write"],odoo_accounting_create_customer_invoice:["write"],odoo_accounting_set_currency_rates:["write"],odoo_accounting_set_lock_date:["write"],odoo_accounting_create_matching_model:["write"],odoo_accounting_get_tax_settings:["read"],odoo_accounting_list_tax_returns:["read"],odoo_accounting_get_tax_return:["read"],odoo_accounting_tax_grids:["read"],odoo_accounting_list_tax_grid_lines:["read"],odoo_accounting_check_tax_period:["read"],odoo_accounting_list_untagged_tax_lines:["read"],odoo_accounting_set_tax_periodicity:["write"],odoo_accounting_set_tax_grids:["write"]},conditions:{},signs:{}},salesforce:{default:[],tools:{},conditions:{},signs:{}},slack:{checked:"2026-10-02",default:[],tools:{slack_list_channels:["read"],slack_post_message:["send"],slack_reply_to_thread:["send"],slack_add_reaction:["send"],slack_get_channel_history:["read"],slack_get_thread_replies:["read"],slack_get_users:["read"],slack_get_user_profile:["read"]},conditions:{},signs:{slack_post_message:"text",slack_reply_to_thread:"text"}},tavily:{checked:"2026-10-02",default:[],tools:{tavily_search:["read"],tavily_extract:["read"],tavily_crawl:["read"],tavily_map:["read"],tavily_research:["read"]},conditions:{},signs:{}}},BEHAVIOURS=["do_it","if_asked","ask_first","leave_to_me"],DEFAULT_BEHAVIOURS={read:"do_it",write:"ask_first",send:"ask_first",buy:"ask_first",delete:"ask_first",publish:"ask_first"},SERVER_TOOL=/^([A-Za-z0-9_-]+)(?::\d+(?:\.\d+)*)?\.([A-Za-z_][A-Za-z0-9_-]*)$/,own$a=(Au,lo)=>Object.prototype.hasOwnProperty.call(Au,lo)?Au[lo]:void 0,idOf=Au=>{const lo=Au.lastIndexOf(":");return lo>0&&Au.slice(lo+1).includes(".")?Au.slice(0,lo):Au};function splitRef(Au){const lo=SERVER_TOOL.exec(Au);return lo?[lo[1],lo[2]]:[void 0,idOf(Au)]}const isPattern=Au=>/[*?]/.test(Au);function matchesPattern(Au,lo){const $u=Array.from(lo,Ru=>Ru==="*"?"[\\s\\S]*":Ru==="?"?"[\\s\\S]":Ru.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("");return new RegExp(`^${$u}$`).test(Au)}const isComparable=Au=>typeof Au=="string"||typeof Au=="boolean"||typeof Au=="number"&&Number.isFinite(Au)&&(!Number.isInteger(Au)||Number.isSafeInteger(Au)),same=(Au,lo)=>typeof Au=="string"&&typeof lo=="string"?Au.trim().toLowerCase()===lo.trim().toLowerCase():isComparable(Au)&&isComparable(lo)&&Au===lo;function conditionHolds(Au,lo){if(!Object.prototype.hasOwnProperty.call(lo,Au.argument))return!1;const $u=lo[Au.argument];return Au.equals?.some(Ru=>same($u,Ru))?!0:Au.includes?.length?(Array.isArray($u)?$u:[$u]).some(Iu=>Au.includes.some(Pu=>same(Iu,Pu))):!1}function entryOf$1(Au,lo){const $u=own$a(SERVER_ACTIONS,Au);if(!$u)return[[],[]];const Ru=own$a($u.tools,lo);if(Ru)return[[...Ru],own$a($u.conditions,lo)??[]];for(const[Iu,Pu]of Object.entries($u.tools))if(isPattern(Iu)&&matchesPattern(lo,Iu))return[[...Pu],own$a($u.conditions,Iu)??[]];return[[...$u.default],[]]}const FORWARDING={"google-workspace.send_gmail_message":{message:"forward_message_id",mailbox:"user_google_email",recipients:["to","cc","bcc"]}};function addresses(Au){return(Array.isArray(Au)?Au:[Au]).filter($u=>typeof $u=="string").flatMap($u=>$u.split(",")).map($u=>{const Ru=/<([^>]*)>/.exec($u);return(Ru?Ru[1]:$u).trim().toLowerCase()}).filter($u=>$u.includes("@"))}const domainOf=Au=>Au.slice(Au.lastIndexOf("@")+1).trim();function forwardsOutside(Au,lo,$u){const Ru=own$a(FORWARDING,`${Au}.${lo}`),Iu=Ru?$u[Ru.message]:void 0;if(!Ru||typeof Iu!="string"||!Iu.trim())return!1;const[Pu]=addresses($u[Ru.mailbox]);return Pu?Ru.recipients.flatMap(Ou=>addresses($u[Ou])).some(Ou=>domainOf(Ou)!==domainOf(Pu)):!0}function classesOf(Au,lo){const[$u,Ru]=splitRef(Au);if($u===void 0)return[...own$a(BACKEND_TOOL_ACTIONS,Ru)??[]];const[Iu,Pu]=entryOf$1($u,Ru);for(const Ou of Pu)if(lo===void 0||conditionHolds(Ou,lo))for(const Mu of Ou.classes)Iu.includes(Mu)||Iu.push(Mu);return lo!==void 0&&Iu.length>0&&!Iu.includes("publish")&&forwardsOutside($u,Ru,lo)&&Iu.push("publish"),Iu}const strictest=Au=>Au.reduce((lo,$u)=>BEHAVIOURS.indexOf($u)>BEHAVIOURS.indexOf(lo)?$u:lo),connectionTo=(Au,lo)=>Au.connections.find($u=>idOf($u.server)===lo),reaches=(Au,lo)=>Au.only.length===0||Au.only.some($u=>matchesPattern(lo,$u)),isClass$1=Au=>Object.prototype.hasOwnProperty.call(DEFAULT_BEHAVIOURS,Au),normal=Au=>{if(isClass$1(Au))return Au;const[lo,$u]=splitRef(Au);return lo!==void 0?`${lo}.${$u}`:$u},byClasses=(Au,lo)=>{const $u={};for(const Ru of Au.rules)for(const Iu of Ru.appliesTo)isClass$1(Iu)&&($u[Iu]=Ru.behaviour);return lo.map(Ru=>$u[Ru]??DEFAULT_BEHAVIOURS[Ru])};function behaviourFor(Au,lo,$u={}){const[Ru,Iu]=splitRef(lo);let Pu,Ou=[],Mu;if($u.classes?Pu=Mu=[...$u.classes]:(Mu=classesOf(lo),Pu=classesOf(lo,{}),Ou=($u.arguments===void 0?Mu:classesOf(lo,$u.arguments)).filter(Bu=>!Pu.includes(Bu))),Ru!==void 0){const Lu=connectionTo(Au,Ru);if(!Lu||!reaches(Lu,Iu)||Lu.access==="read"&&Mu.some(Bu=>Bu!=="read"))return"leave_to_me"}const Du=Ru!==void 0?`${Ru}.${Iu}`:Iu;for(const Lu of Au.rules)if(Lu.appliesTo.some(Bu=>!isClass$1(Bu)&&normal(Bu)===Du))return strictest([Lu.behaviour,...byClasses(Au,Ou)]);return Pu.length===0&&Ou.length===0?"leave_to_me":strictest(byClasses(Au,[...Pu,...Ou]))}const BEHAVIOUR_WORDS={do_it:{says:"Do it",means:"It does it without asking."},if_asked:{says:"Do it if I asked",means:"Only what you approved in advance."},ask_first:{says:"Ask me first",means:"It waits for your yes."},leave_to_me:{says:"Leave it to me",means:"It never does it, and hands it to you."}},ACTION_WORDS={read:"Read",write:"Create or change",send:"Send",buy:"Buy",delete:"Delete",publish:"Share or publish"};function coverOf(Au){const lo=own$a(ACTION_WORDS,Au);if(lo)return lo;const[$u,Ru]=splitRef(Au);return $u?`${Ru} (${$u})`:Ru}const A2A_PROTOCOL_0_0_1={id:"a2a",version:"0.0.1",name:"Agent2Agent",description:"How agents talk to agents: teams and scenes talk over it, an application's route serves it, and its Agent Card advertises its extensions.",publisher:"Google, now the Linux Foundation",layer:"transport",specUrl:"https://a2a-protocol.org",specVersion:"1.0",status:"shipped",connects:"Other agents, each at its address with its Agent Card",packages:{python:["fasta2a","a2a-sdk"],typescript:["@a2a-js/sdk"]},protocolTools:[],appspecBlock:"a2a"},A2UI_PROTOCOL_0_0_1={id:"a2ui",version:"0.0.1",name:"A2UI",description:"How an agent's answer becomes an interface: components the host renders from a declarative surface.",publisher:"Google",layer:"ui",specUrl:"https://a2ui.org",specVersion:"0.9",status:"shipped",connects:"The person, through components an answer draws",packages:{python:["agent-runtimes"],typescript:["@a2ui/react","@a2ui/web_core"]},protocolTools:[]},ACP_PROTOCOL_0_0_1={id:"acp",version:"0.0.1",name:"Agentic Commerce Protocol",description:"Checkout sessions at a seller, completed with a payment the model never sees. In applications at test merchants only, with no real payment token (decided 2026-10-13): each purchase asked of the person first, made at most once.",publisher:"OpenAI, Stripe",layer:"commerce",specUrl:"https://github.com/agentic-commerce-protocol/agentic-commerce-protocol",specVersion:"2026-04-17",status:"shipped",connects:"Sellers, to check out with a delegated payment",packages:{python:["agent-runtimes"],typescript:["@datalayer/agent-runtimes"]},protocolTools:["agentic-commerce"]},AG_UI_PROTOCOL_0_0_1={id:"ag-ui",version:"0.0.1",name:"AG-UI",description:"How an agent streams its run to a page: messages, tool calls and state as events.",publisher:"CopilotKit",layer:"ui",specUrl:"https://docs.ag-ui.com",specVersion:"0.0.57 (@ag-ui/core)",status:"shipped",connects:"The page a person talks to the agent on",packages:{python:["ag-ui-protocol"],typescript:["@ag-ui/client","@ag-ui/core"]},protocolTools:[]},MCP_PROTOCOL_0_0_1={id:"mcp",version:"0.0.1",name:"Model Context Protocol",description:"How an agent calls tools and reads resources: clients and servers in both languages, and the MCP gateway every connection goes through.",publisher:"Anthropic",layer:"transport",specUrl:"https://modelcontextprotocol.io/specification",specVersion:"2026-07-28 (Python), 2025-11-25 (TypeScript)",status:"shipped",connects:"Tools, resources and prompts served by MCP servers",packages:{python:["mcp"],typescript:["@modelcontextprotocol/sdk","@mcp-ui/client"]},protocolTools:[]},PACT_PROTOCOL_0_0_1={id:"pact",version:"0.0.1",name:"Personal Agent Consent & Trust",description:"A personal agent asking a business's agent over A2A, first as itself, then for a person who delegated some of their permissions.",publisher:"Decagon, Instinct",layer:"consent",specUrl:"https://openpactprotocol.org",specVersion:"1.0",status:"shipped",connects:"Businesses' agents, asked for a person with their delegation",packages:{python:["agent-runtimes"],typescript:["@datalayer/agent-runtimes"]},protocolTools:["pact"],appspecBlock:"pact"},PAP_PROTOCOL_0_0_1={id:"pap",version:"0.0.1",name:"Personal Agent Protocol",description:"A person's agent working with a company for them — signed out, then signed in at the company, its changes confirmed by the person — and an application being a company personal agents reach.",publisher:"Sierra, Meta",layer:"consent",specUrl:"https://personalagentprotocol.org",specVersion:"draft 0.2",status:"shipped",connects:"Companies, as a person's agent there, or being one",packages:{python:["personal-agent-protocol"],typescript:["@datalayer/personal-agent-protocol"]},protocolTools:["pap"],appspecBlock:"pap"},TAP_PROTOCOL_0_0_1={id:"tap",version:"0.0.1",name:"Trusted Agent Protocol",description:"An agent-recognition profile over Web Bot Auth for merchants: a signature tagged agent-browser-auth to browse or agent-payer-auth to pay. Still a draft profile, built from Visa's public Merchant Specifications (2026-10-13) until Visa confirms it. In applications at test merchants only (decided 2026-10-14): the MCP gateway signs each UCP or ACP purchase with agent-payer-auth under the application's own key, and the test merchants verify it; browsing stays Web Bot Auth.",publisher:"Visa",layer:"identity",specUrl:"https://developer.visa.com/capabilities/trusted-agent-protocol/trusted-agent-protocol-specifications",specVersion:"draft (Merchant Specifications, read 2026-10-13)",status:"shipped",connects:"Merchants that recognise an agent by its signature",packages:{python:["agent-runtimes"],typescript:["@datalayer/agent-runtimes","http-message-sig"]},protocolTools:[]},UCP_PROTOCOL_0_0_1={id:"ucp",version:"0.0.1",name:"Universal Commerce Protocol",description:"Shopping at a merchant: catalogue, checkout and orders, every purchase an exact proposal the person approves. In applications at test merchants only, with no real payment (decided 2026-10-13): each purchase asked of the person first, made at most once.",publisher:"Google, with Shopify and retailers",layer:"commerce",specUrl:"https://github.com/Universal-Commerce-Protocol/ucp",specVersion:"2026-08-25",status:"shipped",connects:"Merchants, to search, check out and follow orders",packages:{python:["ucp-sdk","agent-runtimes"],typescript:["@ucp-js/sdk","@datalayer/agent-runtimes"]},protocolTools:["ucp"]},WEB_BOT_AUTH_PROTOCOL_0_0_1={id:"web-bot-auth",version:"0.0.1",name:"Web Bot Auth",description:"Signed outbound requests (RFC 9421) and the key directory a website checks them against. In applications, every request to a company, business or merchant is signed, and a signed fetch reads pages at the sites an application names, GET only (decided 2026-10-13).",publisher:"Cloudflare (IETF draft)",layer:"identity",specUrl:"https://datatracker.ietf.org/doc/draft-ietf-webbotauth-httpsig-protocol/",specVersion:"draft-ietf-webbotauth-httpsig-protocol-00",status:"shipped",connects:"Websites, which can tell the application's requests from someone pretending",packages:{python:["agent-runtimes"],typescript:["@datalayer/agent-runtimes","web-bot-auth"]},protocolTools:["signed-fetch"],appspecBlock:"signed_fetch"},PROTOCOL_CATALOGUE={a2a:A2A_PROTOCOL_0_0_1,a2ui:A2UI_PROTOCOL_0_0_1,acp:ACP_PROTOCOL_0_0_1,"ag-ui":AG_UI_PROTOCOL_0_0_1,mcp:MCP_PROTOCOL_0_0_1,pact:PACT_PROTOCOL_0_0_1,pap:PAP_PROTOCOL_0_0_1,tap:TAP_PROTOCOL_0_0_1,ucp:UCP_PROTOCOL_0_0_1,"web-bot-auth":WEB_BOT_AUTH_PROTOCOL_0_0_1},A2UI_SURFACE_UI_0_0_1={id:"a2ui-surface",version:"0.0.1",name:"Surfaces in the conversation",description:"Forms, tables and cards the agent draws in the conversation; what you fill in goes back to it.",emoji:"🪟",octicon:"browser",plugin:"@datalayer/loop-plugin-a2ui-surface",folder:"a2ui-surface",contributions:{slots:["loop.chatHeader"],points:["reactor.ui.renderer","reactor.ui.toolBinding"],commands:[]},contributionPoints:[],settings:{},renderers:["a2ui"],catalog:"a2ui/v0.9",components:[{id:"Text",name:"Text",category:"text",emoji:"🔤",description:"Words on the page: a heading, a paragraph, the answer — plain or Markdown.",version:"0.9.0",standard:!0,properties:{type:"object",required:["text"],properties:{text:{type:"string",title:"Words",description:"What it says, plain or in simple Markdown."},variant:{type:"string",title:"Style",description:"A heading of a level, a caption, or body text.",enum:["h1","h2","h3","h4","h5","caption","body"],default:"body"}}},events:[]},{id:"Image",name:"Image",category:"media",emoji:"🖼️",description:"A picture: a chart rendered elsewhere, a logo, a photo.",version:"0.9.0",standard:!0,properties:{type:"object",required:["url"],properties:{url:{type:"string",title:"Address",description:"Where the picture is."},description:{type:"string",title:"Description",description:"What it shows, for those who cannot see it."},fit:{type:"string",title:"Fit",description:"How it is resized to its place.",enum:["contain","cover","fill","none","scaleDown"],default:"fill"},variant:{type:"string",title:"Size",description:"An icon, an avatar, a feature or a header.",enum:["icon","avatar","smallFeature","mediumFeature","largeFeature","header"],default:"mediumFeature"}}},events:[]},{id:"Icon",name:"Icon",category:"media",emoji:"🔣",description:"A small drawing that says what something is: a check, a warning, a link.",version:"0.9.0",standard:!0,properties:{type:"object",required:["name"],properties:{name:{type:"string",title:"Icon",description:"Which drawing, by its name.",enum:["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"]}}},events:[]},{id:"Video",name:"Video",category:"media",emoji:"🎬",description:"A film played in place.",version:"0.9.0",standard:!0,properties:{type:"object",required:["url"],properties:{url:{type:"string",title:"Address",description:"Where the film is."}}},events:[]},{id:"AudioPlayer",name:"Audio",category:"media",emoji:"🔊",description:"A sound played in place: a recording, a summary read aloud.",version:"0.9.0",standard:!0,properties:{type:"object",required:["url"],properties:{url:{type:"string",title:"Address",description:"Where the sound is."},description:{type:"string",title:"Description",description:"What it is: a title or a summary."}}},events:[]},{id:"Row",name:"Row",category:"layout",emoji:"➡️",description:"Children side by side, left to right.",version:"0.9.0",standard:!0,properties:{type:"object",required:["children"],properties:{children:{type:"array",title:"Blocks",description:"The blocks inside it, by id, left to right.",items:{type:"string"}},justify:{type:"string",title:"Spacing",description:"How the blocks share the width.",enum:["center","end","spaceAround","spaceBetween","spaceEvenly","start","stretch"],default:"start"},align:{type:"string",title:"Alignment",description:"How the blocks line up top to bottom.",enum:["start","center","end","stretch"],default:"stretch"}}},events:[]},{id:"Column",name:"Column",category:"layout",emoji:"⬇️",description:"Children one under the other.",version:"0.9.0",standard:!0,properties:{type:"object",required:["children"],properties:{children:{type:"array",title:"Blocks",description:"The blocks inside it, by id, top to bottom.",items:{type:"string"}},justify:{type:"string",title:"Spacing",description:"How the blocks share the height.",enum:["start","center","end","spaceBetween","spaceAround","spaceEvenly","stretch"],default:"start"},align:{type:"string",title:"Alignment",description:"How the blocks line up left to right.",enum:["center","end","start","stretch"],default:"stretch"}}},events:[]},{id:"List",name:"List",category:"layout",emoji:"📃",description:"Items one after the other, each drawn by the same children: results, alternatives, steps.",version:"0.9.0",standard:!0,properties:{type:"object",required:["children"],properties:{children:{type:"array",title:"Blocks",description:"The blocks inside it, by id, or the template repeated over a list.",items:{type:"string"}},direction:{type:"string",title:"Direction",description:"One under the other, or side by side.",enum:["vertical","horizontal"],default:"vertical"},align:{type:"string",title:"Alignment",description:"How the items line up across.",enum:["start","center","end","stretch"],default:"stretch"}}},events:[]},{id:"Card",name:"Card",category:"layout",emoji:"🗂️",description:"A framed group: what belongs together, set apart.",version:"0.9.0",standard:!0,properties:{type:"object",required:["child"],properties:{child:{type:"string",title:"Block",description:"The one block inside it, by id; a Row or Column for several."}}},events:[]},{id:"Tabs",name:"Tabs",category:"layout",emoji:"📑",description:"Several views of one place, one shown at a time.",version:"0.9.0",standard:!0,properties:{type:"object",required:["tabs"],properties:{tabs:{type:"array",title:"Tabs",description:"Each tab's title and the block it shows, by id.",minItems:1,items:{type:"object",required:["title","child"],properties:{title:{type:"string"},child:{type:"string"}}}}}},events:[]},{id:"Divider",name:"Divider",category:"layout",emoji:"➖",description:"A line between what comes before and after.",version:"0.9.0",standard:!0,properties:{type:"object",properties:{axis:{type:"string",title:"Direction",description:"Across or up and down.",enum:["horizontal","vertical"],default:"horizontal"}}},events:[]},{id:"Modal",name:"Modal",category:"layout",emoji:"🪟",description:"A window over the page, opened by a trigger: details, a confirmation.",version:"0.9.0",standard:!0,properties:{type:"object",required:["trigger","content"],properties:{trigger:{type:"string",title:"Opened by",description:"The block that opens it, by id: a button."},content:{type:"string",title:"Shows",description:"The block shown inside it, by id."}}},events:[]},{id:"Button",name:"Button",category:"action",emoji:"🔘",description:"An action the person takes: send, run, approve. One filled button per screen.",version:"0.9.0",standard:!0,properties:{type:"object",required:["child","action"],properties:{child:{type:"string",title:"Label",description:"The block on it, by id: a Text for its words."},variant:{type:"string",title:"Style",description:"Primary for the one main action, borderless for a link.",enum:["default","primary","borderless"],default:"default"},action:{type:"object",title:"Does",description:"What pressing it sends, by name, with what it reads."}}},events:[]},{id:"TextField",name:"Input",category:"input",emoji:"⌨️",description:"A field the person types in: a word, a sentence, a number, a date.",version:"0.9.0",standard:!0,properties:{type:"object",required:["label"],properties:{label:{type:"string",title:"Label",description:"What the person reads beside it."},value:{type:"string",title:"Value",description:"What is typed in it."},variant:{type:"string",title:"Kind",description:"A short or long text, a number, or hidden as typed.",enum:["longText","number","shortText","obscured"],default:"shortText"},validationRegexp:{type:"string",title:"Pattern",description:"A regular expression what is typed must match."}}},events:[]},{id:"CheckBox",name:"Checkbox",category:"input",emoji:"☑️",description:"Yes or no: an option on or off, a consent given.",version:"0.9.0",standard:!0,properties:{type:"object",required:["label","value"],properties:{label:{type:"string",title:"Label",description:"What the person reads beside it."},value:{type:"boolean",title:"Value",description:"Whether it is ticked."}}},events:[]},{id:"ChoicePicker",name:"Select",category:"input",emoji:"🔽",description:"One choice, or several, among options the builder lists or the data gives.",version:"0.9.0",standard:!0,properties:{type:"object",required:["options","value"],properties:{label:{type:"string",title:"Label",description:"What the person reads above the options."},variant:{type:"string",title:"Choice",description:"One of the options, or several.",enum:["multipleSelection","mutuallyExclusive"],default:"mutuallyExclusive"},options:{type:"array",title:"Options",description:"What may be chosen: the words read and the value sent.",items:{type:"object",required:["label","value"],properties:{label:{type:"string"},value:{type:"string"}}}},value:{type:"array",title:"Value",description:"The values chosen.",items:{type:"string"}},displayStyle:{type:"string",title:"Shown as",description:"Checkboxes or chips.",enum:["checkbox","chips"],default:"checkbox"},filterable:{type:"boolean",title:"Searchable",description:"A search field above the options.",default:!1}}},events:[]},{id:"Slider",name:"Slider",category:"input",emoji:"🎚️",description:"A number chosen along a range: a weight, a budget, a threshold.",version:"0.9.0",standard:!0,properties:{type:"object",required:["value","max"],properties:{label:{type:"string",title:"Label",description:"What the person reads beside it."},min:{type:"number",title:"Least",description:"The smallest value.",default:0},max:{type:"number",title:"Most",description:"The largest value."},value:{type:"number",title:"Value",description:"The value chosen."}}},events:[]},{id:"DateTimeInput",name:"Date and time",category:"input",emoji:"📅",description:"A date, a time, or both, chosen from a calendar.",version:"0.9.0",standard:!0,properties:{type:"object",required:["value"],properties:{value:{type:"string",title:"Value",description:"The date or time chosen, in ISO 8601."},enableDate:{type:"boolean",title:"Date",description:"A date may be chosen.",default:!1},enableTime:{type:"boolean",title:"Time",description:"A time may be chosen.",default:!1},min:{type:"string",title:"Earliest",description:"The earliest that may be chosen, in ISO 8601."},max:{type:"string",title:"Latest",description:"The latest that may be chosen, in ISO 8601."},label:{type:"string",title:"Label",description:"What the person reads beside it."}}},events:[]},{id:"Table",name:"Table",category:"data",emoji:"📋",description:"Rows the application found or keeps, with the columns the builder chooses.",version:"1.0.0",standard:!1,properties:{type:"object",required:["columns"],properties:{title:{type:"string",title:"Title",description:"What the table is, above it."},columns:{type:"array",title:"Columns",description:"The columns, in order.",minItems:1,items:{type:"string"}},page_size:{type:"integer",title:"Rows per page",description:"How many rows show at once.",minimum:1,maximum:500,default:20},selectable:{type:"boolean",title:"Selectable",description:"A row may be chosen, and its choice sent.",default:!1}}},bindings:{shows:["rows"],sends:["selected"]},events:["select"],example:{title:"Runs",columns:["model","pass rate","cost"]}},{id:"Chart",name:"Chart",category:"data",emoji:"📊",description:"Numbers drawn: a bar, a line, a scatter of what the application measured.",version:"1.0.0",standard:!1,properties:{type:"object",required:["kind","x","y"],properties:{title:{type:"string",title:"Title",description:"What the chart shows, above it."},kind:{type:"string",title:"Kind",description:"How the numbers are drawn.",enum:["bar","line","scatter","area"],default:"bar"},x:{type:"string",title:"Across",description:"The field along the bottom."},y:{type:"string",title:"Up",description:"The field measured."},series:{type:"string",title:"Series",description:"A field whose values are drawn apart."}}},bindings:{shows:["points"],sends:[]},events:[],example:{kind:"bar",x:"model",y:"pass rate"}},{id:"FileUpload",name:"File upload",category:"input",emoji:"📎",description:"A file the person gives the application: a document to read, a sheet to check.",version:"1.0.0",standard:!1,properties:{type:"object",required:["label"],properties:{label:{type:"string",title:"Label",description:"What the person reads beside it."},accept:{type:"array",title:"Accepts",description:"The kinds of file it takes, by extension.",items:{type:"string",pattern:"^\\.[a-z0-9]+$"}},multiple:{type:"boolean",title:"Several",description:"More than one file at once.",default:!1},max_mb:{type:"integer",title:"Largest (MB)",description:"The largest file it takes.",minimum:1,maximum:500,default:25}}},bindings:{shows:[],sends:["files"]},events:["upload"],example:{label:"The contract",accept:[".pdf",".docx"]}},{id:"Chat",name:"Chat",category:"conversation",emoji:"💬",description:"The conversation with the application: its welcome, its starters, the composer.",version:"1.0.0",standard:!1,properties:{type:"object",properties:{welcome:{type:"string",title:"Welcome",description:"What it says before anyone writes."},placeholder:{type:"string",title:"Composer hint",description:"Shown in the composer while it is empty.",default:"Ask anything"},starters:{type:"array",title:"Starters",description:"Questions offered before the first message.",maxItems:6,items:{type:"string"}},show_tools:{type:"boolean",title:"Shows its tools",description:"The tool calls are shown as they happen.",default:!0}}},bindings:{shows:["messages"],sends:["message"]},events:["send"],example:{welcome:"Ask me to research anything.",starters:["What changed in Python 3.13?"]}},{id:"Evidence",name:"Evidence",category:"data",emoji:"🔎",description:"What an answer rests on: the sources opened, the passages cited, each with its link.",version:"1.0.0",standard:!1,properties:{type:"object",properties:{title:{type:"string",title:"Title",description:"Above the sources.",default:"Sources"},show_passages:{type:"boolean",title:"Shows passages",description:"Each source with the passage cited from it.",default:!0},max_items:{type:"integer",title:"Most shown",description:"How many sources show before *more*.",minimum:1,maximum:50,default:5}}},bindings:{shows:["sources"],sends:[]},events:["open"],example:{title:"What this rests on"}},{id:"Form",name:"Form",category:"input",emoji:"🧾",description:"Several fields asked at once, from a JSON Schema, checked as they are filled and again when they arrive (drawn with @datalayer/primer-rjsf).",version:"1.1.0",standard:!1,properties:{type:"object",required:["schema"],properties:{title:{type:"string",title:"Title",description:"What the form is for, above it."},schema:{type:"object",title:"Fields",description:"The JSON Schema of what is asked: its fields, their types, what is required."},ui:{type:"object",title:"How its fields are drawn",description:"By field name, the ui: options @datalayer/primer-rjsf reads (a uiSchema): ui:widget one of select, radio, range, updown, switch, checkbox, text, textarea, date, checkboxes, tags; each field's own widget when unsaid."},submit_label:{type:"string",title:"Send button",description:"The words on its button.",default:"Send"}}},bindings:{shows:["values"],sends:["values"]},events:["submit"],example:{title:"The quote",schema:{type:"object",required:["seats"],properties:{seats:{type:"integer",minimum:1,title:"Seats"}}}}},{id:"Download",name:"File to download",category:"data",emoji:"📄",description:"A file the application gives, to save: a report, a sheet, an export — by its link, or the file itself as a data: URL.",version:"1.0.0",standard:!1,properties:{type:"object",required:["name","url"],properties:{name:{type:"string",title:"File name",description:"What the file is saved as, with its extension.",minLength:1},url:{type:"string",title:"Link",description:"Where the file is: an http(s) link, or the file itself as a data: URL.",pattern:"^(https?://|data:)"},media_type:{type:"string",title:"Kind",description:"Its media type (text/csv, application/pdf…), said beside its name."},size:{type:"integer",title:"Size (bytes)",description:"How large it is, said beside its name.",minimum:0},description:{type:"string",title:"Description",description:"A line under its name."}}},bindings:{shows:[],sends:[]},events:["download"],example:{name:"totals.csv",url:"data:text/csv;base64,bW9udGgsdG90YWwKSmFuLDEyMDAK",media_type:"text/csv",size:21,description:"The month's totals."}}]},A2UI_VIEW_UI_0_0_1={id:"a2ui-view",version:"0.0.1",name:"Surface view",description:"The last result of the code, shown as a page you can use rather than as raw output.",emoji:"🖼",octicon:"browser",plugin:"@datalayer/loop-plugin-a2ui",folder:"a2ui",contributions:{slots:[],points:["loop.command","loop.viewType"],commands:["a2ui"]},contributionPoints:[],settings:{},renderers:["a2ui"],catalog:"",components:[]},AGENTSPECS_UI_0_0_1={id:"agentspecs",version:"0.0.1",name:"Agent picker",description:"Choose which agent answers in this conversation.",emoji:"🤖",octicon:"people",plugin:"@datalayer/loop-plugin-agentspecs",folder:"agentspecs",contributions:{slots:["loop.header"],points:["loop.command"],commands:["agents"]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},APP_ACTIVITY_UI_0_0_1={id:"app-activity",version:"0.0.1",name:"Activity",description:"What your application did, is doing, and is about to do, beside its page.",emoji:"🕘",octicon:"pulse",plugin:"@datalayer/loop-plugin-app-activity",folder:"app-activity",per:"application",contributions:{slots:["loop.sidebar"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},APP_COMPONENTS_UI_0_0_1={id:"app-components",version:"0.0.1",name:"Your own components",description:"The components your application's developer wrote, on its page and in its answers.",emoji:"🧩",octicon:"apps",plugin:"@datalayer/loop-plugin-app-components",folder:"app-components",per:"application",contributions:{slots:[],points:["loop.a2ui.component","loop.canvas.block"],commands:[]},contributionPoints:[],settings:{},renderers:["a2ui"],catalog:"",components:[]},APP_COMPUTER_UI_0_0_1={id:"app-computer",version:"0.0.1",name:"Computer",description:"The computer your application works on: what ran there, its files, and taking it over.",emoji:"🖥️",octicon:"device-desktop",plugin:"@datalayer/loop-plugin-app-computer",folder:"app-computer",per:"application",contributions:{slots:["loop.sidebar"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},APP_ELEMENTS_UI_0_0_1={id:"app-elements",version:"0.0.1",name:"Side panel and pages",description:"What your application opens beside the conversation: a side panel, a page of its own, a question for you.",emoji:"🗂️",octicon:"sidebar-expand",plugin:"@datalayer/loop-plugin-app-elements",folder:"app-elements",contributions:{slots:["root"],points:["reactor.ui.renderer"],commands:[]},contributionPoints:[],settings:{},renderers:["a2ui"],catalog:"",components:[]},APP_PAGE_UI_0_0_1={id:"app-page",version:"0.0.1",name:"Application page",description:"Your application's page, drawn beside its conversation.",emoji:"📈",octicon:"browser",plugin:"@datalayer/loop-plugin-app-page",folder:"app-page",per:"application",contributions:{slots:[],points:["loop.chat.surface"],commands:[]},contributionPoints:[],settings:{},renderers:["a2ui","mcp-apps"],catalog:"",components:[]},APP_RULES_UI_0_0_1={id:"app-rules",version:"0.0.1",name:"Rules and approvals",description:"When your application acts alone, when it asks you, and the approvals waiting for your yes.",emoji:"🛡️",octicon:"shield-check",plugin:"@datalayer/loop-plugin-app-rules",folder:"app-rules",per:"application",contributions:{slots:["loop.sidebar"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CANVAS_BLOCKS_UI_0_0_1={id:"canvas-blocks",version:"0.0.1",name:"Blocks",description:"The blocks you place on your application's page in the visual editor, one set for each part that draws them.",emoji:"🧱",octicon:"apps",plugin:"@datalayer/loop-plugin-ui",folder:"canvas-blocks",per:"ui",contributions:{slots:[],points:["loop.canvas.block"],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CANVAS_PARTS_UI_0_0_1={id:"canvas-parts",version:"0.0.1",name:"Parts",description:"What you drop on your agent in the visual editor: connections, skills, models, rules, tests and events.",emoji:"🧰",octicon:"package",plugin:"@datalayer/loop-plugin-parts",folder:"canvas-parts",per:"source",contributions:{slots:[],points:["loop.canvas.part"],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CHAT_EXTRAS_UI_0_0_1={id:"chat-extras",version:"0.0.1",name:"Banner and status",description:"A live banner over the conversation and a status line under it, set by the page around it.",emoji:"📣",octicon:"megaphone",plugin:"@datalayer/loop-plugin-chat-extras",folder:"chat-extras",contributions:{slots:[],points:["loop.chat.extras"],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CHAT_HEADER_UI_0_0_1={id:"chat-header",version:"0.0.1",name:"Chat title bar",description:"The conversation's title bar: who answers, what it runs on, and its actions.",emoji:"🏷️",octicon:"rows",plugin:"@datalayer/loop-plugin-chat-header",folder:"chat-header",contributions:{slots:[],points:["loop.chat.header"],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CHAT_VIEW_UI_0_0_1={id:"chat-view",version:"0.0.1",name:"Chat button",description:"Back to the conversation alone, from under the composer.",emoji:"💬",octicon:"comment-discussion",plugin:"@datalayer/loop-plugin-chat-view",folder:"chat-view",contributions:{slots:["loop.promptAction"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CHAT_UI_0_0_1={id:"chat",version:"0.0.1",name:"Chat",description:"The conversation: what you ask, what it answers, and the work it opens beside it.",emoji:"💬",octicon:"comment-discussion",plugin:"@datalayer/loop-plugin-chat",folder:"chat",contributions:{slots:[],points:["loop.chat.turn","loop.command","loop.document.toolbar.item","loop.notebook.toolbar.item","loop.viewType"],commands:["chat"]},contributionPoints:["loop.agent.available","loop.chat.composer","loop.chat.extras","loop.chat.header","loop.chat.suggestion","loop.chat.turn","loop.frontendTool"],settings:{type:"object",properties:{placeholder:{type:"string",title:"Composer hint",description:"Shown in the composer while it is empty; the agent's own when unsaid.",default:""},defaultSurface:{type:"string",title:"Opens beside it",description:"What opens beside the conversation: notebook, document, a page, or none.",default:"notebook"},showSurfaceSelector:{type:"boolean",title:"Offers the switcher",description:"The strip that switches what is open beside the conversation.",default:!0},hideHeader:{type:"boolean",title:"Hides its title bar",description:"The conversation without its own title bar.",default:!1},headerButtons:{type:"object",title:"Title bar buttons",description:"Whether the title bar offers a new chat and clearing this one.",properties:{newChat:{type:"boolean",title:"New chat",description:"Start another conversation."},clear:{type:"boolean",title:"Clear",description:"Clear this conversation."}},default:{newChat:!1,clear:!1}},hidePrompt:{type:"boolean",title:"Hides the composer",description:"The conversation read without being written to.",default:!1},promptPlacement:{type:"string",title:"Composer place",description:"Where the composer sits.",enum:["top","bottom","bottom-chat","floating"],default:"bottom"},autoFocusPrompt:{type:"boolean",title:"Composer takes the caret",description:"The composer is ready to type in when the page opens.",default:!0},suggestionLabels:{type:"boolean",title:"Openers by the composer",description:"The openers shown as labels by the composer, not only in its menu.",default:!0},fullScreenTopOffset:{type:["number","string"],title:"Room kept at the top",description:"What full screen leaves at the top for the page's own header.",default:0}}},renderers:[],catalog:"",components:[]},COMMANDS_UI_0_0_1={id:"commands",version:"0.0.1",name:"Command palette",description:"Every command at hand, with Ctrl-K.",emoji:"⌘",octicon:"command-palette",plugin:"@datalayer/loop-plugin-commands",folder:"commands",contributions:{slots:["loop.status"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},DOCUMENT_TOOLBAR_UI_0_0_1={id:"document-toolbar",version:"0.0.1",name:"Document toolbar",description:"Shows what the document's code blocks run on.",emoji:"🔵",octicon:"circle",plugin:"@datalayer/loop-plugin-document-toolbar",folder:"document-toolbar",contributions:{slots:[],points:["loop.document.toolbar"],commands:[]},contributionPoints:["loop.document.toolbar.item"],settings:{},renderers:[],catalog:"",components:[]},DOCUMENT_VIEW_UI_0_0_1={id:"document-view",version:"0.0.1",name:"Document button",description:"The document beside the conversation, from under the composer.",emoji:"📄",octicon:"file",plugin:"@datalayer/loop-plugin-document-view",folder:"document-view",contributions:{slots:["loop.promptAction"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},DOCUMENT_UI_0_0_1={id:"document",version:"0.0.1",name:"Document",description:"A document beside the conversation, written with the agent.",emoji:"📄",octicon:"file",plugin:"@datalayer/loop-plugin-document",folder:"document",contributions:{slots:[],points:["loop.chat.surface","loop.command"],commands:["document"]},contributionPoints:["loop.document.opening","loop.document.toolbar"],settings:{},renderers:[],catalog:"",components:[]},INPUT_PROMPT_UI_0_0_1={id:"input-prompt",version:"0.0.1",name:"Composer",description:"Where you write to the agent, under or over the conversation.",emoji:"✏️",octicon:"pencil",plugin:"@datalayer/loop-plugin-input-prompt",folder:"input-prompt",contributions:{slots:[],points:["loop.chat.composer"],commands:[]},contributionPoints:["loop.prompt.panel"],settings:{},renderers:[],catalog:"",components:[]},MODELS_UI_0_0_1={id:"models",version:"0.0.1",name:"Models",description:"Which model answers, and the models you may choose from.",emoji:"🧠",octicon:"cpu",plugin:"@datalayer/loop-plugin-models",folder:"models",contributions:{slots:[],points:["loop.command"],commands:["models"]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},NOTEBOOK_TOOLBAR_UI_0_0_1={id:"notebook-toolbar",version:"0.0.1",name:"Notebook toolbar",description:"Shows what the notebook is running on.",emoji:"🟢",octicon:"circle",plugin:"@datalayer/loop-plugin-notebook-toolbar",folder:"notebook-toolbar",contributions:{slots:[],points:["loop.notebook.toolbar"],commands:[]},contributionPoints:["loop.notebook.toolbar.item"],settings:{},renderers:[],catalog:"",components:[]},NOTEBOOK_VIEW_UI_0_0_1={id:"notebook-view",version:"0.0.1",name:"Notebook button",description:"The notebook beside the conversation, from under the composer.",emoji:"📓",octicon:"rows",plugin:"@datalayer/loop-plugin-notebook-view",folder:"notebook-view",contributions:{slots:["loop.promptAction"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},NOTEBOOK_UI_0_0_1={id:"notebook",version:"0.0.1",name:"Notebook",description:"A notebook beside the conversation, its code run as you go.",emoji:"📓",octicon:"rows",plugin:"@datalayer/loop-plugin-notebook",folder:"notebook",contributions:{slots:[],points:["loop.chat.surface","loop.command"],commands:["notebook"]},contributionPoints:["loop.notebook.opening","loop.notebook.toolbar"],settings:{},renderers:[],catalog:"",components:[]},PAGE_LAYOUT_UI_0_0_1={id:"page-layout",version:"0.0.1",name:"Page layout",description:"The work on a centred sheet like a document, the composer above it and the conversation in a panel beside it; or the conversation and the work side by side.",emoji:"📄",octicon:"file",plugin:"@datalayer/loop-plugin-page-layout",folder:"page-layout",contributions:{slots:["loop.header"],points:["loop.chat.layout","loop.prompt.panel"],commands:[]},contributionPoints:[],settings:{type:"object",properties:{arrangement:{type:"string",title:"Arrangement",description:"The work on a sheet with the conversation in a panel, or both side by side.",enum:["page","split"],default:"page"},turnPanel:{type:"string",title:"Current turn",description:"Where the current turn hangs on the composer.",enum:["below","above","none"],default:"below"},turnPanelFooter:{type:"string",title:"Under the reply",description:"What is drawn under the reply: everything, its actions, or nothing.",enum:["full","actions","none"],default:"full"},prompt:{type:"string",title:"Composer",description:"Docked above the sheet, or floating over it.",enum:["docked","floating"],default:"docked"},promptAnchor:{type:"string",title:"Floating composer starts",description:"The edge a floating composer starts at.",enum:["top","bottom"],default:"top"},pageSize:{type:"object",title:"Sheet",description:"The sheet: free at its reading width when unsaid, or a paper (letter, a4) whose width it takes, with a width or a height of its own over either.",properties:{format:{type:"string",title:"Paper",description:"The paper the sheet is.",enum:["free","letter","a4"]},width:{type:"number",title:"Width",description:"The sheet's width in pixels; over a paper, it replaces the paper's."},height:{type:"number",title:"Height",description:"The sheet's least height in pixels; what is past it grows the sheet."}}}}},renderers:[],catalog:"",components:[]},PAP_SIGN_IN_UI_0_0_1={id:"pap-sign-in",version:"0.0.1",name:"Sign in at a company",description:"Where your agent asks you to sign in at a company: its page, the code, and until when.",emoji:"🔑",octicon:"sign-in",plugin:"@datalayer/loop-plugin-pap-sign-in",folder:"pap-sign-in",contributions:{slots:["loop.chatHeader"],points:["reactor.ui.renderer","reactor.ui.toolBinding"],commands:[]},contributionPoints:[],settings:{},renderers:["mcp-ui"],catalog:"",components:[]},PROMPT_UI_0_0_1={id:"prompt",version:"0.0.1",name:"Floating composer",description:"The composer in a card you move over the page, and the commands that bring it back or start over.",emoji:"🪶",octicon:"paper-airplane",plugin:"@datalayer/loop-plugin-prompt",folder:"prompt",contributions:{slots:["loop.promptAction"],points:["loop.command"],commands:["new","prompt"]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},SUBAGENT_ACTIVITY_UI_0_0_1={id:"subagent-activity",version:"0.0.1",name:"Delegated work",description:"The face of an agent yours handed work to, pulsing while it works.",emoji:"👥",octicon:"people",plugin:"@datalayer/loop-plugin-subagent-activity",folder:"subagent-activity",contributions:{slots:["loop.inpromptMenu"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},WINDOW_FRAME_UI_0_0_1={id:"window-frame",version:"0.0.1",name:"Window",description:"Draws the editor as a window, with room in its title bar for controls and actions.",emoji:"🪟",octicon:"browser",plugin:"@datalayer/loop-plugin-window-frame",folder:"window-frame",contributions:{slots:["loop.header","loop.window.controls"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},UI_CATALOGUE={"a2ui-surface":A2UI_SURFACE_UI_0_0_1,"a2ui-view":A2UI_VIEW_UI_0_0_1,agentspecs:AGENTSPECS_UI_0_0_1,"app-activity":APP_ACTIVITY_UI_0_0_1,"app-components":APP_COMPONENTS_UI_0_0_1,"app-computer":APP_COMPUTER_UI_0_0_1,"app-elements":APP_ELEMENTS_UI_0_0_1,"app-page":APP_PAGE_UI_0_0_1,"app-rules":APP_RULES_UI_0_0_1,"canvas-blocks":CANVAS_BLOCKS_UI_0_0_1,"canvas-parts":CANVAS_PARTS_UI_0_0_1,"chat-extras":CHAT_EXTRAS_UI_0_0_1,"chat-header":CHAT_HEADER_UI_0_0_1,"chat-view":CHAT_VIEW_UI_0_0_1,chat:CHAT_UI_0_0_1,commands:COMMANDS_UI_0_0_1,"document-toolbar":DOCUMENT_TOOLBAR_UI_0_0_1,"document-view":DOCUMENT_VIEW_UI_0_0_1,document:DOCUMENT_UI_0_0_1,"input-prompt":INPUT_PROMPT_UI_0_0_1,models:MODELS_UI_0_0_1,"notebook-toolbar":NOTEBOOK_TOOLBAR_UI_0_0_1,"notebook-view":NOTEBOOK_VIEW_UI_0_0_1,notebook:NOTEBOOK_UI_0_0_1,"page-layout":PAGE_LAYOUT_UI_0_0_1,"pap-sign-in":PAP_SIGN_IN_UI_0_0_1,prompt:PROMPT_UI_0_0_1,"subagent-activity":SUBAGENT_ACTIVITY_UI_0_0_1,"window-frame":WINDOW_FRAME_UI_0_0_1};function listUI(){return Object.values(UI_CATALOGUE)}const COMPONENT_CATALOGUE=Object.fromEntries(Object.values(UI_CATALOGUE).flatMap(Au=>Au.components.map(lo=>[lo.id,lo]))),A2UI_UI_RENDERER_0_0_1={id:"a2ui",version:"0.0.1",name:"A2UI",description:"An agent describes an interface — a form, a table, a card — as a tree of components from a catalogue the host allows, and the host renders it; what the user does in it comes back to the agent as an action.",docsUrl:"https://a2ui.org/",enabled:!0},MCP_APPS_UI_RENDERER_0_0_1={id:"mcp-apps",version:"0.0.1",name:"MCP Apps",description:"An MCP server ships an interactive app with a tool: the host renders it in a sandboxed frame beside the conversation, and the app calls the server's tools through the host.",docsUrl:"https://modelcontextprotocol.io/docs/extensions/apps",enabled:!1},MCP_UI_UI_RENDERER_0_0_1={id:"mcp-ui",version:"0.0.1",name:"MCP UI",description:"An MCP tool answers with a UI resource — HTML, a remote page or a component — that the host renders in place of plain text.",docsUrl:"https://mcpui.dev/",enabled:!1},UI_RENDERER_CATALOGUE={a2ui:A2UI_UI_RENDERER_0_0_1,"mcp-apps":MCP_APPS_UI_RENDERER_0_0_1,"mcp-ui":MCP_UI_UI_RENDERER_0_0_1},DEFAULT_UPLOAD_MB=10,DEFAULT_MAX_FILES=5;function kindTakes(Au,lo){const $u=Au.trim().toLowerCase();if($u.startsWith("."))return lo.name.toLowerCase().endsWith($u);const Ru=(lo.type||"").split(";",1)[0].trim().toLowerCase();return $u.endsWith("/*")?Ru.startsWith($u.slice(0,-1)):Ru===$u}const acceptsFile=(Au,lo)=>!Au?.length||Au.some($u=>kindTakes($u,lo)),megabytes=Au=>`${(Au/(1024*1024)).toFixed(1)} MB`,uploadsAccept=Au=>Au.kinds.map(lo=>lo.type).join(",");function uploadsRefusal(Au,lo){if(lo.length===0)return null;const $u=Au.interface.uploads;if(!$u)return`${Au.name} takes no file sent with a message: its Appspec names none it takes (interface.uploads).`;if(lo.length>$u.maxFiles)return`${lo.length} files were sent at once: ${Au.name} takes at most ${$u.maxFiles}.`;for(const Ru of lo){const Iu=$u.kinds.find(Pu=>kindTakes(Pu.type,Ru));if(!Iu){const Pu=$u.kinds.map(Ou=>Ou.type).join(", ");return`${Ru.name} is not a kind of file ${Au.name} takes: it takes ${Pu}.`}if(Ru.size>Iu.maxMb*1024*1024)return`${Ru.name} is ${megabytes(Ru.size)}: ${Au.name} takes ${Iu.type} of at most ${Iu.maxMb} MB.`}return null}function uploadsInWords(Au){return`Takes ${Au.kinds.map($u=>`${$u.type} up to ${$u.maxMb} MB`).join(", ")}; ${Au.maxFiles} at most at once.`}const APP_SCHEMA="loop.app/v1",DEFAULT_LANGUAGE="en",DEFAULT_EMOJI="👀",APP_KINDS=["chat","widget","decision","worker"],APP_ACCENTS=["green","rose","sky","lime","sun","violet"],APP_THEME_VARIANTS=["datalayer","spatial","lovely","matrix","earth","sand","ivory","sun","loop"],APP_THEME_MODES=["light","dark","auto"],APP_EMBED_MODES=["inline","bubble","panel","assistant"],APP_ASSISTANT_AVATAR_ID=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function isAvatarId(Au){return typeof Au=="string"&&Au.length<=64&&APP_ASSISTANT_AVATAR_ID.test(Au)}const AVATAR_MODEL_URL=/^https:\/\/\S+\.(?:glb|gltf)(?:[?#]\S*)?$/;function isAvatarModel3D(Au){if(typeof Au!="object"||Au===null||Array.isArray(Au))return!1;const{kind:lo,url:$u,...Ru}=Au;return lo==="model3d"&&Object.keys(Ru).length===0&&($u===void 0||$u===""||typeof $u=="string"&&AVATAR_MODEL_URL.test($u))}const ACTION_CLASS_NAMES=["read","write","send","buy","delete","publish"],DEFAULT_LAYOUTS={chat:"chat",widget:"page",decision:"page",worker:"split"},A2UI_OUTPUT="application/json+a2ui";function uiFor(Au,lo={}){if(Au==="decision")return[{plugin:"app-page"}];const $u=[{plugin:"chat"}];return lo.outputs?.includes(A2UI_OUTPUT)&&$u.push({plugin:"a2ui-surface",renderer:"a2ui"}),lo.signsIn&&$u.push({plugin:"pap-sign-in"}),(lo.layout??DEFAULT_LAYOUTS[Au])!=="chat"&&$u.push({plugin:"page-layout"},{plugin:"app-page"},{plugin:"canvas-blocks"}),lo.ownComponents&&$u.push({plugin:"app-components"}),$u}const DEFAULT_RECORD_INCLUDE=["conversations","actions","approvals"],DEFAULT_KEEP_FOR="1_years",DEFAULT_READY_AT=.8,DEFAULT_PROTOCOL="a2ui/v0.9",DEFAULT_ICON="apps",DEFAULT_VERSION="0.0.1",NO_HOST_PARAMETERS={type:"object",properties:{}},isData=Au=>!!Au&&typeof Au=="object"&&!Array.isArray(Au),text$k=(Au,lo="")=>typeof Au=="string"?Au:lo,flag=(Au,lo)=>typeof Au=="boolean"?Au:lo,numberOf=(Au,lo)=>typeof Au=="number"&&Number.isFinite(Au)?Au:lo,texts=Au=>Array.isArray(Au)?Au.filter(lo=>typeof lo=="string"):[],records$1=Au=>Array.isArray(Au)?Au.filter(isData):[],uiChoices=Au=>Array.isArray(Au)?Au.filter(isData).map(lo=>({plugin:text$k(lo.plugin),...text$k(lo.renderer)?{renderer:text$k(lo.renderer)}:{}})):[],uiShapeProblems=Au=>Array.isArray(Au)?Au.filter(lo=>!isData(lo)).map(lo=>`\`ui\` lists UI plugins, each as \`{plugin, renderer}\`: ${JSON.stringify(lo)} is not one`+(typeof lo=="string"&&UI_RENDERER_CATALOGUE[lo]?` (${JSON.stringify(lo)} is a UI renderer: name the plugin it renders, and say it as its \`renderer\`).`:".")):[];function parseTestTurn(Au){return{...text$k(Au.say)?{say:text$k(Au.say)}:{},...text$k(Au.choose)?{choose:text$k(Au.choose)}:{},...text$k(Au.press)?{press:text$k(Au.press)}:{},...isData(Au.payload)&&Object.keys(Au.payload).length?{payload:{...Au.payload}}:{}}}const oneOf$3=(Au,lo,$u)=>lo.includes(Au)?Au:$u,RETENTION$1=/^([1-9]\d*)_(day|days|month|months|year|years)$/,DAYS={day:1,month:30,year:365};function retentionDays(Au){const lo=RETENTION$1.exec(Au.trim());return lo?Number(lo[1])*DAYS[lo[2].replace(/s$/,"")]:0}function emptyAppspec(Au="chat"){return{schema:APP_SCHEMA,id:"",version:DEFAULT_VERSION,name:"",kind:Au,description:"",owner:"",agent:"",team:"",instructions:"",model:"",skills:[],backendTools:[],context:[],contents:[],connections:[],protocols:[],ui:uiFor(Au),rules:[],permissions:{spaces:[],computer:{browse:!1,files:!1,shell:!1}},interface:{layout:DEFAULT_LAYOUTS[Au],welcome:"",starters:[],commands:[],modes:[],actions:[],profiles:[],language:DEFAULT_LANGUAGE,translations:{},components:[],outputs:[]},tests:{readyAt:DEFAULT_READY_AT,evalset:"",cases:[],verified:{live:[],recorded:[],unverified:[]}},record:{keepFor:DEFAULT_KEEP_FOR,retentionDays:retentionDays(DEFAULT_KEEP_FOR),include:[...DEFAULT_RECORD_INCLUDE],suggestTests:!1},checks:{guards:[],gates:[],track:""},deployment:{},goal:"",triggers:[],memory:"",notifications:[],samples:{documents:[],alternatives:[]},setup:[],enabled:!0,unavailable_because:"",tags:[],icon:DEFAULT_ICON,emoji:DEFAULT_EMOJI,avatar:"",banner:""}}const KNOWN_KEYS=["schema","id","version","name","kind","description","owner","agent","team","instructions","model","skills","backend_tools","tools","context","contents","connections","protocols","ui","pap","pact","commerce","signed_fetch","pair","a2a","rules","permissions","interface","tests","record","checks","deployment","goal","triggers","memory","notifications","decision","samples","enabled","unavailable_because","tags","icon","emoji","avatar","banner"],CHECK_STAGES=["answer","tool_call"];function parseTool(Au){return{name:text$k(Au.name),description:text$k(Au.description),parameters:isData(Au.parameters)?Au.parameters:{...NO_HOST_PARAMETERS},does:texts(Au.does)}}function parseConnection(Au){return{server:text$k(Au.server),access:oneOf$3(Au.access,["read","write"],"read"),as:oneOf$3(Au.as,["owner","user"],"owner"),only:texts(Au.only)}}const PAP_PROFILES=["draft-01"],PAP_PROFILE=PAP_PROFILES[PAP_PROFILES.length-1];function papProfileProblem(Au){if(Au==null||Au==="")return`Its \`pap\` block names no Personal Agent Protocol profile: add \`profile: ${PAP_PROFILE}\`.`;if(!PAP_PROFILES.includes(Au))return`This application asks for Personal Agent Protocol profile “${String(Au)}”; Datalayer speaks ${PAP_PROFILES.join(" or ")}.`}const PAP_INTERFACES=["agent","openapi","mcp","web"],PAP_SIGN_IN=["direct","device","mediated"],PAP_DEFAULT_INTERFACES=["agent"],PAP_DEFAULT_SIGN_IN=["direct","device"],enumsOf=(Au,lo,$u)=>Array.isArray(Au)?Au.filter(Ru=>lo.includes(Ru)):[...$u];function parsePap(Au){const lo=isData(Au.company)?Au.company:{};return{profile:Au.profile,connections:records$1(Au.connections).map($u=>({id:text$k($u.id),company:text$k($u.company),access:oneOf$3($u.access,["read","write"],"read"),as:oneOf$3($u.as,["owner","user"],"user"),scopes:texts($u.scopes),interfaces:enumsOf($u.interfaces,PAP_INTERFACES,PAP_DEFAULT_INTERFACES),signIn:enumsOf($u.sign_in,PAP_SIGN_IN,PAP_DEFAULT_SIGN_IN),extensions:texts($u.extensions)})),company:{enabled:flag(lo.enabled,!1),signedOut:flag(lo.signed_out,!0),interfaces:enumsOf(lo.interfaces,PAP_INTERFACES,PAP_DEFAULT_INTERFACES),scopes:texts(lo.scopes),extensions:texts(lo.extensions),personalAgents:oneOf$3(lo.personal_agents,["any","registered"],"any"),registeredAgents:texts(lo.registered_agents),operations:records$1(lo.operations).map($u=>({action:text$k($u.action),tool:text$k($u.tool),...isData($u.allows)?{allows:parsePapStanding($u.allows)}:{},summary:text$k($u.summary),userApprovalRequired:flag($u.user_approval_required,!0)}))}}}function parsePapStanding(Au){return{connection:text$k(Au.connection),action:oneOf$3(Au.action,["write","buy"],"buy"),limits:records$1(Au.limits).map(lo=>({path:text$k(lo.path),...typeof lo.maximum=="string"?{maximum:text$k(lo.maximum)}:{},...typeof lo.allowed=="string"?{allowed:text$k(lo.allowed)}:{}})),uses:text$k(Au.uses),days:text$k(Au.days)}}function dumpPapStanding(Au){return{connection:Au.connection,action:Au.action,limits:Au.limits.map(lo=>({path:lo.path,...lo.maximum!==void 0?{maximum:lo.maximum}:{},...lo.allowed!==void 0?{allowed:lo.allowed}:{}})),uses:Au.uses,days:Au.days}}function dumpPap(Au){return Au?new Writer().text("profile",Au.profile,"\0").list("connections",Au.connections.map(lo=>new Writer().text("id",lo.id,"\0").text("company",lo.company,"\0").value("access",lo.access,"read").value("as",lo.as,"user").list("scopes",lo.scopes).list("interfaces",lo.interfaces,[...PAP_DEFAULT_INTERFACES]).list("sign_in",lo.signIn,[...PAP_DEFAULT_SIGN_IN]).list("extensions",lo.extensions).data)).part("company",new Writer().value("enabled",Au.company.enabled,!1).value("signed_out",Au.company.signedOut,!0).list("interfaces",Au.company.interfaces,[...PAP_DEFAULT_INTERFACES]).list("scopes",Au.company.scopes).list("extensions",Au.company.extensions).value("personal_agents",Au.company.personalAgents,"any").list("registered_agents",Au.company.registeredAgents).list("operations",Au.company.operations.map(lo=>new Writer().text("action",lo.action,"\0").text("tool",lo.tool,lo.allows?"":"\0").present("allows",lo.allows?dumpPapStanding(lo.allows):void 0).text("summary",lo.summary,"\0").value("user_approval_required",lo.userApprovalRequired,!0).data)).data).data:{}}function parsePact(Au){const lo=isData(Au.business)?Au.business:{},$u={};if(isData(lo.scopes))for(const[Ru,Iu]of Object.entries(lo.scopes))$u[Ru]=text$k(Iu);return{connections:records$1(Au.connections).map(Ru=>({id:text$k(Ru.id),brand:text$k(Ru.brand),audience:text$k(Ru.audience),access:oneOf$3(Ru.access,["read","write"],"read"),scopes:texts(Ru.scopes)})),business:{enabled:flag(lo.enabled,!1),brand:text$k(lo.brand),scopes:$u,registeredAgents:records$1(lo.registered_agents).map(Ru=>({issuer:text$k(Ru.issuer),jwksUri:text$k(Ru.jwks_uri)}))}}}function parseCommerce(Au){return{merchants:records$1(Au.merchants).map(lo=>({id:text$k(lo.id),protocol:oneOf$3(lo.protocol,["ucp","acp"],"ucp"),merchant:text$k(lo.merchant),access:oneOf$3(lo.access,["read","write"],"read"),...isData(lo.limit)?{limit:{amount:text$k(lo.limit.amount),currency:text$k(lo.limit.currency)}}:{}}))}}function dumpCommerce(Au){return Au?new Writer().list("merchants",Au.merchants.map(lo=>new Writer().text("id",lo.id,"\0").text("protocol",lo.protocol,"\0").text("merchant",lo.merchant,"\0").value("access",lo.access,"read").part("limit",lo.limit?{amount:lo.limit.amount,currency:lo.limit.currency}:{}).data)).data:{}}function parseSignedFetch(Au){return{sites:records$1(Au.sites).map(lo=>({id:text$k(lo.id),site:text$k(lo.site)}))}}function dumpSignedFetch(Au){return Au?new Writer().list("sites",Au.sites.map(lo=>new Writer().text("id",lo.id,"\0").text("site",lo.site,"\0").data)).data:{}}function parsePair(Au){const lo=text$k(Au.id),$u=text$k(Au.role);return/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(lo)?$u!=="business"&&$u!=="personal_agent"?`One of a pair is its business or its personal_agent, not ${JSON.stringify($u)}.`:{id:lo,role:$u}:`A pair's id is lower-case letters, digits and hyphens: ${JSON.stringify(lo)}.`}function dumpPact(Au){if(!Au)return{};const lo=Au.business??{enabled:!1,brand:"",scopes:{},registeredAgents:[]};return new Writer().list("connections",Au.connections.map($u=>new Writer().text("id",$u.id,"\0").text("brand",$u.brand,"\0").text("audience",$u.audience,"\0").value("access",$u.access,"read").list("scopes",$u.scopes).data)).part("business",new Writer().value("enabled",lo.enabled,!1).text("brand",lo.brand).part("scopes",{...lo.scopes}).list("registered_agents",lo.registeredAgents.map($u=>new Writer().text("issuer",$u.issuer,"\0").text("jwks_uri",$u.jwksUri,"\0").data)).data).data}function parseA2A(Au){return{extensions:records$1(Au.extensions).map(lo=>({uri:text$k(lo.uri),description:text$k(lo.description),required:flag(lo.required,!1),params:isData(lo.params)?{...lo.params}:{}}))}}function dumpA2A(Au){return Au?new Writer().list("extensions",Au.extensions.map(lo=>new Writer().text("uri",lo.uri,"\0").text("description",lo.description).value("required",lo.required,!1).part("params",lo.params).data)).data:{}}function parseRule$1(Au){return{action:text$k(Au.action),appliesTo:typeof Au.applies_to=="string"?[Au.applies_to]:texts(Au.applies_to),behaviour:oneOf$3(Au.behaviour,BEHAVIOURS,"ask_first")}}function parseAction(Au){const lo={name:text$k(Au.name)};return text$k(Au.description)&&(lo.description=text$k(Au.description)),isData(Au.payload)&&(lo.payload=JSON.parse(JSON.stringify(Au.payload))),lo}function parseCommand$1(Au){return{name:text$k(Au.name),description:text$k(Au.description),prompt:text$k(Au.prompt)}}function parseModeOption(Au){const lo={id:text$k(Au.id),label:text$k(Au.label)};for(const $u of["description","instructions","model"])typeof Au[$u]=="string"&&Au[$u]&&(lo[$u]=Au[$u]);return lo}function parseMode(Au){const lo={id:text$k(Au.id),label:text$k(Au.label),options:records$1(Au.options).map(parseModeOption)};return typeof Au.default=="string"&&Au.default&&(lo.default=Au.default),lo}function parseStarter(Au){const lo={label:text$k(Au.label),message:text$k(Au.message)};return typeof Au.category=="string"&&Au.category&&(lo.category=Au.category),lo}function parseProfile(Au){return{id:text$k(Au.id),label:text$k(Au.label),description:text$k(Au.description),instructions:text$k(Au.instructions),model:typeof Au.model=="string"&&Au.model?Au.model:null,starters:records$1(Au.starters).map(parseStarter)}}function wordsBy(Au){return Object.fromEntries(Object.entries(isData(Au)?Au:{}).filter(lo=>typeof lo[1]=="string"))}function recordsBy(Au){return Object.fromEntries(Object.entries(isData(Au)?Au:{}).filter(lo=>isData(lo[1])))}const mapValues=(Au,lo)=>Object.fromEntries(Object.entries(Au).map(([$u,Ru])=>[$u,lo(Ru)]));function parseTranslation(Au){return{name:text$k(Au.name),description:text$k(Au.description),welcome:text$k(Au.welcome),starters:mapValues(recordsBy(Au.starters),lo=>({label:text$k(lo.label),message:text$k(lo.message)})),categories:wordsBy(Au.categories),settings:mapValues(recordsBy(Au.settings),lo=>({title:text$k(lo.title),description:text$k(lo.description),options:wordsBy(lo.options)})),commands:wordsBy(Au.commands),modes:mapValues(recordsBy(Au.modes),lo=>({label:text$k(lo.label),options:mapValues(recordsBy(lo.options),$u=>({label:text$k($u.label),description:text$k($u.description)}))})),profiles:mapValues(recordsBy(Au.profiles),lo=>({label:text$k(lo.label),description:text$k(lo.description)}))}}function parseSurface(Au){return{protocol:text$k(Au.protocol,DEFAULT_PROTOCOL),components:records$1(Au.components).filter(lo=>typeof lo.id=="string"&&typeof lo.component=="string"),composedBy:text$k(Au.composed_by),composedAt:text$k(Au.composed_at)}}const DEFAULT_VOICE={enabled:!1,input:"push_to_talk",output:"on_request",where:"auto"};function parseVoice(Au){const lo=isData(Au)?Au:{};return{enabled:lo.enabled===!0,input:oneOf$3(lo.input,["off","push_to_talk","hands_free"],DEFAULT_VOICE.input),output:oneOf$3(lo.output,["off","on_request","always"],DEFAULT_VOICE.output),voice:text$k(lo.voice),language:text$k(lo.language),where:oneOf$3(lo.where,["auto","device","server"],DEFAULT_VOICE.where)}}function parseUploads(Au){return{kinds:records$1(Au.kinds).map(lo=>({type:text$k(lo.type),maxMb:numberOf(lo.max_mb,DEFAULT_UPLOAD_MB)})),maxFiles:numberOf(Au.max_files,DEFAULT_MAX_FILES)}}const PAGE_OUTPUT_SHOWS={Text:"text",Image:"url",Table:"rows",Chart:"points"},DEFAULT_CUSTOM_HEIGHT=240;function parseCustomComponent(Au){const lo={name:text$k(Au.name),description:text$k(Au.description),props:isData(Au.props)?JSON.parse(JSON.stringify(Au.props)):{type:"object",properties:{}},shows:texts(Au.shows),sends:texts(Au.sends),source:text$k(Au.source),integrity:text$k(Au.integrity),height:numberOf(Au.height,DEFAULT_CUSTOM_HEIGHT)};return isData(Au.example)&&(lo.example=JSON.parse(JSON.stringify(Au.example))),lo}function dumpCustomComponent(Au){const lo=new Writer().text("name",Au.name,"\0").text("description",Au.description,"\0");return lo.data.props=JSON.parse(JSON.stringify(Au.props)),lo.list("shows",Au.shows).list("sends",Au.sends).text("source",Au.source,"\0").text("integrity",Au.integrity).value("height",Au.height,DEFAULT_CUSTOM_HEIGHT),Au.example&&(lo.data.example=JSON.parse(JSON.stringify(Au.example))),lo.data}function pageOutputShows(Au,lo=[]){return Au in PAGE_OUTPUT_SHOWS?PAGE_OUTPUT_SHOWS[Au]:lo.find($u=>$u.name===Au)?.shows[0]}function parsePage(Au){const lo={function:text$k(Au.function),inputs:isData(Au.inputs)?JSON.parse(JSON.stringify(Au.inputs)):{},outputs:records$1(Au.outputs).map($u=>({name:text$k($u.name),title:text$k($u.title),component:text$k($u.component,"Text"),props:isData($u.props)?JSON.parse(JSON.stringify($u.props)):{}})),live:Au.live!==!1};return isData(Au.inputs_ui)&&(lo.inputsUi=JSON.parse(JSON.stringify(Au.inputs_ui))),lo}function dumpPage(Au){const lo=new Writer().text("function",Au.function,"\0");return lo.data.inputs=JSON.parse(JSON.stringify(Au.inputs)),Au.inputsUi&&(lo.data.inputs_ui={...Au.inputsUi}),lo.list("outputs",Au.outputs.map($u=>new Writer().text("name",$u.name,"\0").text("title",$u.title).text("component",$u.component,"Text").part("props",{...$u.props}).data)),lo.value("live",Au.live,!0).data}function parseInterface(Au,lo){const $u={layout:oneOf$3(Au.layout,["chat","page","split"],DEFAULT_LAYOUTS[lo]),accent:APP_ACCENTS.includes(Au.accent)?Au.accent:void 0,welcome:text$k(Au.welcome),starters:records$1(Au.starters).map(parseStarter),commands:records$1(Au.commands).map(parseCommand$1),modes:records$1(Au.modes).map(parseMode),actions:records$1(Au.actions).map(parseAction),profiles:records$1(Au.profiles).map(parseProfile),language:text$k(Au.language,DEFAULT_LANGUAGE),translations:mapValues(recordsBy(Au.translations),parseTranslation),components:texts(Au.components),voice:parseVoice(Au.voice),outputs:texts(Au.outputs)};return isData(Au.settings)&&($u.settings=JSON.parse(JSON.stringify(Au.settings))),isData(Au.settings_ui)&&($u.settingsUi=JSON.parse(JSON.stringify(Au.settings_ui))),isData(Au.uploads)&&($u.uploads=parseUploads(Au.uploads)),Array.isArray(Au.custom_components)&&($u.customComponents=records$1(Au.custom_components).map(parseCustomComponent)),isData(Au.surface)&&($u.surface=parseSurface(Au.surface)),isData(Au.page)&&($u.page=parsePage(Au.page)),isAvatarId(Au.avatar)?$u.avatar=Au.avatar:isAvatarModel3D(Au.avatar)&&($u.avatar=Au.avatar.url?{kind:"model3d",url:Au.avatar.url}:{kind:"model3d"}),(Au.balloon==="history"||Au.balloon==="current")&&($u.balloon=Au.balloon),isData(Au.theme)&&APP_THEME_VARIANTS.includes(Au.theme.variant)&&($u.theme={variant:Au.theme.variant},APP_THEME_MODES.includes(Au.theme.mode)&&($u.theme.mode=Au.theme.mode)),$u}function parseCriterion(Au){return{name:text$k(Au.name),kind:oneOf$3(Au.kind,["metric","noul","choice","score"],"metric"),weight:Math.max(0,numberOf(Au.weight,1)),instructions:text$k(Au.instructions),options:texts(Au.options),direction:Au.direction==="lower"?"lower":"higher",measure:oneOf$3(Au.measure,["","pass_rate","cost_per_task","seconds_per_task"],"")}}function parseDecision(Au){return{question:text$k(Au.question),alternatives:texts(Au.alternatives),criteria:records$1(Au.criteria).map(parseCriterion),minConfidence:Math.min(1,Math.max(0,numberOf(Au.min_confidence,0))),scenarios:records$1(Au.scenarios).map(lo=>({name:text$k(lo.name),weights:Object.fromEntries(Object.entries(isData(lo.weights)?lo.weights:{}).filter($u=>typeof $u[1]=="number"))})),decisionModel:text$k(Au.decision_model)}}function parseSamples(Au){return{documents:records$1(Au.documents).map(lo=>({name:text$k(lo.name),file:text$k(lo.file),text:text$k(lo.text)})),alternatives:records$1(Au.alternatives).map(lo=>({name:text$k(lo.name),evidence:text$k(lo.evidence),metrics:Object.fromEntries(Object.entries(isData(lo.metrics)?lo.metrics:{}).filter($u=>typeof $u[1]=="number"))}))}}function parseDeployment(Au){const lo={};return isData(Au.hosted)&&(lo.hosted={visibility:oneOf$3(Au.hosted.visibility,["private","invited","organization","link","public"],"private"),slug:text$k(Au.hosted.slug),...Au.hosted.avatar_alone===!0?{avatarAlone:!0}:{}}),isData(Au.embedded)&&(lo.embedded={mode:oneOf$3(Au.embedded.mode,APP_EMBED_MODES,"inline"),origins:texts(Au.embedded.origins),...isData(Au.embedded.host)?{host:{context:texts(Au.embedded.host.context),...Au.embedded.host.user!==void 0?{user:text$k(Au.embedded.host.user)}:{},functions:records$1(Au.embedded.host.functions).map($u=>({name:text$k($u.name),description:text$k($u.description),parameters:isData($u.parameters)?$u.parameters:{...NO_HOST_PARAMETERS}}))}}:{}}),lo}function parseTrigger(Au){return{type:oneOf$3(Au.type,["schedule","event","once"],"schedule"),cron:text$k(Au.cron),event:text$k(Au.event),at:text$k(Au.at),description:text$k(Au.description),prompt:text$k(Au.prompt)}}function parseAppspec(Au){const lo=[];if(!isData(Au))return{app:emptyAppspec(),problems:["The document is not an application."]};const $u=Au;for(const Uu of Object.keys($u))KNOWN_KEYS.includes(Uu)||lo.push(`\`${Uu}\` is not a field of the spec.`);lo.push(...uiShapeProblems($u.ui));const Ru=text$k($u.schema,APP_SCHEMA);Ru!==APP_SCHEMA&&lo.push(`This reads ${APP_SCHEMA}; the application is written in ${Ru}.`),APP_KINDS.includes($u.kind)||lo.push($u.kind===void 0?"The application does not say its `kind`.":`\`${String($u.kind)}\` is not a kind: chat, widget, decision or worker.`);const Iu=oneOf$3($u.kind,APP_KINDS,"chat"),Pu=emptyAppspec(Iu),Ou=isData($u.permissions)?$u.permissions:{},Mu=isData(Ou.computer)?Ou.computer:{},Du=isData($u.tests)?$u.tests:{},Lu=isData(Du.verified)?Du.verified:{},Bu=isData($u.record)?$u.record:{},ju=isData($u.checks)?$u.checks:{};for(const Uu of records$1(ju.code))CHECK_STAGES.includes(Uu.on)||lo.push(`The check \`${text$k(Uu.name)}\` of its code runs on answer or tool_call, not \`${String(Uu.on)}\`.`);const Fu=text$k(Bu.keep_for,DEFAULT_KEEP_FOR);retentionDays(Fu)===0&&lo.push(`Cannot read the retention \`${Fu}\`: write 90_days, 18_months or 1_years.`);const zu={...Pu,schema:APP_SCHEMA,id:text$k($u.id),version:text$k($u.version,DEFAULT_VERSION),name:text$k($u.name),kind:Iu,description:text$k($u.description),owner:text$k($u.owner),agent:text$k($u.agent),team:text$k($u.team),instructions:text$k($u.instructions),model:text$k($u.model),skills:texts($u.skills),backendTools:texts($u.backend_tools),tools:records$1($u.tools).map(parseTool),context:texts($u.context),contents:texts($u.contents),connections:records$1($u.connections).map(parseConnection),protocols:texts($u.protocols),ui:uiChoices($u.ui),rules:records$1($u.rules).map(parseRule$1),permissions:{spaces:records$1(Ou.spaces).map(Uu=>({space:text$k(Uu.space),access:oneOf$3(Uu.access,["read","write"],"read")})),computer:{browse:flag(Mu.browse,!1),files:flag(Mu.files,!1),shell:flag(Mu.shell,!1)}},interface:parseInterface(isData($u.interface)?$u.interface:{},Iu),tests:{readyAt:Math.min(1,Math.max(0,numberOf(Du.ready_at,DEFAULT_READY_AT))),evalset:text$k(Du.evalset),cases:records$1(Du.cases).map(Uu=>({ask:text$k(Uu.ask),...records$1(Uu.turns).length?{turns:records$1(Uu.turns).map(parseTestTurn)}:{},expect:text$k(Uu.expect),...text$k(Uu.code)?{code:text$k(Uu.code)}:{},...records$1(Uu.files).length?{files:records$1(Uu.files).map(Hu=>({name:text$k(Hu.name),text:text$k(Hu.text)}))}:{}})),verified:{live:texts(Lu.live),recorded:texts(Lu.recorded),unverified:texts(Lu.unverified)}},record:{keepFor:Fu,retentionDays:retentionDays(Fu),include:Array.isArray(Bu.include)?texts(Bu.include):[...DEFAULT_RECORD_INCLUDE],suggestTests:Bu.suggest_tests===!0},checks:{guards:texts(ju.guards),gates:texts(ju.gates),track:text$k(ju.track),code:records$1(ju.code).map(Uu=>({name:text$k(Uu.name),on:oneOf$3(Uu.on,CHECK_STAGES,"answer"),description:text$k(Uu.description)}))},deployment:parseDeployment(isData($u.deployment)?$u.deployment:{}),goal:text$k($u.goal),triggers:records$1($u.triggers).map(parseTrigger),memory:text$k($u.memory),notifications:texts($u.notifications),samples:parseSamples(isData($u.samples)?$u.samples:{}),enabled:flag($u.enabled,!0),unavailable_because:text$k($u.unavailable_because),tags:texts($u.tags),icon:text$k($u.icon,DEFAULT_ICON),emoji:text$k($u.emoji,DEFAULT_EMOJI)||DEFAULT_EMOJI,avatar:text$k($u.avatar).trim(),banner:text$k($u.banner).trim()};if(isData($u.decision)&&(zu.decision=parseDecision($u.decision)),isData($u.pap)&&Object.keys($u.pap).length>0){const Uu=papProfileProblem($u.pap.profile);Uu?lo.push(Uu):zu.pap=parsePap($u.pap)}if(isData($u.pact)&&(zu.pact=parsePact($u.pact)),isData($u.commerce)&&(zu.commerce=parseCommerce($u.commerce)),isData($u.signed_fetch)&&(zu.signed_fetch=parseSignedFetch($u.signed_fetch)),isData($u.pair)){const Uu=parsePair($u.pair);typeof Uu=="string"?lo.push(Uu):zu.pair=Uu}return isData($u.a2a)&&(zu.a2a=parseA2A($u.a2a)),lo.push(...protocolsProblems(zu),...uiProblems(zu)),{app:zu,problems:lo}}function uiProblems(Au){const lo=[],$u=[];for(const Ru of Au.ui){const Iu=Ru.plugin;if($u.includes(Iu)){lo.push(`It lists the UI plugin '${Iu}' twice.`);continue}$u.push(Iu);const Pu=UI_CATALOGUE[Iu];if(!Pu){lo.push(`There is no UI plugin named '${Iu}': one of ${Object.keys(UI_CATALOGUE).sort().join(", ")}.`+(UI_RENDERER_CATALOGUE[Iu]?` '${Iu}' is a UI renderer: say it as a plugin's \`renderer\`.`:""));continue}if(Ru.renderer===void 0)continue;const Ou=UI_RENDERER_CATALOGUE[Ru.renderer];Ou?Pu.renderers.includes(Ou.id)?Au.enabled&&!Ou.enabled&&lo.push(`The UI renderer ${Ou.name} ('${Ou.id}') is not enabled: an application cannot be exposed through it yet.`):lo.push(`The UI plugin ${Pu.name} ('${Iu}') is not exposed through ${Ou.name}: `+(Pu.renderers.length>0?`through ${Pu.renderers.join(", ")} only.`:"through no renderer.")):lo.push(`There is no UI renderer named '${Ru.renderer}': one of ${Object.keys(UI_RENDERER_CATALOGUE).sort().join(", ")}.`)}return lo}function protocolsProblems(Au){const lo=[],$u=[];for(const Iu of Au.protocols){if($u.includes(Iu)){lo.push(`It lists the protocol '${Iu}' twice.`);continue}$u.push(Iu);const Pu=PROTOCOL_CATALOGUE[Iu];Pu?Au.enabled&&Pu.status==="planned"&&lo.push(`${Pu.name} ('${Iu}') is planned, not shipped: an application cannot speak it yet.`):lo.push(`There is no protocol named '${Iu}': one of ${Object.keys(PROTOCOL_CATALOGUE).sort().join(", ")}.`)}const Ru={pap:!!(Au.pap&&(Au.pap.connections.length>0||Au.pap.company.enabled)),pact:!!(Au.pact&&(Au.pact.connections.length>0||Au.pact.business?.enabled)),a2a:!!(Au.a2a&&Au.a2a.extensions.length>0),signed_fetch:!!(Au.signed_fetch&&Au.signed_fetch.sites.length>0)};for(const Iu of Object.values(PROTOCOL_CATALOGUE)){const Pu=Iu.appspecBlock;Pu&&Ru[Pu]&&!Au.protocols.includes(Iu.id)&&lo.push(`Its \`${Pu}\` block configures ${Iu.name}, which it does not list: add '${Iu.id}' to \`protocols\`.`)}for(const Iu of new Set((Au.commerce?.merchants??[]).map(Pu=>Pu.protocol)))Au.protocols.includes(Iu)||lo.push(`Its \`commerce\` block shops over ${Iu.toUpperCase()}, which it does not list: add '${Iu}' to \`protocols\`.`);return lo}const sameList=(Au,lo)=>Au.length===lo.length&&Au.every(($u,Ru)=>$u===lo[Ru]);class Writer{data={};text(lo,$u,Ru=""){return $u!==Ru&&(this.data[lo]=$u),this}value(lo,$u,Ru){return $u!==Ru&&(this.data[lo]=$u),this}list(lo,$u,Ru=[]){return sameList($u,Ru)||(this.data[lo]=$u),this}part(lo,$u){return Object.keys($u).length>0&&(this.data[lo]=$u),this}present(lo,$u){return $u!==void 0&&(this.data[lo]=$u),this}}function sorted(Au){return Array.isArray(Au)?Au.map(sorted):isData(Au)?Object.fromEntries(Object.keys(Au).sort((lo,$u)=>lo<$u?-1:lo>$u?1:0).map(lo=>[lo,sorted(Au[lo])])):Au}function dumpComponent(Au){const{id:lo,component:$u,...Ru}=Au;return{id:lo,component:$u,...sorted(Ru)}}function dumpSurface(Au){return new Writer().text("protocol",Au.protocol,DEFAULT_PROTOCOL).list("components",Au.components.map(dumpComponent)).text("composed_by",Au.composedBy).text("composed_at",Au.composedAt).data}function dumpStarter(Au){return new Writer().text("label",Au.label,"\0").text("message",Au.message,"\0").text("category",Au.category??"").data}const saidWords=Au=>Object.fromEntries(Object.entries(Au).filter(([,lo])=>lo!==""));function dumpTranslation(Au){const lo=($u,Ru)=>Object.fromEntries(Object.entries($u).map(([Iu,Pu])=>[Iu,Ru(Pu)]));return new Writer().text("name",Au.name).text("description",Au.description).text("welcome",Au.welcome).part("starters",lo(Au.starters,$u=>new Writer().text("label",$u.label).text("message",$u.message).data)).part("categories",saidWords(Au.categories)).part("settings",lo(Au.settings,$u=>new Writer().text("title",$u.title).text("description",$u.description).part("options",saidWords($u.options)).data)).part("commands",saidWords(Au.commands)).part("modes",lo(Au.modes,$u=>new Writer().text("label",$u.label).part("options",lo($u.options,Ru=>new Writer().text("label",Ru.label).text("description",Ru.description).data)).data)).part("profiles",lo(Au.profiles,$u=>new Writer().text("label",$u.label).text("description",$u.description).data)).data}function dumpInterface(Au,lo){const $u=new Writer().value("layout",Au.layout,DEFAULT_LAYOUTS[lo]).value("accent",Au.accent,void 0).text("welcome",Au.welcome).list("starters",Au.starters.map(dumpStarter)).list("commands",Au.commands.map(Ru=>({name:Ru.name,description:Ru.description,prompt:Ru.prompt}))).list("modes",Au.modes.map(Ru=>{const Iu=new Writer().text("id",Ru.id,"\0").text("label",Ru.label,"\0").list("options",Ru.options.map(Pu=>new Writer().text("id",Pu.id,"\0").text("label",Pu.label,"\0").text("description",Pu.description??"").text("instructions",Pu.instructions??"").text("model",Pu.model??"").data));return Ru.default&&(Iu.data.default=Ru.default),Iu.data})).list("actions",(Au.actions??[]).map(Ru=>{const Iu=new Writer().text("name",Ru.name,"\0").text("description",Ru.description??"");return Ru.payload&&(Iu.data.payload={...Ru.payload}),Iu.data})).list("profiles",(Au.profiles??[]).map(Ru=>new Writer().text("id",Ru.id,"\0").text("label",Ru.label,"\0").text("description",Ru.description).text("instructions",Ru.instructions).text("model",Ru.model??"").list("starters",Ru.starters.map(dumpStarter)).data)).part("settings",Au.settings?{...Au.settings}:{});return Au.settingsUi&&($u.data.settings_ui={...Au.settingsUi}),$u.text("language",Au.language??DEFAULT_LANGUAGE,DEFAULT_LANGUAGE).part("translations",mapValues(Au.translations??{},dumpTranslation)),Au.uploads&&($u.data.uploads=new Writer().list("kinds",Au.uploads.kinds.map(Ru=>new Writer().text("type",Ru.type,"\0").value("max_mb",Ru.maxMb,DEFAULT_UPLOAD_MB).data)).value("max_files",Au.uploads.maxFiles,DEFAULT_MAX_FILES).data),$u.list("components",Au.components),$u.list("custom_components",(Au.customComponents??[]).map(dumpCustomComponent)),Au.surface&&($u.data.surface=dumpSurface(Au.surface)),Au.page&&($u.data.page=dumpPage(Au.page)),Au.avatar&&($u.data.avatar=typeof Au.avatar=="string"?Au.avatar:{...Au.avatar}),Au.balloon&&($u.data.balloon=Au.balloon),Au.theme&&($u.data.theme=Au.theme.mode?{variant:Au.theme.variant,mode:Au.theme.mode}:{variant:Au.theme.variant}),Au.voice&&$u.part("voice",new Writer().value("enabled",Au.voice.enabled,DEFAULT_VOICE.enabled).value("input",Au.voice.input,DEFAULT_VOICE.input).value("output",Au.voice.output,DEFAULT_VOICE.output).text("voice",Au.voice.voice).text("language",Au.voice.language).value("where",Au.voice.where,DEFAULT_VOICE.where).data),$u.list("outputs",Au.outputs??[]),$u.data}function dumpDecision(Au){return new Writer().text("question",Au.question,"\0").list("alternatives",Au.alternatives).list("criteria",Au.criteria.map(lo=>new Writer().text("name",lo.name,"\0").value("kind",lo.kind,"metric").value("weight",lo.weight,1).text("instructions",lo.instructions).list("options",lo.options).value("direction",lo.direction,"higher").value("measure",lo.measure,"").data)).value("min_confidence",Au.minConfidence,0).list("scenarios",Au.scenarios.map(lo=>new Writer().text("name",lo.name,"\0").part("weights",sorted(lo.weights)).data)).text("decision_model",Au.decisionModel).data}function dumpSamples(Au){return new Writer().list("documents",Au.documents.map(lo=>new Writer().text("name",lo.name,"\0").text("file",lo.file,"\0").text("text",lo.text,"\0").data)).list("alternatives",Au.alternatives.map(lo=>new Writer().text("name",lo.name,"\0").text("evidence",lo.evidence,"\0").part("metrics",{...lo.metrics}).data)).data}function dumpAppspec(Au){const lo=new Writer().value("browse",Au.permissions.computer.browse,!1).value("files",Au.permissions.computer.files,!1).value("shell",Au.permissions.computer.shell,!1).data,$u=new Writer;return $u.data.schema=APP_SCHEMA,$u.text("id",Au.id,"\0").text("version",Au.version,DEFAULT_VERSION).text("name",Au.name,"\0").text("kind",Au.kind,"\0").text("description",Au.description).text("owner",Au.owner).text("agent",Au.agent).text("team",Au.team).text("instructions",Au.instructions).text("model",Au.model).list("skills",Au.skills).list("backend_tools",Au.backendTools).list("tools",(Au.tools??[]).map(Ru=>({name:Ru.name,description:Ru.description,...JSON.stringify(Ru.parameters)===JSON.stringify(NO_HOST_PARAMETERS)?{}:{parameters:Ru.parameters},does:Ru.does}))).list("context",Au.context).list("contents",Au.contents).list("connections",Au.connections.map(Ru=>new Writer().text("server",Ru.server,"\0").value("access",Ru.access,"read").value("as",Ru.as,"owner").list("only",Ru.only).data)).list("protocols",Au.protocols).list("ui",Au.ui.map(Ru=>Ru.renderer?{plugin:Ru.plugin,renderer:Ru.renderer}:{plugin:Ru.plugin})).part("pap",dumpPap(Au.pap)).part("pact",dumpPact(Au.pact)).part("commerce",dumpCommerce(Au.commerce)).part("signed_fetch",dumpSignedFetch(Au.signed_fetch)).part("pair",Au.pair?{id:Au.pair.id,role:Au.pair.role}:{}).part("a2a",dumpA2A(Au.a2a)).list("rules",Au.rules.map(Ru=>({action:Ru.action,applies_to:Ru.appliesTo.length===1&&ACTION_CLASS_NAMES.includes(Ru.appliesTo[0])?Ru.appliesTo[0]:Ru.appliesTo,behaviour:Ru.behaviour}))).part("permissions",new Writer().list("spaces",Au.permissions.spaces.map(Ru=>new Writer().text("space",Ru.space,"\0").value("access",Ru.access,"read").data)).part("computer",lo).data).part("interface",dumpInterface(Au.interface,Au.kind)).part("tests",new Writer().value("ready_at",Au.tests.readyAt,DEFAULT_READY_AT).text("evalset",Au.tests.evalset).list("cases",Au.tests.cases.map(Ru=>({...Ru.turns?.length?{turns:Ru.turns.map(Iu=>parseTestTurn({...Iu}))}:{ask:Ru.ask},expect:Ru.expect,...Ru.code?{code:Ru.code}:{},...Ru.files?.length?{files:Ru.files.map(Iu=>({name:Iu.name,text:Iu.text}))}:{}}))).part("verified",new Writer().list("live",Au.tests.verified.live).list("recorded",Au.tests.verified.recorded).list("unverified",Au.tests.verified.unverified).data).data).part("record",new Writer().text("keep_for",Au.record.keepFor,DEFAULT_KEEP_FOR).list("include",Au.record.include,DEFAULT_RECORD_INCLUDE).value("suggest_tests",Au.record.suggestTests,!1).data).part("checks",new Writer().list("guards",Au.checks.guards).list("gates",Au.checks.gates).text("track",Au.checks.track).list("code",(Au.checks.code??[]).map(Ru=>({name:Ru.name,on:Ru.on,description:Ru.description}))).data).part("deployment",new Writer().present("hosted",Au.deployment.hosted&&new Writer().value("visibility",Au.deployment.hosted.visibility,"private").text("slug",Au.deployment.hosted.slug).value("avatar_alone",Au.deployment.hosted.avatarAlone===!0,!1).data).present("embedded",Au.deployment.embedded&&new Writer().value("mode",Au.deployment.embedded.mode,"inline").list("origins",Au.deployment.embedded.origins).present("host",Au.deployment.embedded.host&&new Writer().list("context",Au.deployment.embedded.host.context).list("functions",Au.deployment.embedded.host.functions.map(Ru=>({name:Ru.name,description:Ru.description,...JSON.stringify(Ru.parameters)===JSON.stringify(NO_HOST_PARAMETERS)?{}:{parameters:Ru.parameters}}))).value("user",Au.deployment.embedded.host.user??"claimed","claimed").data).data).data).text("goal",Au.goal).list("triggers",Au.triggers.map(Ru=>new Writer().text("type",Ru.type,"\0").text("cron",Ru.cron).text("event",Ru.event).text("at",Ru.at).text("description",Ru.description).text("prompt",Ru.prompt).data)).text("memory",Au.memory).list("notifications",Au.notifications),Au.decision&&($u.data.decision=dumpDecision(Au.decision)),$u.part("samples",dumpSamples(Au.samples)).value("enabled",Au.enabled,!0).text("unavailable_because",Au.unavailable_because).list("tags",Au.tags).text("icon",Au.icon??DEFAULT_ICON,DEFAULT_ICON).text("emoji",Au.emoji,DEFAULT_EMOJI).text("avatar",Au.avatar??"","").text("banner",Au.banner??"",""),$u.data}const ALIAS=Symbol.for("yaml.alias"),DOC=Symbol.for("yaml.document"),MAP$1=Symbol.for("yaml.map"),PAIR=Symbol.for("yaml.pair"),SCALAR$1=Symbol.for("yaml.scalar"),SEQ=Symbol.for("yaml.seq"),NODE_TYPE$1=Symbol.for("yaml.node.type"),isAlias=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===ALIAS,isDocument=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===DOC,isMap=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===MAP$1,isPair=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===PAIR,isScalar=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===SCALAR$1,isSeq$1=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===SEQ;function isCollection(Au){if(Au&&typeof Au=="object")switch(Au[NODE_TYPE$1]){case MAP$1:case SEQ:return!0}return!1}function isNode$1(Au){if(Au&&typeof Au=="object")switch(Au[NODE_TYPE$1]){case ALIAS:case MAP$1:case SCALAR$1:case SEQ:return!0}return!1}const hasAnchor=Au=>(isScalar(Au)||isCollection(Au))&&!!Au.anchor,BREAK=Symbol("break visit"),SKIP$1=Symbol("skip children"),REMOVE=Symbol("remove node");function visit$4(Au,lo){const $u=initVisitor(lo);isDocument(Au)?visit_(null,Au.contents,$u,Object.freeze([Au]))===REMOVE&&(Au.contents=null):visit_(null,Au,$u,Object.freeze([]))}visit$4.BREAK=BREAK;visit$4.SKIP=SKIP$1;visit$4.REMOVE=REMOVE;function visit_(Au,lo,$u,Ru){const Iu=callVisitor(Au,lo,$u,Ru);if(isNode$1(Iu)||isPair(Iu))return replaceNode(Au,Ru,Iu),visit_(Au,Iu,$u,Ru);if(typeof Iu!="symbol"){if(isCollection(lo)){Ru=Object.freeze(Ru.concat(lo));for(let Pu=0;Pu<lo.items.length;++Pu){const Ou=visit_(Pu,lo.items[Pu],$u,Ru);if(typeof Ou=="number")Pu=Ou-1;else{if(Ou===BREAK)return BREAK;Ou===REMOVE&&(lo.items.splice(Pu,1),Pu-=1)}}}else if(isPair(lo)){Ru=Object.freeze(Ru.concat(lo));const Pu=visit_("key",lo.key,$u,Ru);if(Pu===BREAK)return BREAK;Pu===REMOVE&&(lo.key=null);const Ou=visit_("value",lo.value,$u,Ru);if(Ou===BREAK)return BREAK;Ou===REMOVE&&(lo.value=null)}}return Iu}function initVisitor(Au){return typeof Au=="object"&&(Au.Collection||Au.Node||Au.Value)?Object.assign({Alias:Au.Node,Map:Au.Node,Scalar:Au.Node,Seq:Au.Node},Au.Value&&{Map:Au.Value,Scalar:Au.Value,Seq:Au.Value},Au.Collection&&{Map:Au.Collection,Seq:Au.Collection},Au):Au}function callVisitor(Au,lo,$u,Ru){if(typeof $u=="function")return $u(Au,lo,Ru);if(isMap(lo))return $u.Map?.(Au,lo,Ru);if(isSeq$1(lo))return $u.Seq?.(Au,lo,Ru);if(isPair(lo))return $u.Pair?.(Au,lo,Ru);if(isScalar(lo))return $u.Scalar?.(Au,lo,Ru);if(isAlias(lo))return $u.Alias?.(Au,lo,Ru)}function replaceNode(Au,lo,$u){const Ru=lo[lo.length-1];if(isCollection(Ru))Ru.items[Au]=$u;else if(isPair(Ru))Au==="key"?Ru.key=$u:Ru.value=$u;else if(isDocument(Ru))Ru.contents=$u;else{const Iu=isAlias(Ru)?"alias":"scalar";throw new Error(`Cannot replace node with ${Iu} parent`)}}const escapeChars={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},escapeTagName=Au=>Au.replace(/[!,[\]{}]/g,lo=>escapeChars[lo]);class Directives{constructor(lo,$u){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Directives.defaultYaml,lo),this.tags=Object.assign({},Directives.defaultTags,$u)}clone(){const lo=new Directives(this.yaml,this.tags);return lo.docStart=this.docStart,lo}atDocument(){const lo=new Directives(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Directives.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Directives.defaultTags);break}return lo}add(lo,$u){this.atNextDocument&&(this.yaml={explicit:Directives.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Directives.defaultTags),this.atNextDocument=!1);const Ru=lo.trim().split(/[ \t]+/),Iu=Ru.shift();switch(Iu){case"%TAG":{if(Ru.length!==2&&($u(0,"%TAG directive should contain exactly two parts"),Ru.length<2))return!1;const[Pu,Ou]=Ru;return this.tags[Pu]=Ou,!0}case"%YAML":{if(this.yaml.explicit=!0,Ru.length!==1)return $u(0,"%YAML directive should contain exactly one part"),!1;const[Pu]=Ru;if(Pu==="1.1"||Pu==="1.2")return this.yaml.version=Pu,!0;{const Ou=/^\d+\.\d+$/.test(Pu);return $u(6,`Unsupported YAML version ${Pu}`,Ou),!1}}default:return $u(0,`Unknown directive ${Iu}`,!0),!1}}tagName(lo,$u){if(lo==="!")return"!";if(lo[0]!=="!")return $u(`Not a valid tag: ${lo}`),null;if(lo[1]==="<"){const Ou=lo.slice(2,-1);return Ou==="!"||Ou==="!!"?($u(`Verbatim tags aren't resolved, so ${lo} is invalid.`),null):(lo[lo.length-1]!==">"&&$u("Verbatim tags must end with a >"),Ou)}const[,Ru,Iu]=lo.match(/^(.*!)([^!]*)$/s);Iu||$u(`The ${lo} tag has no suffix`);const Pu=this.tags[Ru];if(Pu)try{return Pu+decodeURIComponent(Iu)}catch(Ou){return $u(String(Ou)),null}return Ru==="!"?lo:($u(`Could not resolve tag: ${lo}`),null)}tagString(lo){for(const[$u,Ru]of Object.entries(this.tags))if(lo.startsWith(Ru))return $u+escapeTagName(lo.substring(Ru.length));return lo[0]==="!"?lo:`!<${lo}>`}toString(lo){const $u=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],Ru=Object.entries(this.tags);let Iu;if(lo&&Ru.length>0&&isNode$1(lo.contents)){const Pu={};visit$4(lo.contents,(Ou,Mu)=>{isNode$1(Mu)&&Mu.tag&&(Pu[Mu.tag]=!0)}),Iu=Object.keys(Pu)}else Iu=[];for(const[Pu,Ou]of Ru)Pu==="!!"&&Ou==="tag:yaml.org,2002:"||(!lo||Iu.some(Mu=>Mu.startsWith(Ou)))&&$u.push(`%TAG ${Pu} ${Ou}`);return $u.join(`
|
|
124
124
|
`)}}Directives.defaultYaml={explicit:!1,version:"1.2"};Directives.defaultTags={"!!":"tag:yaml.org,2002:"};function anchorIsValid(Au){if(/[\x00-\x19\s,[\]{}]/.test(Au)){const $u=`Anchor must not contain whitespace or control characters: ${JSON.stringify(Au)}`;throw new Error($u)}return!0}function anchorNames(Au){const lo=new Set;return visit$4(Au,{Value($u,Ru){Ru.anchor&&lo.add(Ru.anchor)}}),lo}function findNewAnchor(Au,lo){for(let $u=1;;++$u){const Ru=`${Au}${$u}`;if(!lo.has(Ru))return Ru}}function createNodeAnchors(Au,lo){const $u=[],Ru=new Map;let Iu=null;return{onAnchor:Pu=>{$u.push(Pu),Iu??(Iu=anchorNames(Au));const Ou=findNewAnchor(lo,Iu);return Iu.add(Ou),Ou},setAnchors:()=>{for(const Pu of $u){const Ou=Ru.get(Pu);if(typeof Ou=="object"&&Ou.anchor&&(isScalar(Ou.node)||isCollection(Ou.node)))Ou.node.anchor=Ou.anchor;else{const Mu=new Error("Failed to resolve repeated object (this should not happen)");throw Mu.source=Pu,Mu}}},sourceObjects:Ru}}function applyReviver(Au,lo,$u,Ru){if(Ru&&typeof Ru=="object")if(Array.isArray(Ru))for(let Iu=0,Pu=Ru.length;Iu<Pu;++Iu){const Ou=Ru[Iu],Mu=applyReviver(Au,Ru,String(Iu),Ou);Mu===void 0?delete Ru[Iu]:Mu!==Ou&&(Ru[Iu]=Mu)}else if(Ru instanceof Map)for(const Iu of Array.from(Ru.keys())){const Pu=Ru.get(Iu),Ou=applyReviver(Au,Ru,Iu,Pu);Ou===void 0?Ru.delete(Iu):Ou!==Pu&&Ru.set(Iu,Ou)}else if(Ru instanceof Set)for(const Iu of Array.from(Ru)){const Pu=applyReviver(Au,Ru,Iu,Iu);Pu===void 0?Ru.delete(Iu):Pu!==Iu&&(Ru.delete(Iu),Ru.add(Pu))}else for(const[Iu,Pu]of Object.entries(Ru)){const Ou=applyReviver(Au,Ru,Iu,Pu);Ou===void 0?delete Ru[Iu]:Ou!==Pu&&(Ru[Iu]=Ou)}return Au.call(lo,$u,Ru)}function toJS(Au,lo,$u){if(Array.isArray(Au))return Au.map((Ru,Iu)=>toJS(Ru,String(Iu),$u));if(Au&&typeof Au.toJSON=="function"){if(!$u||!hasAnchor(Au))return Au.toJSON(lo,$u);const Ru={aliasCount:0,count:1,res:void 0};$u.anchors.set(Au,Ru),$u.onCreate=Pu=>{Ru.res=Pu,delete $u.onCreate};const Iu=Au.toJSON(lo,$u);return $u.onCreate&&$u.onCreate(Iu),Iu}return typeof Au=="bigint"&&!$u?.keep?Number(Au):Au}class NodeBase{constructor(lo){Object.defineProperty(this,NODE_TYPE$1,{value:lo})}clone(){const lo=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(lo.range=this.range.slice()),lo}toJS(lo,{mapAsMap:$u,maxAliasCount:Ru,onAnchor:Iu,reviver:Pu}={}){if(!isDocument(lo))throw new TypeError("A document argument is required");const Ou={anchors:new Map,doc:lo,keep:!0,mapAsMap:$u===!0,mapKeyWarned:!1,maxAliasCount:typeof Ru=="number"?Ru:100},Mu=toJS(this,"",Ou);if(typeof Iu=="function")for(const{count:Du,res:Lu}of Ou.anchors.values())Iu(Lu,Du);return typeof Pu=="function"?applyReviver(Pu,{"":Mu},"",Mu):Mu}}class Alias extends NodeBase{constructor(lo){super(ALIAS),this.source=lo,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(lo,$u){if($u?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let Ru;$u?.aliasResolveCache?Ru=$u.aliasResolveCache:(Ru=[],visit$4(lo,{Node:(Pu,Ou)=>{(isAlias(Ou)||hasAnchor(Ou))&&Ru.push(Ou)}}),$u&&($u.aliasResolveCache=Ru));let Iu;for(const Pu of Ru){if(Pu===this)break;Pu.anchor===this.source&&(Iu=Pu)}if(Iu&&$u){const{anchors:Pu,doc:Ou,maxAliasCount:Mu}=$u;let Du=Pu.get(Iu);if(Du||(toJS(Iu,null,$u),Du=Pu.get(Iu)),Du?.res===void 0){const Lu="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(Lu)}if(Mu>=0&&(Du.count+=1,Du.aliasCount===0&&(Du.aliasCount=getAliasCount(Ou,Iu,Pu)),Du.count*Du.aliasCount>Mu)){const Lu="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(Lu)}}return Iu}toJSON(lo,$u){if(!$u)return{source:this.source};const Ru=this.resolve($u.doc,$u);if(!Ru){const Iu=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(Iu)}return $u.anchors.get(Ru).res}toString(lo,$u,Ru){const Iu=`*${this.source}`;if(lo){if(anchorIsValid(this.source),lo.options.verifyAliasOrder&&!lo.anchors.has(this.source)){const Pu=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(Pu)}if(lo.implicitKey)return`${Iu} `}return Iu}}function getAliasCount(Au,lo,$u){if(isAlias(lo)){const Ru=lo.resolve(Au),Iu=$u&&Ru&&$u.get(Ru);return Iu?Iu.count*Iu.aliasCount:0}else if(isCollection(lo)){let Ru=0;for(const Iu of lo.items){const Pu=getAliasCount(Au,Iu,$u);Pu>Ru&&(Ru=Pu)}return Ru}else if(isPair(lo)){const Ru=getAliasCount(Au,lo.key,$u),Iu=getAliasCount(Au,lo.value,$u);return Math.max(Ru,Iu)}return 1}const isScalarValue=Au=>!Au||typeof Au!="function"&&typeof Au!="object";class Scalar extends NodeBase{constructor(lo){super(SCALAR$1),this.value=lo}toJSON(lo,$u){return $u?.keep?this.value:toJS(this.value,lo,$u)}toString(){return String(this.value)}}Scalar.BLOCK_FOLDED="BLOCK_FOLDED";Scalar.BLOCK_LITERAL="BLOCK_LITERAL";Scalar.PLAIN="PLAIN";Scalar.QUOTE_DOUBLE="QUOTE_DOUBLE";Scalar.QUOTE_SINGLE="QUOTE_SINGLE";const defaultTagPrefix="tag:yaml.org,2002:";function findTagObject(Au,lo,$u){if(lo){const Ru=$u.filter(Pu=>Pu.tag===lo),Iu=Ru.find(Pu=>!Pu.format)??Ru[0];if(!Iu)throw new Error(`Tag ${lo} not found`);return Iu}return $u.find(Ru=>Ru.identify?.(Au)&&!Ru.format)}function createNode(Au,lo,$u){if(isDocument(Au)&&(Au=Au.contents),isNode$1(Au))return Au;if(isPair(Au)){const ju=$u.schema[MAP$1].createNode?.($u.schema,null,$u);return ju.items.push(Au),ju}(Au instanceof String||Au instanceof Number||Au instanceof Boolean||typeof BigInt<"u"&&Au instanceof BigInt)&&(Au=Au.valueOf());const{aliasDuplicateObjects:Ru,onAnchor:Iu,onTagObj:Pu,schema:Ou,sourceObjects:Mu}=$u;let Du;if(Ru&&Au&&typeof Au=="object"){if(Du=Mu.get(Au),Du)return Du.anchor??(Du.anchor=Iu(Au)),new Alias(Du.anchor);Du={anchor:null,node:null},Mu.set(Au,Du)}lo?.startsWith("!!")&&(lo=defaultTagPrefix+lo.slice(2));let Lu=findTagObject(Au,lo,Ou.tags);if(!Lu){if(Au&&typeof Au.toJSON=="function"&&(Au=Au.toJSON()),!Au||typeof Au!="object"){const ju=new Scalar(Au);return Du&&(Du.node=ju),ju}Lu=Au instanceof Map?Ou[MAP$1]:Symbol.iterator in Object(Au)?Ou[SEQ]:Ou[MAP$1]}Pu&&(Pu(Lu),delete $u.onTagObj);const Bu=Lu?.createNode?Lu.createNode($u.schema,Au,$u):typeof Lu?.nodeClass?.from=="function"?Lu.nodeClass.from($u.schema,Au,$u):new Scalar(Au);return lo?Bu.tag=lo:Lu.default||(Bu.tag=Lu.tag),Du&&(Du.node=Bu),Bu}function collectionFromPath(Au,lo,$u){let Ru=$u;for(let Iu=lo.length-1;Iu>=0;--Iu){const Pu=lo[Iu];if(typeof Pu=="number"&&Number.isInteger(Pu)&&Pu>=0){const Ou=[];Ou[Pu]=Ru,Ru=Ou}else Ru=new Map([[Pu,Ru]])}return createNode(Ru,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:Au,sourceObjects:new Map})}const isEmptyPath=Au=>Au==null||typeof Au=="object"&&!!Au[Symbol.iterator]().next().done;class Collection extends NodeBase{constructor(lo,$u){super(lo),Object.defineProperty(this,"schema",{value:$u,configurable:!0,enumerable:!1,writable:!0})}clone(lo){const $u=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return lo&&($u.schema=lo),$u.items=$u.items.map(Ru=>isNode$1(Ru)||isPair(Ru)?Ru.clone(lo):Ru),this.range&&($u.range=this.range.slice()),$u}addIn(lo,$u){if(isEmptyPath(lo))this.add($u);else{const[Ru,...Iu]=lo,Pu=this.get(Ru,!0);if(isCollection(Pu))Pu.addIn(Iu,$u);else if(Pu===void 0&&this.schema)this.set(Ru,collectionFromPath(this.schema,Iu,$u));else throw new Error(`Expected YAML collection at ${Ru}. Remaining path: ${Iu}`)}}deleteIn(lo){const[$u,...Ru]=lo;if(Ru.length===0)return this.delete($u);const Iu=this.get($u,!0);if(isCollection(Iu))return Iu.deleteIn(Ru);throw new Error(`Expected YAML collection at ${$u}. Remaining path: ${Ru}`)}getIn(lo,$u){const[Ru,...Iu]=lo,Pu=this.get(Ru,!0);return Iu.length===0?!$u&&isScalar(Pu)?Pu.value:Pu:isCollection(Pu)?Pu.getIn(Iu,$u):void 0}hasAllNullValues(lo){return this.items.every($u=>{if(!isPair($u))return!1;const Ru=$u.value;return Ru==null||lo&&isScalar(Ru)&&Ru.value==null&&!Ru.commentBefore&&!Ru.comment&&!Ru.tag})}hasIn(lo){const[$u,...Ru]=lo;if(Ru.length===0)return this.has($u);const Iu=this.get($u,!0);return isCollection(Iu)?Iu.hasIn(Ru):!1}setIn(lo,$u){const[Ru,...Iu]=lo;if(Iu.length===0)this.set(Ru,$u);else{const Pu=this.get(Ru,!0);if(isCollection(Pu))Pu.setIn(Iu,$u);else if(Pu===void 0&&this.schema)this.set(Ru,collectionFromPath(this.schema,Iu,$u));else throw new Error(`Expected YAML collection at ${Ru}. Remaining path: ${Iu}`)}}}const stringifyComment=Au=>Au.replace(/^(?!$)(?: $)?/gm,"#");function indentComment(Au,lo){return/^\n+$/.test(Au)?Au.substring(1):lo?Au.replace(/^(?! *$)/gm,lo):Au}const lineComment=(Au,lo,$u)=>Au.endsWith(`
|
|
125
125
|
`)?indentComment($u,lo):$u.includes(`
|
|
126
126
|
`)?`
|
|
@@ -259,7 +259,7 @@ ${$u.comment}`:$u.comment}this.doc.range[2]=$u.offset;break}default:this.errors.
|
|
|
259
259
|
`);Ou=Mu===-1?"":Pu.slice(Mu+1)}if(!Ru.stack)Ru.stack=Ou;else if(Ou){const Mu=Ou.indexOf(`
|
|
260
260
|
`),Du=Mu===-1?-1:Ou.indexOf(`
|
|
261
261
|
`,Mu+1),Lu=Du===-1?"":Ou.slice(Du+1);String(Ru.stack).endsWith(Lu)||(Ru.stack+=`
|
|
262
|
-
`+Ou)}}catch{}throw Ru}}_request(lo,$u){typeof lo=="string"?($u=$u||{},$u.url=lo):$u=lo||{},$u=mergeConfig$1(this.defaults,$u);const{transitional:Ru,paramsSerializer:Iu,headers:Pu}=$u;Ru!==void 0&&validator.assertOptions(Ru,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean),legacyInterceptorReqResOrdering:validators.transitional(validators.boolean),advertiseZstdAcceptEncoding:validators.transitional(validators.boolean),validateStatusUndefinedResolves:validators.transitional(validators.boolean)},!1),Iu!=null&&(utils$3.isFunction(Iu)?$u.paramsSerializer={serialize:Iu}:validator.assertOptions(Iu,{encode:validators.function,serialize:validators.function},!0)),$u.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?$u.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:$u.allowAbsoluteUrls=!0),validator.assertOptions($u,{baseUrl:validators.spelling("baseURL"),withXsrfToken:validators.spelling("withXSRFToken")},!0),$u.method=(utils$3.getSafeProp($u,"method")||utils$3.getSafeProp(this.defaults,"method")||"get").toLowerCase();let Ou=Pu&&utils$3.merge(Pu.common,Pu[$u.method]);Pu&&utils$3.forEach(methodList.concat("common"),Uu=>{delete Pu[Uu]}),$u.headers=AxiosHeaders$1.concat(Ou,Pu);const Mu=[];let Du=!0;this.interceptors.request.forEach(function(Hu){if(typeof Hu.runWhen=="function"&&Hu.runWhen($u)===!1)return;Du=Du&&Hu.synchronous;const Vu=$u.transitional||transitionalDefaults;Vu&&Vu.legacyInterceptorReqResOrdering?Mu.unshift(Hu.fulfilled,Hu.rejected):Mu.push(Hu.fulfilled,Hu.rejected)});const Lu=[];this.interceptors.response.forEach(function(Hu){Lu.push(Hu.fulfilled,Hu.rejected)});let Bu,ju=0,Fu;if(!Du){const Uu=[dispatchRequest.bind(this),void 0];for(Uu.unshift(...Mu),Uu.push(...Lu),Fu=Uu.length,Bu=Promise.resolve($u);ju<Fu;)Bu=Bu.then(Uu[ju++],Uu[ju++]);return Bu}Fu=Mu.length;let zu=$u;for(;ju<Fu;){const Uu=Mu[ju++],Hu=Mu[ju++];try{zu=Uu?Uu(zu):zu}catch(Vu){if(!Hu){Bu=Promise.reject(Vu);break}try{const Gu=Hu.call(this,Vu);utils$3.isThenable(Gu)&&(Bu=Promise.resolve(Gu).then(()=>dispatchRequest.call(this,zu)))}catch(Gu){Bu=Promise.reject(Gu)}break}}if(!Bu)try{Bu=dispatchRequest.call(this,zu)}catch(Uu){Bu=Promise.reject(Uu)}for(ju=0,Fu=Lu.length;ju<Fu;)Bu=Bu.then(Lu[ju++],Lu[ju++]);return Bu}getUri(lo){lo=mergeConfig$1(this.defaults,lo);const $u=buildFullPath(lo.baseURL,lo.url,lo.allowAbsoluteUrls,lo);return buildURL($u,lo.params,lo.paramsSerializer)}};utils$3.forEach(["delete","get","head","options"],function Au(lo){Axios$1.prototype[lo]=function($u,Ru){return this.request(mergeConfig$1(Ru||{},{method:lo,url:$u,data:Ru&&utils$3.hasOwnProp(Ru,"data")?Ru.data:void 0}))}});utils$3.forEach(["post","put","patch","query"],function Au(lo){function $u(Ru){return function(Pu,Ou,Mu){return this.request(mergeConfig$1(Mu||{},{method:lo,headers:Ru?{"Content-Type":"multipart/form-data"}:{},url:Pu,data:Ou}))}}Axios$1.prototype[lo]=$u(),lo!=="query"&&(Axios$1.prototype[lo+"Form"]=$u(!0))});let CancelToken$1=class vS{constructor(lo){if(typeof lo!="function")throw new TypeError("executor must be a function.");let $u;this.promise=new Promise(function(Pu){$u=Pu});const Ru=this;this.promise.then(Iu=>{if(!Ru._listeners)return;let Pu=Ru._listeners.length;for(;Pu-- >0;)Ru._listeners[Pu](Iu);Ru._listeners=null}),this.promise.then=Iu=>{let Pu;const Ou=new Promise(Mu=>{Ru.subscribe(Mu),Pu=Mu}).then(Iu);return Ou.cancel=function(){Ru.unsubscribe(Pu)},Ou},lo(function(Pu,Ou,Mu){Ru.reason||(Ru.reason=new CanceledError$1(Pu,Ou,Mu),$u(Ru.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(lo){if(this.reason){lo(this.reason);return}this._listeners?this._listeners.push(lo):this._listeners=[lo]}unsubscribe(lo){if(!this._listeners)return;const $u=this._listeners.indexOf(lo);$u!==-1&&this._listeners.splice($u,1)}toAbortSignal(){const lo=new AbortController,$u=Ru=>{lo.abort(Ru)};return this.subscribe($u),lo.signal.unsubscribe=()=>this.unsubscribe($u),lo.signal}static source(){let lo;return{token:new vS(function(Iu){lo=Iu}),cancel:lo}}};function spread$1(Au){return function($u){return Au.apply(null,$u)}}function isAxiosError$1(Au){return utils$3.isObject(Au)&&Au.isAxiosError===!0}const HttpStatusCode$1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,ContentTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,UnprocessableContent:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(HttpStatusCode$1).forEach(([Au,lo])=>{HttpStatusCode$1[lo]===void 0&&(HttpStatusCode$1[lo]=Au)});function createInstance(Au){const lo=new Axios$1(Au),$u=bind(Axios$1.prototype.request,lo);return utils$3.extend($u,Axios$1.prototype,lo,{allOwnKeys:!0}),utils$3.extend($u,lo,null,{allOwnKeys:!0}),$u.create=function(Iu){return createInstance(mergeConfig$1(Au,Iu))},$u}const axios=createInstance(defaults$3);axios.Axios=Axios$1;axios.CanceledError=CanceledError$1;axios.CancelToken=CancelToken$1;axios.isCancel=isCancel$1;axios.VERSION=VERSION$7;axios.toFormData=toFormData$1;axios.AxiosError=AxiosError$1;axios.Cancel=axios.CanceledError;axios.all=function Au(lo){return Promise.all(lo)};axios.spread=spread$1;axios.isAxiosError=isAxiosError$1;axios.mergeConfig=mergeConfig$1;axios.AxiosHeaders=AxiosHeaders$1;axios.formToJSON=Au=>formDataToJSON(utils$3.isHTMLForm(Au)?new FormData(Au):Au);axios.getAdapter=adapters.getAdapter;axios.HttpStatusCode=HttpStatusCode$1;axios.default=axios;const{Axios,AxiosError,CanceledError,isCancel,CancelToken,VERSION:VERSION$6,all:all$6,Cancel,isAxiosError,spread,toFormData,AxiosHeaders,HttpStatusCode,formToJSON,getAdapter,mergeConfig,create:create$f}=axios;var define_process_env_default$5={};function isFormDataBody(Au){if(!Au||typeof Au!="object")return!1;if(typeof FormData<"u"&&Au instanceof FormData||Object.prototype.toString.call(Au)==="[object FormData]")return!0;const $u=Au;return typeof $u.append=="function"&&typeof $u.get=="function"&&typeof $u.has=="function"&&typeof $u.entries=="function"}class RunResponseError extends Error{static async create(lo){try{const $u=await lo.json(),{message:Ru,errors:Iu,warnings:Pu,traceback:Ou,exception:Mu,detail:Du}=$u,Lu=Ru??(typeof Du=="string"?Du:Du&&typeof Du=="object"&&"message"in Du?String(Du.message):void 0);return Ou&&console.error(Ou),new RunResponseError(lo,Lu??RunResponseError._defaultMessage(lo),Pu,Iu,Mu,Ou??"",Du)}catch($u){return console.debug($u),new RunResponseError(lo)}}constructor(lo,$u=RunResponseError._defaultMessage(lo),Ru=void 0,Iu=void 0,Pu=void 0,Ou="",Mu=void 0){super($u),this.name="RunResponseError",this.warnings=Ru??[],this.errors=Iu??[],this.response=lo,this.exceptionMessage=Pu,this.traceback=Ou,this.detail=Mu}warnings;errors;response;exceptionMessage;traceback;detail;static _defaultMessage(lo){return`Invalid response: ${lo.status} ${lo.statusText}`}}class NetworkError extends TypeError{constructor(lo){super(lo.message),this.name="NetworkError",this.stack=lo.stack}}class TokenExpiredError extends Error{expiredAt;url;constructor(lo,$u){super(`The Datalayer token expired at ${new Date($u).toISOString()}; not sending the request to ${lo}.`),this.name="TokenExpiredError",this.expiredAt=$u,this.url=lo,Object.setPrototypeOf(this,TokenExpiredError.prototype)}}function throwIfTokenExpired(Au,lo,$u){if(!(Au!==401||!lo||!isJwtExpired(lo)))throw new TokenExpiredError($u,getJwtExpiryMs(lo)??Date.now())}async function requestDatalayerAPIWithResponse({url:Au,method:lo,body:$u,token:Ru,signal:Iu,responseType:Pu,headers:Ou={}}){const Mu=isFormDataBody($u),Du={url:Au,method:lo??"GET",headers:{...Ou},withCredentials:!0,signal:Iu,responseType:Pu};typeof process<"u"&&define_process_env_default$5.VITEST&&(Du.adapter="fetch"),(lo==="GET"||!lo)&&(Du.headers["Cache-Control"]||(Du.headers["Cache-Control"]="no-store, no-cache, must-revalidate"),Du.headers.Pragma||(Du.headers.Pragma="no-cache")),Ru&&(Du.headers.Authorization=`Bearer ${Ru}`),Mu?(Du.data=$u,Du.headers.Accept||(Du.headers.Accept="application/json")):(Du.headers.Accept||(Du.headers.Accept="application/json"),Du.headers["Content-Type"]||(Du.headers["Content-Type"]="application/json"),Du.data=$u);try{const Lu=await axios(Du);if(Lu.status<300){if(Lu.status===202&&Lu.headers.location)return{data:await handleAxiosRedirection(Lu,Du),status:Lu.status,statusText:Lu.statusText,headers:{...Lu.headers}}}else{throwIfTokenExpired(Lu.status,Ru,Au);const Bu={ok:!1,status:Lu.status,statusText:Lu.statusText,json:async()=>Lu?.data,text:async()=>JSON.stringify(Lu?.data)};throw await RunResponseError.create(Bu)}return{data:Lu.data,status:Lu.status,statusText:Lu.statusText,headers:{...Lu.headers}}}catch(Lu){if(axios.isAxiosError(Lu)){if(Lu.response){throwIfTokenExpired(Lu.response.status,Ru,Au);const Bu={ok:!1,status:Lu.response.status,statusText:Lu.response.statusText,json:async()=>Lu.response?.data,text:async()=>JSON.stringify(Lu.response?.data)};throw await RunResponseError.create(Bu)}throw new NetworkError(Lu)}throw Lu}}async function requestDatalayerAPI(Au){return(await requestDatalayerAPIWithResponse(Au)).data}async function handleAxiosRedirection(Au,lo){let $u=Au.headers.location;if($u){const Iu=lo.url??"",Pu=String($u).replace(/^([a-z][a-z0-9+.-]*):\/(?!\/)/i,"$1://");try{const Ou=new URL(Pu,Iu),Mu=new URL(Iu,typeof window<"u"?window.location.origin:void 0);Mu.protocol==="https:"&&Ou.protocol==="http:"&&Ou.hostname===Mu.hostname&&(Ou.protocol="https:",Ou.port==="80"&&(Ou.port="")),$u=Ou.toString()}catch{const Ou=libExports$5.URLExt.parse(Iu),Mu=Ou.protocol+"//"+Ou.hostname;$u=libExports$5.URLExt.join(Mu,Pu)}}let Ru=1e3;for(;Au.status===202&&$u;){await sleep$1(Ru),Ru*=2;const Iu={...lo,url:$u,method:"GET",data:void 0};Au=await axios(Iu)}return Au.data}const userToProfile=Au=>Au?{id:Au.id,uid:Au.uid,handle:Au.handle,email:Au.email,firstName:Au.firstName,lastName:Au.lastName,displayName:Au.displayName,initials:Au.initials,avatarUrl:Au.avatarUrl,avatarIcon:Au.avatarIcon,banner:Au.banner,showOrbits:Au.showOrbits,origin:Au.origin,roles:Au.roles}:void 0,profileStore=createStore$1(Au=>({profile:void 0,setProfile:lo=>Au({profile:lo}),updateProfile:lo=>Au($u=>({profile:{...$u.profile,...lo}})),setProfileFromUser:lo=>Au($u=>{const Ru=userToProfile(lo);if(!Ru)return $u;const Iu={...$u.profile};for(const[Pu,Ou]of Object.entries(Ru))Ou!==void 0&&(Iu[Pu]=Ou);return{profile:Iu}}),clearProfile:()=>Au({profile:void 0})}));function useProfileStore(Au){return useStore$1(profileStore,Au)}const useProfile=()=>useProfileStore(Au=>Au.profile),SESSION_COOKIES=["datalayer-space-context","datalayer-principal-context","datalayer-billing-entity-uid","otel_sql_history"],SESSION_LOCAL_STORAGE_KEYS=["datalayer-principal","datalayer-billing-entity","datalayer-simple-auth"],SESSION_OWNER_KEY="datalayer-session-owner",registrations=new Set,registerSessionState=Au=>(registrations.add(Au),()=>{registrations.delete(Au)}),storageOf=Au=>{try{return typeof window>"u"?void 0:window[Au]}catch{return}},removeFrom=(Au,lo)=>{try{Au?.removeItem(lo)}catch{}},deleteCookie=Au=>{typeof document>"u"||(document.cookie=`${Au}=; path=/; max-age=0; SameSite=Lax`)},readCookie$1=Au=>{if(typeof document>"u")return;const lo=`${Au}=`,$u=document.cookie.split(";").map(Ru=>Ru.trim()).find(Ru=>Ru.startsWith(lo));return $u?$u.slice(lo.length):void 0},forgetSessionState=()=>{const Au=new Set(SESSION_COOKIES),lo=new Set([...SESSION_LOCAL_STORAGE_KEYS,SESSION_OWNER_KEY]),$u=new Set;for(const Pu of registrations){try{Pu.forget?.()}catch(Ou){console.warn("A session state could not be reset.",Ou)}Pu.cookies?.forEach(Ou=>Au.add(Ou)),Pu.localStorageKeys?.forEach(Ou=>lo.add(Ou)),Pu.sessionStorageKeys?.forEach(Ou=>$u.add(Ou))}Au.forEach(deleteCookie);const Ru=storageOf("localStorage");lo.forEach(Pu=>removeFrom(Ru,Pu));const Iu=storageOf("sessionStorage");$u.forEach(Pu=>removeFrom(Iu,Pu))},personalPrincipalInCookie=()=>{const Au=readCookie$1("datalayer-principal-context");if(Au)try{const lo=JSON.parse(decodeURIComponent(Au));return lo?.selectedPrincipalKind==="personal"&&String(lo?.selectedPrincipalUid??"").trim()||void 0}catch{return}},claimSessionState=Au=>{const lo=String(Au??"").trim();if(!lo)return;const $u=storageOf("localStorage");let Ru;try{Ru=$u?.getItem(SESSION_OWNER_KEY)??null}catch{Ru=null}const Iu=personalPrincipalInCookie();(Ru&&Ru!==lo||!Ru&&Iu&&Iu!==lo)&&forgetSessionState();try{$u?.setItem(SESSION_OWNER_KEY,lo)}catch{}},RESERVATION_WARNING_TIME_MS=5*6e4,iamStore=createStore$1((Au,lo)=>({credits:void 0,creditsReservations:[],externalToken:loadRefreshTokenFromCookie()??void 0,user:getStoredUser(),token:getStoredToken(),iamUrl:coreStore.getState().configuration?.iamUrl,iamProvidersAuthorizationURL:{},version:"",isLoginInProgress:!1,addIAMProviderAuthorizationURL:($u,Ru)=>{Au(Iu=>({iamProvidersAuthorizationURL:{...Iu.iamProvidersAuthorizationURL,[$u]:Ru}}))},login:async $u=>{const{refreshUserByToken:Ru,iamUrl:Iu,logout:Pu}=lo();Au({isLoginInProgress:!0});try{const Ou=await requestDatalayerAPI({url:`${Iu}/api/iam/v1/login`,method:"POST",body:{token:$u}});if(Ou.success&&Ou.token)await Ru(Ou.token);else throw new Error("Invalid Token.")}catch(Ou){throw console.debug("Failed to login.",Ou),Ou.name==="RunResponseError"&&Ou.response.status===401&&(console.debug("Received 401 error - Logging out."),Pu()),Ou}finally{Au({isLoginInProgress:!1})}},logout:()=>{storeUser(),storeToken(),profileStore.getState().clearProfile(),forgetSessionState(),Au({credits:void 0,creditsReservations:[],user:ANONYMOUS_USER,token:ANONYMOUS_USER_TOKEN})},checkIAMToken:async $u=>{lo().token!==$u&&await lo().refreshUserByToken($u)},setIAMProviderAccessToken:($u,Ru)=>{const{user:Iu}=lo();if(!Iu)throw Error("You need to be authenticated to set an Access Token for an IAM provider.");const Pu=IAMProvidersSpecs.getProvider($u);Ru?setCookie(Pu.accessTokenCookieName(Iu),Ru):deleteCookie$1(Pu.accessTokenCookieName(Iu))},getIAMProviderAccessToken:($u,Ru)=>{const Pu=IAMProvidersSpecs.getProvider(Ru).accessTokenCookieName($u);return getCookie$1(Pu)},updateUser:$u=>Au(Ru=>{const Iu={user:{...Ru.user,...$u}};return profileStore.getState().setProfileFromUser(Iu.user),Iu}),refreshCredits:async()=>{const{externalToken:$u,token:Ru,iamUrl:Iu,logout:Pu}=lo();if(Ru)try{const Ou=await requestDatalayerAPI({url:`${Iu}/api/iam/v1/usage/credits`,token:Ru,headers:$u?{"X-External-Token":$u}:void 0}),{credits:Mu,reservations:Du=[]}=Ou;Au({credits:{...Mu,available:availableCredits(Mu,Du)},creditsReservations:Du})}catch(Ou){throw console.error("Failed to refresh user credits.",Ou),Ou.name==="RunResponseError"&&Ou.response.status===401&&(console.error("Received 401, logging out."),Pu()),Ou}else Au({credits:void 0})},refreshUser:async()=>{const{token:$u,refreshUserByToken:Ru,logout:Iu}=lo();$u?await Ru($u):Iu()},refreshUserByTokenStored:async()=>{const $u=getStoredToken();$u?await lo().refreshUserByToken($u):lo().logout()},refreshUserByToken:async $u=>{const{iamUrl:Ru,logout:Iu,isLoginInProgress:Pu}=lo();try{const Ou=await requestDatalayerAPI({url:`${Ru}/api/iam/v1/whoami`,token:$u}),Mu=asUser(Ou.profile);claimSessionState(Mu?.id??Mu?.uid),storeUser(Mu),storeToken($u),Au(()=>({user:Mu,token:$u}))}catch(Ou){Ou.name==="RunResponseError"&&Ou.response.status===401?console.debug("Invalid token - Received 401 error."):console.debug("Failed to fetch user identity.",Ou),Pu||Iu()}},setExternalToken:$u=>Au(Ru=>({externalToken:$u})),setLogin:($u,Ru)=>Au(Iu=>(claimSessionState($u?.id??$u?.uid),storeUser($u),storeToken(Ru),profileStore.getState().setProfileFromUser($u),{user:$u,token:Ru})),setVersion:$u=>{$u&&!lo().version&&Au(Ru=>({version:$u}))}}));function useIAMStore(Au){return useStore$1(iamStore,Au)}const creditsPoll=new Poll({name:"@datalayer/ui:credits-refresh",factory:()=>iamStore.getState().refreshCredits(),auto:!1,frequency:{interval:60*1e3,backoff:!0,max:600*1e3},standby:()=>iamStore.getState().user?.id?"when-hidden":!0});iamStore.getState().refreshUserByTokenStored().catch(Au=>{console.error("Failed to refresh to validate the stored token.",Au)}).finally(()=>{const{externalToken:Au,iamUrl:lo,checkIAMToken:$u,token:Ru}=iamStore.getState();!Ru&&Au&&(console.debug("Can not login with token - Trying with the external token."),requestDatalayerAPI({url:`${lo}/api/iam/v1/login`,method:"POST",body:{token:Au}}).then(Pu=>{Pu.token&&$u(Pu.token)}).catch(Pu=>{console.debug("Can not login with token.",Ru,Pu)})),Ru?console.log("Logged in with token and external token."):console.debug("Failed to login with token and no external token available."),creditsPoll.start(),(()=>{if(typeof window>"u")return;const Pu=window.document;if(!Pu||typeof Pu.addEventListener!="function")return;const Ou=()=>{!Pu.hidden&&iamStore.getState().user?.id&&creditsPoll.refresh()};Pu.addEventListener("visibilitychange",Ou)})()});coreStore.subscribe((Au,lo)=>{if(Au.configuration?.iamUrl&&Au.configuration.iamUrl!==lo.configuration?.iamUrl){const $u=Au.configuration.iamUrl;console.log("Updating iamUrl with new value",$u),iamStore.setState({iamUrl:$u}),iamStore.getState().externalToken?iamStore.getState().login(iamStore.getState().externalToken).catch(Ru=>{console.error("Failed to refresh the user after updating the IAM RUN URL.",Ru)}):iamStore.getState().refreshUser().catch(Ru=>{console.error("Failed to refresh the user after updating the IAM server URL.",Ru)})}});function emojiKey(Au){return Array.from(Au.trim()).map(lo=>lo.codePointAt(0)??0).filter(lo=>lo!==65039).map(lo=>lo.toString(16)).join("-")}const scriptRel=(function Au(){const lo=typeof document<"u"&&document.createElement("link").relList;return lo&&lo.supports&&lo.supports("modulepreload")?"modulepreload":"preload"})(),assetsURL=function(Au,lo){return new URL(Au,lo).href},seen={},__vitePreload=function Au(lo,$u,Ru){let Iu=Promise.resolve();if($u&&$u.length>0){let Lu=function(Bu){return Promise.all(Bu.map(ju=>Promise.resolve(ju).then(Fu=>({status:"fulfilled",value:Fu}),Fu=>({status:"rejected",reason:Fu}))))};const Ou=document.getElementsByTagName("link"),Mu=document.querySelector("meta[property=csp-nonce]"),Du=Mu?.nonce||Mu?.getAttribute("nonce");Iu=Lu($u.map(Bu=>{if(Bu=assetsURL(Bu,Ru),Bu in seen)return;seen[Bu]=!0;const ju=Bu.endsWith(".css"),Fu=ju?'[rel="stylesheet"]':"";if(Ru)for(let Uu=Ou.length-1;Uu>=0;Uu--){const Hu=Ou[Uu];if(Hu.href===Bu&&(!ju||Hu.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${Bu}"]${Fu}`))return;const zu=document.createElement("link");if(zu.rel=ju?"stylesheet":scriptRel,ju||(zu.as="script"),zu.crossOrigin="",zu.href=Bu,Du&&zu.setAttribute("nonce",Du),document.head.appendChild(zu),ju)return new Promise((Uu,Hu)=>{zu.addEventListener("load",Uu),zu.addEventListener("error",()=>Hu(new Error(`Unable to preload CSS for ${Bu}`)))})}))}function Pu(Ou){const Mu=new Event("vite:preloadError",{cancelable:!0});if(Mu.payload=Ou,window.dispatchEvent(Mu),!Mu.defaultPrevented)throw Ou}return Iu.then(Ou=>{for(const Mu of Ou||[])Mu.status==="rejected"&&Pu(Mu.reason);return lo().catch(Pu)})},FLUENT_EMOJI_LOADERS={"1f440":()=>__vitePreload(()=>import("./chunks/1f440-p4rvIPef.js"),[],import.meta.url),"1f4d1":()=>__vitePreload(()=>import("./chunks/1f4d1-2yeMP7i5.js"),[],import.meta.url),"1f399":()=>__vitePreload(()=>import("./chunks/1f399-GX_7MVl_.js"),[],import.meta.url),"1f6a2":()=>__vitePreload(()=>import("./chunks/1f6a2-gL6kUzw5.js"),[],import.meta.url),"1f69a":()=>__vitePreload(()=>import("./chunks/1f69a-CbAMmMYx.js"),[],import.meta.url),"1f50e":()=>__vitePreload(()=>import("./chunks/1f50e-CNC8yd3r.js"),[],import.meta.url),"1f4ec":()=>__vitePreload(()=>import("./chunks/1f4ec-e7JJiuI4.js"),[],import.meta.url),"1f4c8":()=>__vitePreload(()=>import("./chunks/1f4c8-CNuFlfRg.js"),[],import.meta.url),"1f9f9":()=>__vitePreload(()=>import("./chunks/1f9f9-DNoxae13.js"),[],import.meta.url),"1f9e0":()=>__vitePreload(()=>import("./chunks/1f9e0-7eqXrAdK.js"),[],import.meta.url),"1f6df":()=>__vitePreload(()=>import("./chunks/1f6df-DcnntiKi.js"),[],import.meta.url),"1f9ee":()=>__vitePreload(()=>import("./chunks/1f9ee-BuIxmQEW.js"),[],import.meta.url),"1f47e":()=>__vitePreload(()=>import("./chunks/1f47e-CVrptMZb.js"),[],import.meta.url),"1f47d":()=>__vitePreload(()=>import("./chunks/1f47d-DKGX1RHr.js"),[],import.meta.url),"1f9d1-200d-1f680":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f680-C9wxDlc0.js"),[],import.meta.url),"269b":()=>__vitePreload(()=>import("./chunks/269b-CIDlSWpG.js"),[],import.meta.url),"1f3e6":()=>__vitePreload(()=>import("./chunks/1f3e6-LRmfNoyK.js"),[],import.meta.url),2712:()=>__vitePreload(()=>import("./chunks/2712-5PLssGP2.js"),[],import.meta.url),"1f4bc":()=>__vitePreload(()=>import("./chunks/1f4bc-DPph9Yum.js"),[],import.meta.url),"1f3db":()=>__vitePreload(()=>import("./chunks/1f3db-D8W2ZDGL.js"),[],import.meta.url),"1f3d7":()=>__vitePreload(()=>import("./chunks/1f3d7-BCgsEYI1.js"),[],import.meta.url),"1f3e2":()=>__vitePreload(()=>import("./chunks/1f3e2-Ck-pGqVC.js"),[],import.meta.url),"1f3af":()=>__vitePreload(()=>import("./chunks/1f3af-BjGhox67.js"),[],import.meta.url),2601:()=>__vitePreload(()=>import("./chunks/2601-BxBuW0c5.js"),[],import.meta.url),"1f6a7":()=>__vitePreload(()=>import("./chunks/1f6a7-Bf7dX4bM.js"),[],import.meta.url),"1f477":()=>__vitePreload(()=>import("./chunks/1f477--ZfEh0BR.js"),[],import.meta.url),"1f920":()=>__vitePreload(()=>import("./chunks/1f920-DdqVzdU_.js"),[],import.meta.url),"1f9ec":()=>__vitePreload(()=>import("./chunks/1f9ec-BiccuNAi.js"),[],import.meta.url),"1f432":()=>__vitePreload(()=>import("./chunks/1f432-BBBxgCDF.js"),[],import.meta.url),"1f409":()=>__vitePreload(()=>import("./chunks/1f409-B-A-r5OE.js"),[],import.meta.url),"1f9dd":()=>__vitePreload(()=>import("./chunks/1f9dd-Bjlh5f8S.js"),[],import.meta.url),"1f525":()=>__vitePreload(()=>import("./chunks/1f525-DugGj6UX.js"),[],import.meta.url),"1f386":()=>__vitePreload(()=>import("./chunks/1f386-D1j06612.js"),[],import.meta.url),"1f6f8":()=>__vitePreload(()=>import("./chunks/1f6f8-CzpZp4fr.js"),[],import.meta.url),"1f340":()=>__vitePreload(()=>import("./chunks/1f340-B2CJ9tGB.js"),[],import.meta.url),"1f393":()=>__vitePreload(()=>import("./chunks/1f393-Cule2ZWh.js"),[],import.meta.url),"1f600":()=>__vitePreload(()=>import("./chunks/1f600-DHzS58-a.js"),[],import.meta.url),"1f3e0":()=>__vitePreload(()=>import("./chunks/1f3e0-Dvy0EpCV.js"),[],import.meta.url),"1f98e":()=>__vitePreload(()=>import("./chunks/1f98e-BRdu0IxY.js"),[],import.meta.url),"1fa84":()=>__vitePreload(()=>import("./chunks/1fa84-C7Zz9Ttn.js"),[],import.meta.url),"1f9d1-200d-1f4bc":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f4bc-FkyMuHj6.js"),[],import.meta.url),"1f9d1-200d-1f4bb":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f4bb-Bxh01EAD.js"),[],import.meta.url),"1f3b5":()=>__vitePreload(()=>import("./chunks/1f3b5-BdjcFmdt.js"),[],import.meta.url),"1f977":()=>__vitePreload(()=>import("./chunks/1f977-g-J1jf1x.js"),[],import.meta.url),"1f450":()=>__vitePreload(()=>import("./chunks/1f450-CbtsXspW.js"),[],import.meta.url),"1f58a":()=>__vitePreload(()=>import("./chunks/1f58a-mulZ-CFH.js"),[],import.meta.url),"1f427":()=>__vitePreload(()=>import("./chunks/1f427-DglaWI4D.js"),[],import.meta.url),"1f3c4":()=>__vitePreload(()=>import("./chunks/1f3c4-BhpD29zf.js"),[],import.meta.url),"1f3ca":()=>__vitePreload(()=>import("./chunks/1f3ca-gIlr1kJ5.js"),[],import.meta.url),"1f5bc":()=>__vitePreload(()=>import("./chunks/1f5bc-MigptVzH.js"),[],import.meta.url),"1f304":()=>__vitePreload(()=>import("./chunks/1f304-aDc2qDui.js"),[],import.meta.url),"1f6eb":()=>__vitePreload(()=>import("./chunks/1f6eb-lf0G-q-a.js"),[],import.meta.url),"1fa90":()=>__vitePreload(()=>import("./chunks/1fa90-Ccp91l-o.js"),[],import.meta.url),"1f916":()=>__vitePreload(()=>import("./chunks/1f916-BqoYgu9n.js"),[],import.meta.url),"1f680":()=>__vitePreload(()=>import("./chunks/1f680-dnPjZK4l.js"),[],import.meta.url),"1f385":()=>__vitePreload(()=>import("./chunks/1f385-Dt5AZfN7.js"),[],import.meta.url),"1f6f0":()=>__vitePreload(()=>import("./chunks/1f6f0-DiDzAbox.js"),[],import.meta.url),"1f9d1-200d-1f52c":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f52c-DIXbDrbI.js"),[],import.meta.url),"1f988":()=>__vitePreload(()=>import("./chunks/1f988-wqhZ7Rxe.js"),[],import.meta.url),2603:()=>__vitePreload(()=>import("./chunks/2603-DNj-gj-j.js"),[],import.meta.url),"1f387":()=>__vitePreload(()=>import("./chunks/1f387-D0SVWvyW.js"),[],import.meta.url),"2b50":()=>__vitePreload(()=>import("./chunks/2b50-DgcciXHA.js"),[],import.meta.url),"1f9d1-200d-1f393":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f393-DhlpNrMG.js"),[],import.meta.url),2600:()=>__vitePreload(()=>import("./chunks/2600-DZnZtR2D.js"),[],import.meta.url),"1f44b":()=>__vitePreload(()=>import("./chunks/1f44b-CDEzsnIT.js"),[],import.meta.url),"1f433":()=>__vitePreload(()=>import("./chunks/1f433-BGsjKcaL.js"),[],import.meta.url),"1f381":()=>__vitePreload(()=>import("./chunks/1f381-NG1UoP_K.js"),[],import.meta.url),"270d":()=>__vitePreload(()=>import("./chunks/270d-DAjo8CgW.js"),[],import.meta.url),"262f":()=>__vitePreload(()=>import("./chunks/262f-BHwzZDRR.js"),[],import.meta.url),"1f4ca":()=>__vitePreload(()=>import("./chunks/1f4ca-DwUKcdqA.js"),[],import.meta.url),"1f4dd":()=>__vitePreload(()=>import("./chunks/1f4dd-CjeXE9pk.js"),[],import.meta.url),"1f4c5":()=>__vitePreload(()=>import("./chunks/1f4c5-BuR_5gXZ.js"),[],import.meta.url),"1f5d3":()=>__vitePreload(()=>import("./chunks/1f5d3-CD7YTnlH.js"),[],import.meta.url),"1f4da":()=>__vitePreload(()=>import("./chunks/1f4da-T00kbbB7.js"),[],import.meta.url),"1f4a1":()=>__vitePreload(()=>import("./chunks/1f4a1-DuAncIYW.js"),[],import.meta.url),"1f527":()=>__vitePreload(()=>import("./chunks/1f527-DGFX9oVv.js"),[],import.meta.url),"1f6e0":()=>__vitePreload(()=>import("./chunks/1f6e0-BN_iAibr.js"),[],import.meta.url),"1f9f0":()=>__vitePreload(()=>import("./chunks/1f9f0-NjV-EBzJ.js"),[],import.meta.url),2699:()=>__vitePreload(()=>import("./chunks/2699-DHeK1la1.js"),[],import.meta.url),"1f9ea":()=>__vitePreload(()=>import("./chunks/1f9ea-Dn-cjqlg.js"),[],import.meta.url),"1f52c":()=>__vitePreload(()=>import("./chunks/1f52c-PWG_VsFe.js"),[],import.meta.url),"1f5c2":()=>__vitePreload(()=>import("./chunks/1f5c2-BwHVJFvn.js"),[],import.meta.url),"1f4e6":()=>__vitePreload(()=>import("./chunks/1f4e6-iVURZ5lW.js"),[],import.meta.url),"1f6d2":()=>__vitePreload(()=>import("./chunks/1f6d2-C4PVtG90.js"),[],import.meta.url),"1f6b2":()=>__vitePreload(()=>import("./chunks/1f6b2-BvodiaEs.js"),[],import.meta.url),"1f4ac":()=>__vitePreload(()=>import("./chunks/1f4ac-B0hyiBGy.js"),[],import.meta.url),"1f4e3":()=>__vitePreload(()=>import("./chunks/1f4e3-BCLpfdwX.js"),[],import.meta.url),"1f9fe":()=>__vitePreload(()=>import("./chunks/1f9fe-vjnIOB6Q.js"),[],import.meta.url),"1f4b0":()=>__vitePreload(()=>import("./chunks/1f4b0-Bgl_9Qt3.js"),[],import.meta.url),"1f4b3":()=>__vitePreload(()=>import("./chunks/1f4b3-C3bg4q6a.js"),[],import.meta.url),"1f30d":()=>__vitePreload(()=>import("./chunks/1f30d-RKwL3Nsg.js"),[],import.meta.url),"1f512":()=>__vitePreload(()=>import("./chunks/1f512-CfUiEAwd.js"),[],import.meta.url),"1f511":()=>__vitePreload(()=>import("./chunks/1f511-n1Y90TZn.js"),[],import.meta.url),"1f6e1":()=>__vitePreload(()=>import("./chunks/1f6e1-Cu0Gi0Ok.js"),[],import.meta.url),"1f9ed":()=>__vitePreload(()=>import("./chunks/1f9ed-BdM-tuKc.js"),[],import.meta.url),"1f5fa":()=>__vitePreload(()=>import("./chunks/1f5fa-BbhAXfOC.js"),[],import.meta.url),"1f4f0":()=>__vitePreload(()=>import("./chunks/1f4f0-BqBFK1vM.js"),[],import.meta.url),2709:()=>__vitePreload(()=>import("./chunks/2709-R2m2qaPB.js"),[],import.meta.url),"1f4de":()=>__vitePreload(()=>import("./chunks/1f4de-DMKOmTcC.js"),[],import.meta.url),"1f91d":()=>__vitePreload(()=>import("./chunks/1f91d-BLSo-qgX.js"),[],import.meta.url),"1f3e5":()=>__vitePreload(()=>import("./chunks/1f3e5-BZAbo425.js"),[],import.meta.url),2696:()=>__vitePreload(()=>import("./chunks/2696-DCPh-ddG.js"),[],import.meta.url),"1f3a8":()=>__vitePreload(()=>import("./chunks/1f3a8-BVDoGacX.js"),[],import.meta.url),"1f3ac":()=>__vitePreload(()=>import("./chunks/1f3ac-D8k4rvLe.js"),[],import.meta.url),"1f4f7":()=>__vitePreload(()=>import("./chunks/1f4f7-BwaVsOpm.js"),[],import.meta.url),"1f9d1-200d-1f3eb":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f3eb-CMaKZADj.js"),[],import.meta.url),"1f9d1-200d-2695":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-2695-DCucKT0e.js"),[],import.meta.url),"1f9d1-200d-1f373":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f373-DvkX_q7n.js"),[],import.meta.url),"1f9d1-200d-1f33e":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f33e-C1GbmRM7.js"),[],import.meta.url),"1f331":()=>__vitePreload(()=>import("./chunks/1f331-_RrI1iL2.js"),[],import.meta.url),"1f41d":()=>__vitePreload(()=>import("./chunks/1f41d-BFxQMyWe.js"),[],import.meta.url),"1f989":()=>__vitePreload(()=>import("./chunks/1f989-BnANhNFy.js"),[],import.meta.url),"1f98a":()=>__vitePreload(()=>import("./chunks/1f98a-D9FmXaXZ.js"),[],import.meta.url),"1f419":()=>__vitePreload(()=>import("./chunks/1f419-5WEpY3Qm.js"),[],import.meta.url),2764:()=>__vitePreload(()=>import("./chunks/2764-BqnS842k.js"),[],import.meta.url),2705:()=>__vitePreload(()=>import("./chunks/2705-C2znzsf2.js"),[],import.meta.url),"23f0":()=>__vitePreload(()=>import("./chunks/23f0-dWLnhjSv.js"),[],import.meta.url),"1f514":()=>__vitePreload(()=>import("./chunks/1f514-B1X39g06.js"),[],import.meta.url),"1f9e9":()=>__vitePreload(()=>import("./chunks/1f9e9-i_U9-xN7.js"),[],import.meta.url),"1f3f7":()=>__vitePreload(()=>import("./chunks/1f3f7-CcKaOA8W.js"),[],import.meta.url),"1f4cb":()=>__vitePreload(()=>import("./chunks/1f4cb-oUiKe7zE.js"),[],import.meta.url),"1f4cc":()=>__vitePreload(()=>import("./chunks/1f4cc-CBUTvGMt.js"),[],import.meta.url),"1f50d":()=>__vitePreload(()=>import("./chunks/1f50d-1bvZKHvT.js"),[],import.meta.url),"1f642":()=>__vitePreload(()=>import("./chunks/1f642-C6Qm_-ba.js"),[],import.meta.url),"1f913":()=>__vitePreload(()=>import("./chunks/1f913-hQT-pf0C.js"),[],import.meta.url),"1f9d0":()=>__vitePreload(()=>import("./chunks/1f9d0-Bg0qtSKU.js"),[],import.meta.url),"1f60e":()=>__vitePreload(()=>import("./chunks/1f60e-Dxrd05Jo.js"),[],import.meta.url),"1f984":()=>__vitePreload(()=>import("./chunks/1f984-DOK3uNT7.js"),[],import.meta.url),"1f436":()=>__vitePreload(()=>import("./chunks/1f436-CfGEu66M.js"),[],import.meta.url),"1f431":()=>__vitePreload(()=>import("./chunks/1f431-Cy-L3DQS.js"),[],import.meta.url),"1f308":()=>__vitePreload(()=>import("./chunks/1f308-DAQVzKND.js"),[],import.meta.url),"1f31f":()=>__vitePreload(()=>import("./chunks/1f31f-BV2d8NX3.js"),[],import.meta.url),"26a1":()=>__vitePreload(()=>import("./chunks/26a1-Cpmzv_rj.js"),[],import.meta.url),"1f355":()=>__vitePreload(()=>import("./chunks/1f355-C-u8bPC3.js"),[],import.meta.url),2615:()=>__vitePreload(()=>import("./chunks/2615-CoDRCZkH.js"),[],import.meta.url),"1f389":()=>__vitePreload(()=>import("./chunks/1f389-B6nBX5We.js"),[],import.meta.url),"1f3c6":()=>__vitePreload(()=>import("./chunks/1f3c6-PZd-tUlI.js"),[],import.meta.url),"23f3":()=>__vitePreload(()=>import("./chunks/23f3-ASjqFsbT.js"),[],import.meta.url),2611:()=>__vitePreload(()=>import("./chunks/2611-BnnmLm-K.js"),[],import.meta.url),2702:()=>__vitePreload(()=>import("./chunks/2702-CfLyp35r.js"),[],import.meta.url),"1f30a":()=>__vitePreload(()=>import("./chunks/1f30a-DxwAt2Ba.js"),[],import.meta.url),"1f327":()=>__vitePreload(()=>import("./chunks/1f327-Ie-nQBNO.js"),[],import.meta.url),"1f33e":()=>__vitePreload(()=>import("./chunks/1f33e-Cfl2WM63.js"),[],import.meta.url),"1f3ab":()=>__vitePreload(()=>import("./chunks/1f3ab-BUCNQHz1.js"),[],import.meta.url),"1f4be":()=>__vitePreload(()=>import("./chunks/1f4be-DPAcAU4R.js"),[],import.meta.url),"1f4d3":()=>__vitePreload(()=>import("./chunks/1f4d3-GTxRgjv7.js"),[],import.meta.url),"1f4d6":()=>__vitePreload(()=>import("./chunks/1f4d6-COOZY-Q_.js"),[],import.meta.url),"1f4e2":()=>__vitePreload(()=>import("./chunks/1f4e2-DsStZsI-.js"),[],import.meta.url),"1f504":()=>__vitePreload(()=>import("./chunks/1f504-BYIHMoDP.js"),[],import.meta.url),"1f465":()=>__vitePreload(()=>import("./chunks/1f465-CPle6Hjq.js"),[],import.meta.url),"270f":()=>__vitePreload(()=>import("./chunks/270f-CLwo30mk.js"),[],import.meta.url),2728:()=>__vitePreload(()=>import("./chunks/2728-Qg6be-6p.js"),[],import.meta.url),"2b1c":()=>__vitePreload(()=>import("./chunks/2b1c-Uc1aRwAf.js"),[],import.meta.url),"1f310":()=>__vitePreload(()=>import("./chunks/1f310-AqUM9a8q.js"),[],import.meta.url),"1f324":()=>__vitePreload(()=>import("./chunks/1f324-8MHLOhTj.js"),[],import.meta.url),"1f372":()=>__vitePreload(()=>import("./chunks/1f372-3XLDlXkE.js"),[],import.meta.url),"1f373":()=>__vitePreload(()=>import("./chunks/1f373-BPUJt2bp.js"),[],import.meta.url),"1f39b":()=>__vitePreload(()=>import("./chunks/1f39b-CSNtbAXr.js"),[],import.meta.url),"1f41b":()=>__vitePreload(()=>import("./chunks/1f41b-Dre1z0gP.js"),[],import.meta.url),"1f4c2":()=>__vitePreload(()=>import("./chunks/1f4c2-Dx7BKmLO.js"),[],import.meta.url),"1f4c4":()=>__vitePreload(()=>import("./chunks/1f4c4-CNvjvC5k.js"),[],import.meta.url),"1f4dc":()=>__vitePreload(()=>import("./chunks/1f4dc-BhoW4cjD.js"),[],import.meta.url),"1f4e1":()=>__vitePreload(()=>import("./chunks/1f4e1-DezU8ow-.js"),[],import.meta.url),"1f500":()=>__vitePreload(()=>import("./chunks/1f500-D9xRo-IT.js"),[],import.meta.url),"1f501":()=>__vitePreload(()=>import("./chunks/1f501-CzKeDPcw.js"),[],import.meta.url),"1f52d":()=>__vitePreload(()=>import("./chunks/1f52d-2QxCLKhU.js"),[],import.meta.url),"1f552":()=>__vitePreload(()=>import("./chunks/1f552-4d0Y0kn7.js"),[],import.meta.url),"1f58b":()=>__vitePreload(()=>import("./chunks/1f58b-Cp8F_HBg.js"),[],import.meta.url),"1f5b2":()=>__vitePreload(()=>import("./chunks/1f5b2-D6BUULuh.js"),[],import.meta.url),"1f5c3":()=>__vitePreload(()=>import("./chunks/1f5c3-DjkgJLaz.js"),[],import.meta.url),"1f5d1":()=>__vitePreload(()=>import("./chunks/1f5d1-C4Kpe4HL.js"),[],import.meta.url),"1f5dc":()=>__vitePreload(()=>import("./chunks/1f5dc-DyLO7aB9.js"),[],import.meta.url),"1f9d1-200d-2696":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-2696-D9eSB-0q.js"),[],import.meta.url),"1fa79":()=>__vitePreload(()=>import("./chunks/1fa79-DHhIZbWB.js"),[],import.meta.url),"1fa9d":()=>__vitePreload(()=>import("./chunks/1fa9d-DUI9e77m.js"),[],import.meta.url),"1fa9f":()=>__vitePreload(()=>import("./chunks/1fa9f-10ALsMaD.js"),[],import.meta.url),"1f441":()=>__vitePreload(()=>import("./chunks/1f441-D8yah4C4.js"),[],import.meta.url),"1f604":()=>__vitePreload(()=>import("./chunks/1f604-CEekcaYE.js"),[],import.meta.url),"1f326":()=>__vitePreload(()=>import("./chunks/1f326-YSBr3aXI.js"),[],import.meta.url),"1f4b9":()=>__vitePreload(()=>import("./chunks/1f4b9-aacFyckt.js"),[],import.meta.url),"1f4c1":()=>__vitePreload(()=>import("./chunks/1f4c1-Ch6aJ0cj.js"),[],import.meta.url),"1f4e7":()=>__vitePreload(()=>import("./chunks/1f4e7-BBi7c_zx.js"),[],import.meta.url),"1f917":()=>__vitePreload(()=>import("./chunks/1f917-CyyS9fgf.js"),[],import.meta.url)},DRAWN=new Map;function hasFluentEmoji(Au){return!!Au&&Object.prototype.hasOwnProperty.call(FLUENT_EMOJI_LOADERS,emojiKey(Au))}async function loadFluentEmoji(Au){const lo=emojiKey(Au),$u=DRAWN.get(lo);if($u)return $u;if(!Object.prototype.hasOwnProperty.call(FLUENT_EMOJI_LOADERS,lo))return;const Ru=(await FLUENT_EMOJI_LOADERS[lo]()).default,Iu=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(Ru)}`;return DRAWN.set(lo,Iu),Iu}function FluentEmoji({emoji:Au,size:lo,label:$u,className:Ru,style:Iu}){const Pu=emojiKey(Au),Ou=hasFluentEmoji(Au),[Mu,Du]=reactExports.useState(()=>DRAWN.get(Pu));reactExports.useEffect(()=>{let ju=!0;return Du(DRAWN.get(Pu)),Ou&&!DRAWN.has(Pu)&&loadFluentEmoji(Au).then(Fu=>ju&&Du(Fu),()=>{}),()=>{ju=!1}},[Pu,Ou,Au]);const Lu=$u??Au,Bu={display:"inline-flex",alignItems:"center",justifyContent:"center",flex:"none",width:lo,height:lo,...Iu};return Ou?Mu?jsxRuntimeExports.jsx("img",{className:Ru,src:Mu,alt:Lu,"aria-hidden":Lu?void 0:!0,width:lo,height:lo,draggable:!1,"data-emoji":"fluent",style:{...Bu,display:"inline-block"}}):jsxRuntimeExports.jsx("span",{className:Ru,"aria-hidden":"true","data-emoji":"loading",style:Bu}):jsxRuntimeExports.jsx("span",{className:Ru,role:Lu?"img":void 0,"aria-label":Lu||void 0,"aria-hidden":Lu?void 0:!0,"data-emoji":"system",style:{...Bu,fontSize:Math.round(lo*.85),lineHeight:1},children:Au})}function generateMessageId(){return`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function createUserMessage(Au,lo){return{id:generateMessageId(),role:"user",content:Au,createdAt:new Date,metadata:lo}}function createAssistantMessage(Au,lo){return{id:generateMessageId(),role:"assistant",content:Au,createdAt:new Date,agentName:lo?.agentName,toolCalls:lo?.toolCalls,metadata:lo?.metadata}}const createStoreImpl=Au=>{let lo;const $u=new Set,Ru=(Lu,Bu)=>{const ju=typeof Lu=="function"?Lu(lo):Lu;if(!Object.is(ju,lo)){const Fu=lo;lo=Bu??(typeof ju!="object"||ju===null)?ju:Object.assign({},lo,ju),$u.forEach(zu=>zu(lo,Fu))}},Iu=()=>lo,Mu={setState:Ru,getState:Iu,getInitialState:()=>Du,subscribe:Lu=>($u.add(Lu),()=>$u.delete(Lu))},Du=lo=Au(Ru,Iu,Mu);return Mu},createStore=(Au=>Au?createStoreImpl(Au):createStoreImpl),identity=Au=>Au;function useStore(Au,lo=identity){const $u=vM.useSyncExternalStore(Au.subscribe,vM.useCallback(()=>lo(Au.getState()),[Au,lo]),vM.useCallback(()=>lo(Au.getInitialState()),[Au,lo]));return vM.useDebugValue($u),$u}const createImpl=Au=>{const lo=createStore(Au),$u=Ru=>useStore(lo,Ru);return Object.assign($u,lo),$u},create$e=(Au=>Au?createImpl(Au):createImpl),useReactorStore=create$e(()=>({reactor:null,isBackendPluginAvailable:()=>!1})),unavailableBackendPlugin=()=>!1;function registerReactor(Au,lo=unavailableBackendPlugin){useReactorStore.setState({reactor:Au,isBackendPluginAvailable:lo})}function useReactor(Au,lo={}){const{autoStart:$u=!0,availableBackendPlugins:Ru,isBackendPluginAvailable:Iu}=lo,Pu=reactExports.useMemo(()=>{if(Iu)return Iu;const Ou=new Set(Ru??[]);return Mu=>Ou.has(Mu)},[Iu,Ru]);return reactExports.useState(()=>(registerReactor(Au,Pu),null)),reactExports.useEffect(()=>(registerReactor(Au,Pu),()=>{useReactorStore.getState().reactor===Au&®isterReactor(null,unavailableBackendPlugin)}),[Au,Pu]),reactExports.useEffect(()=>{if($u)return Au.start(),()=>{Au.stop()}},[$u,Au]),Au}const NO_SUBSCRIPTION$1=()=>()=>{};function useOptionalReactorPlatform(){return useReactorStore(Au=>Au.reactor)}function useReactorPlatform(){const Au=useReactorStore(lo=>lo.reactor);if(!Au)throw new Error("useReactorPlatform: no reactor store registered. Call useReactor(reactor) (or registerReactor) before using reactor hooks.");return Au}function useSignalValue$1(Au){return reactExports.useSyncExternalStore(lo=>{let $u=!1;return effect$1(()=>{Au.value,$u?lo():$u=!0})},()=>Au.peek(),()=>Au.peek())}function useBackendPluginAvailability(){return useReactorStore(Au=>Au.isBackendPluginAvailable)}function useBackendPluginStream(Au,lo={}){const{pollMs:$u=5e3,onState:Ru}=lo,Iu=Au?.replace(/\/+$/,""),Pu=useReactorStore(Mu=>Mu.reactor),Ou=reactExports.useRef(Ru);Ou.current=Ru,reactExports.useEffect(()=>{if(!Iu||!Pu)return;let Mu=!1,Du=-1;const Lu=zu=>{Mu||zu.revision===Du||(Du=zu.revision,Ou.current?.(zu),Pu.setBackendPlugins(zu.plugins.filter(Uu=>Uu.enabled).map(Uu=>Uu.name)))},Bu=()=>fetch(`${Iu}/plugins/state`).then(zu=>zu.ok?zu.json():void 0).then(zu=>zu&&Lu(zu)).catch(()=>{});if(Bu(),typeof EventSource>"u"){const zu=setInterval(Bu,$u);return()=>{Mu=!0,clearInterval(zu)}}const ju=new EventSource(`${Iu}/events/stream`);ju.onmessage=zu=>{try{Lu(JSON.parse(zu.data))}catch{}};const Fu=setInterval(Bu,$u);return()=>{Mu=!0,clearInterval(Fu),ju.close()}},[Iu,Pu,$u])}function useReactorEvent(Au){const lo=useReactorPlatform();reactExports.useEffect(()=>{Au&&lo.fire(Au)},[lo,Au])}function useOptionalSlotComponents(Au){const lo=useOptionalReactorPlatform();return useSlotComponentsFrom(lo,Au)}function useSlotComponents(Au){const lo=useReactorPlatform();return useSlotComponentsFrom(lo,Au)}function useSlotComponentsFrom(Au,lo){const $u=useBackendPluginAvailability(),Ru=reactExports.useSyncExternalStore(Au?Au.subscribe:NO_SUBSCRIPTION$1,()=>Au?Au.getRevision():-1);return reactExports.useMemo(()=>{const Iu=[];if(!Au)return Iu;function Pu(Ou){return Ou.every(Mu=>$u(Mu))}for(const Ou of Au.listPlugins()){if(!Au.isEnabled(Ou))continue;const Mu=Au.getRequiredBackendPlugins(Ou);if(!Pu(Mu))continue;const Du=Au.getOutput(Ou);for(const Lu of Du?.components??[]){const Bu=Lu.requiredBackendPlugins??[];Lu.slot===lo&&Pu(Bu)&&Iu.push(Lu)}}return Iu.map((Ou,Mu)=>({component:Ou,index:Mu})).sort((Ou,Mu)=>(Ou.component.order??0)-(Mu.component.order??0)||Ou.index-Mu.index).map(Ou=>Ou.component)},[Au,lo,Ru,$u])}function ReactorSlot({slot:Au,props:lo={}}){const $u=useOptionalSlotComponents(Au);return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:$u.map(Ru=>{const Iu=Ru.Component;return jsxRuntimeExports.jsx(Iu,{...lo},`${Ru.slot}:${Ru.id}`)})})}function useGate(Au,lo){const $u=useContributions(Au);return reactExports.useMemo(()=>resolveGate($u,lo),[$u,lo])}function useContributions(Au){const lo=useReactorPlatform(),$u=reactExports.useSyncExternalStore(lo.subscribe,()=>lo.getRevision());return reactExports.useMemo(()=>lo.getContributions(Au),[lo,Au,$u])}function useCommands(){const Au=useReactorPlatform(),lo=reactExports.useSyncExternalStore(Au.subscribe,()=>Au.getRevision());return reactExports.useMemo(()=>Au.listCommands(),[Au,lo])}class LazyErrorBoundary extends reactExports.Component{state={error:null};static getDerivedStateFromError(lo){return{error:lo}}componentDidUpdate(lo){lo.resetKey!==this.props.resetKey&&this.state.error&&this.setState({error:null})}render(){return this.state.error?this.props.fallback(this.state.error):this.props.children}}const lazyComponents=new WeakMap;function lazyFor(Au){const lo=lazyComponents.get(Au);if(lo)return lo;const $u=vM.lazy(Au);return lazyComponents.set(Au,$u),$u}function ReactorLazy({load:Au,props:lo,fallback:$u=null,errorFallback:Ru}){const Iu=reactExports.useMemo(()=>lazyFor(Au),[Au]),Pu=Ru??(Ou=>jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:`Failed to load view: ${Ou.message}`}));return jsxRuntimeExports.jsx(LazyErrorBoundary,{fallback:Pu,resetKey:Au,children:jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:$u,children:jsxRuntimeExports.jsx(Iu,{...lo??{}})})})}function defaultResolve(Au){const lo=Au;if(lo&&typeof lo.load=="function")return{load:lo.load};if(lo&&typeof lo.Component=="function")return{Component:lo.Component}}function ReactorViewHost({point:Au,active:lo,props:$u,fallback:Ru=null,empty:Iu=null,errorFallback:Pu,resolve:Ou=defaultResolve,render:Mu}){const Du=useContributions(Au),Lu=reactExports.useMemo(()=>lo===void 0?void 0:Du.find(Fu=>Fu.id===lo),[Du,lo]);if(!Lu)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Iu});if(Mu)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Mu(Lu)});const Bu=Ou(Lu.value);if(!Bu)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Iu});if(Bu.load)return jsxRuntimeExports.jsx(ReactorLazy,{load:Bu.load,props:$u,fallback:Ru,errorFallback:Pu});const ju=Bu.Component;return jsxRuntimeExports.jsx(ju,{...$u??{}})}const UI_WIRE_VERSION=1,DISPLAY_META_KEY$1="reactor.ui/display",ANSWER_ACTION="reactor.answer",UI_OP_NAMES=["show","patch","append","remove","state","ask","window","meta"];function isRecord$6(Au){return typeof Au=="object"&&Au!==null&&!Array.isArray(Au)}function isOptional$1(Au,lo){return Au==null||lo(Au)}function isString$3(Au){return typeof Au=="string"}function isActionOffer(Au){return isRecord$6(Au)&&isString$3(Au.name)&&isString$3(Au.token)&&isOptional$1(Au.label,isString$3)}function isDisplay(Au){return isRecord$6(Au)&&isString$3(Au.type)&&isString$3(Au.id)&&isString$3(Au.text)&&(Au.version===void 0||Number.isInteger(Au.version))&&(Au.data===void 0||isRecord$6(Au.data))&&(Au.actions===void 0||Array.isArray(Au.actions)&&Au.actions.every(isActionOffer))}function isPatchOperation(Au){if(!isRecord$6(Au)||!isString$3(Au.path))return!1;switch(Au.op){case"add":case"replace":case"test":return"value"in Au;case"remove":return!0;case"move":case"copy":return isString$3(Au.from);default:return!1}}function isPatch(Au){return Array.isArray(Au)&&Au.every(isPatchOperation)}const OP_SHAPES={show:Au=>isDisplay(Au.body),ask:Au=>isDisplay(Au.body),patch:Au=>isString$3(Au.id)&&isPatch(Au.body),append:Au=>isString$3(Au.id)&&isRecord$6(Au.body)&&isString$3(Au.body.path),remove:Au=>isString$3(Au.id)&&(Au.body===void 0||Au.body===null),state:Au=>isPatch(Au.body),window:Au=>isRecord$6(Au.body)&&isString$3(Au.body.name)&&(Au.body.args===void 0||isRecord$6(Au.body.args)),meta:Au=>isRecord$6(Au.body)};function isUiOp(Au){return isRecord$6(Au)&&Au.v===UI_WIRE_VERSION&&isString$3(Au.scope)&&isOptional$1(Au.id,isString$3)&&UI_OP_NAMES.includes(Au.op)&&OP_SHAPES[Au.op](Au)}function isSeq(Au,lo){return Number.isInteger(Au)&&Au>=lo}function hasKeys(Au,lo,$u=[]){const Ru=Object.keys(Au);return lo.every(Iu=>Iu in Au)&&Ru.every(Iu=>lo.includes(Iu)||$u.includes(Iu))}function isDownFrame(Au){if(!isRecord$6(Au))return!1;switch(Au.t){case"welcome":return hasKeys(Au,["t","scope","seq"],["v"])&&(Au.v===void 0||Au.v===UI_WIRE_VERSION)&&isString$3(Au.scope)&&isSeq(Au.seq,0);case"op":return hasKeys(Au,["t","seq","op"])&&isSeq(Au.seq,1)&&isUiOp(Au.op);case"result":return hasKeys(Au,["t","ref","ok","status"],["detail","value"])&&isString$3(Au.ref)&&typeof Au.ok=="boolean"&&Number.isInteger(Au.status)&&isOptional$1(Au.detail,isString$3);case"ping":case"pong":return hasKeys(Au,["t"]);default:return!1}}const Renderers=defineContributionPoint("reactor.ui.renderer"),ToolBindings=defineContributionPoint("reactor.ui.toolBinding");function versionInRange(Au,lo){return lo?(lo.min===void 0||Au>=lo.min)&&(lo.max===void 0||Au<=lo.max):!0}function pickRenderer(Au,lo){const $u=lo.version??1;let Ru;for(const Iu of Au)Iu.value.type!==lo.type||!versionInRange($u,Iu.value.versions)||(!Ru||(Iu.value.rank??0)>(Ru.value.rank??0))&&(Ru=Iu);return Ru}function parsedObject(Au){if(typeof Au!="string")return Au;const lo=Au.trimStart();if(!lo.startsWith("{"))return Au;try{return JSON.parse(lo)}catch{return Au}}function embeddedDisplay(Au){const lo=parsedObject(Au);if(typeof lo!="object"||lo===null)return;const $u=lo._meta;if(typeof $u!="object"||$u===null)return;const Ru=$u[DISPLAY_META_KEY$1];return isDisplay(Ru)?Ru:void 0}function bindingMatches(Au,lo){return typeof Au.tool=="string"?Au.tool===lo:(Au.tool.lastIndex=0,Au.tool.test(lo))}function textOf(Au){if(Au==null)return"";if(typeof Au=="string")return Au;try{return JSON.stringify(Au)??String(Au)}catch{return String(Au)}}function resolveToolResult(Au,lo){const $u=embeddedDisplay(lo.result);if($u)return $u;const Ru=Au.getContributions(ToolBindings).find(Iu=>bindingMatches(Iu.value,lo.toolName));if(Ru)return{type:Ru.value.type,version:Ru.value.version??1,id:lo.toolCallId??lo.toolName,text:textOf(lo.result),data:{toolName:lo.toolName,result:lo.result}}}function emptyUiModel(){return{displays:{},order:[],asks:[],state:{},meta:{}}}function clone$2(Au){return Au===void 0?Au:JSON.parse(JSON.stringify(Au))}function parsePointer(Au){if(Au==="")return[];if(!Au.startsWith("/"))throw new Error(`A JSON pointer starts with '/': ${Au}`);return Au.slice(1).split("/").map(lo=>lo.replace(/~1/g,"/").replace(/~0/g,"~")).map(lo=>{if(FORBIDDEN_TOKENS.has(lo))throw new Error(`${Au}: '${lo}' is never a path token`);return lo})}const FORBIDDEN_TOKENS=new Set(["__proto__","constructor","prototype"]);function hasOwn(Au,lo){return Object.prototype.hasOwnProperty.call(Au,lo)}function walk(Au,lo,$u){let Ru=Au;for(const Iu of lo)if(Array.isArray(Ru))Ru=Ru[arrayIndex(Ru,Iu,$u,!1)];else if(typeof Ru=="object"&&Ru!==null&&hasOwn(Ru,Iu))Ru=Ru[Iu];else throw new Error(`No value at ${$u}`);if(typeof Ru!="object"||Ru===null)throw new Error(`${$u} does not lead into an object or an array`);return Ru}function arrayIndex(Au,lo,$u,Ru){if(Ru&&lo==="-")return Au.length;if(!/^(0|[1-9][0-9]*)$/.test(lo))throw new Error(`${$u}: '${lo}' is not an array index`);const Iu=Number(lo);if(Iu>Au.length||!Ru&&Iu===Au.length)throw new Error(`${$u}: index ${Iu} is out of bounds`);return Iu}function read$2(Au,lo){const $u=parsePointer(lo);if($u.length===0)return Au;const Ru=walk(Au,$u.slice(0,-1),lo),Iu=$u[$u.length-1];if(Array.isArray(Ru))return Ru[arrayIndex(Ru,Iu,lo,!1)];if(!hasOwn(Ru,Iu))throw new Error(`No value at ${lo}`);return Ru[Iu]}function add$1(Au,lo,$u){const Ru=parsePointer(lo);if(Ru.length===0)return $u;const Iu=walk(Au,Ru.slice(0,-1),lo),Pu=Ru[Ru.length-1];return Array.isArray(Iu)?Iu.splice(arrayIndex(Iu,Pu,lo,!0),0,$u):Iu[Pu]=$u,Au}function removeAt(Au,lo){const $u=parsePointer(lo);if($u.length===0)return;const Ru=walk(Au,$u.slice(0,-1),lo),Iu=$u[$u.length-1];if(Array.isArray(Ru))Ru.splice(arrayIndex(Ru,Iu,lo,!1),1);else{if(!hasOwn(Ru,Iu))throw new Error(`No value at ${lo}`);delete Ru[Iu]}return Au}function replaceAt(Au,lo,$u){const Ru=parsePointer(lo);if(Ru.length===0)return $u;const Iu=walk(Au,Ru.slice(0,-1),lo),Pu=Ru[Ru.length-1];if(Array.isArray(Iu))Iu[arrayIndex(Iu,Pu,lo,!1)]=$u;else{if(!hasOwn(Iu,Pu))throw new Error(`No value at ${lo}`);Iu[Pu]=$u}return Au}function equal$1(Au,lo){if(Au===lo)return!0;if(Array.isArray(Au)||Array.isArray(lo))return Array.isArray(Au)&&Array.isArray(lo)&&Au.length===lo.length&&Au.every((Pu,Ou)=>equal$1(Pu,lo[Ou]));if(typeof Au!="object"||typeof lo!="object"||Au===null||lo===null)return!1;const $u=Au,Ru=lo,Iu=Object.keys($u);return Iu.length===Object.keys(Ru).length&&Iu.every(Pu=>hasOwn(Ru,Pu)&&equal$1($u[Pu],Ru[Pu]))}function applyPatch$1(Au,lo){let $u=clone$2(Au);for(const Ru of lo)switch(Ru.op){case"add":$u=add$1($u,Ru.path,clone$2(Ru.value));break;case"remove":$u=removeAt($u,Ru.path);break;case"replace":$u=replaceAt($u,Ru.path,clone$2(Ru.value));break;case"move":{const Iu=requireFrom(Ru),Pu=read$2($u,Iu);$u=add$1(removeAt($u,Iu),Ru.path,Pu);break}case"copy":$u=add$1($u,Ru.path,clone$2(read$2($u,requireFrom(Ru))));break;case"test":if(!equal$1(read$2($u,Ru.path),Ru.value))throw new Error(`test failed at ${Ru.path}`);break;default:throw new Error(`Unknown patch op ${Ru.op}`)}return $u}function requireFrom(Au){if(typeof Au.from!="string")throw new Error(`'${Au.op}' at ${Au.path} needs 'from'`);return Au.from}function displayOf(Au,lo){const $u=Au.displays[lo.id];if(!$u)throw new Error(`'${lo.op}' for display '${lo.id}', which was never shown`);return $u}function shown(Au,lo){const $u=lo.id in Au.displays;return{...Au,displays:{...Au.displays,[lo.id]:lo},order:$u?Au.order:[...Au.order,lo.id]}}function applyUiOp(Au,lo){if(lo.v!==UI_WIRE_VERSION)throw new Error(`reactor.ui wire v${String(lo.v)} is not v${UI_WIRE_VERSION}`);switch(lo.op){case"show":return shown(Au,lo.body);case"ask":{const $u=shown(Au,lo.body);return $u.asks.includes(lo.body.id)?$u:{...$u,asks:[...$u.asks,lo.body.id]}}case"patch":{const $u=applyPatch$1(displayOf(Au,lo),lo.body);return{...Au,displays:{...Au.displays,[lo.id]:{...$u,id:lo.id}}}}case"append":{const $u=displayOf(Au,lo),Ru=applyPatch$1($u,[{op:"add",path:`${lo.body.path}/-`,value:lo.body.value}]);return{...Au,displays:{...Au.displays,[lo.id]:Ru}}}case"remove":{if(!(lo.id in Au.displays))return Au;const $u={...Au.displays};return delete $u[lo.id],{...Au,displays:$u,order:Au.order.filter(Ru=>Ru!==lo.id),asks:Au.asks.filter(Ru=>Ru!==lo.id)}}case"state":return{...Au,state:applyPatch$1(Au.state,lo.body)};case"meta":return{...Au,meta:{...Au.meta,...lo.body}};case"window":return Au;default:throw new Error(`Unknown reactor.ui op '${lo.op}'`)}}const AGUI_NAME="reactor.ui",UI_FILE_SCOPE_HEADER="X-Reactor-Scope",UI_FILE_NAME_HEADER="X-Reactor-File-Name";class UiFileRefused extends Error{status;constructor(lo,$u){super($u),this.status=lo,this.name="UiFileRefused"}}async function uploadFile(Au,lo){const $u=await(lo.fetcher??fetch)(lo.url,{method:"POST",headers:{"Content-Type":Au.type||"application/octet-stream",[UI_FILE_SCOPE_HEADER]:lo.scope,[UI_FILE_NAME_HEADER]:encodeURIComponent(Au.name),...lo.token?{Authorization:`Bearer ${lo.token}`}:{}},body:Au});if(!$u.ok){let Iu="";try{const Pu=await $u.json();Iu=typeof Pu.detail=="string"?Pu.detail:""}catch{}throw new UiFileRefused($u.status,Iu||`${Au.name} was refused (${$u.status}).`)}const Ru=await $u.json();if(typeof Ru.ref!="string"||typeof Ru.name!="string"||typeof Ru.media_type!="string")throw new UiFileRefused($u.status,`The host kept ${Au.name} under no ref.`);return Ru}function isFileRef(Au){const lo=Au;return typeof lo=="object"&&lo!==null&&typeof lo.ref=="string"&&typeof lo.name=="string"&&typeof lo.media_type=="string"}const UI_WS_PROTOCOL="reactor.ui.v1",UI_WS_CLOSE={refused:4400,unauthorized:4401,forbidden:4403,timeout:4408,gone:4410};class UiSocketStopped extends Error{status;reason;constructor(lo,$u){super(`reactor.ui socket ${lo}: ${$u}`),this.status=lo,this.reason=$u}}const FINAL_CLOSES={[UI_WS_CLOSE.refused]:"refused",[UI_WS_CLOSE.unauthorized]:"refused",[UI_WS_CLOSE.forbidden]:"refused",[UI_WS_CLOSE.gone]:"gone"};function randomId(){const Au=globalThis.crypto;return Au?.randomUUID?Au.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}class UiSocket{lastSeq;status="connecting";ws=null;welcomed=!1;historyUpTo=0;resumable;stopped=!1;attempt=0;heard=0;beat=null;retry=null;pending=new Map;options;constructor(lo){this.options={heartbeatMs:2e4,timeoutMs:6e4,backoffMs:[250,1e3,2e3,5e3],maxPending:64,newId:randomId,...lo},this.lastSeq=lo.since??0,this.resumable=lo.since!==void 0}connect(){if(this.stopped||this.ws)return;this.setStatus(this.attempt===0&&!this.resumable?"connecting":"reconnecting");const $u=(this.options.open??((Ru,Iu)=>new globalThis.WebSocket(Ru,Iu)))(this.options.url,[UI_WS_PROTOCOL]);this.ws=$u,this.welcomed=!1,$u.onopen=()=>{this.hello($u)},$u.onmessage=Ru=>this.receive($u,Ru.data),$u.onclose=Ru=>this.closed($u,Ru.code,Ru.reason),$u.onerror=()=>{}}act(lo){const $u={...lo,idempotency_id:lo.idempotency_id??this.options.newId()};return this.request({t:"action",ref:this.options.newId(),action:$u})}state(lo){return this.request({t:"state",ref:this.options.newId(),body:lo})}close(){this.stop("closed","closed by the page",1e3)}request(lo){return this.stopped?Promise.reject(new UiSocketStopped(this.status,"the socket is stopped")):this.pending.size>=this.options.maxPending?Promise.reject(new Error(`${this.pending.size} presses are waiting for their result`)):new Promise(($u,Ru)=>{this.pending.set(lo.ref,{frame:lo,resolve:$u,reject:Ru}),this.welcomed&&this.send(lo)})}async hello(lo){let $u;try{$u=await this.options.token()}catch(Ru){this.stop("refused",`no credential: ${String(Ru)}`,1e3);return}lo===this.ws&&(this.heard=Date.now(),this.send({t:"hello",v:UI_WIRE_VERSION,token:$u,scope:this.options.scope,since:this.resumable?this.lastSeq:null}),this.beat=setInterval(()=>this.heartbeat(lo),this.options.heartbeatMs))}heartbeat(lo){if(lo===this.ws){if(Date.now()-this.heard>this.options.timeoutMs){lo.close(UI_WS_CLOSE.timeout,"nothing heard"),this.closed(lo,UI_WS_CLOSE.timeout,"nothing heard");return}this.send({t:"ping"})}}receive(lo,$u){if(lo!==this.ws)return;let Ru;try{Ru=typeof $u=="string"?JSON.parse($u):void 0}catch{Ru=void 0}if(!isDownFrame(Ru)){this.stop("refused","the host sent a frame that is not the schema’s",UI_WS_CLOSE.refused);return}this.heard=Date.now(),this.handle(lo,Ru)}handle(lo,$u){switch($u.t){case"welcome":if($u.scope!==this.options.scope){this.stop("refused",`welcomed to ${$u.scope}, not ${this.options.scope}`,UI_WS_CLOSE.refused);return}if(this.resumable&&$u.seq<this.lastSeq){this.stop("gone",`the host is at op ${$u.seq}, the page at ${this.lastSeq}`,1e3);return}this.resumable||(this.historyUpTo=$u.seq),this.welcomed=!0,this.attempt=0,this.setStatus("open");for(const Ru of this.pending.values())this.send(Ru.frame);return;case"op":if(!this.welcomed){this.stop("refused","an op before the welcome",UI_WS_CLOSE.refused);return}if($u.seq<=this.lastSeq)return;if($u.seq!==this.lastSeq+1){lo.close(1e3,`op ${$u.seq} after ${this.lastSeq}`),this.closed(lo,1e3,"a gap");return}this.lastSeq=$u.seq,this.resumable=!0,this.options.onOp($u.op,$u.seq,$u.seq<=this.historyUpTo);return;case"result":{const Ru=this.pending.get($u.ref);Ru&&(this.pending.delete($u.ref),Ru.resolve({ok:$u.ok,status:$u.status,detail:$u.detail,value:$u.value}));return}case"ping":this.send({t:"pong"});return;case"pong":return}}closed(lo,$u,Ru){if(lo!==this.ws||(this.ws=null,this.welcomed=!1,this.clearBeat(),this.stopped))return;const Iu=FINAL_CLOSES[$u];if(Iu){this.stop(Iu,Ru||`closed with ${$u}`);return}this.resumable=this.resumable||this.lastSeq>0;const Pu=this.options.backoffMs,Ou=Pu[Math.min(this.attempt,Pu.length-1)]??1e3;this.attempt+=1,this.setStatus("reconnecting",Ru),this.retry=setTimeout(()=>{this.retry=null,this.connect()},Ou)}stop(lo,$u,Ru){if(this.stopped)return;this.stopped=!0,this.clearBeat(),this.retry&&(clearTimeout(this.retry),this.retry=null);const Iu=this.ws;this.ws=null,Iu&&Ru!==void 0&&Iu.close(Ru,$u.slice(0,120));for(const Pu of this.pending.values())Pu.reject(new UiSocketStopped(lo,$u));this.pending.clear(),this.setStatus(lo,$u)}send(lo){this.ws?.send(JSON.stringify(lo))}clearBeat(){this.beat&&(clearInterval(this.beat),this.beat=null)}setStatus(lo,$u){this.status=lo,this.options.onStatus?.(lo,$u)}}var lib$b={},basemanager={},serverconnection={},serialize$2={},messages$1={},hasRequiredMessages;function requireMessages(){if(hasRequiredMessages)return messages$1;hasRequiredMessages=1,Object.defineProperty(messages$1,"__esModule",{value:!0}),messages$1.supportedKernelWebSocketProtocols=void 0,messages$1.createMessage=lo,messages$1.isStreamMsg=$u,messages$1.isDisplayDataMsg=Ru,messages$1.isUpdateDisplayDataMsg=Iu,messages$1.isExecuteInputMsg=Pu,messages$1.isExecuteResultMsg=Ou,messages$1.isErrorMsg=Mu,messages$1.isStatusMsg=Du,messages$1.isClearOutputMsg=Lu,messages$1.isDebugEventMsg=Bu,messages$1.isCommOpenMsg=ju,messages$1.isCommCloseMsg=Fu,messages$1.isCommMsgMsg=zu,messages$1.isInfoRequestMsg=Uu,messages$1.isExecuteReplyMsg=Hu,messages$1.isDebugRequestMsg=Vu,messages$1.isDebugReplyMsg=Gu,messages$1.isInputRequestMsg=Wu,messages$1.isInputReplyMsg=Ku;const Au=requireDist();function lo(Yu){var Xu,ed,td,nd,od,sd;return{buffers:(Xu=Yu.buffers)!==null&&Xu!==void 0?Xu:[],channel:Yu.channel,content:Yu.content,header:{date:new Date().toISOString(),msg_id:(ed=Yu.msgId)!==null&&ed!==void 0?ed:Au.UUID.uuid4(),msg_type:Yu.msgType,session:Yu.session,username:(td=Yu.username)!==null&&td!==void 0?td:"",subshell_id:(nd=Yu.subshellId)!==null&&nd!==void 0?nd:null,version:"5.2"},metadata:(od=Yu.metadata)!==null&&od!==void 0?od:{},parent_header:(sd=Yu.parentHeader)!==null&&sd!==void 0?sd:{}}}function $u(Yu){return Yu.header.msg_type==="stream"}function Ru(Yu){return Yu.header.msg_type==="display_data"}function Iu(Yu){return Yu.header.msg_type==="update_display_data"}function Pu(Yu){return Yu.header.msg_type==="execute_input"}function Ou(Yu){return Yu.header.msg_type==="execute_result"}function Mu(Yu){return Yu.header.msg_type==="error"}function Du(Yu){return Yu.header.msg_type==="status"}function Lu(Yu){return Yu.header.msg_type==="clear_output"}function Bu(Yu){return Yu.header.msg_type==="debug_event"}function ju(Yu){return Yu.header.msg_type==="comm_open"}function Fu(Yu){return Yu.header.msg_type==="comm_close"}function zu(Yu){return Yu.header.msg_type==="comm_msg"}function Uu(Yu){return Yu.header.msg_type==="kernel_info_request"}function Hu(Yu){return Yu.header.msg_type==="execute_reply"}function Vu(Yu){return Yu.header.msg_type==="debug_request"}function Gu(Yu){return Yu.header.msg_type==="debug_reply"}function Wu(Yu){return Yu.header.msg_type==="input_request"}function Ku(Yu){return Yu.header.msg_type==="input_reply"}var Ju;return(function(Yu){Yu.v1KernelWebsocketJupyterOrg="v1.kernel.websocket.jupyter.org"})(Ju||(messages$1.supportedKernelWebSocketProtocols=Ju={})),messages$1}var hasRequiredSerialize;function requireSerialize(){if(hasRequiredSerialize)return serialize$2;hasRequiredSerialize=1;var Au=serialize$2&&serialize$2.__createBinding||(Object.create?(function(Mu,Du,Lu,Bu){Bu===void 0&&(Bu=Lu);var ju=Object.getOwnPropertyDescriptor(Du,Lu);(!ju||("get"in ju?!Du.__esModule:ju.writable||ju.configurable))&&(ju={enumerable:!0,get:function(){return Du[Lu]}}),Object.defineProperty(Mu,Bu,ju)}):(function(Mu,Du,Lu,Bu){Bu===void 0&&(Bu=Lu),Mu[Bu]=Du[Lu]})),lo=serialize$2&&serialize$2.__setModuleDefault||(Object.create?(function(Mu,Du){Object.defineProperty(Mu,"default",{enumerable:!0,value:Du})}):function(Mu,Du){Mu.default=Du}),$u=serialize$2&&serialize$2.__importStar||(function(){var Mu=function(Du){return Mu=Object.getOwnPropertyNames||function(Lu){var Bu=[];for(var ju in Lu)Object.prototype.hasOwnProperty.call(Lu,ju)&&(Bu[Bu.length]=ju);return Bu},Mu(Du)};return function(Du){if(Du&&Du.__esModule)return Du;var Lu={};if(Du!=null)for(var Bu=Mu(Du),ju=0;ju<Bu.length;ju++)Bu[ju]!=="default"&&Au(Lu,Du,Bu[ju]);return lo(Lu,Du),Lu}})();Object.defineProperty(serialize$2,"__esModule",{value:!0}),serialize$2.serialize=Iu,serialize$2.deserialize=Pu;const Ru=$u(requireMessages());function Iu(Mu,Du=""){return Du===Ru.supportedKernelWebSocketProtocols.v1KernelWebsocketJupyterOrg?Ou.serializeV1KernelWebsocketJupyterOrg(Mu):Ou.serializeDefault(Mu)}function Pu(Mu,Du=""){return Du===Ru.supportedKernelWebSocketProtocols.v1KernelWebsocketJupyterOrg?Ou.deserializeV1KernelWebsocketJupyterOrg(Mu):Ou.deserializeDefault(Mu)}var Ou;return(function(Mu){function Du(Uu){let Hu;const Vu=new DataView(Uu),Gu=Number(Vu.getBigUint64(0,!0));let Wu=[];for(let od=0;od<Gu;od++)Wu.push(Number(Vu.getBigUint64(8*(od+1),!0)));const Ku=new TextDecoder("utf8"),Ju=Ku.decode(Uu.slice(Wu[0],Wu[1])),Yu=JSON.parse(Ku.decode(Uu.slice(Wu[1],Wu[2]))),Xu=JSON.parse(Ku.decode(Uu.slice(Wu[2],Wu[3]))),ed=JSON.parse(Ku.decode(Uu.slice(Wu[3],Wu[4]))),td=JSON.parse(Ku.decode(Uu.slice(Wu[4],Wu[5])));let nd=[];for(let od=5;od<Wu.length-1;od++)nd.push(new DataView(Uu.slice(Wu[od],Wu[od+1])));return Hu={channel:Ju,header:Yu,parent_header:Xu,metadata:ed,content:td,buffers:nd},Hu}Mu.deserializeV1KernelWebsocketJupyterOrg=Du;function Lu(Uu){const Hu=JSON.stringify(Uu.header),Vu=Uu.parent_header==null?"{}":JSON.stringify(Uu.parent_header),Gu=JSON.stringify(Uu.metadata),Wu=JSON.stringify(Uu.content),Ku=Uu.buffers!==void 0?Uu.buffers:[],Ju=5+Ku.length+1;let Yu=[];Yu.push(8*(1+Ju)),Yu.push(Uu.channel.length+Yu[Yu.length-1]);const Xu=new TextEncoder,ed=Xu.encode(Uu.channel),td=Xu.encode(Hu),nd=Xu.encode(Vu),od=Xu.encode(Gu),sd=Xu.encode(Wu),ad=new Uint8Array(ed.length+td.length+nd.length+od.length+sd.length);ad.set(ed),ad.set(td,ed.length),ad.set(nd,ed.length+td.length),ad.set(od,ed.length+td.length+nd.length),ad.set(sd,ed.length+td.length+nd.length+od.length);for(let yd of[td.length,nd.length,od.length,sd.length])Yu.push(yd+Yu[Yu.length-1]);let pd=0;for(let yd of Ku){let wd=yd.byteLength;Yu.push(wd+Yu[Yu.length-1]),pd+=wd}const gd=new Uint8Array(8*(1+Ju)+ad.byteLength+pd),Sd=new ArrayBuffer(8),_d=new DataView(Sd);_d.setBigUint64(0,BigInt(Ju),!0),gd.set(new Uint8Array(Sd),0);for(let yd=0;yd<Yu.length;yd++)_d.setBigUint64(0,BigInt(Yu[yd]),!0),gd.set(new Uint8Array(Sd),8*(yd+1));gd.set(ad,Yu[0]);for(let yd=0;yd<Ku.length;yd++){const wd=Ku[yd];gd.set(new Uint8Array(ArrayBuffer.isView(wd)?wd.buffer:wd),Yu[5+yd])}return gd.buffer}Mu.serializeV1KernelWebsocketJupyterOrg=Lu;function Bu(Uu){let Hu;return typeof Uu=="string"?Hu=JSON.parse(Uu):Hu=Fu(Uu),Hu}Mu.deserializeDefault=Bu;function ju(Uu){var Hu;let Vu;return!((Hu=Uu.buffers)===null||Hu===void 0)&&Hu.length?Vu=zu(Uu):Vu=JSON.stringify(Uu),Vu}Mu.serializeDefault=ju;function Fu(Uu){const Hu=new DataView(Uu),Vu=Hu.getUint32(0),Gu=[];if(Vu<2)throw new Error("Invalid incoming Kernel Message");for(let Ju=1;Ju<=Vu;Ju++)Gu.push(Hu.getUint32(Ju*4));const Wu=new Uint8Array(Uu.slice(Gu[0],Gu[1])),Ku=JSON.parse(new TextDecoder("utf8").decode(Wu));Ku.buffers=[];for(let Ju=1;Ju<Vu;Ju++){const Yu=Gu[Ju],Xu=Gu[Ju+1]||Uu.byteLength;Ku.buffers.push(new DataView(Uu.slice(Yu,Xu)))}return Ku}function zu(Uu){const Hu=[],Vu=[],Gu=new TextEncoder;let Wu=[];Uu.buffers!==void 0&&(Wu=Uu.buffers,delete Uu.buffers);const Ku=Gu.encode(JSON.stringify(Uu));Vu.push(Ku.buffer);for(let ed=0;ed<Wu.length;ed++){const td=Wu[ed];Vu.push(ArrayBuffer.isView(td)?td.buffer:td)}const Ju=Vu.length;Hu.push(4*(Ju+1));for(let ed=0;ed+1<Vu.length;ed++)Hu.push(Hu[Hu.length-1]+Vu[ed].byteLength);const Yu=new Uint8Array(Hu[Hu.length-1]+Vu[Vu.length-1].byteLength),Xu=new DataView(Yu.buffer);Xu.setUint32(0,Ju);for(let ed=0;ed<Hu.length;ed++)Xu.setUint32(4*(ed+1),Hu[ed]);for(let ed=0;ed<Vu.length;ed++)Yu.set(new Uint8Array(Vu[ed]),Hu[ed]);return Yu.buffer}})(Ou||(Ou={})),serialize$2}var ws$1={},hasRequiredWs;function requireWs(){return hasRequiredWs||(hasRequiredWs=1,Object.defineProperty(ws$1,"__esModule",{value:!0}),ws$1.default=WebSocket),ws$1}var hasRequiredServerconnection;function requireServerconnection(){if(hasRequiredServerconnection)return serverconnection;hasRequiredServerconnection=1;var Au={};Object.defineProperty(serverconnection,"__esModule",{value:!0}),serverconnection.ServerConnection=void 0;const lo=requireLib$b(),$u=requireSerialize();let Ru;typeof window>"u"?Ru=requireWs():Ru=WebSocket;var Iu;(function(Ou){function Mu(ju){return Pu.makeSettings(ju)}Ou.makeSettings=Mu;function Du(ju,Fu,zu){return Pu.handleRequest(ju,Fu,zu)}Ou.makeRequest=Du;class Lu extends Error{static async create(Fu){try{const zu=await Fu.json(),{message:Uu,traceback:Hu}=zu;return Hu&&console.error(Hu),new Lu(Fu,Uu??Lu._defaultMessage(Fu),Hu??"")}catch(zu){return console.debug(zu),new Lu(Fu)}}constructor(Fu,zu=Lu._defaultMessage(Fu),Uu=""){super(zu),this.response=Fu,this.traceback=Uu}static _defaultMessage(Fu){return`Invalid response: ${Fu.status} ${Fu.statusText}`}}Ou.ResponseError=Lu;class Bu extends TypeError{constructor(Fu){super(Fu.message),this.stack=Fu.stack}}Ou.NetworkError=Bu})(Iu||(serverconnection.ServerConnection=Iu={}));var Pu;return(function(Ou){function Mu(Bu={}){var ju;const Fu=lo.PageConfig.getBaseUrl(),zu=lo.PageConfig.getWsUrl(),Uu=lo.URLExt.normalize(Bu.baseUrl)||Fu;let Hu=Bu.wsUrl;!Hu&&Uu===Fu&&(Hu=zu),!Hu&&Uu.indexOf("http")===0&&(Hu="ws"+Uu.slice(4)),Hu=Hu??zu;const Vu=lo.PageConfig.getOption("appendToken").toLowerCase();let Gu;return Vu===""?Gu=typeof window>"u"||typeof process<"u"&&((ju=process==null?void 0:Au)===null||ju===void 0?void 0:ju.JEST_WORKER_ID)!==void 0||lo.URLExt.getHostName(Fu)!==lo.URLExt.getHostName(Hu):Gu=Vu==="true",{init:{cache:"no-store",credentials:"same-origin"},fetch,Headers,Request,WebSocket:Ru,token:lo.PageConfig.getToken(),appUrl:lo.PageConfig.getOption("appUrl"),appendToken:Gu,serializer:{serialize:$u.serialize,deserialize:$u.deserialize},...Bu,baseUrl:Uu,wsUrl:Hu}}Ou.makeSettings=Mu;function Du(Bu,ju,Fu){var zu;if(Bu.indexOf(Fu.baseUrl)!==0)throw new Error("Can only be used for notebook server requests");((zu=ju.cache)!==null&&zu!==void 0?zu:Fu.init.cache)==="no-store"&&(Bu+=(/\?/.test(Bu)?"&":"?")+new Date().getTime());const Hu=new Fu.Request(Bu,{...Fu.init,...ju});let Vu=!1;if(Fu.token&&(Vu=!0,Hu.headers.append("Authorization",`token ${Fu.token}`)),typeof document<"u"){const Gu=Lu("_xsrf");Gu!==void 0&&(Vu=!0,Hu.headers.append("X-XSRFToken",Gu))}return!Hu.headers.has("Content-Type")&&Vu&&Hu.headers.set("Content-Type","application/json"),Fu.fetch.call(null,Hu).catch(Gu=>{throw new Iu.NetworkError(Gu)})}Ou.handleRequest=Du;function Lu(Bu){let ju="";try{ju=document.cookie}catch{return}const Fu=Bu+"=";let zu;for(const Uu of ju.split(";")){const Hu=Uu.trim();Hu.startsWith(Fu)&&(zu=Hu.substring(Fu.length))}return zu}})(Pu||(Pu={})),serverconnection}var hasRequiredBasemanager;function requireBasemanager(){if(hasRequiredBasemanager)return basemanager;hasRequiredBasemanager=1,Object.defineProperty(basemanager,"__esModule",{value:!0}),basemanager.BaseManager=void 0;const Au=require$$0$3,lo=requireServerconnection();class $u{constructor(Iu){var Pu;this._isDisposed=!1,this._disposed=new Au.Signal(this),this.serverSettings=(Pu=Iu.serverSettings)!==null&&Pu!==void 0?Pu:lo.ServerConnection.makeSettings()}get disposed(){return this._disposed}get isDisposed(){return this._isDisposed}get isActive(){return!0}dispose(){this.isDisposed||(this._isDisposed=!0,this._disposed.emit(void 0),Au.Signal.clearData(this))}}return basemanager.BaseManager=$u,basemanager}var config$4={},hasRequiredConfig;function requireConfig(){if(hasRequiredConfig)return config$4;hasRequiredConfig=1,Object.defineProperty(config$4,"__esModule",{value:!0}),config$4.ConfigWithDefaults=config$4.ConfigSection=config$4.ConfigSectionManager=void 0;const Au=requireLib$b(),lo=requireLib$8(),$u="api/config";class Ru{constructor(Du){var Lu;this.serverSettings=(Lu=Du.serverSettings)!==null&&Lu!==void 0?Lu:lo.ServerConnection.makeSettings()}async create(Du){const Lu=new Pu({...Du,serverSettings:this.serverSettings});return await Lu.load(),Lu}}config$4.ConfigSectionManager=Ru;var Iu;(function(Mu){async function Du(ju){if(!Lu){const zu=new Pu(ju);return await zu.load(),zu}return await Lu.create(ju)}Mu.create=Du;let Lu;function Bu(ju){if(Lu)throw new Error("ConfigSectionManager already set. If you would like to create a config section, use the `IConfigSectionManager` token in a plugin.");Lu=ju}Mu._setConfigSectionManager=Bu})(Iu||(config$4.ConfigSection=Iu={}));class Pu{constructor(Du){var Lu;this.serverSettings=(Lu=Du.serverSettings)!==null&&Lu!==void 0?Lu:lo.ServerConnection.makeSettings(),this._name=Du.name}get data(){return this._data}async load(){const Du=await lo.ServerConnection.makeRequest(this._url,{},this.serverSettings);if(Du.status!==200)throw await lo.ServerConnection.ResponseError.create(Du);this._data=await Du.json()}async update(Du){this._data={...this._data,...Du};const Lu={method:"PATCH",body:JSON.stringify(Du)},Bu=await lo.ServerConnection.makeRequest(this._url,Lu,this.serverSettings);if(Bu.status!==200)throw await lo.ServerConnection.ResponseError.create(Bu);return this._data=await Bu.json(),this._data}get _url(){return Au.URLExt.join(this.serverSettings.baseUrl,$u,encodeURIComponent(this._name))}}class Ou{constructor(Du){var Lu,Bu;this._className="",this._section=Du.section,this._defaults=(Lu=Du.defaults)!==null&&Lu!==void 0?Lu:{},this._className=(Bu=Du.className)!==null&&Bu!==void 0?Bu:""}get(Du){const Lu=this._classData();return Du in Lu?Lu[Du]:this._defaults[Du]}set(Du,Lu){const Bu={};if(Bu[Du]=Lu,this._className){const ju={};return ju[this._className]=Bu,this._section.update(ju)}else return this._section.update(Bu)}_classData(){const Du=this._section.data;return this._className&&this._className in Du?Du[this._className]:Du}}return config$4.ConfigWithDefaults=Ou,config$4}var connectionstatus={},hasRequiredConnectionstatus;function requireConnectionstatus(){if(hasRequiredConnectionstatus)return connectionstatus;hasRequiredConnectionstatus=1,Object.defineProperty(connectionstatus,"__esModule",{value:!0}),connectionstatus.ConnectionStatus=void 0;class Au{constructor(){this.isConnected=!0}}return connectionstatus.ConnectionStatus=Au,connectionstatus}var contents={};class DisposableDelegate{constructor(lo){this._fn=lo}get isDisposed(){return!this._fn}dispose(){if(!this._fn)return;let lo=this._fn;this._fn=null,lo()}}class ObservableDisposableDelegate extends DisposableDelegate{constructor(){super(...arguments),this._disposed=new Signal(this)}get disposed(){return this._disposed}dispose(){this.isDisposed||(super.dispose(),this._disposed.emit(void 0),Signal.clearData(this))}}class DisposableSet{constructor(){this._isDisposed=!1,this._items=new Set}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,this._items.forEach(lo=>{lo.dispose()}),this._items.clear())}contains(lo){return this._items.has(lo)}add(lo){this._items.add(lo)}remove(lo){this._items.delete(lo)}clear(){this._items.clear()}}(function(Au){function lo($u){let Ru=new Au;for(const Iu of $u)Ru.add(Iu);return Ru}Au.from=lo})(DisposableSet||(DisposableSet={}));class ObservableDisposableSet extends DisposableSet{constructor(){super(...arguments),this._disposed=new Signal(this)}get disposed(){return this._disposed}dispose(){this.isDisposed||(super.dispose(),this._disposed.emit(void 0),Signal.clearData(this))}}(function(Au){function lo($u){let Ru=new Au;for(const Iu of $u)Ru.add(Iu);return Ru}Au.from=lo})(ObservableDisposableSet||(ObservableDisposableSet={}));const index_es6$1=Object.freeze(Object.defineProperty({__proto__:null,DisposableDelegate,get DisposableSet(){return DisposableSet},ObservableDisposableDelegate,get ObservableDisposableSet(){return ObservableDisposableSet}},Symbol.toStringTag,{value:"Module"})),require$$1$2=getAugmentedNamespace(index_es6$1);var validate$7={},validate$6={},hasRequiredValidate$5;function requireValidate$5(){if(hasRequiredValidate$5)return validate$6;hasRequiredValidate$5=1,Object.defineProperty(validate$6,"__esModule",{value:!0}),validate$6.validateProperty=Au;function Au(lo,$u,Ru,Iu=[]){if(!lo.hasOwnProperty($u))throw Error(`Missing property '${$u}'`);const Pu=lo[$u];if(Ru!==void 0){let Ou;switch(Ru){case"array":Ou=Array.isArray(Pu);break;case"object":Ou=typeof Pu<"u";break;default:Ou=typeof Pu===Ru}if(!Ou)throw new Error(`Property '${$u}' is not of type '${Ru}'`);if(Iu.length>0){let Mu;switch(Ru){case"string":case"number":case"boolean":Mu=Iu.includes(Pu);break;default:Mu=Iu.findIndex(Du=>Du===Pu)>=0;break}if(!Mu)throw new Error(`Property '${$u}' is not one of the valid values ${JSON.stringify(Iu)}`)}}}return validate$6}var hasRequiredValidate$4;function requireValidate$4(){if(hasRequiredValidate$4)return validate$7;hasRequiredValidate$4=1,Object.defineProperty(validate$7,"__esModule",{value:!0}),validate$7.validateContentsModel=lo,validate$7.validateCheckpointModel=$u;const Au=requireValidate$5();function lo(Ru){(0,Au.validateProperty)(Ru,"name","string"),(0,Au.validateProperty)(Ru,"path","string"),(0,Au.validateProperty)(Ru,"type","string"),(0,Au.validateProperty)(Ru,"created","string"),(0,Au.validateProperty)(Ru,"last_modified","string"),(0,Au.validateProperty)(Ru,"mimetype","object"),(0,Au.validateProperty)(Ru,"content","object"),(0,Au.validateProperty)(Ru,"format","object")}function $u(Ru){(0,Au.validateProperty)(Ru,"id","string"),(0,Au.validateProperty)(Ru,"last_modified","string")}return validate$7}var hasRequiredContents;function requireContents(){if(hasRequiredContents)return contents;hasRequiredContents=1;var Au=contents&&contents.__createBinding||(Object.create?(function(Gu,Wu,Ku,Ju){Ju===void 0&&(Ju=Ku);var Yu=Object.getOwnPropertyDescriptor(Wu,Ku);(!Yu||("get"in Yu?!Wu.__esModule:Yu.writable||Yu.configurable))&&(Yu={enumerable:!0,get:function(){return Wu[Ku]}}),Object.defineProperty(Gu,Ju,Yu)}):(function(Gu,Wu,Ku,Ju){Ju===void 0&&(Ju=Ku),Gu[Ju]=Wu[Ku]})),lo=contents&&contents.__setModuleDefault||(Object.create?(function(Gu,Wu){Object.defineProperty(Gu,"default",{enumerable:!0,value:Wu})}):function(Gu,Wu){Gu.default=Wu}),$u=contents&&contents.__importStar||(function(){var Gu=function(Wu){return Gu=Object.getOwnPropertyNames||function(Ku){var Ju=[];for(var Yu in Ku)Object.prototype.hasOwnProperty.call(Ku,Yu)&&(Ju[Ju.length]=Yu);return Ju},Gu(Wu)};return function(Wu){if(Wu&&Wu.__esModule)return Wu;var Ku={};if(Wu!=null)for(var Ju=Gu(Wu),Yu=0;Yu<Ju.length;Yu++)Ju[Yu]!=="default"&&Au(Ku,Wu,Ju[Yu]);return lo(Ku,Wu),Ku}})();Object.defineProperty(contents,"__esModule",{value:!0}),contents.RestContentProvider=contents.ContentProviderRegistry=contents.Drive=contents.ContentsManager=contents.Contents=void 0;const Ru=requireLib$b(),Iu=requireDist(),Pu=require$$1$2,Ou=require$$0$3,Mu=requireLib$8(),Du=$u(requireValidate$4()),Lu="api/contents",Bu="files";var ju;(function(Gu){function Wu(Ju){Du.validateContentsModel(Ju)}Gu.validateContentsModel=Wu;function Ku(Ju){Du.validateCheckpointModel(Ju)}Gu.validateCheckpointModel=Ku})(ju||(contents.Contents=ju={}));class Fu{constructor(Wu={}){var Ku,Ju;this._isDisposed=!1,this._additionalDrives=new Map,this._fileChanged=new Ou.Signal(this);const Yu=this.serverSettings=(Ku=Wu.serverSettings)!==null&&Ku!==void 0?Ku:Mu.ServerConnection.makeSettings();this._defaultDrive=(Ju=Wu.defaultDrive)!==null&&Ju!==void 0?Ju:new zu({serverSettings:Yu}),this._defaultDrive.fileChanged.connect(this._onFileChanged,this)}get defaultDrive(){return this._defaultDrive}get fileChanged(){return this._fileChanged}get isDisposed(){return this._isDisposed}dispose(){this.isDisposed||(this._isDisposed=!0,Ou.Signal.clearData(this))}addDrive(Wu){this._additionalDrives.set(Wu.name,Wu),Wu.fileChanged.connect(this._onFileChanged,this)}getSharedModelFactory(Wu,Ku){var Ju,Yu;const[Xu]=this._driveForPath(Wu),ed=(Ju=Xu.contentProviderRegistry)===null||Ju===void 0?void 0:Ju.getProvider(Ku?.contentProviderId);return ed?.sharedModelFactory?ed.sharedModelFactory:(Yu=Xu.sharedModelFactory)!==null&&Yu!==void 0?Yu:null}localPath(Wu){const Ku=Wu.split("/"),Ju=Ku[0].split(":");return Ju.length===1||!this._additionalDrives.has(Ju[0])?Ru.PathExt.removeSlash(Wu):Ru.PathExt.join(Ju.slice(1).join(":"),...Ku.slice(1))}normalize(Wu){const Ku=Wu.split(":");return Ku.length===1?Ru.PathExt.normalize(Wu):`${Ku[0]}:${Ru.PathExt.normalize(Ku.slice(1).join(":"))}`}resolvePath(Wu,Ku){const Ju=this.driveName(Wu),Yu=this.localPath(Wu),Xu=Ru.PathExt.resolve("/",Yu,Ku);return Ju?`${Ju}:${Xu}`:Xu}driveName(Wu){const Ju=Wu.split("/")[0].split(":");return Ju.length===1?"":this._additionalDrives.has(Ju[0])?Ju[0]:""}get(Wu,Ku){const[Ju,Yu]=this._driveForPath(Wu);return Ju.get(Yu,Ku).then(Xu=>{const ed=[];if(Xu.type==="directory"&&Xu.content){for(const td of Xu.content)ed.push({...td,path:this._toGlobalPath(Ju,td.path)});return{...Xu,path:this._toGlobalPath(Ju,Yu),content:ed,serverPath:Xu.path}}else return{...Xu,path:this._toGlobalPath(Ju,Yu),serverPath:Xu.path}})}getDownloadUrl(Wu){const[Ku,Ju]=this._driveForPath(Wu);return Ku.getDownloadUrl(Ju)}newUntitled(Wu={}){if(Wu.path){const Ku=this.normalize(Wu.path),[Ju,Yu]=this._driveForPath(Ku);return Ju.newUntitled({...Wu,path:Yu}).then(Xu=>({...Xu,path:Ru.PathExt.join(Ku,Xu.name),serverPath:Xu.path}))}else return this._defaultDrive.newUntitled(Wu)}delete(Wu){const[Ku,Ju]=this._driveForPath(Wu);return Ku.delete(Ju)}rename(Wu,Ku){const[Ju,Yu]=this._driveForPath(Wu),[Xu,ed]=this._driveForPath(Ku);if(Ju!==Xu)throw Error("ContentsManager: renaming files must occur within a Drive");return Ju.rename(Yu,ed).then(td=>({...td,path:this._toGlobalPath(Ju,ed),serverPath:td.path}))}async overwrite(Wu,Ku){const Ju=`${Ku}.${Iu.UUID.uuid4()}`;return await this.rename(Wu,Ju),await this.delete(Ku),await this.rename(Ju,Ku)}save(Wu,Ku={}){const Ju=this.normalize(Wu),[Yu,Xu]=this._driveForPath(Wu);return Yu.save(Xu,{...Ku,path:Xu}).then(ed=>({...ed,path:Ju,serverPath:ed.path}))}copy(Wu,Ku){const[Ju,Yu]=this._driveForPath(Wu),[Xu,ed]=this._driveForPath(Ku);if(Ju===Xu)return Ju.copy(Yu,ed).then(td=>({...td,path:this._toGlobalPath(Ju,td.path),serverPath:td.path}));throw Error("Copying files between drives is not currently implemented")}createCheckpoint(Wu){const[Ku,Ju]=this._driveForPath(Wu);return Ku.createCheckpoint(Ju)}listCheckpoints(Wu){const[Ku,Ju]=this._driveForPath(Wu);return Ku.listCheckpoints(Ju)}restoreCheckpoint(Wu,Ku){const[Ju,Yu]=this._driveForPath(Wu);return Ju.restoreCheckpoint(Yu,Ku)}deleteCheckpoint(Wu,Ku){const[Ju,Yu]=this._driveForPath(Wu);return Ju.deleteCheckpoint(Yu,Ku)}_toGlobalPath(Wu,Ku){return Wu===this._defaultDrive?Ru.PathExt.removeSlash(Ku):`${Wu.name}:${Ru.PathExt.removeSlash(Ku)}`}_driveForPath(Wu){const Ku=this.driveName(Wu),Ju=this.localPath(Wu);return Ku?[this._additionalDrives.get(Ku),Ju]:[this._defaultDrive,Ju]}_onFileChanged(Wu,Ku){var Ju,Yu;if(Wu===this._defaultDrive)this._fileChanged.emit(Ku);else{let Xu=null,ed=null;!((Ju=Ku.newValue)===null||Ju===void 0)&&Ju.path&&(Xu={...Ku.newValue,path:this._toGlobalPath(Wu,Ku.newValue.path)}),!((Yu=Ku.oldValue)===null||Yu===void 0)&&Yu.path&&(ed={...Ku.oldValue,path:this._toGlobalPath(Wu,Ku.oldValue.path)}),this._fileChanged.emit({type:Ku.type,newValue:Xu,oldValue:ed})}}}contents.ContentsManager=Fu;class zu{constructor(Wu={}){var Ku,Ju,Yu;this._isDisposed=!1,this._fileChanged=new Ou.Signal(this),this.name=(Ku=Wu.name)!==null&&Ku!==void 0?Ku:"Default",this._apiEndpoint=(Ju=Wu.apiEndpoint)!==null&&Ju!==void 0?Ju:Lu,this.serverSettings=(Yu=Wu.serverSettings)!==null&&Yu!==void 0?Yu:Mu.ServerConnection.makeSettings(),this._restContentProvider=new Vu({...Wu,apiEndpoint:this._apiEndpoint,serverSettings:this.serverSettings}),Wu.defaultContentProvider?this.contentProviderRegistry=new Hu({defaultProvider:Wu.defaultContentProvider}):this.contentProviderRegistry=new Hu,this.contentProviderRegistry.fileChanged.connect((Xu,ed)=>{this._fileChanged.emit(ed)})}get fileChanged(){return this._fileChanged}get isDisposed(){return this._isDisposed}dispose(){this.isDisposed||(this._isDisposed=!0,Ou.Signal.clearData(this))}async get(Wu,Ku){const Ju=this.contentProviderRegistry.getProvider(Ku?.contentProviderId);return Ju?Ju.get(Wu,Ku):await this._restContentProvider.get(Wu,Ku)}getDownloadUrl(Wu){const Ku=this.serverSettings.baseUrl;let Ju=Ru.URLExt.join(Ku,Bu,Ru.URLExt.encodeParts(Wu)),Yu="";try{Yu=document.cookie}catch{}const Xu=Yu.match("\\b_xsrf=([^;]*)\\b");if(Xu){const ed=new URL(Ju);ed.searchParams.append("_xsrf",Xu[1]),Ju=ed.toString()}return Promise.resolve(Ju)}async newUntitled(Wu={}){var Ku;let Ju="{}";Wu&&(Wu.ext&&(Wu.ext=Uu.normalizeExtension(Wu.ext)),Ju=JSON.stringify(Wu));const Yu=this.serverSettings,Xu=this._getUrl((Ku=Wu.path)!==null&&Ku!==void 0?Ku:""),ed={method:"POST",body:Ju},td=await Mu.ServerConnection.makeRequest(Xu,ed,Yu);if(td.status!==201)throw await Mu.ServerConnection.ResponseError.create(td);const nd=await td.json();return Du.validateContentsModel(nd),this._fileChanged.emit({type:"new",oldValue:null,newValue:nd}),nd}async delete(Wu){const Ku=this._getUrl(Wu),Ju=this.serverSettings,Yu={method:"DELETE"},Xu=await Mu.ServerConnection.makeRequest(Ku,Yu,Ju);if(Xu.status!==204)throw await Mu.ServerConnection.ResponseError.create(Xu);this._fileChanged.emit({type:"delete",oldValue:{path:Wu},newValue:null})}async rename(Wu,Ku){const Ju=this.serverSettings,Yu=this._getUrl(Wu),Xu={method:"PATCH",body:JSON.stringify({path:Ku})},ed=await Mu.ServerConnection.makeRequest(Yu,Xu,Ju);if(ed.status!==200)throw await Mu.ServerConnection.ResponseError.create(ed);const td=await ed.json();return Du.validateContentsModel(td),this._fileChanged.emit({type:"rename",oldValue:{path:Wu},newValue:td}),td}async save(Wu,Ku={}){const Ju=this.contentProviderRegistry.getProvider(Ku?.contentProviderId);let Yu;return Ju?Yu=await Ju.save(Wu,Ku):Yu=await this._restContentProvider.save(Wu,Ku),this._fileChanged.emit({type:"save",oldValue:null,newValue:Yu}),Yu}async copy(Wu,Ku){const Ju=this.serverSettings,Yu=this._getUrl(Ku),Xu={method:"POST",body:JSON.stringify({copy_from:Wu})},ed=await Mu.ServerConnection.makeRequest(Yu,Xu,Ju);if(ed.status!==201)throw await Mu.ServerConnection.ResponseError.create(ed);const td=await ed.json();return Du.validateContentsModel(td),this._fileChanged.emit({type:"new",oldValue:null,newValue:td}),td}async createCheckpoint(Wu){const Ku=this._getUrl(Wu,"checkpoints"),Ju={method:"POST"},Yu=await Mu.ServerConnection.makeRequest(Ku,Ju,this.serverSettings);if(Yu.status!==201)throw await Mu.ServerConnection.ResponseError.create(Yu);const Xu=await Yu.json();return Du.validateCheckpointModel(Xu),Xu}async listCheckpoints(Wu){const Ku=this._getUrl(Wu,"checkpoints"),Ju=await Mu.ServerConnection.makeRequest(Ku,{},this.serverSettings);if(Ju.status!==200)throw await Mu.ServerConnection.ResponseError.create(Ju);const Yu=await Ju.json();if(!Array.isArray(Yu))throw new Error("Invalid Checkpoint list");for(let Xu=0;Xu<Yu.length;Xu++)Du.validateCheckpointModel(Yu[Xu]);return Yu}async restoreCheckpoint(Wu,Ku){const Ju=this._getUrl(Wu,"checkpoints",Ku),Yu={method:"POST"},Xu=await Mu.ServerConnection.makeRequest(Ju,Yu,this.serverSettings);if(Xu.status!==204)throw await Mu.ServerConnection.ResponseError.create(Xu)}async deleteCheckpoint(Wu,Ku){const Ju=this._getUrl(Wu,"checkpoints",Ku),Yu={method:"DELETE"},Xu=await Mu.ServerConnection.makeRequest(Ju,Yu,this.serverSettings);if(Xu.status!==204)throw await Mu.ServerConnection.ResponseError.create(Xu)}_getUrl(...Wu){const Ku=Wu.map(Yu=>Ru.URLExt.encodeParts(Yu)),Ju=this.serverSettings.baseUrl;return Ru.URLExt.join(Ju,this._apiEndpoint,...Ku)}}contents.Drive=zu;var Uu;(function(Gu){function Wu(Ku){return Ku.length>0&&Ku.indexOf(".")!==0&&(Ku=`.${Ku}`),Ku}Gu.normalizeExtension=Wu})(Uu||(Uu={}));class Hu{constructor(Wu){this._providers=new Map,this._fileChanged=new Ou.Signal(this),Wu?.defaultProvider&&this.register("default",Wu.defaultProvider)}register(Wu,Ku){if(this._providers.has(Wu))throw Error(`Provider with ${Wu} identifier was already registered on this drive`);this._providers.set(Wu,Ku);const Ju=(Yu,Xu)=>{this._fileChanged.emit(Xu)};return Ku.fileChanged&&Ku.fileChanged.connect(Ju),new Pu.DisposableDelegate(()=>{Ku.fileChanged&&Ku.fileChanged.disconnect(Ju),this._providers.has(Wu)&&this._providers.delete(Wu)})}getProvider(Wu){if(!Wu)return null;const Ku=this._providers.get(Wu);if(!Ku)throw Error(`Provider ${Wu} is not registered`);return Ku}get fileChanged(){return this._fileChanged}}contents.ContentProviderRegistry=Hu;class Vu{constructor(Wu){this._options=Wu}async get(Wu,Ku){let Ju=this._getUrl(Wu);if(Ku){Ku.type==="notebook"&&delete Ku.format;const td=Ku.content?"1":"0",nd=Ku.hash?"1":"0",od={...Ku,content:td,hash:nd};Ju+=Ru.URLExt.objectToQueryString(od)}const Yu=this._options.serverSettings,Xu=await Mu.ServerConnection.makeRequest(Ju,{},Yu);if(Xu.status!==200)throw await Mu.ServerConnection.ResponseError.create(Xu);const ed=await Xu.json();return Du.validateContentsModel(ed),ed}async save(Wu,Ku={}){const Ju=this._options.serverSettings,Yu=this._getUrl(Wu),ed={method:"PUT",body:new File([JSON.stringify(Ku)],"data.json",{type:"application/json"})},td=await Mu.ServerConnection.makeRequest(Yu,ed,Ju);if(td.status!==200&&td.status!==201)throw await Mu.ServerConnection.ResponseError.create(td);const nd=await td.json();return Du.validateContentsModel(nd),nd}_getUrl(...Wu){const Ku=Wu.map(Yu=>Ru.URLExt.encodeParts(Yu)),Ju=this._options.serverSettings.baseUrl;return Ru.URLExt.join(Ju,this._options.apiEndpoint,...Ku)}}return contents.RestContentProvider=Vu,contents}var event={};const require$$1$1=getAugmentedNamespace(index_es6$2);var hasRequiredEvent;function requireEvent(){if(hasRequiredEvent)return event;hasRequiredEvent=1,Object.defineProperty(event,"__esModule",{value:!0}),event.EventManager=void 0;const Au=requireLib$b(),lo=require$$1$1,$u=require$$0$3,Ru=requireServerconnection(),Iu="api/events";class Pu{constructor(Mu={}){var Du,Lu;this._socket=null,this.serverSettings=(Du=Mu.serverSettings)!==null&&Du!==void 0?Du:Ru.ServerConnection.makeSettings(),this._poll=new lo.Poll({factory:()=>this._subscribe(),standby:(Lu=Mu.standby)!==null&&Lu!==void 0?Lu:"when-hidden"}),this._stream=new $u.Stream(this),this._poll.start()}get isDisposed(){return this._poll.isDisposed}get stream(){return this._stream}dispose(){if(this.isDisposed)return;this._poll.dispose();const Mu=this._socket;Mu&&(this._socket=null,Mu.onopen=()=>{},Mu.onerror=()=>{},Mu.onmessage=()=>{},Mu.onclose=()=>{},Mu.close()),$u.Signal.clearData(this),this._stream.stop()}async emit(Mu){const{serverSettings:Du}=this,{baseUrl:Lu}=Du,{makeRequest:Bu,ResponseError:ju}=Ru.ServerConnection,Fu=Au.URLExt.join(Lu,Iu),zu={body:JSON.stringify(Mu),method:"POST"},Uu=await Bu(Fu,zu,Du);if(Uu.status!==204)throw new ju(Uu)}_subscribe(){return new Promise((Mu,Du)=>{if(this.isDisposed)return;const{appendToken:Lu,token:Bu,WebSocket:ju,wsUrl:Fu}=this.serverSettings;let zu=Au.URLExt.join(Fu,Iu,"subscribe");Lu&&Bu!==""&&(zu+=`?token=${encodeURIComponent(Bu)}`);const Uu=this._socket=new ju(zu),Hu=this._stream;Uu.onclose=()=>Du(new Error("EventManager socket closed")),Uu.onmessage=Vu=>Vu.data&&Hu.emit(JSON.parse(Vu.data))})}}return event.EventManager=Pu,event}var kernel$1={},comm={},hasRequiredComm;function requireComm(){if(hasRequiredComm)return comm;hasRequiredComm=1;var Au=comm&&comm.__createBinding||(Object.create?(function(Du,Lu,Bu,ju){ju===void 0&&(ju=Bu);var Fu=Object.getOwnPropertyDescriptor(Lu,Bu);(!Fu||("get"in Fu?!Lu.__esModule:Fu.writable||Fu.configurable))&&(Fu={enumerable:!0,get:function(){return Lu[Bu]}}),Object.defineProperty(Du,ju,Fu)}):(function(Du,Lu,Bu,ju){ju===void 0&&(ju=Bu),Du[ju]=Lu[Bu]})),lo=comm&&comm.__setModuleDefault||(Object.create?(function(Du,Lu){Object.defineProperty(Du,"default",{enumerable:!0,value:Lu})}):function(Du,Lu){Du.default=Lu}),$u=comm&&comm.__importStar||(function(){var Du=function(Lu){return Du=Object.getOwnPropertyNames||function(Bu){var ju=[];for(var Fu in Bu)Object.prototype.hasOwnProperty.call(Bu,Fu)&&(ju[ju.length]=Fu);return ju},Du(Lu)};return function(Lu){if(Lu&&Lu.__esModule)return Lu;var Bu={};if(Lu!=null)for(var ju=Du(Lu),Fu=0;Fu<ju.length;Fu++)ju[Fu]!=="default"&&Au(Bu,Lu,ju[Fu]);return lo(Bu,Lu),Bu}})();Object.defineProperty(comm,"__esModule",{value:!0}),comm.CommHandler=comm.CommsOverSubshells=void 0;const Ru=requireDist(),Iu=require$$1$2,Pu=$u(requireMessages());var Ou;(function(Du){Du.Disabled="disabled",Du.PerComm="perComm",Du.PerCommTarget="perCommTarget"})(Ou||(comm.CommsOverSubshells=Ou={}));class Mu extends Iu.DisposableDelegate{constructor(Lu,Bu,ju,Fu,zu){super(Fu),this._subshellStarted=new Ru.PromiseDelegate,this._subshellId=null,this._target="",this._id="",this._id=Bu,this._target=Lu,this._kernel=ju,this._kernel.statusChanged.connect(()=>{this._kernel.status==="restarting"&&this._cleanSubshells()}),this.commsOverSubshells=zu??Ou.PerCommTarget}get commId(){return this._id}get targetName(){return this._target}get subshellId(){return this._subshellId}get subshellStarted(){return this._subshellStarted.promise}get commsOverSubshells(){return this._commsOverSubshells}set commsOverSubshells(Lu){if(Lu===this._commsOverSubshells)return;const Bu=this._maybeCloseSubshell(this._commsOverSubshells);this._commsOverSubshells=Lu,Bu.then(()=>{this._commsOverSubshells!==Ou.Disabled&&this._maybeStartSubshell()}).catch(console.warn)}get onClose(){return this._onClose}set onClose(Lu){this._onClose=Lu}get onMsg(){return this._onMsg}set onMsg(Lu){this._onMsg=Lu}open(Lu,Bu,ju=[]){if(this.isDisposed||this._kernel.isDisposed)throw new Error("Cannot open");const Fu=Pu.createMessage({msgType:"comm_open",channel:"shell",username:this._kernel.username,session:this._kernel.clientId,subshellId:this._subshellId||this._kernel.subshellId,content:{comm_id:this._id,target_name:this._target,data:Lu??{}},metadata:Bu,buffers:ju});return this._kernel.sendShellMessage(Fu,!1,!0)}send(Lu,Bu,ju=[],Fu=!0){if(this.isDisposed||this._kernel.isDisposed)throw new Error("Cannot send");const zu=Pu.createMessage({msgType:"comm_msg",channel:"shell",username:this._kernel.username,session:this._kernel.clientId,subshellId:this._subshellId||this._kernel.subshellId,content:{comm_id:this._id,data:Lu},metadata:Bu,buffers:ju});return this._kernel.sendShellMessage(zu,!1,Fu)}close(Lu,Bu,ju=[]){if(this.isDisposed||this._kernel.isDisposed)throw new Error("Cannot close");const Fu=Pu.createMessage({msgType:"comm_close",channel:"shell",username:this._kernel.username,session:this._kernel.clientId,subshellId:this._subshellId||this._kernel.subshellId,content:{comm_id:this._id,data:Lu??{}},metadata:Bu,buffers:ju}),zu=this._kernel.sendShellMessage(Fu,!1,!0),Uu=this._onClose;if(Uu){const Hu=Pu.createMessage({msgType:"comm_close",channel:"iopub",username:this._kernel.username,session:this._kernel.clientId,subshellId:this._subshellId||this._kernel.subshellId,content:{comm_id:this._id,data:Lu??{}},metadata:Bu,buffers:ju});Uu(Hu)}return this.dispose(),zu}dispose(){this._maybeCloseSubshell(this._commsOverSubshells),super.dispose()}_cleanSubshells(){const Lu=this._kernel.id;Mu._commTargetSubShellsId.hasOwnProperty(Lu)&&delete Mu._commTargetSubShellsId[Lu]}async _maybeStartSubshell(){if(await this._kernel.info,!this._kernel.supportsSubshells)return;if(this._commsOverSubshells===Ou.PerComm){const Uu=await this._kernel.requestCreateSubshell({}).done;this._subshellId=Uu.content.subshell_id,this._subshellStarted.resolve();return}const Lu=this._subshellStarted,Bu=this._kernel.id;Mu._commTargetSubShellsId.hasOwnProperty(Bu)||(Mu._commTargetSubShellsId[Bu]={});const ju=Mu._commTargetSubShellsId[Bu],Fu=ju[this._target];if(Fu){Fu.referenceCount+=1;try{this._subshellId=await Fu.subshellId,Lu.resolve()}catch(Uu){await this._closePerCommTargetSubshell(!1),Lu.reject(`Per comm-target subshell creation failed: ${Uu}`)}return}const zu={subshellId:this._kernel.requestCreateSubshell({}).done.then(Uu=>Uu.content.subshell_id),referenceCount:1};ju[this._target]=zu;try{this._subshellId=await zu.subshellId,Lu.resolve()}catch(Uu){await this._closePerCommTargetSubshell(!1),Lu.reject(`Per comm-target subshell creation failed: ${Uu}`)}}async _closePerCommTargetSubshell(Lu=!0){const Bu=this._kernel.id,ju=this._target;if(Mu._commTargetSubShellsId.hasOwnProperty(Bu)){const Fu=Mu._commTargetSubShellsId[Bu],zu=Fu[ju];if(zu&&(zu.referenceCount-=1,zu.referenceCount<=0)){if(Lu){let Uu=null;try{Uu=await zu.subshellId}catch(Hu){console.warn(`Subshell identifier not available in the closeout sequence, will not request deletion: ${Hu}`)}Uu!==null&&this._kernel.requestDeleteSubshell({subshell_id:Uu},!0)}delete Fu[ju]}Object.keys(Fu).length===0&&delete Mu._commTargetSubShellsId[Bu],this._subshellId=null}this._subshellStarted=new Ru.PromiseDelegate}async _maybeCloseSubshell(Lu){if(this._kernel.status!=="dead")switch(Lu){case Ou.PerComm:{this._subshellId&&(this._kernel.requestDeleteSubshell({subshell_id:this._subshellId},!0),this._subshellId=null),this._subshellStarted=new Ru.PromiseDelegate;break}case Ou.PerCommTarget:{await this._closePerCommTargetSubshell();break}case Ou.Disabled:break}}}return comm.CommHandler=Mu,Mu._commTargetSubShellsId={},comm}var kernel={},hasRequiredKernel$1;function requireKernel$1(){return hasRequiredKernel$1||(hasRequiredKernel$1=1,Object.defineProperty(kernel,"__esModule",{value:!0})),kernel}var restapi$4={},validate$5={},hasRequiredValidate$3;function requireValidate$3(){if(hasRequiredValidate$3)return validate$5;hasRequiredValidate$3=1,Object.defineProperty(validate$5,"__esModule",{value:!0}),validate$5.validateMessage=Iu,validate$5.validateModel=Ou,validate$5.validateModels=Mu;const Au=requireValidate$5(),lo=["username","version","session","msg_id","msg_type"],$u={stream:{name:"string",text:"string"},display_data:{data:"object",metadata:"object"},execute_input:{code:"string",execution_count:"number"},execute_result:{execution_count:"number",data:"object",metadata:"object"},error:{ename:"string",evalue:"string",traceback:"object"},status:{execution_state:["string",["starting","idle","busy","restarting","dead"]]},clear_output:{wait:"boolean"},comm_open:{comm_id:"string",target_name:"string",data:"object"},comm_msg:{comm_id:"string",data:"object"},comm_close:{comm_id:"string"},shutdown_reply:{restart:"boolean"}};function Ru(Du){for(let Lu=0;Lu<lo.length;Lu++)(0,Au.validateProperty)(Du,lo[Lu],"string")}function Iu(Du){(0,Au.validateProperty)(Du,"metadata","object"),(0,Au.validateProperty)(Du,"content","object"),(0,Au.validateProperty)(Du,"channel","string"),Ru(Du.header),Du.channel==="iopub"&&Pu(Du)}function Pu(Du){if(Du.channel==="iopub"){const Lu=$u[Du.header.msg_type];if(Lu===void 0)return;const Bu=Object.keys(Lu),ju=Du.content;for(let Fu=0;Fu<Bu.length;Fu++){let zu=Lu[Bu[Fu]];Array.isArray(zu)||(zu=[zu]),(0,Au.validateProperty)(ju,Bu[Fu],...zu)}}}function Ou(Du){(0,Au.validateProperty)(Du,"name","string"),(0,Au.validateProperty)(Du,"id","string")}function Mu(Du){if(!Array.isArray(Du))throw new Error("Invalid kernel list");Du.forEach(Lu=>Ou(Lu))}return validate$5}var hasRequiredRestapi$4;function requireRestapi$4(){return hasRequiredRestapi$4||(hasRequiredRestapi$4=1,(function(Au){Object.defineProperty(Au,"__esModule",{value:!0}),Au.KernelAPIClient=Au.KERNEL_SERVICE_URL=void 0,Au.listRunning=Iu,Au.startNew=Pu,Au.restartKernel=Ou,Au.interruptKernel=Mu,Au.shutdownKernel=Du,Au.getKernelModel=Lu;const lo=requireServerconnection(),$u=requireLib$b(),Ru=requireValidate$3();Au.KERNEL_SERVICE_URL="api/kernels";async function Iu(ju=lo.ServerConnection.makeSettings()){const Fu=$u.URLExt.join(ju.baseUrl,Au.KERNEL_SERVICE_URL),zu=await lo.ServerConnection.makeRequest(Fu,{},ju);if(zu.status!==200)throw await lo.ServerConnection.ResponseError.create(zu);const Uu=await zu.json();return(0,Ru.validateModels)(Uu),Uu}async function Pu(ju={},Fu=lo.ServerConnection.makeSettings()){const zu=$u.URLExt.join(Fu.baseUrl,Au.KERNEL_SERVICE_URL),Uu={method:"POST",body:JSON.stringify(ju)},Hu=await lo.ServerConnection.makeRequest(zu,Uu,Fu);if(Hu.status!==201)throw await lo.ServerConnection.ResponseError.create(Hu);const Vu=await Hu.json();return(0,Ru.validateModel)(Vu),Vu}async function Ou(ju,Fu=lo.ServerConnection.makeSettings()){const zu=$u.URLExt.join(Fu.baseUrl,Au.KERNEL_SERVICE_URL,encodeURIComponent(ju),"restart"),Uu={method:"POST"},Hu=await lo.ServerConnection.makeRequest(zu,Uu,Fu);if(Hu.status!==200)throw await lo.ServerConnection.ResponseError.create(Hu);const Vu=await Hu.json();(0,Ru.validateModel)(Vu)}async function Mu(ju,Fu=lo.ServerConnection.makeSettings()){const zu=$u.URLExt.join(Fu.baseUrl,Au.KERNEL_SERVICE_URL,encodeURIComponent(ju),"interrupt"),Uu={method:"POST"},Hu=await lo.ServerConnection.makeRequest(zu,Uu,Fu);if(Hu.status!==204)throw await lo.ServerConnection.ResponseError.create(Hu)}async function Du(ju,Fu=lo.ServerConnection.makeSettings()){const zu=$u.URLExt.join(Fu.baseUrl,Au.KERNEL_SERVICE_URL,encodeURIComponent(ju)),Uu={method:"DELETE"},Hu=await lo.ServerConnection.makeRequest(zu,Uu,Fu);if(Hu.status===404){const Vu=`The kernel "${ju}" does not exist on the server`;console.warn(Vu)}else if(Hu.status!==204)throw await lo.ServerConnection.ResponseError.create(Hu)}async function Lu(ju,Fu=lo.ServerConnection.makeSettings()){const zu=$u.URLExt.join(Fu.baseUrl,Au.KERNEL_SERVICE_URL,encodeURIComponent(ju)),Uu=await lo.ServerConnection.makeRequest(zu,{},Fu);if(Uu.status===404)return;if(Uu.status!==200)throw await lo.ServerConnection.ResponseError.create(Uu);const Hu=await Uu.json();return(0,Ru.validateModel)(Hu),Hu}class Bu{constructor(Fu={}){var zu;this.serverSettings=(zu=Fu.serverSettings)!==null&&zu!==void 0?zu:lo.ServerConnection.makeSettings()}async listRunning(){return Iu(this.serverSettings)}async getModel(Fu){return Lu(Fu,this.serverSettings)}async startNew(Fu={}){return Pu(Fu,this.serverSettings)}async restart(Fu){return Ou(Fu,this.serverSettings)}async interrupt(Fu){return Mu(Fu,this.serverSettings)}async shutdown(Fu){return Du(Fu,this.serverSettings)}}Au.KernelAPIClient=Bu})(restapi$4)),restapi$4}var _default$3={},future={},hasRequiredFuture;function requireFuture(){if(hasRequiredFuture)return future;hasRequiredFuture=1;var Au=future&&future.__createBinding||(Object.create?(function(Bu,ju,Fu,zu){zu===void 0&&(zu=Fu);var Uu=Object.getOwnPropertyDescriptor(ju,Fu);(!Uu||("get"in Uu?!ju.__esModule:Uu.writable||Uu.configurable))&&(Uu={enumerable:!0,get:function(){return ju[Fu]}}),Object.defineProperty(Bu,zu,Uu)}):(function(Bu,ju,Fu,zu){zu===void 0&&(zu=Fu),Bu[zu]=ju[Fu]})),lo=future&&future.__setModuleDefault||(Object.create?(function(Bu,ju){Object.defineProperty(Bu,"default",{enumerable:!0,value:ju})}):function(Bu,ju){Bu.default=ju}),$u=future&&future.__importStar||(function(){var Bu=function(ju){return Bu=Object.getOwnPropertyNames||function(Fu){var zu=[];for(var Uu in Fu)Object.prototype.hasOwnProperty.call(Fu,Uu)&&(zu[zu.length]=Uu);return zu},Bu(ju)};return function(ju){if(ju&&ju.__esModule)return ju;var Fu={};if(ju!=null)for(var zu=Bu(ju),Uu=0;Uu<zu.length;Uu++)zu[Uu]!=="default"&&Au(Fu,ju,zu[Uu]);return lo(Fu,ju),Fu}})();Object.defineProperty(future,"__esModule",{value:!0}),future.KernelShellFutureHandler=future.KernelControlFutureHandler=future.KernelFutureHandler=void 0;const Ru=requireDist(),Iu=require$$1$2,Pu=$u(requireMessages());class Ou extends Iu.DisposableDelegate{constructor(ju,Fu,zu,Uu,Hu){super(ju),this._status=0,this._stdin=Lu.noOp,this._iopub=Lu.noOp,this._reply=Lu.noOp,this._done=new Ru.PromiseDelegate,this._hooks=new Lu.HookList,this._disposeOnDone=!0,this._msg=Fu,zu||this._setFlag(Lu.KernelFutureFlag.GotReply),this._disposeOnDone=Uu,this._kernel=Hu}get msg(){return this._msg}get done(){return this._done.promise}get onReply(){return this._reply}set onReply(ju){this._reply=ju}get onIOPub(){return this._iopub}set onIOPub(ju){this._iopub=ju}get onStdin(){return this._stdin}set onStdin(ju){this._stdin=ju}registerMessageHook(ju){if(this.isDisposed)throw new Error("Kernel future is disposed");this._hooks.add(ju)}removeMessageHook(ju){this.isDisposed||this._hooks.remove(ju)}sendInputReply(ju,Fu){this._kernel.sendInputReply(ju,Fu)}dispose(){this._stdin=Lu.noOp,this._iopub=Lu.noOp,this._reply=Lu.noOp,this._hooks=null,this._testFlag(Lu.KernelFutureFlag.IsDone)||(this._done.promise.catch(()=>{}),this._done.reject(new Error(`Canceled future for ${this.msg.header.msg_type} message before replies were done`))),super.dispose()}async handleMsg(ju){switch(ju.channel){case"control":case"shell":ju.channel===this.msg.channel&&ju.parent_header.msg_id===this.msg.header.msg_id&&await this._handleReply(ju);break;case"stdin":await this._handleStdin(ju);break;case"iopub":await this._handleIOPub(ju);break}}async _handleReply(ju){const Fu=this._reply;Fu&&await Fu(ju),this._replyMsg=ju,this._setFlag(Lu.KernelFutureFlag.GotReply),this._testFlag(Lu.KernelFutureFlag.GotIdle)&&this._handleDone()}async _handleStdin(ju){this._kernel.hasPendingInput=!0;const Fu=this._stdin;Fu&&await Fu(ju)}async _handleIOPub(ju){const Fu=await this._hooks.process(ju),zu=this._iopub;Fu&&zu&&await zu(ju),Pu.isStatusMsg(ju)&&ju.content.execution_state==="idle"&&(this._setFlag(Lu.KernelFutureFlag.GotIdle),this._testFlag(Lu.KernelFutureFlag.GotReply)&&this._handleDone())}_handleDone(){this._testFlag(Lu.KernelFutureFlag.IsDone)||(this._setFlag(Lu.KernelFutureFlag.IsDone),this._done.resolve(this._replyMsg),this._disposeOnDone&&this.dispose())}_testFlag(ju){return(this._status&ju)!==0}_setFlag(ju){this._status|=ju}}future.KernelFutureHandler=Ou;class Mu extends Ou{}future.KernelControlFutureHandler=Mu;class Du extends Ou{}future.KernelShellFutureHandler=Du;var Lu;return(function(Bu){Bu.noOp=()=>{};const ju=typeof requestAnimationFrame=="function"?requestAnimationFrame:setImmediate;class Fu{constructor(){this._hooks=[]}add(Uu){this.remove(Uu),this._hooks.push(Uu)}remove(Uu){const Hu=this._hooks.indexOf(Uu);Hu>=0&&(this._hooks[Hu]=null,this._scheduleCompact())}async process(Uu){await this._processing;const Hu=new Ru.PromiseDelegate;this._processing=Hu.promise;let Vu;for(let Gu=this._hooks.length-1;Gu>=0;Gu--){const Wu=this._hooks[Gu];if(Wu!==null){try{Vu=await Wu(Uu)}catch(Ku){Vu=!0,console.error(Ku)}if(Vu===!1)return Hu.resolve(void 0),!1}}return Hu.resolve(void 0),!0}_scheduleCompact(){this._compactScheduled||(this._compactScheduled=!0,ju(()=>{this._processing=this._processing.then(()=>{this._compactScheduled=!1,this._compact()})}))}_compact(){let Uu=0;for(let Hu=0,Vu=this._hooks.length;Hu<Vu;Hu++){const Gu=this._hooks[Hu];this._hooks[Hu]===null?Uu++:this._hooks[Hu-Uu]=Gu}this._hooks.length-=Uu}}Bu.HookList=Fu,(function(zu){zu[zu.GotReply=1]="GotReply",zu[zu.GotIdle=2]="GotIdle",zu[zu.IsDone=4]="IsDone",zu[zu.DisposeOnDone=8]="DisposeOnDone"})(Bu.KernelFutureFlag||(Bu.KernelFutureFlag={}))})(Lu||(Lu={})),future}var restapi$3={},validate$4={},hasRequiredValidate$2;function requireValidate$2(){if(hasRequiredValidate$2)return validate$4;hasRequiredValidate$2=1,Object.defineProperty(validate$4,"__esModule",{value:!0}),validate$4.validateSpecModel=lo,validate$4.validateSpecModels=$u;const Au=requireValidate$5();function lo(Ru){const Iu=Ru.spec;if(!Iu)throw new Error("Invalid kernel spec");(0,Au.validateProperty)(Ru,"name","string"),(0,Au.validateProperty)(Ru,"resources","object"),(0,Au.validateProperty)(Iu,"language","string"),(0,Au.validateProperty)(Iu,"display_name","string"),(0,Au.validateProperty)(Iu,"argv","array");let Pu=null;Iu.hasOwnProperty("metadata")&&((0,Au.validateProperty)(Iu,"metadata","object"),Pu=Iu.metadata);let Ou=null;return Iu.hasOwnProperty("env")&&((0,Au.validateProperty)(Iu,"env","object"),Ou=Iu.env),Iu.hasOwnProperty("interrupt_mode")&&((0,Au.validateProperty)(Iu,"interrupt_mode","string"),Ou=Iu.env),{name:Ru.name,resources:Ru.resources,language:Iu.language,display_name:Iu.display_name,argv:Iu.argv,metadata:Pu,env:Ou}}function $u(Ru){if(!Ru.hasOwnProperty("kernelspecs"))throw new Error("No kernelspecs found");let Iu=Object.keys(Ru.kernelspecs);const Pu=Object.create(null);let Ou=Ru.default;for(let Mu=0;Mu<Iu.length;Mu++){const Du=Ru.kernelspecs[Iu[Mu]];try{Pu[Iu[Mu]]=lo(Du)}catch{console.warn(`Removing errant kernel spec: ${Iu[Mu]}`)}}if(Iu=Object.keys(Pu),!Iu.length)throw new Error("No valid kernelspecs found");return(!Ou||typeof Ou!="string"||!(Ou in Pu))&&(Ou=Iu[0],console.warn(`Default kernel not found, using '${Iu[0]}'`)),{default:Ou,kernelspecs:Pu}}return validate$4}var hasRequiredRestapi$3;function requireRestapi$3(){if(hasRequiredRestapi$3)return restapi$3;hasRequiredRestapi$3=1,Object.defineProperty(restapi$3,"__esModule",{value:!0}),restapi$3.KernelSpecAPIClient=void 0,restapi$3.getSpecs=Iu;const Au=requireServerconnection(),lo=requireValidate$2(),$u=requireLib$b(),Ru="api/kernelspecs";async function Iu(Ou=Au.ServerConnection.makeSettings()){const Mu=$u.URLExt.join(Ou.baseUrl,Ru),Du=await Au.ServerConnection.makeRequest(Mu,{},Ou);if(Du.status!==200)throw await Au.ServerConnection.ResponseError.create(Du);const Lu=await Du.json();return(0,lo.validateSpecModels)(Lu)}class Pu{constructor(Mu={}){var Du;this.serverSettings=(Du=Mu.serverSettings)!==null&&Du!==void 0?Du:Au.ServerConnection.makeSettings()}async get(){return Iu(this.serverSettings)}}return restapi$3.KernelSpecAPIClient=Pu,restapi$3}var hasRequired_default$2;function require_default$2(){return hasRequired_default$2||(hasRequired_default$2=1,(function(Au){var lo=_default$3&&_default$3.__createBinding||(Object.create?(function(Wu,Ku,Ju,Yu){Yu===void 0&&(Yu=Ju);var Xu=Object.getOwnPropertyDescriptor(Ku,Ju);(!Xu||("get"in Xu?!Ku.__esModule:Xu.writable||Xu.configurable))&&(Xu={enumerable:!0,get:function(){return Ku[Ju]}}),Object.defineProperty(Wu,Yu,Xu)}):(function(Wu,Ku,Ju,Yu){Yu===void 0&&(Yu=Ju),Wu[Yu]=Ku[Ju]})),$u=_default$3&&_default$3.__setModuleDefault||(Object.create?(function(Wu,Ku){Object.defineProperty(Wu,"default",{enumerable:!0,value:Ku})}):function(Wu,Ku){Wu.default=Ku}),Ru=_default$3&&_default$3.__importStar||(function(){var Wu=function(Ku){return Wu=Object.getOwnPropertyNames||function(Ju){var Yu=[];for(var Xu in Ju)Object.prototype.hasOwnProperty.call(Ju,Xu)&&(Yu[Yu.length]=Xu);return Yu},Wu(Ku)};return function(Ku){if(Ku&&Ku.__esModule)return Ku;var Ju={};if(Ku!=null)for(var Yu=Wu(Ku),Xu=0;Xu<Yu.length;Xu++)Yu[Xu]!=="default"&&lo(Ju,Ku,Yu[Xu]);return $u(Ju,Ku),Ju}})();Object.defineProperty(Au,"__esModule",{value:!0}),Au.KernelConnection=Au.DEFAULT_KERNEL_INFO_TIMEOUT=void 0;const Iu=requireLib$b(),Pu=requireDist(),Ou=require$$0$3,Mu=requireLib$8(),Du=requireComm(),Lu=Ru(requireMessages()),Bu=requireFuture(),ju=Ru(requireValidate$3()),Fu=requireRestapi$4(),zu=requireRestapi$3(),Uu=requireLib$b();Au.DEFAULT_KERNEL_INFO_TIMEOUT=3e3;const Hu="";class Vu{constructor(Ku){var Ju,Yu,Xu,ed,td,nd,od,sd,ad;this._createSocket=(pd=!0)=>{this._errorIfDisposed(),this._clearSocket(),this._updateConnectionStatus("connecting");const gd=this.serverSettings,Sd=Iu.URLExt.join(gd.wsUrl,Fu.KERNEL_SERVICE_URL,encodeURIComponent(this._id)),_d=Sd.replace(/^((?:\w+:)?\/\/)[^@/]+@/,"$1");console.debug(`Starting WebSocket: ${_d}`);let yd=Iu.URLExt.join(Sd,"channels?session_id="+encodeURIComponent(this._clientId));const wd=gd.token;gd.appendToken&&wd!==""&&(yd=yd+`&token=${encodeURIComponent(wd)}`);const Ad=pd?this._supportedProtocols:[];this._ws=new gd.WebSocket(yd,Ad),this._ws.binaryType="arraybuffer";let md=!1;const dd=async ld=>{var ud,hd;if(!this._isDisposed){this._reason="",this._model=void 0;try{const vd=await this._kernelAPIClient.getModel(this._id);this._model=vd,vd?.execution_state==="dead"?this._updateStatus("dead"):this._onWSClose(ld)}catch(vd){if(vd instanceof Mu.ServerConnection.NetworkError||((ud=vd.response)===null||ud===void 0?void 0:ud.status)===503||((hd=vd.response)===null||hd===void 0?void 0:hd.status)===424){const Ed=Gu.getRandomIntInclusive(10,30)*1e3;setTimeout(dd,Ed,ld)}else this._reason="Kernel died unexpectedly",this._updateStatus("dead")}}},bd=async ld=>{md||(md=!0,await dd(ld))};this._ws.onmessage=this._onWSMessage,this._ws.onopen=this._onWSOpen,this._ws.onclose=bd,this._ws.onerror=bd},this._onWSOpen=pd=>{if(this._ws.protocol!==""&&!this._supportedProtocols.includes(this._ws.protocol))throw console.log("Server selected unknown kernel wire protocol:",this._ws.protocol),this._updateStatus("dead"),new Error(`Unknown kernel wire protocol: ${this._ws.protocol}`);this._selectedProtocol=this._ws.protocol,this._ws.onclose=this._onWSClose,this._ws.onerror=this._onWSClose,this._updateConnectionStatus("connected")},this._onWSMessage=pd=>{let gd;try{gd=this.serverSettings.serializer.deserialize(pd.data,this._ws.protocol),ju.validateMessage(gd)}catch(Sd){throw Sd.message=`Kernel message validation error: ${Sd.message}`,Sd}this._kernelSession=gd.header.session,this._msgChain=this._msgChain.then(()=>this._handleMessage(gd)).catch(Sd=>{Sd.message.startsWith("Canceled future for ")&&console.error(Sd)}),this._anyMessage.emit({msg:gd,direction:"recv"})},this._onWSClose=pd=>{if(!this.isDisposed){if("code"in pd&&(pd.code===1e3||pd.code===1001)){this._updateConnectionStatus("disconnected");return}this._reconnect()}},this._id="",this._name="",this._status="unknown",this._connectionStatus="connecting",this._kernelSession="",this._isRestarting=!1,this._isDisposed=!1,this._ws=null,this._username="",this._reconnectLimit=7,this._reconnectAttempt=0,this._reconnectTimeout=null,this._supportedProtocols=Object.values(Lu.supportedKernelWebSocketProtocols),this._selectedProtocol="",this._commsOverSubshells=Mu.CommsOverSubshells.PerCommTarget,this._futures=new Map,this._comms=new Map,this._targetRegistry=Object.create(null),this._info=new Pu.PromiseDelegate,this._pendingMessages=[],this._statusChanged=new Ou.Signal(this),this._connectionStatusChanged=new Ou.Signal(this),this._disposed=new Ou.Signal(this),this._iopubMessage=new Ou.Signal(this),this._anyMessage=new Ou.Signal(this),this._pendingInput=new Ou.Signal(this),this._unhandledMessage=new Ou.Signal(this),this._displayIdToParentIds=new Map,this._msgIdToDisplayIds=new Map,this._msgChain=Promise.resolve(),this._hasPendingInput=!1,this._reason="",this._noOp=()=>{},this._supportsSubshells=!1,this._kernelInfoTimeout=Au.DEFAULT_KERNEL_INFO_TIMEOUT,this._name=Ku.model.name,this._id=Ku.model.id,this.serverSettings=(Ju=Ku.serverSettings)!==null&&Ju!==void 0?Ju:Mu.ServerConnection.makeSettings(),this._kernelAPIClient=(Yu=Ku.kernelAPIClient)!==null&&Yu!==void 0?Yu:new Fu.KernelAPIClient({serverSettings:this.serverSettings}),this._kernelSpecAPIClient=(Xu=Ku.kernelSpecAPIClient)!==null&&Xu!==void 0?Xu:new zu.KernelSpecAPIClient({serverSettings:this.serverSettings}),this._clientId=(ed=Ku.clientId)!==null&&ed!==void 0?ed:Pu.UUID.uuid4(),this._username=(td=Ku.username)!==null&&td!==void 0?td:"",this.handleComms=(nd=Ku.handleComms)!==null&&nd!==void 0?nd:!0,this._commsOverSubshells=(od=Ku.commsOverSubshells)!==null&&od!==void 0?od:Mu.CommsOverSubshells.PerCommTarget,this._subshellId=(sd=Ku.subshellId)!==null&&sd!==void 0?sd:null,this._createSocket(),this._kernelInfoTimeout=(ad=Ku?.kernelInfoTimeout)!==null&&ad!==void 0?ad:Au.DEFAULT_KERNEL_INFO_TIMEOUT}get disposed(){return this._disposed}get commsOverSubshells(){return this._commsOverSubshells}set commsOverSubshells(Ku){this._commsOverSubshells=Ku;for(const[Ju,Yu]of this._comms)Yu.commsOverSubshells=Ku}get statusChanged(){return this._statusChanged}get connectionStatusChanged(){return this._connectionStatusChanged}get iopubMessage(){return this._iopubMessage}get unhandledMessage(){return this._unhandledMessage}get model(){return this._model||{id:this.id,name:this.name,reason:this._reason}}get anyMessage(){return this._anyMessage}get pendingInput(){return this._pendingInput}get id(){return this._id}get name(){return this._name}get username(){return this._username}get clientId(){return this._clientId}get subshellId(){return this._subshellId}set subshellId(Ku){this._subshellId=Ku}get status(){return this._status}get connectionStatus(){return this._connectionStatus}get isDisposed(){return this._isDisposed}get info(){return this._info.promise}get spec(){return this._specPromise?this._specPromise:(this._specPromise=this._kernelSpecAPIClient.get().then(Ku=>Ku.kernelspecs[this._name]),this._specPromise)}get supportsSubshells(){return this._supportsSubshells}clone(Ku={}){return new Vu({model:this.model,username:this.username,serverSettings:this.serverSettings,handleComms:!1,kernelAPIClient:this._kernelAPIClient,commsOverSubshells:Mu.CommsOverSubshells.Disabled,kernelInfoTimeout:this._kernelInfoTimeout,...Ku})}dispose(){if(this.isDisposed)return;const Ku=()=>{this._isDisposed=!0,this._disposed.emit(),this._updateConnectionStatus("disconnected"),this._clearKernelState(),this._pendingMessages=[],this._clearSocket(),Ou.Signal.clearData(this)};if(this._subshellId!==null){const Ju=this.requestDeleteSubshell({subshell_id:this._subshellId},!0);Ju.onReply=Yu=>{Ku()}}else Ku()}sendShellMessage(Ku,Ju=!1,Yu=!0){return this._sendKernelShellControl(Bu.KernelShellFutureHandler,Ku,Ju,Yu)}sendControlMessage(Ku,Ju=!1,Yu=!0){return this._sendKernelShellControl(Bu.KernelControlFutureHandler,Ku,Ju,Yu)}_sendKernelShellControl(Ku,Ju,Yu=!1,Xu=!0){this._sendMessage(Ju),this._anyMessage.emit({msg:Ju,direction:"send"});const ed=new Ku(()=>{const td=Ju.header.msg_id;this._futures.delete(td);const nd=this._msgIdToDisplayIds.get(td);nd&&(nd.forEach(od=>{const sd=this._displayIdToParentIds.get(od);if(sd){const ad=sd.indexOf(td);if(ad===-1)return;sd.length===1?this._displayIdToParentIds.delete(od):(sd.splice(ad,1),this._displayIdToParentIds.set(od,sd))}}),this._msgIdToDisplayIds.delete(td))},Ju,Yu,Xu,this);return this._futures.set(Ju.header.msg_id,ed),ed}_sendMessage(Ku,Ju=!0){if(this.status==="dead")throw new Error("Kernel is dead");if((this._kernelSession===Hu||this._isRestarting)&&Lu.isInfoRequestMsg(Ku))if(this.connectionStatus==="connected"){this._ws.send(this.serverSettings.serializer.serialize(Ku,this._ws.protocol));return}else throw new Error("Could not send message: status is not connected");if(Ju&&this._pendingMessages.length>0){this._pendingMessages.push(Ku);return}if(this.connectionStatus==="connected"&&!this._isRestarting)this._ws.send(this.serverSettings.serializer.serialize(Ku,this._ws.protocol));else if(Ju)this._pendingMessages.push(Ku);else throw new Error("Could not send message")}async interrupt(){if(this.hasPendingInput=!1,this.status==="dead")throw new Error("Kernel is dead");return this._kernelAPIClient.interrupt(this.id)}async restart(){if(this.status==="dead")throw new Error("Kernel is dead");this._updateStatus("restarting"),this._clearKernelState(),this._isRestarting=!0;try{await this._kernelAPIClient.restart(this.id),await this.reconnect()}catch(Ku){throw this._isRestarting=!1,Ku}this.hasPendingInput=!1}reconnect(){this._errorIfDisposed();const Ku=new Pu.PromiseDelegate,Ju=(Yu,Xu)=>{Xu==="connected"?(Ku.resolve(),this.connectionStatusChanged.disconnect(Ju,this)):Xu==="disconnected"&&(Ku.reject(new Error("Kernel connection disconnected")),this.connectionStatusChanged.disconnect(Ju,this))};return this.connectionStatusChanged.connect(Ju,this),this._reconnectAttempt=0,this._reconnect(),Ku.promise}async shutdown(){this.status!=="dead"&&await this._kernelAPIClient.shutdown(this.id),this.handleShutdown()}handleShutdown(){this._updateStatus("dead"),this.dispose()}async requestKernelInfo(){const Ku=Lu.createMessage({msgType:"kernel_info_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:{}});let Ju;try{Ju=await Gu.handleShellMessage(this,Ku)}catch(Xu){if(this.isDisposed)return;throw Xu}if(this._errorIfDisposed(),!Ju)return;if(Ju.content.status===void 0&&(Ju.content.status="ok"),Ju.content.status!=="ok")return this._info.reject("Kernel info reply errored"),Ju;this._info.resolve(Ju.content),this._kernelSession=Ju.header.session;const Yu=Ju.content.supported_features;return this._supportsSubshells=Yu!==void 0&&Yu.includes("kernel subshells"),Ju}requestComplete(Ku){const Ju=Lu.createMessage({msgType:"complete_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:Ku});return Gu.handleShellMessage(this,Ju)}requestInspect(Ku){const Ju=Lu.createMessage({msgType:"inspect_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:Ku});return Gu.handleShellMessage(this,Ju)}requestHistory(Ku){const Ju=Lu.createMessage({msgType:"history_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:Ku});return Gu.handleShellMessage(this,Ju)}requestExecute(Ku,Ju=!0,Yu){const Xu={silent:!1,store_history:!0,user_expressions:{},allow_stdin:!0,stop_on_error:!1},ed=Lu.createMessage({msgType:"execute_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:{...Xu,...Ku},metadata:Yu});return this.sendShellMessage(ed,!0,Ju)}requestDebug(Ku,Ju=!0){const Yu=Lu.createMessage({msgType:"debug_request",channel:"control",username:this._username,session:this._clientId,content:Ku});return this.sendControlMessage(Yu,!0,Ju)}requestCreateSubshell(Ku,Ju=!0){if(!this.supportsSubshells)throw new Error("Kernel subshells are not supported");const Yu=Lu.createMessage({msgType:"create_subshell_request",channel:"control",username:this._username,session:this._clientId,content:Ku});return this.sendControlMessage(Yu,!0,Ju)}requestDeleteSubshell(Ku,Ju=!0){if(!this.supportsSubshells)throw new Error("Kernel subshells are not supported");const Yu=Lu.createMessage({msgType:"delete_subshell_request",channel:"control",username:this._username,session:this._clientId,content:Ku});return this.sendControlMessage(Yu,!0,Ju)}requestListSubshell(Ku,Ju=!0){if(!this.supportsSubshells)throw new Error("Kernel subshells are not supported");const Yu=Lu.createMessage({msgType:"list_subshell_request",channel:"control",username:this._username,session:this._clientId,content:Ku});return this.sendControlMessage(Yu,!0,Ju)}requestIsComplete(Ku){const Ju=Lu.createMessage({msgType:"is_complete_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:Ku});return Gu.handleShellMessage(this,Ju)}requestCommInfo(Ku){const Ju=Lu.createMessage({msgType:"comm_info_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:Ku});return Gu.handleShellMessage(this,Ju)}sendInputReply(Ku,Ju){const Yu=Lu.createMessage({msgType:"input_reply",channel:"stdin",username:this._username,session:this._clientId,content:Ku});Yu.parent_header=Ju,this._sendMessage(Yu),this._anyMessage.emit({msg:Yu,direction:"send"}),this.hasPendingInput=!1}createComm(Ku,Ju=Pu.UUID.uuid4()){if(!this.handleComms)throw new Error("Comms are disabled on this kernel connection");if(this._comms.has(Ju))throw new Error("Comm is already created");const Yu=new Du.CommHandler(Ku,Ju,this,()=>{this._unregisterComm(Ju)},this._commsOverSubshells);return this._comms.set(Ju,Yu),Yu}hasComm(Ku){return this._comms.has(Ku)}registerCommTarget(Ku,Ju){this.handleComms&&(this._targetRegistry[Ku]=Ju)}removeCommTarget(Ku,Ju){this.handleComms&&!this.isDisposed&&this._targetRegistry[Ku]===Ju&&delete this._targetRegistry[Ku]}registerMessageHook(Ku,Ju){var Yu;const Xu=(Yu=this._futures)===null||Yu===void 0?void 0:Yu.get(Ku);Xu&&Xu.registerMessageHook(Ju)}removeMessageHook(Ku,Ju){var Yu;const Xu=(Yu=this._futures)===null||Yu===void 0?void 0:Yu.get(Ku);Xu&&Xu.removeMessageHook(Ju)}removeInputGuard(){this.hasPendingInput=!1}async _handleDisplayId(Ku,Ju){var Yu,Xu;const ed=Ju.parent_header.msg_id;let td=this._displayIdToParentIds.get(Ku);if(td){const od={header:Pu.JSONExt.deepCopy(Ju.header),parent_header:Pu.JSONExt.deepCopy(Ju.parent_header),metadata:Pu.JSONExt.deepCopy(Ju.metadata),content:Pu.JSONExt.deepCopy(Ju.content),channel:Ju.channel,buffers:Ju.buffers?Ju.buffers.slice():[]};od.header.msg_type="update_display_data",await Promise.all(td.map(async sd=>{const ad=this._futures&&this._futures.get(sd);ad&&await ad.handleMsg(od)}))}if(Ju.header.msg_type==="update_display_data")return!0;td=(Yu=this._displayIdToParentIds.get(Ku))!==null&&Yu!==void 0?Yu:[],td.indexOf(ed)===-1&&td.push(ed),this._displayIdToParentIds.set(Ku,td);const nd=(Xu=this._msgIdToDisplayIds.get(ed))!==null&&Xu!==void 0?Xu:[];return nd.indexOf(ed)===-1&&nd.push(ed),this._msgIdToDisplayIds.set(ed,nd),!1}_clearSocket(){this._ws!==null&&(this._ws.onopen=this._noOp,this._ws.onclose=this._noOp,this._ws.onerror=this._noOp,this._ws.onmessage=this._noOp,this._ws.close(),this._ws=null)}_updateStatus(Ku){this._status===Ku||this._status==="dead"||(this._status=Ku,Gu.logKernelStatus(this),this._statusChanged.emit(Ku),Ku==="dead"&&this.dispose())}_sendPending(){for(;this.connectionStatus==="connected"&&!this._isRestarting&&this._pendingMessages.length>0;)this._sendMessage(this._pendingMessages[0],!1),this._pendingMessages.shift()}_clearKernelState(){this._kernelSession="",this._pendingMessages=[],this._futures.forEach(Ku=>{Ku.dispose()}),this._comms.forEach(Ku=>{Ku.dispose()}),this._msgChain=Promise.resolve(),this._futures=new Map,this._comms=new Map,this._displayIdToParentIds.clear(),this._msgIdToDisplayIds.clear()}_assertCurrentMessage(Ku){if(this._errorIfDisposed(),Ku.header.session!==this._kernelSession)throw new Error(`Canceling handling of old message: ${Ku.header.msg_type}`)}async _handleCommOpen(Ku){this._assertCurrentMessage(Ku);const Ju=Ku.content,Yu=new Du.CommHandler(Ju.target_name,Ju.comm_id,this,()=>{this._unregisterComm(Ju.comm_id)},this.commsOverSubshells);this._comms.set(Ju.comm_id,Yu);try{await(await Gu.loadObject(Ju.target_name,Ju.target_module,this._targetRegistry))(Yu,Ku)}catch(Xu){throw Yu.close(),console.error("Exception opening new comm"),Xu}}async _handleCommClose(Ku){this._assertCurrentMessage(Ku);const Ju=Ku.content,Yu=this._comms.get(Ju.comm_id);if(!Yu){console.error("Comm not found for comm id "+Ju.comm_id);return}this._unregisterComm(Yu.commId);const Xu=Yu.onClose;Xu&&await Xu(Ku),Yu.dispose()}async _handleCommMsg(Ku){this._assertCurrentMessage(Ku);const Ju=Ku.content,Yu=this._comms.get(Ju.comm_id);if(!Yu)return;const Xu=Yu.onMsg;Xu&&await Xu(Ku)}_unregisterComm(Ku){this._comms.delete(Ku)}_updateConnectionStatus(Ku){if(this._connectionStatus!==Ku){if(this._connectionStatus=Ku,Ku!=="connecting"&&(this._reconnectAttempt=0,clearTimeout(this._reconnectTimeout)),this.status!=="dead")if(Ku==="connected"){let Ju=this._isRestarting,Yu=this.requestKernelInfo(),Xu=!1,ed=()=>{Xu||(Xu=!0,Ju&&this._isRestarting&&(this._isRestarting=!1,this._kernelSession=""),clearTimeout(td),this._pendingMessages.length>0&&this._sendPending())};Yu.then(()=>{Ju&&(this._isRestarting=!1),ed()});let td=setTimeout(ed,this._kernelInfoTimeout)}else this._updateStatus("unknown");this._connectionStatusChanged.emit(Ku)}}async _handleMessage(Ku){var Ju,Yu;let Xu=!1;if(Ku.parent_header&&Ku.channel==="iopub"&&(Lu.isDisplayDataMsg(Ku)||Lu.isUpdateDisplayDataMsg(Ku)||Lu.isExecuteResultMsg(Ku))){const td=((Ju=Ku.content.transient)!==null&&Ju!==void 0?Ju:{}).display_id;td&&(Xu=await this._handleDisplayId(td,Ku),this._assertCurrentMessage(Ku))}if(!Xu&&Ku.parent_header){const ed=Ku.parent_header,td=(Yu=this._futures)===null||Yu===void 0?void 0:Yu.get(ed.msg_id);if(td)await td.handleMsg(Ku),this._assertCurrentMessage(Ku);else{const nd=ed.session===this.clientId;Ku.channel!=="iopub"&&nd&&this._unhandledMessage.emit(Ku)}}if(Ku.channel==="iopub"){switch(Ku.header.msg_type){case"status":{const ed=Uu.PageConfig.getOption("untracked_message_types");if(JSON.parse(ed||"[]").includes(Ku.parent_header.msg_type))break;const nd=Ku.content.execution_state;nd==="restarting"&&Promise.resolve().then(async()=>{this._updateStatus("autorestarting"),this._clearKernelState(),await this.reconnect()}),this._updateStatus(nd);break}case"comm_open":this.handleComms&&await this._handleCommOpen(Ku);break;case"comm_msg":this.handleComms&&await this._handleCommMsg(Ku);break;case"comm_close":this.handleComms&&await this._handleCommClose(Ku);break}this.isDisposed||(this._assertCurrentMessage(Ku),this._iopubMessage.emit(Ku))}}_reconnect(){if(this._errorIfDisposed(),clearTimeout(this._reconnectTimeout),this._reconnectAttempt<this._reconnectLimit){this._updateConnectionStatus("connecting");const Ku=Gu.getRandomIntInclusive(0,1e3*(Math.pow(2,this._reconnectAttempt)-1));console.warn(`Connection lost, reconnecting in ${Math.floor(Ku/1e3)} seconds.`);const Ju=this._selectedProtocol!=="";this._reconnectTimeout=setTimeout(this._createSocket,Ku,Ju),this._reconnectAttempt+=1}else this._updateConnectionStatus("disconnected");this._clearSocket()}_errorIfDisposed(){if(this.isDisposed)throw new Error("Kernel connection is disposed")}get hasPendingInput(){return this._hasPendingInput}set hasPendingInput(Ku){this._hasPendingInput=Ku,this._pendingInput.emit(Ku)}}Au.KernelConnection=Vu;var Gu;(function(Wu){function Ku(ed){switch(ed.status){case"idle":case"busy":case"unknown":return;default:console.debug(`Kernel: ${ed.status} (${ed.id})`);break}}Wu.logKernelStatus=Ku;async function Ju(ed,td){return ed.sendShellMessage(td,!0).done}Wu.handleShellMessage=Ju;function Yu(ed,td,nd){return new Promise((od,sd)=>{if(td){if(typeof requirejs>"u")throw new Error("requirejs not found");requirejs([td],ad=>{if(ad[ed]===void 0){const pd=`Object '${ed}' not found in module '${td}'`;sd(new Error(pd))}else od(ad[ed])},sd)}else nd?.[ed]?od(nd[ed]):sd(new Error(`Object '${ed}' not found in registry`))})}Wu.loadObject=Yu;function Xu(ed,td){return ed=Math.ceil(ed),td=Math.floor(td),Math.floor(Math.random()*(td-ed+1))+ed}Wu.getRandomIntInclusive=Xu})(Gu||(Gu={}))})(_default$3)),_default$3}var manager$5={},hasRequiredManager$5;function requireManager$5(){if(hasRequiredManager$5)return manager$5;hasRequiredManager$5=1,Object.defineProperty(manager$5,"__esModule",{value:!0}),manager$5.KernelManager=void 0;const Au=require$$1$1,lo=require$$0$3,$u=requireLib$8(),Ru=requireBasemanager(),Iu=requireRestapi$4(),Pu=require_default$2(),Ou=requireRestapi$3();class Mu extends Ru.BaseManager{constructor(Lu={}){var Bu,ju,Fu;super(Lu),this._commsOverSubshells=$u.CommsOverSubshells.PerCommTarget,this._isReady=!1,this._kernelConnections=new Set,this._models=new Map,this._runningChanged=new lo.Signal(this),this._connectionFailure=new lo.Signal(this),this._kernelInfoTimeout=Pu.DEFAULT_KERNEL_INFO_TIMEOUT,this._kernelAPIClient=(Bu=Lu.kernelAPIClient)!==null&&Bu!==void 0?Bu:new Iu.KernelAPIClient({serverSettings:this.serverSettings}),this._kernelSpecAPIClient=(ju=Lu.kernelSpecAPIClient)!==null&&ju!==void 0?ju:new Ou.KernelSpecAPIClient({serverSettings:this.serverSettings}),this._pollModels=new Au.Poll({auto:!1,factory:()=>this.requestRunning(),frequency:{interval:10*1e3,backoff:!0,max:300*1e3},name:"@jupyterlab/services:KernelManager#models",standby:(Fu=Lu.standby)!==null&&Fu!==void 0?Fu:"when-hidden"}),this._ready=(async()=>{await this._pollModels.start(),await this._pollModels.tick,this._isReady=!0})()}get isReady(){return this._isReady}get ready(){return this._ready}get runningChanged(){return this._runningChanged}get connectionFailure(){return this._connectionFailure}get kernelInfoTimeout(){return this._kernelInfoTimeout}set kernelInfoTimeout(Lu){this._kernelInfoTimeout=Lu}dispose(){this.isDisposed||(this._models.clear(),this._kernelConnections.forEach(Lu=>Lu.dispose()),this._pollModels.dispose(),super.dispose())}connectTo(Lu){var Bu,ju;const{id:Fu}=Lu.model;let zu=(Bu=Lu.handleComms)!==null&&Bu!==void 0?Bu:!0;if(Lu.handleComms===void 0){for(const Hu of this._kernelConnections)if(Hu.id===Fu&&Hu.handleComms){zu=!1;break}}const Uu=new Pu.KernelConnection({handleComms:zu,...Lu,commsOverSubshells:(ju=Lu.commsOverSubshells)!==null&&ju!==void 0?ju:this._commsOverSubshells,serverSettings:this.serverSettings,kernelAPIClient:this._kernelAPIClient,kernelSpecAPIClient:this._kernelSpecAPIClient,kernelInfoTimeout:this._kernelInfoTimeout});return this._onStarted(Uu),this._models.has(Fu)||this.refreshRunning().catch(()=>{}),Uu}running(){return this._models.values()}get runningCount(){return this._models.size}get commsOverSubshells(){return this._commsOverSubshells}set commsOverSubshells(Lu){this._commsOverSubshells=Lu;for(const Bu of this._kernelConnections)Bu.commsOverSubshells=Lu}async refreshRunning(){await this._pollModels.refresh(),await this._pollModels.tick}async startNew(Lu={},Bu={}){const ju=await this._kernelAPIClient.startNew(Lu);return this.connectTo({...Bu,model:ju})}async shutdown(Lu){await this._kernelAPIClient.shutdown(Lu),await this.refreshRunning()}async shutdownAll(){await this.refreshRunning(),await Promise.all([...this._models.keys()].map(Lu=>this._kernelAPIClient.shutdown(Lu))),await this.refreshRunning()}async findById(Lu){return this._models.has(Lu)?this._models.get(Lu):(await this.refreshRunning(),this._models.get(Lu))}async requestRunning(){var Lu,Bu;let ju;try{ju=await this._kernelAPIClient.listRunning()}catch(Fu){throw(Fu instanceof $u.ServerConnection.NetworkError||((Lu=Fu.response)===null||Lu===void 0?void 0:Lu.status)===503||((Bu=Fu.response)===null||Bu===void 0?void 0:Bu.status)===424)&&this._connectionFailure.emit(Fu),Fu}this.isDisposed||this._models.size===ju.length&&ju.every(Fu=>{const zu=this._models.get(Fu.id);return zu?zu.connections===Fu.connections&&zu.execution_state===Fu.execution_state&&zu.last_activity===Fu.last_activity&&zu.name===Fu.name&&zu.reason===Fu.reason&&zu.traceback===Fu.traceback:!1})||(this._models=new Map(ju.map(Fu=>[Fu.id,Fu])),this._kernelConnections.forEach(Fu=>{this._models.has(Fu.id)||Fu.handleShutdown()}),this._runningChanged.emit(ju))}_onStarted(Lu){this._kernelConnections.add(Lu),Lu.statusChanged.connect(this._onStatusChanged,this),Lu.disposed.connect(this._onDisposed,this)}_onDisposed(Lu){this._kernelConnections.delete(Lu),this.refreshRunning().catch(()=>{})}_onStatusChanged(Lu,Bu){Bu==="dead"&&this.refreshRunning().catch(()=>{})}}return manager$5.KernelManager=Mu,(function(Du){class Lu extends Du{constructor(){super(...arguments),this._readyPromise=new Promise(()=>{})}get isActive(){return!1}get parentReady(){return super.ready}async startNew(ju={},Fu={}){return Promise.reject(new Error("Not implemented in no-op Kernel Manager"))}connectTo(ju){throw new Error("Not implemented in no-op Kernel Manager")}async shutdown(ju){return Promise.reject(new Error("Not implemented in no-op Kernel Manager"))}get ready(){return this.parentReady.then(()=>this._readyPromise)}async requestRunning(){return Promise.resolve()}}Du.NoopManager=Lu})(Mu||(manager$5.KernelManager=Mu={})),manager$5}var hasRequiredKernel;function requireKernel(){return hasRequiredKernel||(hasRequiredKernel=1,(function(Au){var lo=kernel$1&&kernel$1.__createBinding||(Object.create?(function(Bu,ju,Fu,zu){zu===void 0&&(zu=Fu);var Uu=Object.getOwnPropertyDescriptor(ju,Fu);(!Uu||("get"in Uu?!ju.__esModule:Uu.writable||Uu.configurable))&&(Uu={enumerable:!0,get:function(){return ju[Fu]}}),Object.defineProperty(Bu,zu,Uu)}):(function(Bu,ju,Fu,zu){zu===void 0&&(zu=Fu),Bu[zu]=ju[Fu]})),$u=kernel$1&&kernel$1.__setModuleDefault||(Object.create?(function(Bu,ju){Object.defineProperty(Bu,"default",{enumerable:!0,value:ju})}):function(Bu,ju){Bu.default=ju}),Ru=kernel$1&&kernel$1.__importStar||(function(){var Bu=function(ju){return Bu=Object.getOwnPropertyNames||function(Fu){var zu=[];for(var Uu in Fu)Object.prototype.hasOwnProperty.call(Fu,Uu)&&(zu[zu.length]=Uu);return zu},Bu(ju)};return function(ju){if(ju&&ju.__esModule)return ju;var Fu={};if(ju!=null)for(var zu=Bu(ju),Uu=0;Uu<zu.length;Uu++)zu[Uu]!=="default"&&lo(Fu,ju,zu[Uu]);return $u(Fu,ju),Fu}})(),Iu=kernel$1&&kernel$1.__exportStar||function(Bu,ju){for(var Fu in Bu)Fu!=="default"&&!Object.prototype.hasOwnProperty.call(ju,Fu)&&lo(ju,Bu,Fu)};Object.defineProperty(Au,"__esModule",{value:!0}),Au.CommsOverSubshells=Au.KernelConnection=Au.KernelAPI=Au.KernelMessage=Au.Kernel=void 0;const Pu=requireComm();Object.defineProperty(Au,"CommsOverSubshells",{enumerable:!0,get:function(){return Pu.CommsOverSubshells}});const Ou=Ru(requireKernel$1());Au.Kernel=Ou;const Mu=Ru(requireMessages());Au.KernelMessage=Mu;const Du=Ru(requireRestapi$4());Au.KernelAPI=Du;const Lu=require_default$2();Object.defineProperty(Au,"KernelConnection",{enumerable:!0,get:function(){return Lu.KernelConnection}}),Iu(requireManager$5(),Au)})(kernel$1)),kernel$1}var kernelspec$1={},kernelspec={},hasRequiredKernelspec$1;function requireKernelspec$1(){return hasRequiredKernelspec$1||(hasRequiredKernelspec$1=1,Object.defineProperty(kernelspec,"__esModule",{value:!0})),kernelspec}var manager$4={},hasRequiredManager$4;function requireManager$4(){if(hasRequiredManager$4)return manager$4;hasRequiredManager$4=1,Object.defineProperty(manager$4,"__esModule",{value:!0}),manager$4.KernelSpecManager=void 0;const Au=requireDist(),lo=require$$1$1,$u=require$$0$3,Ru=requireBasemanager(),Iu=requireRestapi$3();class Pu extends Ru.BaseManager{constructor(Mu={}){var Du,Lu;super(Mu),this._isReady=!1,this._connectionFailure=new $u.Signal(this),this._specs=null,this._specsChanged=new $u.Signal(this),this._kernelSpecAPIClient=(Du=Mu.kernelSpecAPIClient)!==null&&Du!==void 0?Du:new Iu.KernelSpecAPIClient({serverSettings:this.serverSettings}),this._ready=Promise.all([this.requestSpecs()]).then(Bu=>{}).catch(Bu=>{}).then(()=>{this.isDisposed||(this._isReady=!0)}),this._pollSpecs=new lo.Poll({auto:!1,factory:()=>this.requestSpecs(),frequency:{interval:61*1e3,backoff:!0,max:300*1e3},name:"@jupyterlab/services:KernelSpecManager#specs",standby:(Lu=Mu.standby)!==null&&Lu!==void 0?Lu:"when-hidden"}),this.ready.then(()=>{this._pollSpecs.start()})}get isReady(){return this._isReady}get ready(){return this._ready}get specs(){return this._specs}get specsChanged(){return this._specsChanged}get connectionFailure(){return this._connectionFailure}dispose(){this._pollSpecs.dispose(),super.dispose()}async refreshSpecs(){await this._pollSpecs.refresh(),await this._pollSpecs.tick}async requestSpecs(){const Mu=await this._kernelSpecAPIClient.get();this.isDisposed||Au.JSONExt.deepEqual(Mu,this._specs)||(this._specs=Mu,this._specsChanged.emit(Mu))}}return manager$4.KernelSpecManager=Pu,manager$4}var hasRequiredKernelspec;function requireKernelspec(){return hasRequiredKernelspec||(hasRequiredKernelspec=1,(function(Au){var lo=kernelspec$1&&kernelspec$1.__createBinding||(Object.create?(function(Mu,Du,Lu,Bu){Bu===void 0&&(Bu=Lu);var ju=Object.getOwnPropertyDescriptor(Du,Lu);(!ju||("get"in ju?!Du.__esModule:ju.writable||ju.configurable))&&(ju={enumerable:!0,get:function(){return Du[Lu]}}),Object.defineProperty(Mu,Bu,ju)}):(function(Mu,Du,Lu,Bu){Bu===void 0&&(Bu=Lu),Mu[Bu]=Du[Lu]})),$u=kernelspec$1&&kernelspec$1.__setModuleDefault||(Object.create?(function(Mu,Du){Object.defineProperty(Mu,"default",{enumerable:!0,value:Du})}):function(Mu,Du){Mu.default=Du}),Ru=kernelspec$1&&kernelspec$1.__importStar||(function(){var Mu=function(Du){return Mu=Object.getOwnPropertyNames||function(Lu){var Bu=[];for(var ju in Lu)Object.prototype.hasOwnProperty.call(Lu,ju)&&(Bu[Bu.length]=ju);return Bu},Mu(Du)};return function(Du){if(Du&&Du.__esModule)return Du;var Lu={};if(Du!=null)for(var Bu=Mu(Du),ju=0;ju<Bu.length;ju++)Bu[ju]!=="default"&&lo(Lu,Du,Bu[ju]);return $u(Lu,Du),Lu}})(),Iu=kernelspec$1&&kernelspec$1.__exportStar||function(Mu,Du){for(var Lu in Mu)Lu!=="default"&&!Object.prototype.hasOwnProperty.call(Du,Lu)&&lo(Du,Mu,Lu)};Object.defineProperty(Au,"__esModule",{value:!0}),Au.KernelSpecAPI=Au.KernelSpec=void 0;const Pu=Ru(requireKernelspec$1());Au.KernelSpec=Pu;const Ou=Ru(requireRestapi$3());Au.KernelSpecAPI=Ou,Iu(requireManager$4(),Au)})(kernelspec$1)),kernelspec$1}var manager$3={},builder={},hasRequiredBuilder;function requireBuilder(){if(hasRequiredBuilder)return builder;hasRequiredBuilder=1,Object.defineProperty(builder,"__esModule",{value:!0}),builder.BuildManager=void 0;const Au=requireLib$b(),lo=requireServerconnection(),$u="api/build";class Ru{constructor(Pu={}){var Ou;this.serverSettings=(Ou=Pu.serverSettings)!==null&&Ou!==void 0?Ou:lo.ServerConnection.makeSettings()}get isAvailable(){return Au.PageConfig.getOption("buildAvailable").toLowerCase()==="true"}get shouldCheck(){return Au.PageConfig.getOption("buildCheck").toLowerCase()==="true"}getStatus(){const{_url:Pu,serverSettings:Ou}=this;return lo.ServerConnection.makeRequest(Pu,{},Ou).then(Du=>{if(Du.status!==200)throw new lo.ServerConnection.ResponseError(Du);return Du.json()}).then(Du=>{if(typeof Du.status!="string")throw new Error("Invalid data");if(typeof Du.message!="string")throw new Error("Invalid data");return Du})}build(){const{_url:Pu,serverSettings:Ou}=this,Mu={method:"POST"};return lo.ServerConnection.makeRequest(Pu,Mu,Ou).then(Lu=>{if(Lu.status===400)throw new lo.ServerConnection.ResponseError(Lu,"Build aborted");if(Lu.status!==200){const Bu=`Build failed with ${Lu.status}.
|
|
262
|
+
`+Ou)}}catch{}throw Ru}}_request(lo,$u){typeof lo=="string"?($u=$u||{},$u.url=lo):$u=lo||{},$u=mergeConfig$1(this.defaults,$u);const{transitional:Ru,paramsSerializer:Iu,headers:Pu}=$u;Ru!==void 0&&validator.assertOptions(Ru,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean),legacyInterceptorReqResOrdering:validators.transitional(validators.boolean),advertiseZstdAcceptEncoding:validators.transitional(validators.boolean),validateStatusUndefinedResolves:validators.transitional(validators.boolean)},!1),Iu!=null&&(utils$3.isFunction(Iu)?$u.paramsSerializer={serialize:Iu}:validator.assertOptions(Iu,{encode:validators.function,serialize:validators.function},!0)),$u.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?$u.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:$u.allowAbsoluteUrls=!0),validator.assertOptions($u,{baseUrl:validators.spelling("baseURL"),withXsrfToken:validators.spelling("withXSRFToken")},!0),$u.method=(utils$3.getSafeProp($u,"method")||utils$3.getSafeProp(this.defaults,"method")||"get").toLowerCase();let Ou=Pu&&utils$3.merge(Pu.common,Pu[$u.method]);Pu&&utils$3.forEach(methodList.concat("common"),Uu=>{delete Pu[Uu]}),$u.headers=AxiosHeaders$1.concat(Ou,Pu);const Mu=[];let Du=!0;this.interceptors.request.forEach(function(Hu){if(typeof Hu.runWhen=="function"&&Hu.runWhen($u)===!1)return;Du=Du&&Hu.synchronous;const Vu=$u.transitional||transitionalDefaults;Vu&&Vu.legacyInterceptorReqResOrdering?Mu.unshift(Hu.fulfilled,Hu.rejected):Mu.push(Hu.fulfilled,Hu.rejected)});const Lu=[];this.interceptors.response.forEach(function(Hu){Lu.push(Hu.fulfilled,Hu.rejected)});let Bu,ju=0,Fu;if(!Du){const Uu=[dispatchRequest.bind(this),void 0];for(Uu.unshift(...Mu),Uu.push(...Lu),Fu=Uu.length,Bu=Promise.resolve($u);ju<Fu;)Bu=Bu.then(Uu[ju++],Uu[ju++]);return Bu}Fu=Mu.length;let zu=$u;for(;ju<Fu;){const Uu=Mu[ju++],Hu=Mu[ju++];try{zu=Uu?Uu(zu):zu}catch(Vu){if(!Hu){Bu=Promise.reject(Vu);break}try{const Gu=Hu.call(this,Vu);utils$3.isThenable(Gu)&&(Bu=Promise.resolve(Gu).then(()=>dispatchRequest.call(this,zu)))}catch(Gu){Bu=Promise.reject(Gu)}break}}if(!Bu)try{Bu=dispatchRequest.call(this,zu)}catch(Uu){Bu=Promise.reject(Uu)}for(ju=0,Fu=Lu.length;ju<Fu;)Bu=Bu.then(Lu[ju++],Lu[ju++]);return Bu}getUri(lo){lo=mergeConfig$1(this.defaults,lo);const $u=buildFullPath(lo.baseURL,lo.url,lo.allowAbsoluteUrls,lo);return buildURL($u,lo.params,lo.paramsSerializer)}};utils$3.forEach(["delete","get","head","options"],function Au(lo){Axios$1.prototype[lo]=function($u,Ru){return this.request(mergeConfig$1(Ru||{},{method:lo,url:$u,data:Ru&&utils$3.hasOwnProp(Ru,"data")?Ru.data:void 0}))}});utils$3.forEach(["post","put","patch","query"],function Au(lo){function $u(Ru){return function(Pu,Ou,Mu){return this.request(mergeConfig$1(Mu||{},{method:lo,headers:Ru?{"Content-Type":"multipart/form-data"}:{},url:Pu,data:Ou}))}}Axios$1.prototype[lo]=$u(),lo!=="query"&&(Axios$1.prototype[lo+"Form"]=$u(!0))});let CancelToken$1=class vS{constructor(lo){if(typeof lo!="function")throw new TypeError("executor must be a function.");let $u;this.promise=new Promise(function(Pu){$u=Pu});const Ru=this;this.promise.then(Iu=>{if(!Ru._listeners)return;let Pu=Ru._listeners.length;for(;Pu-- >0;)Ru._listeners[Pu](Iu);Ru._listeners=null}),this.promise.then=Iu=>{let Pu;const Ou=new Promise(Mu=>{Ru.subscribe(Mu),Pu=Mu}).then(Iu);return Ou.cancel=function(){Ru.unsubscribe(Pu)},Ou},lo(function(Pu,Ou,Mu){Ru.reason||(Ru.reason=new CanceledError$1(Pu,Ou,Mu),$u(Ru.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(lo){if(this.reason){lo(this.reason);return}this._listeners?this._listeners.push(lo):this._listeners=[lo]}unsubscribe(lo){if(!this._listeners)return;const $u=this._listeners.indexOf(lo);$u!==-1&&this._listeners.splice($u,1)}toAbortSignal(){const lo=new AbortController,$u=Ru=>{lo.abort(Ru)};return this.subscribe($u),lo.signal.unsubscribe=()=>this.unsubscribe($u),lo.signal}static source(){let lo;return{token:new vS(function(Iu){lo=Iu}),cancel:lo}}};function spread$1(Au){return function($u){return Au.apply(null,$u)}}function isAxiosError$1(Au){return utils$3.isObject(Au)&&Au.isAxiosError===!0}const HttpStatusCode$1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,ContentTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,UnprocessableContent:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(HttpStatusCode$1).forEach(([Au,lo])=>{HttpStatusCode$1[lo]===void 0&&(HttpStatusCode$1[lo]=Au)});function createInstance(Au){const lo=new Axios$1(Au),$u=bind(Axios$1.prototype.request,lo);return utils$3.extend($u,Axios$1.prototype,lo,{allOwnKeys:!0}),utils$3.extend($u,lo,null,{allOwnKeys:!0}),$u.create=function(Iu){return createInstance(mergeConfig$1(Au,Iu))},$u}const axios=createInstance(defaults$3);axios.Axios=Axios$1;axios.CanceledError=CanceledError$1;axios.CancelToken=CancelToken$1;axios.isCancel=isCancel$1;axios.VERSION=VERSION$7;axios.toFormData=toFormData$1;axios.AxiosError=AxiosError$1;axios.Cancel=axios.CanceledError;axios.all=function Au(lo){return Promise.all(lo)};axios.spread=spread$1;axios.isAxiosError=isAxiosError$1;axios.mergeConfig=mergeConfig$1;axios.AxiosHeaders=AxiosHeaders$1;axios.formToJSON=Au=>formDataToJSON(utils$3.isHTMLForm(Au)?new FormData(Au):Au);axios.getAdapter=adapters.getAdapter;axios.HttpStatusCode=HttpStatusCode$1;axios.default=axios;const{Axios,AxiosError,CanceledError,isCancel,CancelToken,VERSION:VERSION$6,all:all$6,Cancel,isAxiosError,spread,toFormData,AxiosHeaders,HttpStatusCode,formToJSON,getAdapter,mergeConfig,create:create$f}=axios;var define_process_env_default$5={};function isFormDataBody(Au){if(!Au||typeof Au!="object")return!1;if(typeof FormData<"u"&&Au instanceof FormData||Object.prototype.toString.call(Au)==="[object FormData]")return!0;const $u=Au;return typeof $u.append=="function"&&typeof $u.get=="function"&&typeof $u.has=="function"&&typeof $u.entries=="function"}class RunResponseError extends Error{static async create(lo){try{const $u=await lo.json(),{message:Ru,errors:Iu,warnings:Pu,traceback:Ou,exception:Mu,detail:Du}=$u,Lu=Ru??(typeof Du=="string"?Du:Du&&typeof Du=="object"&&"message"in Du?String(Du.message):void 0);return Ou&&console.error(Ou),new RunResponseError(lo,Lu??RunResponseError._defaultMessage(lo),Pu,Iu,Mu,Ou??"",Du)}catch($u){return console.debug($u),new RunResponseError(lo)}}constructor(lo,$u=RunResponseError._defaultMessage(lo),Ru=void 0,Iu=void 0,Pu=void 0,Ou="",Mu=void 0){super($u),this.name="RunResponseError",this.warnings=Ru??[],this.errors=Iu??[],this.response=lo,this.exceptionMessage=Pu,this.traceback=Ou,this.detail=Mu}warnings;errors;response;exceptionMessage;traceback;detail;static _defaultMessage(lo){return`Invalid response: ${lo.status} ${lo.statusText}`}}class NetworkError extends TypeError{constructor(lo){super(lo.message),this.name="NetworkError",this.stack=lo.stack}}class TokenExpiredError extends Error{expiredAt;url;constructor(lo,$u){super(`The Datalayer token expired at ${new Date($u).toISOString()}; not sending the request to ${lo}.`),this.name="TokenExpiredError",this.expiredAt=$u,this.url=lo,Object.setPrototypeOf(this,TokenExpiredError.prototype)}}function throwIfTokenExpired(Au,lo,$u){if(!(Au!==401||!lo||!isJwtExpired(lo)))throw new TokenExpiredError($u,getJwtExpiryMs(lo)??Date.now())}async function requestDatalayerAPIWithResponse({url:Au,method:lo,body:$u,token:Ru,signal:Iu,responseType:Pu,headers:Ou={}}){const Mu=isFormDataBody($u),Du={url:Au,method:lo??"GET",headers:{...Ou},withCredentials:!0,signal:Iu,responseType:Pu};typeof process<"u"&&define_process_env_default$5.VITEST&&(Du.adapter="fetch"),(lo==="GET"||!lo)&&(Du.headers["Cache-Control"]||(Du.headers["Cache-Control"]="no-store, no-cache, must-revalidate"),Du.headers.Pragma||(Du.headers.Pragma="no-cache")),Ru&&(Du.headers.Authorization=`Bearer ${Ru}`),Mu?(Du.data=$u,Du.headers.Accept||(Du.headers.Accept="application/json")):(Du.headers.Accept||(Du.headers.Accept="application/json"),Du.headers["Content-Type"]||(Du.headers["Content-Type"]="application/json"),Du.data=$u);try{const Lu=await axios(Du);if(Lu.status<300){if(Lu.status===202&&Lu.headers.location)return{data:await handleAxiosRedirection(Lu,Du),status:Lu.status,statusText:Lu.statusText,headers:{...Lu.headers}}}else{throwIfTokenExpired(Lu.status,Ru,Au);const Bu={ok:!1,status:Lu.status,statusText:Lu.statusText,json:async()=>Lu?.data,text:async()=>JSON.stringify(Lu?.data)};throw await RunResponseError.create(Bu)}return{data:Lu.data,status:Lu.status,statusText:Lu.statusText,headers:{...Lu.headers}}}catch(Lu){if(axios.isAxiosError(Lu)){if(Lu.response){throwIfTokenExpired(Lu.response.status,Ru,Au);const Bu={ok:!1,status:Lu.response.status,statusText:Lu.response.statusText,json:async()=>Lu.response?.data,text:async()=>JSON.stringify(Lu.response?.data)};throw await RunResponseError.create(Bu)}throw new NetworkError(Lu)}throw Lu}}async function requestDatalayerAPI(Au){return(await requestDatalayerAPIWithResponse(Au)).data}async function handleAxiosRedirection(Au,lo){let $u=Au.headers.location;if($u){const Iu=lo.url??"",Pu=String($u).replace(/^([a-z][a-z0-9+.-]*):\/(?!\/)/i,"$1://");try{const Ou=new URL(Pu,Iu),Mu=new URL(Iu,typeof window<"u"?window.location.origin:void 0);Mu.protocol==="https:"&&Ou.protocol==="http:"&&Ou.hostname===Mu.hostname&&(Ou.protocol="https:",Ou.port==="80"&&(Ou.port="")),$u=Ou.toString()}catch{const Ou=libExports$5.URLExt.parse(Iu),Mu=Ou.protocol+"//"+Ou.hostname;$u=libExports$5.URLExt.join(Mu,Pu)}}let Ru=1e3;for(;Au.status===202&&$u;){await sleep$1(Ru),Ru*=2;const Iu={...lo,url:$u,method:"GET",data:void 0};Au=await axios(Iu)}return Au.data}const userToProfile=Au=>Au?{id:Au.id,uid:Au.uid,handle:Au.handle,email:Au.email,firstName:Au.firstName,lastName:Au.lastName,displayName:Au.displayName,initials:Au.initials,avatarUrl:Au.avatarUrl,avatarIcon:Au.avatarIcon,banner:Au.banner,showOrbits:Au.showOrbits,origin:Au.origin,roles:Au.roles}:void 0,profileStore=createStore$1(Au=>({profile:void 0,setProfile:lo=>Au({profile:lo}),updateProfile:lo=>Au($u=>({profile:{...$u.profile,...lo}})),setProfileFromUser:lo=>Au($u=>{const Ru=userToProfile(lo);if(!Ru)return $u;const Iu={...$u.profile};for(const[Pu,Ou]of Object.entries(Ru))Ou!==void 0&&(Iu[Pu]=Ou);return{profile:Iu}}),clearProfile:()=>Au({profile:void 0})}));function useProfileStore(Au){return useStore$1(profileStore,Au)}const useProfile=()=>useProfileStore(Au=>Au.profile),SESSION_COOKIES=["datalayer-space-context","datalayer-principal-context","datalayer-billing-entity-uid","otel_sql_history"],SESSION_LOCAL_STORAGE_KEYS=["datalayer-principal","datalayer-billing-entity","datalayer-simple-auth"],SESSION_OWNER_KEY="datalayer-session-owner",registrations=new Set,registerSessionState=Au=>(registrations.add(Au),()=>{registrations.delete(Au)}),storageOf=Au=>{try{return typeof window>"u"?void 0:window[Au]}catch{return}},removeFrom=(Au,lo)=>{try{Au?.removeItem(lo)}catch{}},deleteCookie=Au=>{typeof document>"u"||(document.cookie=`${Au}=; path=/; max-age=0; SameSite=Lax`)},readCookie$1=Au=>{if(typeof document>"u")return;const lo=`${Au}=`,$u=document.cookie.split(";").map(Ru=>Ru.trim()).find(Ru=>Ru.startsWith(lo));return $u?$u.slice(lo.length):void 0},forgetSessionState=()=>{const Au=new Set(SESSION_COOKIES),lo=new Set([...SESSION_LOCAL_STORAGE_KEYS,SESSION_OWNER_KEY]),$u=new Set;for(const Pu of registrations){try{Pu.forget?.()}catch(Ou){console.warn("A session state could not be reset.",Ou)}Pu.cookies?.forEach(Ou=>Au.add(Ou)),Pu.localStorageKeys?.forEach(Ou=>lo.add(Ou)),Pu.sessionStorageKeys?.forEach(Ou=>$u.add(Ou))}Au.forEach(deleteCookie);const Ru=storageOf("localStorage");lo.forEach(Pu=>removeFrom(Ru,Pu));const Iu=storageOf("sessionStorage");$u.forEach(Pu=>removeFrom(Iu,Pu))},personalPrincipalInCookie=()=>{const Au=readCookie$1("datalayer-principal-context");if(Au)try{const lo=JSON.parse(decodeURIComponent(Au));return lo?.selectedPrincipalKind==="personal"&&String(lo?.selectedPrincipalUid??"").trim()||void 0}catch{return}},claimSessionState=Au=>{const lo=String(Au??"").trim();if(!lo)return;const $u=storageOf("localStorage");let Ru;try{Ru=$u?.getItem(SESSION_OWNER_KEY)??null}catch{Ru=null}const Iu=personalPrincipalInCookie();(Ru&&Ru!==lo||!Ru&&Iu&&Iu!==lo)&&forgetSessionState();try{$u?.setItem(SESSION_OWNER_KEY,lo)}catch{}},RESERVATION_WARNING_TIME_MS=5*6e4,iamStore=createStore$1((Au,lo)=>({credits:void 0,creditsReservations:[],externalToken:loadRefreshTokenFromCookie()??void 0,user:getStoredUser(),token:getStoredToken(),iamUrl:coreStore.getState().configuration?.iamUrl,iamProvidersAuthorizationURL:{},version:"",isLoginInProgress:!1,addIAMProviderAuthorizationURL:($u,Ru)=>{Au(Iu=>({iamProvidersAuthorizationURL:{...Iu.iamProvidersAuthorizationURL,[$u]:Ru}}))},login:async $u=>{const{refreshUserByToken:Ru,iamUrl:Iu,logout:Pu}=lo();Au({isLoginInProgress:!0});try{const Ou=await requestDatalayerAPI({url:`${Iu}/api/iam/v1/login`,method:"POST",body:{token:$u}});if(Ou.success&&Ou.token)await Ru(Ou.token);else throw new Error("Invalid Token.")}catch(Ou){throw console.debug("Failed to login.",Ou),Ou.name==="RunResponseError"&&Ou.response.status===401&&(console.debug("Received 401 error - Logging out."),Pu()),Ou}finally{Au({isLoginInProgress:!1})}},logout:()=>{storeUser(),storeToken(),profileStore.getState().clearProfile(),forgetSessionState(),Au({credits:void 0,creditsReservations:[],user:ANONYMOUS_USER,token:ANONYMOUS_USER_TOKEN})},checkIAMToken:async $u=>{lo().token!==$u&&await lo().refreshUserByToken($u)},setIAMProviderAccessToken:($u,Ru)=>{const{user:Iu}=lo();if(!Iu)throw Error("You need to be authenticated to set an Access Token for an IAM provider.");const Pu=IAMProvidersSpecs.getProvider($u);Ru?setCookie(Pu.accessTokenCookieName(Iu),Ru):deleteCookie$1(Pu.accessTokenCookieName(Iu))},getIAMProviderAccessToken:($u,Ru)=>{const Pu=IAMProvidersSpecs.getProvider(Ru).accessTokenCookieName($u);return getCookie$1(Pu)},updateUser:$u=>Au(Ru=>{const Iu={user:{...Ru.user,...$u}};return profileStore.getState().setProfileFromUser(Iu.user),Iu}),refreshCredits:async()=>{const{externalToken:$u,token:Ru,iamUrl:Iu,logout:Pu}=lo();if(Ru)try{const Ou=await requestDatalayerAPI({url:`${Iu}/api/iam/v1/usage/credits`,token:Ru,headers:$u?{"X-External-Token":$u}:void 0}),{credits:Mu,reservations:Du=[]}=Ou;Au({credits:{...Mu,available:availableCredits(Mu,Du)},creditsReservations:Du})}catch(Ou){throw console.error("Failed to refresh user credits.",Ou),Ou.name==="RunResponseError"&&Ou.response.status===401&&(console.error("Received 401, logging out."),Pu()),Ou}else Au({credits:void 0})},refreshUser:async()=>{const{token:$u,refreshUserByToken:Ru,logout:Iu}=lo();$u?await Ru($u):Iu()},refreshUserByTokenStored:async()=>{const $u=getStoredToken();$u?await lo().refreshUserByToken($u):lo().logout()},refreshUserByToken:async $u=>{const{iamUrl:Ru,logout:Iu,isLoginInProgress:Pu}=lo();try{const Ou=await requestDatalayerAPI({url:`${Ru}/api/iam/v1/whoami`,token:$u}),Mu=asUser(Ou.profile);claimSessionState(Mu?.id??Mu?.uid),storeUser(Mu),storeToken($u),Au(()=>({user:Mu,token:$u}))}catch(Ou){Ou.name==="RunResponseError"&&Ou.response.status===401?console.debug("Invalid token - Received 401 error."):console.debug("Failed to fetch user identity.",Ou),Pu||Iu()}},setExternalToken:$u=>Au(Ru=>({externalToken:$u})),setLogin:($u,Ru)=>Au(Iu=>(claimSessionState($u?.id??$u?.uid),storeUser($u),storeToken(Ru),profileStore.getState().setProfileFromUser($u),{user:$u,token:Ru})),setVersion:$u=>{$u&&!lo().version&&Au(Ru=>({version:$u}))}}));function useIAMStore(Au){return useStore$1(iamStore,Au)}const creditsPoll=new Poll({name:"@datalayer/ui:credits-refresh",factory:()=>iamStore.getState().refreshCredits(),auto:!1,frequency:{interval:60*1e3,backoff:!0,max:600*1e3},standby:()=>iamStore.getState().user?.id?"when-hidden":!0});iamStore.getState().refreshUserByTokenStored().catch(Au=>{console.error("Failed to refresh to validate the stored token.",Au)}).finally(()=>{const{externalToken:Au,iamUrl:lo,checkIAMToken:$u,token:Ru}=iamStore.getState();!Ru&&Au&&(console.debug("Can not login with token - Trying with the external token."),requestDatalayerAPI({url:`${lo}/api/iam/v1/login`,method:"POST",body:{token:Au}}).then(Pu=>{Pu.token&&$u(Pu.token)}).catch(Pu=>{console.debug("Can not login with token.",Ru,Pu)})),Ru?console.log("Logged in with token and external token."):console.debug("Failed to login with token and no external token available."),creditsPoll.start(),(()=>{if(typeof window>"u")return;const Pu=window.document;if(!Pu||typeof Pu.addEventListener!="function")return;const Ou=()=>{!Pu.hidden&&iamStore.getState().user?.id&&creditsPoll.refresh()};Pu.addEventListener("visibilitychange",Ou)})()});coreStore.subscribe((Au,lo)=>{if(Au.configuration?.iamUrl&&Au.configuration.iamUrl!==lo.configuration?.iamUrl){const $u=Au.configuration.iamUrl;console.log("Updating iamUrl with new value",$u),iamStore.setState({iamUrl:$u}),iamStore.getState().externalToken?iamStore.getState().login(iamStore.getState().externalToken).catch(Ru=>{console.error("Failed to refresh the user after updating the IAM RUN URL.",Ru)}):iamStore.getState().refreshUser().catch(Ru=>{console.error("Failed to refresh the user after updating the IAM server URL.",Ru)})}});function emojiKey(Au){return Array.from(Au.trim()).map(lo=>lo.codePointAt(0)??0).filter(lo=>lo!==65039).map(lo=>lo.toString(16)).join("-")}const scriptRel=(function Au(){const lo=typeof document<"u"&&document.createElement("link").relList;return lo&&lo.supports&&lo.supports("modulepreload")?"modulepreload":"preload"})(),assetsURL=function(Au,lo){return new URL(Au,lo).href},seen={},__vitePreload=function Au(lo,$u,Ru){let Iu=Promise.resolve();if($u&&$u.length>0){let Lu=function(Bu){return Promise.all(Bu.map(ju=>Promise.resolve(ju).then(Fu=>({status:"fulfilled",value:Fu}),Fu=>({status:"rejected",reason:Fu}))))};const Ou=document.getElementsByTagName("link"),Mu=document.querySelector("meta[property=csp-nonce]"),Du=Mu?.nonce||Mu?.getAttribute("nonce");Iu=Lu($u.map(Bu=>{if(Bu=assetsURL(Bu,Ru),Bu in seen)return;seen[Bu]=!0;const ju=Bu.endsWith(".css"),Fu=ju?'[rel="stylesheet"]':"";if(Ru)for(let Uu=Ou.length-1;Uu>=0;Uu--){const Hu=Ou[Uu];if(Hu.href===Bu&&(!ju||Hu.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${Bu}"]${Fu}`))return;const zu=document.createElement("link");if(zu.rel=ju?"stylesheet":scriptRel,ju||(zu.as="script"),zu.crossOrigin="",zu.href=Bu,Du&&zu.setAttribute("nonce",Du),document.head.appendChild(zu),ju)return new Promise((Uu,Hu)=>{zu.addEventListener("load",Uu),zu.addEventListener("error",()=>Hu(new Error(`Unable to preload CSS for ${Bu}`)))})}))}function Pu(Ou){const Mu=new Event("vite:preloadError",{cancelable:!0});if(Mu.payload=Ou,window.dispatchEvent(Mu),!Mu.defaultPrevented)throw Ou}return Iu.then(Ou=>{for(const Mu of Ou||[])Mu.status==="rejected"&&Pu(Mu.reason);return lo().catch(Pu)})},FLUENT_EMOJI_LOADERS={"1f440":()=>__vitePreload(()=>import("./chunks/1f440-p4rvIPef.js"),[],import.meta.url),"1f4d1":()=>__vitePreload(()=>import("./chunks/1f4d1-2yeMP7i5.js"),[],import.meta.url),"1f399":()=>__vitePreload(()=>import("./chunks/1f399-GX_7MVl_.js"),[],import.meta.url),"1f6a2":()=>__vitePreload(()=>import("./chunks/1f6a2-gL6kUzw5.js"),[],import.meta.url),"1f69a":()=>__vitePreload(()=>import("./chunks/1f69a-CbAMmMYx.js"),[],import.meta.url),"1f50e":()=>__vitePreload(()=>import("./chunks/1f50e-CNC8yd3r.js"),[],import.meta.url),"1f4ec":()=>__vitePreload(()=>import("./chunks/1f4ec-e7JJiuI4.js"),[],import.meta.url),"1f4c8":()=>__vitePreload(()=>import("./chunks/1f4c8-CNuFlfRg.js"),[],import.meta.url),"1f9f9":()=>__vitePreload(()=>import("./chunks/1f9f9-DNoxae13.js"),[],import.meta.url),"1f9e0":()=>__vitePreload(()=>import("./chunks/1f9e0-7eqXrAdK.js"),[],import.meta.url),"1f6df":()=>__vitePreload(()=>import("./chunks/1f6df-DcnntiKi.js"),[],import.meta.url),"1f9ee":()=>__vitePreload(()=>import("./chunks/1f9ee-BuIxmQEW.js"),[],import.meta.url),"1f47e":()=>__vitePreload(()=>import("./chunks/1f47e-CVrptMZb.js"),[],import.meta.url),"1f47d":()=>__vitePreload(()=>import("./chunks/1f47d-DKGX1RHr.js"),[],import.meta.url),"1f9d1-200d-1f680":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f680-C9wxDlc0.js"),[],import.meta.url),"269b":()=>__vitePreload(()=>import("./chunks/269b-CIDlSWpG.js"),[],import.meta.url),"1f3e6":()=>__vitePreload(()=>import("./chunks/1f3e6-LRmfNoyK.js"),[],import.meta.url),2712:()=>__vitePreload(()=>import("./chunks/2712-5PLssGP2.js"),[],import.meta.url),"1f4bc":()=>__vitePreload(()=>import("./chunks/1f4bc-DPph9Yum.js"),[],import.meta.url),"1f3db":()=>__vitePreload(()=>import("./chunks/1f3db-D8W2ZDGL.js"),[],import.meta.url),"1f3d7":()=>__vitePreload(()=>import("./chunks/1f3d7-BCgsEYI1.js"),[],import.meta.url),"1f3e2":()=>__vitePreload(()=>import("./chunks/1f3e2-Ck-pGqVC.js"),[],import.meta.url),"1f3af":()=>__vitePreload(()=>import("./chunks/1f3af-BjGhox67.js"),[],import.meta.url),2601:()=>__vitePreload(()=>import("./chunks/2601-BxBuW0c5.js"),[],import.meta.url),"1f6a7":()=>__vitePreload(()=>import("./chunks/1f6a7-Bf7dX4bM.js"),[],import.meta.url),"1f477":()=>__vitePreload(()=>import("./chunks/1f477--ZfEh0BR.js"),[],import.meta.url),"1f920":()=>__vitePreload(()=>import("./chunks/1f920-DdqVzdU_.js"),[],import.meta.url),"1f9ec":()=>__vitePreload(()=>import("./chunks/1f9ec-BiccuNAi.js"),[],import.meta.url),"1f432":()=>__vitePreload(()=>import("./chunks/1f432-BBBxgCDF.js"),[],import.meta.url),"1f409":()=>__vitePreload(()=>import("./chunks/1f409-B-A-r5OE.js"),[],import.meta.url),"1f9dd":()=>__vitePreload(()=>import("./chunks/1f9dd-Bjlh5f8S.js"),[],import.meta.url),"1f525":()=>__vitePreload(()=>import("./chunks/1f525-DugGj6UX.js"),[],import.meta.url),"1f386":()=>__vitePreload(()=>import("./chunks/1f386-D1j06612.js"),[],import.meta.url),"1f6f8":()=>__vitePreload(()=>import("./chunks/1f6f8-CzpZp4fr.js"),[],import.meta.url),"1f340":()=>__vitePreload(()=>import("./chunks/1f340-B2CJ9tGB.js"),[],import.meta.url),"1f393":()=>__vitePreload(()=>import("./chunks/1f393-Cule2ZWh.js"),[],import.meta.url),"1f600":()=>__vitePreload(()=>import("./chunks/1f600-DHzS58-a.js"),[],import.meta.url),"1f3e0":()=>__vitePreload(()=>import("./chunks/1f3e0-Dvy0EpCV.js"),[],import.meta.url),"1f98e":()=>__vitePreload(()=>import("./chunks/1f98e-BRdu0IxY.js"),[],import.meta.url),"1fa84":()=>__vitePreload(()=>import("./chunks/1fa84-C7Zz9Ttn.js"),[],import.meta.url),"1f9d1-200d-1f4bc":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f4bc-FkyMuHj6.js"),[],import.meta.url),"1f9d1-200d-1f4bb":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f4bb-Bxh01EAD.js"),[],import.meta.url),"1f3b5":()=>__vitePreload(()=>import("./chunks/1f3b5-BdjcFmdt.js"),[],import.meta.url),"1f977":()=>__vitePreload(()=>import("./chunks/1f977-g-J1jf1x.js"),[],import.meta.url),"1f450":()=>__vitePreload(()=>import("./chunks/1f450-CbtsXspW.js"),[],import.meta.url),"1f58a":()=>__vitePreload(()=>import("./chunks/1f58a-mulZ-CFH.js"),[],import.meta.url),"1f427":()=>__vitePreload(()=>import("./chunks/1f427-DglaWI4D.js"),[],import.meta.url),"1f3c4":()=>__vitePreload(()=>import("./chunks/1f3c4-BhpD29zf.js"),[],import.meta.url),"1f3ca":()=>__vitePreload(()=>import("./chunks/1f3ca-gIlr1kJ5.js"),[],import.meta.url),"1f5bc":()=>__vitePreload(()=>import("./chunks/1f5bc-MigptVzH.js"),[],import.meta.url),"1f304":()=>__vitePreload(()=>import("./chunks/1f304-aDc2qDui.js"),[],import.meta.url),"1f6eb":()=>__vitePreload(()=>import("./chunks/1f6eb-lf0G-q-a.js"),[],import.meta.url),"1fa90":()=>__vitePreload(()=>import("./chunks/1fa90-Ccp91l-o.js"),[],import.meta.url),"1f916":()=>__vitePreload(()=>import("./chunks/1f916-BqoYgu9n.js"),[],import.meta.url),"1f680":()=>__vitePreload(()=>import("./chunks/1f680-dnPjZK4l.js"),[],import.meta.url),"1f385":()=>__vitePreload(()=>import("./chunks/1f385-Dt5AZfN7.js"),[],import.meta.url),"1f6f0":()=>__vitePreload(()=>import("./chunks/1f6f0-DiDzAbox.js"),[],import.meta.url),"1f9d1-200d-1f52c":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f52c-DIXbDrbI.js"),[],import.meta.url),"1f988":()=>__vitePreload(()=>import("./chunks/1f988-wqhZ7Rxe.js"),[],import.meta.url),2603:()=>__vitePreload(()=>import("./chunks/2603-DNj-gj-j.js"),[],import.meta.url),"1f387":()=>__vitePreload(()=>import("./chunks/1f387-D0SVWvyW.js"),[],import.meta.url),"2b50":()=>__vitePreload(()=>import("./chunks/2b50-DgcciXHA.js"),[],import.meta.url),"1f9d1-200d-1f393":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f393-DhlpNrMG.js"),[],import.meta.url),2600:()=>__vitePreload(()=>import("./chunks/2600-DZnZtR2D.js"),[],import.meta.url),"1f44b":()=>__vitePreload(()=>import("./chunks/1f44b-CDEzsnIT.js"),[],import.meta.url),"1f433":()=>__vitePreload(()=>import("./chunks/1f433-BGsjKcaL.js"),[],import.meta.url),"1f381":()=>__vitePreload(()=>import("./chunks/1f381-NG1UoP_K.js"),[],import.meta.url),"270d":()=>__vitePreload(()=>import("./chunks/270d-DAjo8CgW.js"),[],import.meta.url),"262f":()=>__vitePreload(()=>import("./chunks/262f-BHwzZDRR.js"),[],import.meta.url),"1f4ca":()=>__vitePreload(()=>import("./chunks/1f4ca-DwUKcdqA.js"),[],import.meta.url),"1f4dd":()=>__vitePreload(()=>import("./chunks/1f4dd-CjeXE9pk.js"),[],import.meta.url),"1f4c5":()=>__vitePreload(()=>import("./chunks/1f4c5-BuR_5gXZ.js"),[],import.meta.url),"1f5d3":()=>__vitePreload(()=>import("./chunks/1f5d3-CD7YTnlH.js"),[],import.meta.url),"1f4da":()=>__vitePreload(()=>import("./chunks/1f4da-T00kbbB7.js"),[],import.meta.url),"1f4a1":()=>__vitePreload(()=>import("./chunks/1f4a1-DuAncIYW.js"),[],import.meta.url),"1f527":()=>__vitePreload(()=>import("./chunks/1f527-DGFX9oVv.js"),[],import.meta.url),"1f6e0":()=>__vitePreload(()=>import("./chunks/1f6e0-BN_iAibr.js"),[],import.meta.url),"1f9f0":()=>__vitePreload(()=>import("./chunks/1f9f0-NjV-EBzJ.js"),[],import.meta.url),2699:()=>__vitePreload(()=>import("./chunks/2699-DHeK1la1.js"),[],import.meta.url),"1f9ea":()=>__vitePreload(()=>import("./chunks/1f9ea-Dn-cjqlg.js"),[],import.meta.url),"1f52c":()=>__vitePreload(()=>import("./chunks/1f52c-PWG_VsFe.js"),[],import.meta.url),"1f5c2":()=>__vitePreload(()=>import("./chunks/1f5c2-BwHVJFvn.js"),[],import.meta.url),"1f4e6":()=>__vitePreload(()=>import("./chunks/1f4e6-iVURZ5lW.js"),[],import.meta.url),"1f6d2":()=>__vitePreload(()=>import("./chunks/1f6d2-C4PVtG90.js"),[],import.meta.url),"1f6b2":()=>__vitePreload(()=>import("./chunks/1f6b2-BvodiaEs.js"),[],import.meta.url),"1f4ac":()=>__vitePreload(()=>import("./chunks/1f4ac-B0hyiBGy.js"),[],import.meta.url),"1f4e3":()=>__vitePreload(()=>import("./chunks/1f4e3-BCLpfdwX.js"),[],import.meta.url),"1f9fe":()=>__vitePreload(()=>import("./chunks/1f9fe-vjnIOB6Q.js"),[],import.meta.url),"1f4b0":()=>__vitePreload(()=>import("./chunks/1f4b0-Bgl_9Qt3.js"),[],import.meta.url),"1f4b3":()=>__vitePreload(()=>import("./chunks/1f4b3-C3bg4q6a.js"),[],import.meta.url),"1f30d":()=>__vitePreload(()=>import("./chunks/1f30d-RKwL3Nsg.js"),[],import.meta.url),"1f512":()=>__vitePreload(()=>import("./chunks/1f512-CfUiEAwd.js"),[],import.meta.url),"1f511":()=>__vitePreload(()=>import("./chunks/1f511-n1Y90TZn.js"),[],import.meta.url),"1f6e1":()=>__vitePreload(()=>import("./chunks/1f6e1-Cu0Gi0Ok.js"),[],import.meta.url),"1f9ed":()=>__vitePreload(()=>import("./chunks/1f9ed-BdM-tuKc.js"),[],import.meta.url),"1f5fa":()=>__vitePreload(()=>import("./chunks/1f5fa-BbhAXfOC.js"),[],import.meta.url),"1f4f0":()=>__vitePreload(()=>import("./chunks/1f4f0-BqBFK1vM.js"),[],import.meta.url),2709:()=>__vitePreload(()=>import("./chunks/2709-R2m2qaPB.js"),[],import.meta.url),"1f4de":()=>__vitePreload(()=>import("./chunks/1f4de-DMKOmTcC.js"),[],import.meta.url),"1f91d":()=>__vitePreload(()=>import("./chunks/1f91d-BLSo-qgX.js"),[],import.meta.url),"1f3e5":()=>__vitePreload(()=>import("./chunks/1f3e5-BZAbo425.js"),[],import.meta.url),2696:()=>__vitePreload(()=>import("./chunks/2696-DCPh-ddG.js"),[],import.meta.url),"1f3a8":()=>__vitePreload(()=>import("./chunks/1f3a8-BVDoGacX.js"),[],import.meta.url),"1f3ac":()=>__vitePreload(()=>import("./chunks/1f3ac-D8k4rvLe.js"),[],import.meta.url),"1f4f7":()=>__vitePreload(()=>import("./chunks/1f4f7-BwaVsOpm.js"),[],import.meta.url),"1f9d1-200d-1f3eb":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f3eb-CMaKZADj.js"),[],import.meta.url),"1f9d1-200d-2695":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-2695-DCucKT0e.js"),[],import.meta.url),"1f9d1-200d-1f373":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f373-DvkX_q7n.js"),[],import.meta.url),"1f9d1-200d-1f33e":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f33e-C1GbmRM7.js"),[],import.meta.url),"1f331":()=>__vitePreload(()=>import("./chunks/1f331-_RrI1iL2.js"),[],import.meta.url),"1f41d":()=>__vitePreload(()=>import("./chunks/1f41d-BFxQMyWe.js"),[],import.meta.url),"1f989":()=>__vitePreload(()=>import("./chunks/1f989-BnANhNFy.js"),[],import.meta.url),"1f98a":()=>__vitePreload(()=>import("./chunks/1f98a-D9FmXaXZ.js"),[],import.meta.url),"1f419":()=>__vitePreload(()=>import("./chunks/1f419-5WEpY3Qm.js"),[],import.meta.url),2764:()=>__vitePreload(()=>import("./chunks/2764-BqnS842k.js"),[],import.meta.url),2705:()=>__vitePreload(()=>import("./chunks/2705-C2znzsf2.js"),[],import.meta.url),"23f0":()=>__vitePreload(()=>import("./chunks/23f0-dWLnhjSv.js"),[],import.meta.url),"1f514":()=>__vitePreload(()=>import("./chunks/1f514-B1X39g06.js"),[],import.meta.url),"1f9e9":()=>__vitePreload(()=>import("./chunks/1f9e9-i_U9-xN7.js"),[],import.meta.url),"1f3f7":()=>__vitePreload(()=>import("./chunks/1f3f7-CcKaOA8W.js"),[],import.meta.url),"1f4cb":()=>__vitePreload(()=>import("./chunks/1f4cb-oUiKe7zE.js"),[],import.meta.url),"1f4cc":()=>__vitePreload(()=>import("./chunks/1f4cc-CBUTvGMt.js"),[],import.meta.url),"1f50d":()=>__vitePreload(()=>import("./chunks/1f50d-1bvZKHvT.js"),[],import.meta.url),"1f642":()=>__vitePreload(()=>import("./chunks/1f642-C6Qm_-ba.js"),[],import.meta.url),"1f913":()=>__vitePreload(()=>import("./chunks/1f913-hQT-pf0C.js"),[],import.meta.url),"1f9d0":()=>__vitePreload(()=>import("./chunks/1f9d0-Bg0qtSKU.js"),[],import.meta.url),"1f60e":()=>__vitePreload(()=>import("./chunks/1f60e-Dxrd05Jo.js"),[],import.meta.url),"1f984":()=>__vitePreload(()=>import("./chunks/1f984-DOK3uNT7.js"),[],import.meta.url),"1f436":()=>__vitePreload(()=>import("./chunks/1f436-CfGEu66M.js"),[],import.meta.url),"1f431":()=>__vitePreload(()=>import("./chunks/1f431-Cy-L3DQS.js"),[],import.meta.url),"1f308":()=>__vitePreload(()=>import("./chunks/1f308-DAQVzKND.js"),[],import.meta.url),"1f31f":()=>__vitePreload(()=>import("./chunks/1f31f-BV2d8NX3.js"),[],import.meta.url),"26a1":()=>__vitePreload(()=>import("./chunks/26a1-Cpmzv_rj.js"),[],import.meta.url),"1f355":()=>__vitePreload(()=>import("./chunks/1f355-C-u8bPC3.js"),[],import.meta.url),2615:()=>__vitePreload(()=>import("./chunks/2615-CoDRCZkH.js"),[],import.meta.url),"1f389":()=>__vitePreload(()=>import("./chunks/1f389-B6nBX5We.js"),[],import.meta.url),"1f3c6":()=>__vitePreload(()=>import("./chunks/1f3c6-PZd-tUlI.js"),[],import.meta.url),"23f3":()=>__vitePreload(()=>import("./chunks/23f3-ASjqFsbT.js"),[],import.meta.url),2611:()=>__vitePreload(()=>import("./chunks/2611-BnnmLm-K.js"),[],import.meta.url),2702:()=>__vitePreload(()=>import("./chunks/2702-CfLyp35r.js"),[],import.meta.url),"1f30a":()=>__vitePreload(()=>import("./chunks/1f30a-DxwAt2Ba.js"),[],import.meta.url),"1f327":()=>__vitePreload(()=>import("./chunks/1f327-Ie-nQBNO.js"),[],import.meta.url),"1f33e":()=>__vitePreload(()=>import("./chunks/1f33e-Cfl2WM63.js"),[],import.meta.url),"1f3ab":()=>__vitePreload(()=>import("./chunks/1f3ab-BUCNQHz1.js"),[],import.meta.url),"1f4be":()=>__vitePreload(()=>import("./chunks/1f4be-DPAcAU4R.js"),[],import.meta.url),"1f4d3":()=>__vitePreload(()=>import("./chunks/1f4d3-GTxRgjv7.js"),[],import.meta.url),"1f4d6":()=>__vitePreload(()=>import("./chunks/1f4d6-COOZY-Q_.js"),[],import.meta.url),"1f4e2":()=>__vitePreload(()=>import("./chunks/1f4e2-DsStZsI-.js"),[],import.meta.url),"1f504":()=>__vitePreload(()=>import("./chunks/1f504-BYIHMoDP.js"),[],import.meta.url),"1f465":()=>__vitePreload(()=>import("./chunks/1f465-CPle6Hjq.js"),[],import.meta.url),"270f":()=>__vitePreload(()=>import("./chunks/270f-CLwo30mk.js"),[],import.meta.url),2728:()=>__vitePreload(()=>import("./chunks/2728-Qg6be-6p.js"),[],import.meta.url),"2b1c":()=>__vitePreload(()=>import("./chunks/2b1c-Uc1aRwAf.js"),[],import.meta.url),"1f310":()=>__vitePreload(()=>import("./chunks/1f310-AqUM9a8q.js"),[],import.meta.url),"1f324":()=>__vitePreload(()=>import("./chunks/1f324-8MHLOhTj.js"),[],import.meta.url),"1f372":()=>__vitePreload(()=>import("./chunks/1f372-3XLDlXkE.js"),[],import.meta.url),"1f373":()=>__vitePreload(()=>import("./chunks/1f373-BPUJt2bp.js"),[],import.meta.url),"1f39b":()=>__vitePreload(()=>import("./chunks/1f39b-CSNtbAXr.js"),[],import.meta.url),"1f41b":()=>__vitePreload(()=>import("./chunks/1f41b-Dre1z0gP.js"),[],import.meta.url),"1f4c2":()=>__vitePreload(()=>import("./chunks/1f4c2-Dx7BKmLO.js"),[],import.meta.url),"1f4c4":()=>__vitePreload(()=>import("./chunks/1f4c4-CNvjvC5k.js"),[],import.meta.url),"1f4dc":()=>__vitePreload(()=>import("./chunks/1f4dc-BhoW4cjD.js"),[],import.meta.url),"1f4e1":()=>__vitePreload(()=>import("./chunks/1f4e1-DezU8ow-.js"),[],import.meta.url),"1f500":()=>__vitePreload(()=>import("./chunks/1f500-D9xRo-IT.js"),[],import.meta.url),"1f501":()=>__vitePreload(()=>import("./chunks/1f501-CzKeDPcw.js"),[],import.meta.url),"1f52d":()=>__vitePreload(()=>import("./chunks/1f52d-2QxCLKhU.js"),[],import.meta.url),"1f552":()=>__vitePreload(()=>import("./chunks/1f552-4d0Y0kn7.js"),[],import.meta.url),"1f58b":()=>__vitePreload(()=>import("./chunks/1f58b-Cp8F_HBg.js"),[],import.meta.url),"1f5b2":()=>__vitePreload(()=>import("./chunks/1f5b2-D6BUULuh.js"),[],import.meta.url),"1f5c3":()=>__vitePreload(()=>import("./chunks/1f5c3-DjkgJLaz.js"),[],import.meta.url),"1f5d1":()=>__vitePreload(()=>import("./chunks/1f5d1-C4Kpe4HL.js"),[],import.meta.url),"1f5dc":()=>__vitePreload(()=>import("./chunks/1f5dc-DyLO7aB9.js"),[],import.meta.url),"1f9d1-200d-2696":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-2696-D9eSB-0q.js"),[],import.meta.url),"1fa79":()=>__vitePreload(()=>import("./chunks/1fa79-DHhIZbWB.js"),[],import.meta.url),"1fa9d":()=>__vitePreload(()=>import("./chunks/1fa9d-DUI9e77m.js"),[],import.meta.url),"1fa9f":()=>__vitePreload(()=>import("./chunks/1fa9f-10ALsMaD.js"),[],import.meta.url),"1f441":()=>__vitePreload(()=>import("./chunks/1f441-D8yah4C4.js"),[],import.meta.url),"1f604":()=>__vitePreload(()=>import("./chunks/1f604-CEekcaYE.js"),[],import.meta.url),"1f326":()=>__vitePreload(()=>import("./chunks/1f326-YSBr3aXI.js"),[],import.meta.url),"1f4b9":()=>__vitePreload(()=>import("./chunks/1f4b9-aacFyckt.js"),[],import.meta.url),"1f4c1":()=>__vitePreload(()=>import("./chunks/1f4c1-Ch6aJ0cj.js"),[],import.meta.url),"1f4e7":()=>__vitePreload(()=>import("./chunks/1f4e7-BBi7c_zx.js"),[],import.meta.url),"1f917":()=>__vitePreload(()=>import("./chunks/1f917-CyyS9fgf.js"),[],import.meta.url)},DRAWN=new Map;function hasFluentEmoji(Au){return!!Au&&Object.prototype.hasOwnProperty.call(FLUENT_EMOJI_LOADERS,emojiKey(Au))}async function loadFluentEmoji(Au){const lo=emojiKey(Au),$u=DRAWN.get(lo);if($u)return $u;if(!Object.prototype.hasOwnProperty.call(FLUENT_EMOJI_LOADERS,lo))return;const Ru=(await FLUENT_EMOJI_LOADERS[lo]()).default,Iu=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(Ru)}`;return DRAWN.set(lo,Iu),Iu}function FluentEmoji({emoji:Au,size:lo,label:$u,className:Ru,style:Iu}){const Pu=emojiKey(Au),Ou=hasFluentEmoji(Au),[Mu,Du]=reactExports.useState(()=>DRAWN.get(Pu));reactExports.useEffect(()=>{let ju=!0;return Du(DRAWN.get(Pu)),Ou&&!DRAWN.has(Pu)&&loadFluentEmoji(Au).then(Fu=>ju&&Du(Fu),()=>{}),()=>{ju=!1}},[Pu,Ou,Au]);const Lu=$u??Au,Bu={display:"inline-flex",alignItems:"center",justifyContent:"center",flex:"none",width:lo,height:lo,...Iu};return Ou?Mu?jsxRuntimeExports.jsx("img",{className:Ru,src:Mu,alt:Lu,"aria-hidden":Lu?void 0:!0,width:lo,height:lo,draggable:!1,"data-emoji":"fluent",style:{...Bu,display:"inline-block"}}):jsxRuntimeExports.jsx("span",{className:Ru,"aria-hidden":"true","data-emoji":"loading",style:Bu}):jsxRuntimeExports.jsx("span",{className:Ru,role:Lu?"img":void 0,"aria-label":Lu||void 0,"aria-hidden":Lu?void 0:!0,"data-emoji":"system",style:{...Bu,fontSize:Math.round(lo*.85),lineHeight:1},children:Au})}function generateMessageId(){return`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function createUserMessage(Au,lo){return{id:generateMessageId(),role:"user",content:Au,createdAt:new Date,metadata:lo}}function createAssistantMessage(Au,lo){return{id:generateMessageId(),role:"assistant",content:Au,createdAt:new Date,agentName:lo?.agentName,toolCalls:lo?.toolCalls,metadata:lo?.metadata}}const createStoreImpl=Au=>{let lo;const $u=new Set,Ru=(Lu,Bu)=>{const ju=typeof Lu=="function"?Lu(lo):Lu;if(!Object.is(ju,lo)){const Fu=lo;lo=Bu??(typeof ju!="object"||ju===null)?ju:Object.assign({},lo,ju),$u.forEach(zu=>zu(lo,Fu))}},Iu=()=>lo,Mu={setState:Ru,getState:Iu,getInitialState:()=>Du,subscribe:Lu=>($u.add(Lu),()=>$u.delete(Lu))},Du=lo=Au(Ru,Iu,Mu);return Mu},createStore=(Au=>Au?createStoreImpl(Au):createStoreImpl),identity=Au=>Au;function useStore(Au,lo=identity){const $u=vM.useSyncExternalStore(Au.subscribe,vM.useCallback(()=>lo(Au.getState()),[Au,lo]),()=>lo(Au.getInitialState()));return vM.useDebugValue($u),$u}const createImpl=Au=>{const lo=createStore(Au),$u=Ru=>useStore(lo,Ru);return Object.assign($u,lo),$u},create$e=(Au=>Au?createImpl(Au):createImpl),useReactorStore=create$e(()=>({reactor:null,isBackendPluginAvailable:()=>!1})),unavailableBackendPlugin=()=>!1;function registerReactor(Au,lo=unavailableBackendPlugin){useReactorStore.setState({reactor:Au,isBackendPluginAvailable:lo})}function useReactor(Au,lo={}){const{autoStart:$u=!0,availableBackendPlugins:Ru,isBackendPluginAvailable:Iu}=lo,Pu=reactExports.useMemo(()=>{if(Iu)return Iu;const Ou=new Set(Ru??[]);return Mu=>Ou.has(Mu)},[Iu,Ru]);return reactExports.useState(()=>(registerReactor(Au,Pu),null)),reactExports.useEffect(()=>(registerReactor(Au,Pu),()=>{useReactorStore.getState().reactor===Au&®isterReactor(null,unavailableBackendPlugin)}),[Au,Pu]),reactExports.useEffect(()=>{if($u)return Au.start(),()=>{Au.stop()}},[$u,Au]),Au}const NO_SUBSCRIPTION$1=()=>()=>{};function useOptionalReactorPlatform(){return useReactorStore(Au=>Au.reactor)}function useReactorPlatform(){const Au=useReactorStore(lo=>lo.reactor);if(!Au)throw new Error("useReactorPlatform: no reactor store registered. Call useReactor(reactor) (or registerReactor) before using reactor hooks.");return Au}function useSignalValue$1(Au){return reactExports.useSyncExternalStore(lo=>{let $u=!1;return effect$1(()=>{Au.value,$u?lo():$u=!0})},()=>Au.peek(),()=>Au.peek())}function useBackendPluginAvailability(){return useReactorStore(Au=>Au.isBackendPluginAvailable)}function useBackendPluginStream(Au,lo={}){const{pollMs:$u=5e3,onState:Ru}=lo,Iu=Au?.replace(/\/+$/,""),Pu=useReactorStore(Mu=>Mu.reactor),Ou=reactExports.useRef(Ru);Ou.current=Ru,reactExports.useEffect(()=>{if(!Iu||!Pu)return;let Mu=!1,Du=-1;const Lu=zu=>{Mu||zu.revision===Du||(Du=zu.revision,Ou.current?.(zu),Pu.setBackendPlugins(zu.plugins.filter(Uu=>Uu.enabled).map(Uu=>Uu.name)))},Bu=()=>fetch(`${Iu}/plugins/state`).then(zu=>zu.ok?zu.json():void 0).then(zu=>zu&&Lu(zu)).catch(()=>{});if(Bu(),typeof EventSource>"u"){const zu=setInterval(Bu,$u);return()=>{Mu=!0,clearInterval(zu)}}const ju=new EventSource(`${Iu}/events/stream`);ju.onmessage=zu=>{try{Lu(JSON.parse(zu.data))}catch{}};const Fu=setInterval(Bu,$u);return()=>{Mu=!0,clearInterval(Fu),ju.close()}},[Iu,Pu,$u])}function useReactorEvent(Au){const lo=useReactorPlatform();reactExports.useEffect(()=>{Au&&lo.fire(Au)},[lo,Au])}function useOptionalSlotComponents(Au){const lo=useOptionalReactorPlatform();return useSlotComponentsFrom(lo,Au)}function useSlotComponents(Au){const lo=useReactorPlatform();return useSlotComponentsFrom(lo,Au)}function useSlotComponentsFrom(Au,lo){const $u=useBackendPluginAvailability(),Ru=reactExports.useSyncExternalStore(Au?Au.subscribe:NO_SUBSCRIPTION$1,()=>Au?Au.getRevision():-1);return reactExports.useMemo(()=>{const Iu=[];if(!Au)return Iu;function Pu(Ou){return Ou.every(Mu=>$u(Mu))}for(const Ou of Au.listPlugins()){if(!Au.isEnabled(Ou))continue;const Mu=Au.getRequiredBackendPlugins(Ou);if(!Pu(Mu))continue;const Du=Au.getOutput(Ou);for(const Lu of Du?.components??[]){const Bu=Lu.requiredBackendPlugins??[];Lu.slot===lo&&Pu(Bu)&&Iu.push(Lu)}}return Iu.map((Ou,Mu)=>({component:Ou,index:Mu})).sort((Ou,Mu)=>(Ou.component.order??0)-(Mu.component.order??0)||Ou.index-Mu.index).map(Ou=>Ou.component)},[Au,lo,Ru,$u])}function ReactorSlot({slot:Au,props:lo={}}){const $u=useOptionalSlotComponents(Au);return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:$u.map(Ru=>{const Iu=Ru.Component;return jsxRuntimeExports.jsx(Iu,{...lo},`${Ru.slot}:${Ru.id}`)})})}function useGate(Au,lo){const $u=useContributions(Au);return reactExports.useMemo(()=>resolveGate($u,lo),[$u,lo])}function useContributions(Au){const lo=useReactorPlatform(),$u=reactExports.useSyncExternalStore(lo.subscribe,()=>lo.getRevision());return reactExports.useMemo(()=>lo.getContributions(Au),[lo,Au,$u])}function useCommands(){const Au=useReactorPlatform(),lo=reactExports.useSyncExternalStore(Au.subscribe,()=>Au.getRevision());return reactExports.useMemo(()=>Au.listCommands(),[Au,lo])}class LazyErrorBoundary extends reactExports.Component{state={error:null};static getDerivedStateFromError(lo){return{error:lo}}componentDidUpdate(lo){lo.resetKey!==this.props.resetKey&&this.state.error&&this.setState({error:null})}render(){return this.state.error?this.props.fallback(this.state.error):this.props.children}}const lazyComponents=new WeakMap;function lazyFor(Au){const lo=lazyComponents.get(Au);if(lo)return lo;const $u=vM.lazy(Au);return lazyComponents.set(Au,$u),$u}function ReactorLazy({load:Au,props:lo,fallback:$u=null,errorFallback:Ru}){const Iu=reactExports.useMemo(()=>lazyFor(Au),[Au]),Pu=Ru??(Ou=>jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:`Failed to load view: ${Ou.message}`}));return jsxRuntimeExports.jsx(LazyErrorBoundary,{fallback:Pu,resetKey:Au,children:jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:$u,children:jsxRuntimeExports.jsx(Iu,{...lo??{}})})})}function defaultResolve(Au){const lo=Au;if(lo&&typeof lo.load=="function")return{load:lo.load};if(lo&&typeof lo.Component=="function")return{Component:lo.Component}}function ReactorViewHost({point:Au,active:lo,props:$u,fallback:Ru=null,empty:Iu=null,errorFallback:Pu,resolve:Ou=defaultResolve,render:Mu}){const Du=useContributions(Au),Lu=reactExports.useMemo(()=>lo===void 0?void 0:Du.find(Fu=>Fu.id===lo),[Du,lo]);if(!Lu)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Iu});if(Mu)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Mu(Lu)});const Bu=Ou(Lu.value);if(!Bu)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Iu});if(Bu.load)return jsxRuntimeExports.jsx(ReactorLazy,{load:Bu.load,props:$u,fallback:Ru,errorFallback:Pu});const ju=Bu.Component;return jsxRuntimeExports.jsx(ju,{...$u??{}})}const UI_WIRE_VERSION=1,DISPLAY_META_KEY$1="reactor.ui/display",ANSWER_ACTION="reactor.answer",UI_OP_NAMES=["show","patch","append","remove","state","ask","window","meta"];function isRecord$6(Au){return typeof Au=="object"&&Au!==null&&!Array.isArray(Au)}function isOptional$1(Au,lo){return Au==null||lo(Au)}function isString$3(Au){return typeof Au=="string"}function isActionOffer(Au){return isRecord$6(Au)&&isString$3(Au.name)&&isString$3(Au.token)&&isOptional$1(Au.label,isString$3)}function isDisplay(Au){return isRecord$6(Au)&&isString$3(Au.type)&&isString$3(Au.id)&&isString$3(Au.text)&&(Au.version===void 0||Number.isInteger(Au.version))&&(Au.data===void 0||isRecord$6(Au.data))&&(Au.actions===void 0||Array.isArray(Au.actions)&&Au.actions.every(isActionOffer))}function isPatchOperation(Au){if(!isRecord$6(Au)||!isString$3(Au.path))return!1;switch(Au.op){case"add":case"replace":case"test":return"value"in Au;case"remove":return!0;case"move":case"copy":return isString$3(Au.from);default:return!1}}function isPatch(Au){return Array.isArray(Au)&&Au.every(isPatchOperation)}const OP_SHAPES={show:Au=>isDisplay(Au.body),ask:Au=>isDisplay(Au.body),patch:Au=>isString$3(Au.id)&&isPatch(Au.body),append:Au=>isString$3(Au.id)&&isRecord$6(Au.body)&&isString$3(Au.body.path),remove:Au=>isString$3(Au.id)&&(Au.body===void 0||Au.body===null),state:Au=>isPatch(Au.body),window:Au=>isRecord$6(Au.body)&&isString$3(Au.body.name)&&(Au.body.args===void 0||isRecord$6(Au.body.args)),meta:Au=>isRecord$6(Au.body)};function isUiOp(Au){return isRecord$6(Au)&&Au.v===UI_WIRE_VERSION&&isString$3(Au.scope)&&isOptional$1(Au.id,isString$3)&&UI_OP_NAMES.includes(Au.op)&&OP_SHAPES[Au.op](Au)}function isSeq(Au,lo){return Number.isInteger(Au)&&Au>=lo}function hasKeys(Au,lo,$u=[]){const Ru=Object.keys(Au);return lo.every(Iu=>Iu in Au)&&Ru.every(Iu=>lo.includes(Iu)||$u.includes(Iu))}function isDownFrame(Au){if(!isRecord$6(Au))return!1;switch(Au.t){case"welcome":return hasKeys(Au,["t","scope","seq"],["v"])&&(Au.v===void 0||Au.v===UI_WIRE_VERSION)&&isString$3(Au.scope)&&isSeq(Au.seq,0);case"op":return hasKeys(Au,["t","seq","op"])&&isSeq(Au.seq,1)&&isUiOp(Au.op);case"result":return hasKeys(Au,["t","ref","ok","status"],["detail","value"])&&isString$3(Au.ref)&&typeof Au.ok=="boolean"&&Number.isInteger(Au.status)&&isOptional$1(Au.detail,isString$3);case"ping":case"pong":return hasKeys(Au,["t"]);default:return!1}}const Renderers=defineContributionPoint("reactor.ui.renderer"),ToolBindings=defineContributionPoint("reactor.ui.toolBinding");function versionInRange(Au,lo){return lo?(lo.min===void 0||Au>=lo.min)&&(lo.max===void 0||Au<=lo.max):!0}function pickRenderer(Au,lo){const $u=lo.version??1;let Ru;for(const Iu of Au)Iu.value.type!==lo.type||!versionInRange($u,Iu.value.versions)||(!Ru||(Iu.value.rank??0)>(Ru.value.rank??0))&&(Ru=Iu);return Ru}function parsedObject(Au){if(typeof Au!="string")return Au;const lo=Au.trimStart();if(!lo.startsWith("{"))return Au;try{return JSON.parse(lo)}catch{return Au}}function embeddedDisplay(Au){const lo=parsedObject(Au);if(typeof lo!="object"||lo===null)return;const $u=lo._meta;if(typeof $u!="object"||$u===null)return;const Ru=$u[DISPLAY_META_KEY$1];return isDisplay(Ru)?Ru:void 0}function bindingMatches(Au,lo){return typeof Au.tool=="string"?Au.tool===lo:(Au.tool.lastIndex=0,Au.tool.test(lo))}function textOf(Au){if(Au==null)return"";if(typeof Au=="string")return Au;try{return JSON.stringify(Au)??String(Au)}catch{return String(Au)}}function resolveToolResult(Au,lo){const $u=embeddedDisplay(lo.result);if($u)return $u;const Ru=Au.getContributions(ToolBindings).find(Iu=>bindingMatches(Iu.value,lo.toolName));if(Ru)return{type:Ru.value.type,version:Ru.value.version??1,id:lo.toolCallId??lo.toolName,text:textOf(lo.result),data:{toolName:lo.toolName,result:lo.result}}}function emptyUiModel(){return{displays:{},order:[],asks:[],state:{},meta:{}}}function clone$2(Au){return Au===void 0?Au:JSON.parse(JSON.stringify(Au))}function parsePointer(Au){if(Au==="")return[];if(!Au.startsWith("/"))throw new Error(`A JSON pointer starts with '/': ${Au}`);return Au.slice(1).split("/").map(lo=>lo.replace(/~1/g,"/").replace(/~0/g,"~")).map(lo=>{if(FORBIDDEN_TOKENS.has(lo))throw new Error(`${Au}: '${lo}' is never a path token`);return lo})}const FORBIDDEN_TOKENS=new Set(["__proto__","constructor","prototype"]);function hasOwn(Au,lo){return Object.prototype.hasOwnProperty.call(Au,lo)}function walk(Au,lo,$u){let Ru=Au;for(const Iu of lo)if(Array.isArray(Ru))Ru=Ru[arrayIndex(Ru,Iu,$u,!1)];else if(typeof Ru=="object"&&Ru!==null&&hasOwn(Ru,Iu))Ru=Ru[Iu];else throw new Error(`No value at ${$u}`);if(typeof Ru!="object"||Ru===null)throw new Error(`${$u} does not lead into an object or an array`);return Ru}function arrayIndex(Au,lo,$u,Ru){if(Ru&&lo==="-")return Au.length;if(!/^(0|[1-9][0-9]*)$/.test(lo))throw new Error(`${$u}: '${lo}' is not an array index`);const Iu=Number(lo);if(Iu>Au.length||!Ru&&Iu===Au.length)throw new Error(`${$u}: index ${Iu} is out of bounds`);return Iu}function read$2(Au,lo){const $u=parsePointer(lo);if($u.length===0)return Au;const Ru=walk(Au,$u.slice(0,-1),lo),Iu=$u[$u.length-1];if(Array.isArray(Ru))return Ru[arrayIndex(Ru,Iu,lo,!1)];if(!hasOwn(Ru,Iu))throw new Error(`No value at ${lo}`);return Ru[Iu]}function add$1(Au,lo,$u){const Ru=parsePointer(lo);if(Ru.length===0)return $u;const Iu=walk(Au,Ru.slice(0,-1),lo),Pu=Ru[Ru.length-1];return Array.isArray(Iu)?Iu.splice(arrayIndex(Iu,Pu,lo,!0),0,$u):Iu[Pu]=$u,Au}function removeAt(Au,lo){const $u=parsePointer(lo);if($u.length===0)return;const Ru=walk(Au,$u.slice(0,-1),lo),Iu=$u[$u.length-1];if(Array.isArray(Ru))Ru.splice(arrayIndex(Ru,Iu,lo,!1),1);else{if(!hasOwn(Ru,Iu))throw new Error(`No value at ${lo}`);delete Ru[Iu]}return Au}function replaceAt(Au,lo,$u){const Ru=parsePointer(lo);if(Ru.length===0)return $u;const Iu=walk(Au,Ru.slice(0,-1),lo),Pu=Ru[Ru.length-1];if(Array.isArray(Iu))Iu[arrayIndex(Iu,Pu,lo,!1)]=$u;else{if(!hasOwn(Iu,Pu))throw new Error(`No value at ${lo}`);Iu[Pu]=$u}return Au}function equal$1(Au,lo){if(Au===lo)return!0;if(Array.isArray(Au)||Array.isArray(lo))return Array.isArray(Au)&&Array.isArray(lo)&&Au.length===lo.length&&Au.every((Pu,Ou)=>equal$1(Pu,lo[Ou]));if(typeof Au!="object"||typeof lo!="object"||Au===null||lo===null)return!1;const $u=Au,Ru=lo,Iu=Object.keys($u);return Iu.length===Object.keys(Ru).length&&Iu.every(Pu=>hasOwn(Ru,Pu)&&equal$1($u[Pu],Ru[Pu]))}function applyPatch$1(Au,lo){let $u=clone$2(Au);for(const Ru of lo)switch(Ru.op){case"add":$u=add$1($u,Ru.path,clone$2(Ru.value));break;case"remove":$u=removeAt($u,Ru.path);break;case"replace":$u=replaceAt($u,Ru.path,clone$2(Ru.value));break;case"move":{const Iu=requireFrom(Ru),Pu=read$2($u,Iu);$u=add$1(removeAt($u,Iu),Ru.path,Pu);break}case"copy":$u=add$1($u,Ru.path,clone$2(read$2($u,requireFrom(Ru))));break;case"test":if(!equal$1(read$2($u,Ru.path),Ru.value))throw new Error(`test failed at ${Ru.path}`);break;default:throw new Error(`Unknown patch op ${Ru.op}`)}return $u}function requireFrom(Au){if(typeof Au.from!="string")throw new Error(`'${Au.op}' at ${Au.path} needs 'from'`);return Au.from}function displayOf(Au,lo){const $u=Au.displays[lo.id];if(!$u)throw new Error(`'${lo.op}' for display '${lo.id}', which was never shown`);return $u}function shown(Au,lo){const $u=lo.id in Au.displays;return{...Au,displays:{...Au.displays,[lo.id]:lo},order:$u?Au.order:[...Au.order,lo.id]}}function applyUiOp(Au,lo){if(lo.v!==UI_WIRE_VERSION)throw new Error(`reactor.ui wire v${String(lo.v)} is not v${UI_WIRE_VERSION}`);switch(lo.op){case"show":return shown(Au,lo.body);case"ask":{const $u=shown(Au,lo.body);return $u.asks.includes(lo.body.id)?$u:{...$u,asks:[...$u.asks,lo.body.id]}}case"patch":{const $u=applyPatch$1(displayOf(Au,lo),lo.body);return{...Au,displays:{...Au.displays,[lo.id]:{...$u,id:lo.id}}}}case"append":{const $u=displayOf(Au,lo),Ru=applyPatch$1($u,[{op:"add",path:`${lo.body.path}/-`,value:lo.body.value}]);return{...Au,displays:{...Au.displays,[lo.id]:Ru}}}case"remove":{if(!(lo.id in Au.displays))return Au;const $u={...Au.displays};return delete $u[lo.id],{...Au,displays:$u,order:Au.order.filter(Ru=>Ru!==lo.id),asks:Au.asks.filter(Ru=>Ru!==lo.id)}}case"state":return{...Au,state:applyPatch$1(Au.state,lo.body)};case"meta":return{...Au,meta:{...Au.meta,...lo.body}};case"window":return Au;default:throw new Error(`Unknown reactor.ui op '${lo.op}'`)}}const AGUI_NAME="reactor.ui",UI_FILE_SCOPE_HEADER="X-Reactor-Scope",UI_FILE_NAME_HEADER="X-Reactor-File-Name";class UiFileRefused extends Error{status;constructor(lo,$u){super($u),this.status=lo,this.name="UiFileRefused"}}async function uploadFile(Au,lo){const $u=await(lo.fetcher??fetch)(lo.url,{method:"POST",headers:{"Content-Type":Au.type||"application/octet-stream",[UI_FILE_SCOPE_HEADER]:lo.scope,[UI_FILE_NAME_HEADER]:encodeURIComponent(Au.name),...lo.token?{Authorization:`Bearer ${lo.token}`}:{}},body:Au});if(!$u.ok){let Iu="";try{const Pu=await $u.json();Iu=typeof Pu.detail=="string"?Pu.detail:""}catch{}throw new UiFileRefused($u.status,Iu||`${Au.name} was refused (${$u.status}).`)}const Ru=await $u.json();if(typeof Ru.ref!="string"||typeof Ru.name!="string"||typeof Ru.media_type!="string")throw new UiFileRefused($u.status,`The host kept ${Au.name} under no ref.`);return Ru}function isFileRef(Au){const lo=Au;return typeof lo=="object"&&lo!==null&&typeof lo.ref=="string"&&typeof lo.name=="string"&&typeof lo.media_type=="string"}const UI_WS_PROTOCOL="reactor.ui.v1",UI_WS_CLOSE={refused:4400,unauthorized:4401,forbidden:4403,timeout:4408,gone:4410};class UiSocketStopped extends Error{status;reason;constructor(lo,$u){super(`reactor.ui socket ${lo}: ${$u}`),this.status=lo,this.reason=$u}}const FINAL_CLOSES={[UI_WS_CLOSE.refused]:"refused",[UI_WS_CLOSE.unauthorized]:"refused",[UI_WS_CLOSE.forbidden]:"refused",[UI_WS_CLOSE.gone]:"gone"};function randomId(){const Au=globalThis.crypto;return Au?.randomUUID?Au.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}class UiSocket{lastSeq;status="connecting";ws=null;welcomed=!1;historyUpTo=0;resumable;stopped=!1;attempt=0;heard=0;beat=null;retry=null;pending=new Map;options;constructor(lo){this.options={heartbeatMs:2e4,timeoutMs:6e4,backoffMs:[250,1e3,2e3,5e3],maxPending:64,newId:randomId,...lo},this.lastSeq=lo.since??0,this.resumable=lo.since!==void 0}connect(){if(this.stopped||this.ws)return;this.setStatus(this.attempt===0&&!this.resumable?"connecting":"reconnecting");const $u=(this.options.open??((Ru,Iu)=>new globalThis.WebSocket(Ru,Iu)))(this.options.url,[UI_WS_PROTOCOL]);this.ws=$u,this.welcomed=!1,$u.onopen=()=>{this.hello($u)},$u.onmessage=Ru=>this.receive($u,Ru.data),$u.onclose=Ru=>this.closed($u,Ru.code,Ru.reason),$u.onerror=()=>{}}act(lo){const $u={...lo,idempotency_id:lo.idempotency_id??this.options.newId()};return this.request({t:"action",ref:this.options.newId(),action:$u})}state(lo){return this.request({t:"state",ref:this.options.newId(),body:lo})}close(){this.stop("closed","closed by the page",1e3)}request(lo){return this.stopped?Promise.reject(new UiSocketStopped(this.status,"the socket is stopped")):this.pending.size>=this.options.maxPending?Promise.reject(new Error(`${this.pending.size} presses are waiting for their result`)):new Promise(($u,Ru)=>{this.pending.set(lo.ref,{frame:lo,resolve:$u,reject:Ru}),this.welcomed&&this.send(lo)})}async hello(lo){let $u;try{$u=await this.options.token()}catch(Ru){this.stop("refused",`no credential: ${String(Ru)}`,1e3);return}lo===this.ws&&(this.heard=Date.now(),this.send({t:"hello",v:UI_WIRE_VERSION,token:$u,scope:this.options.scope,since:this.resumable?this.lastSeq:null}),this.beat=setInterval(()=>this.heartbeat(lo),this.options.heartbeatMs))}heartbeat(lo){if(lo===this.ws){if(Date.now()-this.heard>this.options.timeoutMs){lo.close(UI_WS_CLOSE.timeout,"nothing heard"),this.closed(lo,UI_WS_CLOSE.timeout,"nothing heard");return}this.send({t:"ping"})}}receive(lo,$u){if(lo!==this.ws)return;let Ru;try{Ru=typeof $u=="string"?JSON.parse($u):void 0}catch{Ru=void 0}if(!isDownFrame(Ru)){this.stop("refused","the host sent a frame that is not the schema’s",UI_WS_CLOSE.refused);return}this.heard=Date.now(),this.handle(lo,Ru)}handle(lo,$u){switch($u.t){case"welcome":if($u.scope!==this.options.scope){this.stop("refused",`welcomed to ${$u.scope}, not ${this.options.scope}`,UI_WS_CLOSE.refused);return}if(this.resumable&&$u.seq<this.lastSeq){this.stop("gone",`the host is at op ${$u.seq}, the page at ${this.lastSeq}`,1e3);return}this.resumable||(this.historyUpTo=$u.seq),this.welcomed=!0,this.attempt=0,this.setStatus("open");for(const Ru of this.pending.values())this.send(Ru.frame);return;case"op":if(!this.welcomed){this.stop("refused","an op before the welcome",UI_WS_CLOSE.refused);return}if($u.seq<=this.lastSeq)return;if($u.seq!==this.lastSeq+1){lo.close(1e3,`op ${$u.seq} after ${this.lastSeq}`),this.closed(lo,1e3,"a gap");return}this.lastSeq=$u.seq,this.resumable=!0,this.options.onOp($u.op,$u.seq,$u.seq<=this.historyUpTo);return;case"result":{const Ru=this.pending.get($u.ref);Ru&&(this.pending.delete($u.ref),Ru.resolve({ok:$u.ok,status:$u.status,detail:$u.detail,value:$u.value}));return}case"ping":this.send({t:"pong"});return;case"pong":return}}closed(lo,$u,Ru){if(lo!==this.ws||(this.ws=null,this.welcomed=!1,this.clearBeat(),this.stopped))return;const Iu=FINAL_CLOSES[$u];if(Iu){this.stop(Iu,Ru||`closed with ${$u}`);return}this.resumable=this.resumable||this.lastSeq>0;const Pu=this.options.backoffMs,Ou=Pu[Math.min(this.attempt,Pu.length-1)]??1e3;this.attempt+=1,this.setStatus("reconnecting",Ru),this.retry=setTimeout(()=>{this.retry=null,this.connect()},Ou)}stop(lo,$u,Ru){if(this.stopped)return;this.stopped=!0,this.clearBeat(),this.retry&&(clearTimeout(this.retry),this.retry=null);const Iu=this.ws;this.ws=null,Iu&&Ru!==void 0&&Iu.close(Ru,$u.slice(0,120));for(const Pu of this.pending.values())Pu.reject(new UiSocketStopped(lo,$u));this.pending.clear(),this.setStatus(lo,$u)}send(lo){this.ws?.send(JSON.stringify(lo))}clearBeat(){this.beat&&(clearInterval(this.beat),this.beat=null)}setStatus(lo,$u){this.status=lo,this.options.onStatus?.(lo,$u)}}var lib$b={},basemanager={},serverconnection={},serialize$2={},messages$1={},hasRequiredMessages;function requireMessages(){if(hasRequiredMessages)return messages$1;hasRequiredMessages=1,Object.defineProperty(messages$1,"__esModule",{value:!0}),messages$1.supportedKernelWebSocketProtocols=void 0,messages$1.createMessage=lo,messages$1.isStreamMsg=$u,messages$1.isDisplayDataMsg=Ru,messages$1.isUpdateDisplayDataMsg=Iu,messages$1.isExecuteInputMsg=Pu,messages$1.isExecuteResultMsg=Ou,messages$1.isErrorMsg=Mu,messages$1.isStatusMsg=Du,messages$1.isClearOutputMsg=Lu,messages$1.isDebugEventMsg=Bu,messages$1.isCommOpenMsg=ju,messages$1.isCommCloseMsg=Fu,messages$1.isCommMsgMsg=zu,messages$1.isInfoRequestMsg=Uu,messages$1.isExecuteReplyMsg=Hu,messages$1.isDebugRequestMsg=Vu,messages$1.isDebugReplyMsg=Gu,messages$1.isInputRequestMsg=Wu,messages$1.isInputReplyMsg=Ku;const Au=requireDist();function lo(Yu){var Xu,ed,td,nd,od,sd;return{buffers:(Xu=Yu.buffers)!==null&&Xu!==void 0?Xu:[],channel:Yu.channel,content:Yu.content,header:{date:new Date().toISOString(),msg_id:(ed=Yu.msgId)!==null&&ed!==void 0?ed:Au.UUID.uuid4(),msg_type:Yu.msgType,session:Yu.session,username:(td=Yu.username)!==null&&td!==void 0?td:"",subshell_id:(nd=Yu.subshellId)!==null&&nd!==void 0?nd:null,version:"5.2"},metadata:(od=Yu.metadata)!==null&&od!==void 0?od:{},parent_header:(sd=Yu.parentHeader)!==null&&sd!==void 0?sd:{}}}function $u(Yu){return Yu.header.msg_type==="stream"}function Ru(Yu){return Yu.header.msg_type==="display_data"}function Iu(Yu){return Yu.header.msg_type==="update_display_data"}function Pu(Yu){return Yu.header.msg_type==="execute_input"}function Ou(Yu){return Yu.header.msg_type==="execute_result"}function Mu(Yu){return Yu.header.msg_type==="error"}function Du(Yu){return Yu.header.msg_type==="status"}function Lu(Yu){return Yu.header.msg_type==="clear_output"}function Bu(Yu){return Yu.header.msg_type==="debug_event"}function ju(Yu){return Yu.header.msg_type==="comm_open"}function Fu(Yu){return Yu.header.msg_type==="comm_close"}function zu(Yu){return Yu.header.msg_type==="comm_msg"}function Uu(Yu){return Yu.header.msg_type==="kernel_info_request"}function Hu(Yu){return Yu.header.msg_type==="execute_reply"}function Vu(Yu){return Yu.header.msg_type==="debug_request"}function Gu(Yu){return Yu.header.msg_type==="debug_reply"}function Wu(Yu){return Yu.header.msg_type==="input_request"}function Ku(Yu){return Yu.header.msg_type==="input_reply"}var Ju;return(function(Yu){Yu.v1KernelWebsocketJupyterOrg="v1.kernel.websocket.jupyter.org"})(Ju||(messages$1.supportedKernelWebSocketProtocols=Ju={})),messages$1}var hasRequiredSerialize;function requireSerialize(){if(hasRequiredSerialize)return serialize$2;hasRequiredSerialize=1;var Au=serialize$2&&serialize$2.__createBinding||(Object.create?(function(Mu,Du,Lu,Bu){Bu===void 0&&(Bu=Lu);var ju=Object.getOwnPropertyDescriptor(Du,Lu);(!ju||("get"in ju?!Du.__esModule:ju.writable||ju.configurable))&&(ju={enumerable:!0,get:function(){return Du[Lu]}}),Object.defineProperty(Mu,Bu,ju)}):(function(Mu,Du,Lu,Bu){Bu===void 0&&(Bu=Lu),Mu[Bu]=Du[Lu]})),lo=serialize$2&&serialize$2.__setModuleDefault||(Object.create?(function(Mu,Du){Object.defineProperty(Mu,"default",{enumerable:!0,value:Du})}):function(Mu,Du){Mu.default=Du}),$u=serialize$2&&serialize$2.__importStar||(function(){var Mu=function(Du){return Mu=Object.getOwnPropertyNames||function(Lu){var Bu=[];for(var ju in Lu)Object.prototype.hasOwnProperty.call(Lu,ju)&&(Bu[Bu.length]=ju);return Bu},Mu(Du)};return function(Du){if(Du&&Du.__esModule)return Du;var Lu={};if(Du!=null)for(var Bu=Mu(Du),ju=0;ju<Bu.length;ju++)Bu[ju]!=="default"&&Au(Lu,Du,Bu[ju]);return lo(Lu,Du),Lu}})();Object.defineProperty(serialize$2,"__esModule",{value:!0}),serialize$2.serialize=Iu,serialize$2.deserialize=Pu;const Ru=$u(requireMessages());function Iu(Mu,Du=""){return Du===Ru.supportedKernelWebSocketProtocols.v1KernelWebsocketJupyterOrg?Ou.serializeV1KernelWebsocketJupyterOrg(Mu):Ou.serializeDefault(Mu)}function Pu(Mu,Du=""){return Du===Ru.supportedKernelWebSocketProtocols.v1KernelWebsocketJupyterOrg?Ou.deserializeV1KernelWebsocketJupyterOrg(Mu):Ou.deserializeDefault(Mu)}var Ou;return(function(Mu){function Du(Uu){let Hu;const Vu=new DataView(Uu),Gu=Number(Vu.getBigUint64(0,!0));let Wu=[];for(let od=0;od<Gu;od++)Wu.push(Number(Vu.getBigUint64(8*(od+1),!0)));const Ku=new TextDecoder("utf8"),Ju=Ku.decode(Uu.slice(Wu[0],Wu[1])),Yu=JSON.parse(Ku.decode(Uu.slice(Wu[1],Wu[2]))),Xu=JSON.parse(Ku.decode(Uu.slice(Wu[2],Wu[3]))),ed=JSON.parse(Ku.decode(Uu.slice(Wu[3],Wu[4]))),td=JSON.parse(Ku.decode(Uu.slice(Wu[4],Wu[5])));let nd=[];for(let od=5;od<Wu.length-1;od++)nd.push(new DataView(Uu.slice(Wu[od],Wu[od+1])));return Hu={channel:Ju,header:Yu,parent_header:Xu,metadata:ed,content:td,buffers:nd},Hu}Mu.deserializeV1KernelWebsocketJupyterOrg=Du;function Lu(Uu){const Hu=JSON.stringify(Uu.header),Vu=Uu.parent_header==null?"{}":JSON.stringify(Uu.parent_header),Gu=JSON.stringify(Uu.metadata),Wu=JSON.stringify(Uu.content),Ku=Uu.buffers!==void 0?Uu.buffers:[],Ju=5+Ku.length+1;let Yu=[];Yu.push(8*(1+Ju)),Yu.push(Uu.channel.length+Yu[Yu.length-1]);const Xu=new TextEncoder,ed=Xu.encode(Uu.channel),td=Xu.encode(Hu),nd=Xu.encode(Vu),od=Xu.encode(Gu),sd=Xu.encode(Wu),ad=new Uint8Array(ed.length+td.length+nd.length+od.length+sd.length);ad.set(ed),ad.set(td,ed.length),ad.set(nd,ed.length+td.length),ad.set(od,ed.length+td.length+nd.length),ad.set(sd,ed.length+td.length+nd.length+od.length);for(let yd of[td.length,nd.length,od.length,sd.length])Yu.push(yd+Yu[Yu.length-1]);let pd=0;for(let yd of Ku){let wd=yd.byteLength;Yu.push(wd+Yu[Yu.length-1]),pd+=wd}const gd=new Uint8Array(8*(1+Ju)+ad.byteLength+pd),Sd=new ArrayBuffer(8),_d=new DataView(Sd);_d.setBigUint64(0,BigInt(Ju),!0),gd.set(new Uint8Array(Sd),0);for(let yd=0;yd<Yu.length;yd++)_d.setBigUint64(0,BigInt(Yu[yd]),!0),gd.set(new Uint8Array(Sd),8*(yd+1));gd.set(ad,Yu[0]);for(let yd=0;yd<Ku.length;yd++){const wd=Ku[yd];gd.set(new Uint8Array(ArrayBuffer.isView(wd)?wd.buffer:wd),Yu[5+yd])}return gd.buffer}Mu.serializeV1KernelWebsocketJupyterOrg=Lu;function Bu(Uu){let Hu;return typeof Uu=="string"?Hu=JSON.parse(Uu):Hu=Fu(Uu),Hu}Mu.deserializeDefault=Bu;function ju(Uu){var Hu;let Vu;return!((Hu=Uu.buffers)===null||Hu===void 0)&&Hu.length?Vu=zu(Uu):Vu=JSON.stringify(Uu),Vu}Mu.serializeDefault=ju;function Fu(Uu){const Hu=new DataView(Uu),Vu=Hu.getUint32(0),Gu=[];if(Vu<2)throw new Error("Invalid incoming Kernel Message");for(let Ju=1;Ju<=Vu;Ju++)Gu.push(Hu.getUint32(Ju*4));const Wu=new Uint8Array(Uu.slice(Gu[0],Gu[1])),Ku=JSON.parse(new TextDecoder("utf8").decode(Wu));Ku.buffers=[];for(let Ju=1;Ju<Vu;Ju++){const Yu=Gu[Ju],Xu=Gu[Ju+1]||Uu.byteLength;Ku.buffers.push(new DataView(Uu.slice(Yu,Xu)))}return Ku}function zu(Uu){const Hu=[],Vu=[],Gu=new TextEncoder;let Wu=[];Uu.buffers!==void 0&&(Wu=Uu.buffers,delete Uu.buffers);const Ku=Gu.encode(JSON.stringify(Uu));Vu.push(Ku.buffer);for(let ed=0;ed<Wu.length;ed++){const td=Wu[ed];Vu.push(ArrayBuffer.isView(td)?td.buffer:td)}const Ju=Vu.length;Hu.push(4*(Ju+1));for(let ed=0;ed+1<Vu.length;ed++)Hu.push(Hu[Hu.length-1]+Vu[ed].byteLength);const Yu=new Uint8Array(Hu[Hu.length-1]+Vu[Vu.length-1].byteLength),Xu=new DataView(Yu.buffer);Xu.setUint32(0,Ju);for(let ed=0;ed<Hu.length;ed++)Xu.setUint32(4*(ed+1),Hu[ed]);for(let ed=0;ed<Vu.length;ed++)Yu.set(new Uint8Array(Vu[ed]),Hu[ed]);return Yu.buffer}})(Ou||(Ou={})),serialize$2}var ws$1={},hasRequiredWs;function requireWs(){return hasRequiredWs||(hasRequiredWs=1,Object.defineProperty(ws$1,"__esModule",{value:!0}),ws$1.default=WebSocket),ws$1}var hasRequiredServerconnection;function requireServerconnection(){if(hasRequiredServerconnection)return serverconnection;hasRequiredServerconnection=1;var Au={};Object.defineProperty(serverconnection,"__esModule",{value:!0}),serverconnection.ServerConnection=void 0;const lo=requireLib$b(),$u=requireSerialize();let Ru;typeof window>"u"?Ru=requireWs():Ru=WebSocket;var Iu;(function(Ou){function Mu(ju){return Pu.makeSettings(ju)}Ou.makeSettings=Mu;function Du(ju,Fu,zu){return Pu.handleRequest(ju,Fu,zu)}Ou.makeRequest=Du;class Lu extends Error{static async create(Fu){try{const zu=await Fu.json(),{message:Uu,traceback:Hu}=zu;return Hu&&console.error(Hu),new Lu(Fu,Uu??Lu._defaultMessage(Fu),Hu??"")}catch(zu){return console.debug(zu),new Lu(Fu)}}constructor(Fu,zu=Lu._defaultMessage(Fu),Uu=""){super(zu),this.response=Fu,this.traceback=Uu}static _defaultMessage(Fu){return`Invalid response: ${Fu.status} ${Fu.statusText}`}}Ou.ResponseError=Lu;class Bu extends TypeError{constructor(Fu){super(Fu.message),this.stack=Fu.stack}}Ou.NetworkError=Bu})(Iu||(serverconnection.ServerConnection=Iu={}));var Pu;return(function(Ou){function Mu(Bu={}){var ju;const Fu=lo.PageConfig.getBaseUrl(),zu=lo.PageConfig.getWsUrl(),Uu=lo.URLExt.normalize(Bu.baseUrl)||Fu;let Hu=Bu.wsUrl;!Hu&&Uu===Fu&&(Hu=zu),!Hu&&Uu.indexOf("http")===0&&(Hu="ws"+Uu.slice(4)),Hu=Hu??zu;const Vu=lo.PageConfig.getOption("appendToken").toLowerCase();let Gu;return Vu===""?Gu=typeof window>"u"||typeof process<"u"&&((ju=process==null?void 0:Au)===null||ju===void 0?void 0:ju.JEST_WORKER_ID)!==void 0||lo.URLExt.getHostName(Fu)!==lo.URLExt.getHostName(Hu):Gu=Vu==="true",{init:{cache:"no-store",credentials:"same-origin"},fetch,Headers,Request,WebSocket:Ru,token:lo.PageConfig.getToken(),appUrl:lo.PageConfig.getOption("appUrl"),appendToken:Gu,serializer:{serialize:$u.serialize,deserialize:$u.deserialize},...Bu,baseUrl:Uu,wsUrl:Hu}}Ou.makeSettings=Mu;function Du(Bu,ju,Fu){var zu;if(Bu.indexOf(Fu.baseUrl)!==0)throw new Error("Can only be used for notebook server requests");((zu=ju.cache)!==null&&zu!==void 0?zu:Fu.init.cache)==="no-store"&&(Bu+=(/\?/.test(Bu)?"&":"?")+new Date().getTime());const Hu=new Fu.Request(Bu,{...Fu.init,...ju});let Vu=!1;if(Fu.token&&(Vu=!0,Hu.headers.append("Authorization",`token ${Fu.token}`)),typeof document<"u"){const Gu=Lu("_xsrf");Gu!==void 0&&(Vu=!0,Hu.headers.append("X-XSRFToken",Gu))}return!Hu.headers.has("Content-Type")&&Vu&&Hu.headers.set("Content-Type","application/json"),Fu.fetch.call(null,Hu).catch(Gu=>{throw new Iu.NetworkError(Gu)})}Ou.handleRequest=Du;function Lu(Bu){let ju="";try{ju=document.cookie}catch{return}const Fu=Bu+"=";let zu;for(const Uu of ju.split(";")){const Hu=Uu.trim();Hu.startsWith(Fu)&&(zu=Hu.substring(Fu.length))}return zu}})(Pu||(Pu={})),serverconnection}var hasRequiredBasemanager;function requireBasemanager(){if(hasRequiredBasemanager)return basemanager;hasRequiredBasemanager=1,Object.defineProperty(basemanager,"__esModule",{value:!0}),basemanager.BaseManager=void 0;const Au=require$$0$3,lo=requireServerconnection();class $u{constructor(Iu){var Pu;this._isDisposed=!1,this._disposed=new Au.Signal(this),this.serverSettings=(Pu=Iu.serverSettings)!==null&&Pu!==void 0?Pu:lo.ServerConnection.makeSettings()}get disposed(){return this._disposed}get isDisposed(){return this._isDisposed}get isActive(){return!0}dispose(){this.isDisposed||(this._isDisposed=!0,this._disposed.emit(void 0),Au.Signal.clearData(this))}}return basemanager.BaseManager=$u,basemanager}var config$4={},hasRequiredConfig;function requireConfig(){if(hasRequiredConfig)return config$4;hasRequiredConfig=1,Object.defineProperty(config$4,"__esModule",{value:!0}),config$4.ConfigWithDefaults=config$4.ConfigSection=config$4.ConfigSectionManager=void 0;const Au=requireLib$b(),lo=requireLib$8(),$u="api/config";class Ru{constructor(Du){var Lu;this.serverSettings=(Lu=Du.serverSettings)!==null&&Lu!==void 0?Lu:lo.ServerConnection.makeSettings()}async create(Du){const Lu=new Pu({...Du,serverSettings:this.serverSettings});return await Lu.load(),Lu}}config$4.ConfigSectionManager=Ru;var Iu;(function(Mu){async function Du(ju){if(!Lu){const zu=new Pu(ju);return await zu.load(),zu}return await Lu.create(ju)}Mu.create=Du;let Lu;function Bu(ju){if(Lu)throw new Error("ConfigSectionManager already set. If you would like to create a config section, use the `IConfigSectionManager` token in a plugin.");Lu=ju}Mu._setConfigSectionManager=Bu})(Iu||(config$4.ConfigSection=Iu={}));class Pu{constructor(Du){var Lu;this.serverSettings=(Lu=Du.serverSettings)!==null&&Lu!==void 0?Lu:lo.ServerConnection.makeSettings(),this._name=Du.name}get data(){return this._data}async load(){const Du=await lo.ServerConnection.makeRequest(this._url,{},this.serverSettings);if(Du.status!==200)throw await lo.ServerConnection.ResponseError.create(Du);this._data=await Du.json()}async update(Du){this._data={...this._data,...Du};const Lu={method:"PATCH",body:JSON.stringify(Du)},Bu=await lo.ServerConnection.makeRequest(this._url,Lu,this.serverSettings);if(Bu.status!==200)throw await lo.ServerConnection.ResponseError.create(Bu);return this._data=await Bu.json(),this._data}get _url(){return Au.URLExt.join(this.serverSettings.baseUrl,$u,encodeURIComponent(this._name))}}class Ou{constructor(Du){var Lu,Bu;this._className="",this._section=Du.section,this._defaults=(Lu=Du.defaults)!==null&&Lu!==void 0?Lu:{},this._className=(Bu=Du.className)!==null&&Bu!==void 0?Bu:""}get(Du){const Lu=this._classData();return Du in Lu?Lu[Du]:this._defaults[Du]}set(Du,Lu){const Bu={};if(Bu[Du]=Lu,this._className){const ju={};return ju[this._className]=Bu,this._section.update(ju)}else return this._section.update(Bu)}_classData(){const Du=this._section.data;return this._className&&this._className in Du?Du[this._className]:Du}}return config$4.ConfigWithDefaults=Ou,config$4}var connectionstatus={},hasRequiredConnectionstatus;function requireConnectionstatus(){if(hasRequiredConnectionstatus)return connectionstatus;hasRequiredConnectionstatus=1,Object.defineProperty(connectionstatus,"__esModule",{value:!0}),connectionstatus.ConnectionStatus=void 0;class Au{constructor(){this.isConnected=!0}}return connectionstatus.ConnectionStatus=Au,connectionstatus}var contents={};class DisposableDelegate{constructor(lo){this._fn=lo}get isDisposed(){return!this._fn}dispose(){if(!this._fn)return;let lo=this._fn;this._fn=null,lo()}}class ObservableDisposableDelegate extends DisposableDelegate{constructor(){super(...arguments),this._disposed=new Signal(this)}get disposed(){return this._disposed}dispose(){this.isDisposed||(super.dispose(),this._disposed.emit(void 0),Signal.clearData(this))}}class DisposableSet{constructor(){this._isDisposed=!1,this._items=new Set}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,this._items.forEach(lo=>{lo.dispose()}),this._items.clear())}contains(lo){return this._items.has(lo)}add(lo){this._items.add(lo)}remove(lo){this._items.delete(lo)}clear(){this._items.clear()}}(function(Au){function lo($u){let Ru=new Au;for(const Iu of $u)Ru.add(Iu);return Ru}Au.from=lo})(DisposableSet||(DisposableSet={}));class ObservableDisposableSet extends DisposableSet{constructor(){super(...arguments),this._disposed=new Signal(this)}get disposed(){return this._disposed}dispose(){this.isDisposed||(super.dispose(),this._disposed.emit(void 0),Signal.clearData(this))}}(function(Au){function lo($u){let Ru=new Au;for(const Iu of $u)Ru.add(Iu);return Ru}Au.from=lo})(ObservableDisposableSet||(ObservableDisposableSet={}));const index_es6$1=Object.freeze(Object.defineProperty({__proto__:null,DisposableDelegate,get DisposableSet(){return DisposableSet},ObservableDisposableDelegate,get ObservableDisposableSet(){return ObservableDisposableSet}},Symbol.toStringTag,{value:"Module"})),require$$1$2=getAugmentedNamespace(index_es6$1);var validate$7={},validate$6={},hasRequiredValidate$5;function requireValidate$5(){if(hasRequiredValidate$5)return validate$6;hasRequiredValidate$5=1,Object.defineProperty(validate$6,"__esModule",{value:!0}),validate$6.validateProperty=Au;function Au(lo,$u,Ru,Iu=[]){if(!lo.hasOwnProperty($u))throw Error(`Missing property '${$u}'`);const Pu=lo[$u];if(Ru!==void 0){let Ou;switch(Ru){case"array":Ou=Array.isArray(Pu);break;case"object":Ou=typeof Pu<"u";break;default:Ou=typeof Pu===Ru}if(!Ou)throw new Error(`Property '${$u}' is not of type '${Ru}'`);if(Iu.length>0){let Mu;switch(Ru){case"string":case"number":case"boolean":Mu=Iu.includes(Pu);break;default:Mu=Iu.findIndex(Du=>Du===Pu)>=0;break}if(!Mu)throw new Error(`Property '${$u}' is not one of the valid values ${JSON.stringify(Iu)}`)}}}return validate$6}var hasRequiredValidate$4;function requireValidate$4(){if(hasRequiredValidate$4)return validate$7;hasRequiredValidate$4=1,Object.defineProperty(validate$7,"__esModule",{value:!0}),validate$7.validateContentsModel=lo,validate$7.validateCheckpointModel=$u;const Au=requireValidate$5();function lo(Ru){(0,Au.validateProperty)(Ru,"name","string"),(0,Au.validateProperty)(Ru,"path","string"),(0,Au.validateProperty)(Ru,"type","string"),(0,Au.validateProperty)(Ru,"created","string"),(0,Au.validateProperty)(Ru,"last_modified","string"),(0,Au.validateProperty)(Ru,"mimetype","object"),(0,Au.validateProperty)(Ru,"content","object"),(0,Au.validateProperty)(Ru,"format","object")}function $u(Ru){(0,Au.validateProperty)(Ru,"id","string"),(0,Au.validateProperty)(Ru,"last_modified","string")}return validate$7}var hasRequiredContents;function requireContents(){if(hasRequiredContents)return contents;hasRequiredContents=1;var Au=contents&&contents.__createBinding||(Object.create?(function(Gu,Wu,Ku,Ju){Ju===void 0&&(Ju=Ku);var Yu=Object.getOwnPropertyDescriptor(Wu,Ku);(!Yu||("get"in Yu?!Wu.__esModule:Yu.writable||Yu.configurable))&&(Yu={enumerable:!0,get:function(){return Wu[Ku]}}),Object.defineProperty(Gu,Ju,Yu)}):(function(Gu,Wu,Ku,Ju){Ju===void 0&&(Ju=Ku),Gu[Ju]=Wu[Ku]})),lo=contents&&contents.__setModuleDefault||(Object.create?(function(Gu,Wu){Object.defineProperty(Gu,"default",{enumerable:!0,value:Wu})}):function(Gu,Wu){Gu.default=Wu}),$u=contents&&contents.__importStar||(function(){var Gu=function(Wu){return Gu=Object.getOwnPropertyNames||function(Ku){var Ju=[];for(var Yu in Ku)Object.prototype.hasOwnProperty.call(Ku,Yu)&&(Ju[Ju.length]=Yu);return Ju},Gu(Wu)};return function(Wu){if(Wu&&Wu.__esModule)return Wu;var Ku={};if(Wu!=null)for(var Ju=Gu(Wu),Yu=0;Yu<Ju.length;Yu++)Ju[Yu]!=="default"&&Au(Ku,Wu,Ju[Yu]);return lo(Ku,Wu),Ku}})();Object.defineProperty(contents,"__esModule",{value:!0}),contents.RestContentProvider=contents.ContentProviderRegistry=contents.Drive=contents.ContentsManager=contents.Contents=void 0;const Ru=requireLib$b(),Iu=requireDist(),Pu=require$$1$2,Ou=require$$0$3,Mu=requireLib$8(),Du=$u(requireValidate$4()),Lu="api/contents",Bu="files";var ju;(function(Gu){function Wu(Ju){Du.validateContentsModel(Ju)}Gu.validateContentsModel=Wu;function Ku(Ju){Du.validateCheckpointModel(Ju)}Gu.validateCheckpointModel=Ku})(ju||(contents.Contents=ju={}));class Fu{constructor(Wu={}){var Ku,Ju;this._isDisposed=!1,this._additionalDrives=new Map,this._fileChanged=new Ou.Signal(this);const Yu=this.serverSettings=(Ku=Wu.serverSettings)!==null&&Ku!==void 0?Ku:Mu.ServerConnection.makeSettings();this._defaultDrive=(Ju=Wu.defaultDrive)!==null&&Ju!==void 0?Ju:new zu({serverSettings:Yu}),this._defaultDrive.fileChanged.connect(this._onFileChanged,this)}get defaultDrive(){return this._defaultDrive}get fileChanged(){return this._fileChanged}get isDisposed(){return this._isDisposed}dispose(){this.isDisposed||(this._isDisposed=!0,Ou.Signal.clearData(this))}addDrive(Wu){this._additionalDrives.set(Wu.name,Wu),Wu.fileChanged.connect(this._onFileChanged,this)}getSharedModelFactory(Wu,Ku){var Ju,Yu;const[Xu]=this._driveForPath(Wu),ed=(Ju=Xu.contentProviderRegistry)===null||Ju===void 0?void 0:Ju.getProvider(Ku?.contentProviderId);return ed?.sharedModelFactory?ed.sharedModelFactory:(Yu=Xu.sharedModelFactory)!==null&&Yu!==void 0?Yu:null}localPath(Wu){const Ku=Wu.split("/"),Ju=Ku[0].split(":");return Ju.length===1||!this._additionalDrives.has(Ju[0])?Ru.PathExt.removeSlash(Wu):Ru.PathExt.join(Ju.slice(1).join(":"),...Ku.slice(1))}normalize(Wu){const Ku=Wu.split(":");return Ku.length===1?Ru.PathExt.normalize(Wu):`${Ku[0]}:${Ru.PathExt.normalize(Ku.slice(1).join(":"))}`}resolvePath(Wu,Ku){const Ju=this.driveName(Wu),Yu=this.localPath(Wu),Xu=Ru.PathExt.resolve("/",Yu,Ku);return Ju?`${Ju}:${Xu}`:Xu}driveName(Wu){const Ju=Wu.split("/")[0].split(":");return Ju.length===1?"":this._additionalDrives.has(Ju[0])?Ju[0]:""}get(Wu,Ku){const[Ju,Yu]=this._driveForPath(Wu);return Ju.get(Yu,Ku).then(Xu=>{const ed=[];if(Xu.type==="directory"&&Xu.content){for(const td of Xu.content)ed.push({...td,path:this._toGlobalPath(Ju,td.path)});return{...Xu,path:this._toGlobalPath(Ju,Yu),content:ed,serverPath:Xu.path}}else return{...Xu,path:this._toGlobalPath(Ju,Yu),serverPath:Xu.path}})}getDownloadUrl(Wu){const[Ku,Ju]=this._driveForPath(Wu);return Ku.getDownloadUrl(Ju)}newUntitled(Wu={}){if(Wu.path){const Ku=this.normalize(Wu.path),[Ju,Yu]=this._driveForPath(Ku);return Ju.newUntitled({...Wu,path:Yu}).then(Xu=>({...Xu,path:Ru.PathExt.join(Ku,Xu.name),serverPath:Xu.path}))}else return this._defaultDrive.newUntitled(Wu)}delete(Wu){const[Ku,Ju]=this._driveForPath(Wu);return Ku.delete(Ju)}rename(Wu,Ku){const[Ju,Yu]=this._driveForPath(Wu),[Xu,ed]=this._driveForPath(Ku);if(Ju!==Xu)throw Error("ContentsManager: renaming files must occur within a Drive");return Ju.rename(Yu,ed).then(td=>({...td,path:this._toGlobalPath(Ju,ed),serverPath:td.path}))}async overwrite(Wu,Ku){const Ju=`${Ku}.${Iu.UUID.uuid4()}`;return await this.rename(Wu,Ju),await this.delete(Ku),await this.rename(Ju,Ku)}save(Wu,Ku={}){const Ju=this.normalize(Wu),[Yu,Xu]=this._driveForPath(Wu);return Yu.save(Xu,{...Ku,path:Xu}).then(ed=>({...ed,path:Ju,serverPath:ed.path}))}copy(Wu,Ku){const[Ju,Yu]=this._driveForPath(Wu),[Xu,ed]=this._driveForPath(Ku);if(Ju===Xu)return Ju.copy(Yu,ed).then(td=>({...td,path:this._toGlobalPath(Ju,td.path),serverPath:td.path}));throw Error("Copying files between drives is not currently implemented")}createCheckpoint(Wu){const[Ku,Ju]=this._driveForPath(Wu);return Ku.createCheckpoint(Ju)}listCheckpoints(Wu){const[Ku,Ju]=this._driveForPath(Wu);return Ku.listCheckpoints(Ju)}restoreCheckpoint(Wu,Ku){const[Ju,Yu]=this._driveForPath(Wu);return Ju.restoreCheckpoint(Yu,Ku)}deleteCheckpoint(Wu,Ku){const[Ju,Yu]=this._driveForPath(Wu);return Ju.deleteCheckpoint(Yu,Ku)}_toGlobalPath(Wu,Ku){return Wu===this._defaultDrive?Ru.PathExt.removeSlash(Ku):`${Wu.name}:${Ru.PathExt.removeSlash(Ku)}`}_driveForPath(Wu){const Ku=this.driveName(Wu),Ju=this.localPath(Wu);return Ku?[this._additionalDrives.get(Ku),Ju]:[this._defaultDrive,Ju]}_onFileChanged(Wu,Ku){var Ju,Yu;if(Wu===this._defaultDrive)this._fileChanged.emit(Ku);else{let Xu=null,ed=null;!((Ju=Ku.newValue)===null||Ju===void 0)&&Ju.path&&(Xu={...Ku.newValue,path:this._toGlobalPath(Wu,Ku.newValue.path)}),!((Yu=Ku.oldValue)===null||Yu===void 0)&&Yu.path&&(ed={...Ku.oldValue,path:this._toGlobalPath(Wu,Ku.oldValue.path)}),this._fileChanged.emit({type:Ku.type,newValue:Xu,oldValue:ed})}}}contents.ContentsManager=Fu;class zu{constructor(Wu={}){var Ku,Ju,Yu;this._isDisposed=!1,this._fileChanged=new Ou.Signal(this),this.name=(Ku=Wu.name)!==null&&Ku!==void 0?Ku:"Default",this._apiEndpoint=(Ju=Wu.apiEndpoint)!==null&&Ju!==void 0?Ju:Lu,this.serverSettings=(Yu=Wu.serverSettings)!==null&&Yu!==void 0?Yu:Mu.ServerConnection.makeSettings(),this._restContentProvider=new Vu({...Wu,apiEndpoint:this._apiEndpoint,serverSettings:this.serverSettings}),Wu.defaultContentProvider?this.contentProviderRegistry=new Hu({defaultProvider:Wu.defaultContentProvider}):this.contentProviderRegistry=new Hu,this.contentProviderRegistry.fileChanged.connect((Xu,ed)=>{this._fileChanged.emit(ed)})}get fileChanged(){return this._fileChanged}get isDisposed(){return this._isDisposed}dispose(){this.isDisposed||(this._isDisposed=!0,Ou.Signal.clearData(this))}async get(Wu,Ku){const Ju=this.contentProviderRegistry.getProvider(Ku?.contentProviderId);return Ju?Ju.get(Wu,Ku):await this._restContentProvider.get(Wu,Ku)}getDownloadUrl(Wu){const Ku=this.serverSettings.baseUrl;let Ju=Ru.URLExt.join(Ku,Bu,Ru.URLExt.encodeParts(Wu)),Yu="";try{Yu=document.cookie}catch{}const Xu=Yu.match("\\b_xsrf=([^;]*)\\b");if(Xu){const ed=new URL(Ju);ed.searchParams.append("_xsrf",Xu[1]),Ju=ed.toString()}return Promise.resolve(Ju)}async newUntitled(Wu={}){var Ku;let Ju="{}";Wu&&(Wu.ext&&(Wu.ext=Uu.normalizeExtension(Wu.ext)),Ju=JSON.stringify(Wu));const Yu=this.serverSettings,Xu=this._getUrl((Ku=Wu.path)!==null&&Ku!==void 0?Ku:""),ed={method:"POST",body:Ju},td=await Mu.ServerConnection.makeRequest(Xu,ed,Yu);if(td.status!==201)throw await Mu.ServerConnection.ResponseError.create(td);const nd=await td.json();return Du.validateContentsModel(nd),this._fileChanged.emit({type:"new",oldValue:null,newValue:nd}),nd}async delete(Wu){const Ku=this._getUrl(Wu),Ju=this.serverSettings,Yu={method:"DELETE"},Xu=await Mu.ServerConnection.makeRequest(Ku,Yu,Ju);if(Xu.status!==204)throw await Mu.ServerConnection.ResponseError.create(Xu);this._fileChanged.emit({type:"delete",oldValue:{path:Wu},newValue:null})}async rename(Wu,Ku){const Ju=this.serverSettings,Yu=this._getUrl(Wu),Xu={method:"PATCH",body:JSON.stringify({path:Ku})},ed=await Mu.ServerConnection.makeRequest(Yu,Xu,Ju);if(ed.status!==200)throw await Mu.ServerConnection.ResponseError.create(ed);const td=await ed.json();return Du.validateContentsModel(td),this._fileChanged.emit({type:"rename",oldValue:{path:Wu},newValue:td}),td}async save(Wu,Ku={}){const Ju=this.contentProviderRegistry.getProvider(Ku?.contentProviderId);let Yu;return Ju?Yu=await Ju.save(Wu,Ku):Yu=await this._restContentProvider.save(Wu,Ku),this._fileChanged.emit({type:"save",oldValue:null,newValue:Yu}),Yu}async copy(Wu,Ku){const Ju=this.serverSettings,Yu=this._getUrl(Ku),Xu={method:"POST",body:JSON.stringify({copy_from:Wu})},ed=await Mu.ServerConnection.makeRequest(Yu,Xu,Ju);if(ed.status!==201)throw await Mu.ServerConnection.ResponseError.create(ed);const td=await ed.json();return Du.validateContentsModel(td),this._fileChanged.emit({type:"new",oldValue:null,newValue:td}),td}async createCheckpoint(Wu){const Ku=this._getUrl(Wu,"checkpoints"),Ju={method:"POST"},Yu=await Mu.ServerConnection.makeRequest(Ku,Ju,this.serverSettings);if(Yu.status!==201)throw await Mu.ServerConnection.ResponseError.create(Yu);const Xu=await Yu.json();return Du.validateCheckpointModel(Xu),Xu}async listCheckpoints(Wu){const Ku=this._getUrl(Wu,"checkpoints"),Ju=await Mu.ServerConnection.makeRequest(Ku,{},this.serverSettings);if(Ju.status!==200)throw await Mu.ServerConnection.ResponseError.create(Ju);const Yu=await Ju.json();if(!Array.isArray(Yu))throw new Error("Invalid Checkpoint list");for(let Xu=0;Xu<Yu.length;Xu++)Du.validateCheckpointModel(Yu[Xu]);return Yu}async restoreCheckpoint(Wu,Ku){const Ju=this._getUrl(Wu,"checkpoints",Ku),Yu={method:"POST"},Xu=await Mu.ServerConnection.makeRequest(Ju,Yu,this.serverSettings);if(Xu.status!==204)throw await Mu.ServerConnection.ResponseError.create(Xu)}async deleteCheckpoint(Wu,Ku){const Ju=this._getUrl(Wu,"checkpoints",Ku),Yu={method:"DELETE"},Xu=await Mu.ServerConnection.makeRequest(Ju,Yu,this.serverSettings);if(Xu.status!==204)throw await Mu.ServerConnection.ResponseError.create(Xu)}_getUrl(...Wu){const Ku=Wu.map(Yu=>Ru.URLExt.encodeParts(Yu)),Ju=this.serverSettings.baseUrl;return Ru.URLExt.join(Ju,this._apiEndpoint,...Ku)}}contents.Drive=zu;var Uu;(function(Gu){function Wu(Ku){return Ku.length>0&&Ku.indexOf(".")!==0&&(Ku=`.${Ku}`),Ku}Gu.normalizeExtension=Wu})(Uu||(Uu={}));class Hu{constructor(Wu){this._providers=new Map,this._fileChanged=new Ou.Signal(this),Wu?.defaultProvider&&this.register("default",Wu.defaultProvider)}register(Wu,Ku){if(this._providers.has(Wu))throw Error(`Provider with ${Wu} identifier was already registered on this drive`);this._providers.set(Wu,Ku);const Ju=(Yu,Xu)=>{this._fileChanged.emit(Xu)};return Ku.fileChanged&&Ku.fileChanged.connect(Ju),new Pu.DisposableDelegate(()=>{Ku.fileChanged&&Ku.fileChanged.disconnect(Ju),this._providers.has(Wu)&&this._providers.delete(Wu)})}getProvider(Wu){if(!Wu)return null;const Ku=this._providers.get(Wu);if(!Ku)throw Error(`Provider ${Wu} is not registered`);return Ku}get fileChanged(){return this._fileChanged}}contents.ContentProviderRegistry=Hu;class Vu{constructor(Wu){this._options=Wu}async get(Wu,Ku){let Ju=this._getUrl(Wu);if(Ku){Ku.type==="notebook"&&delete Ku.format;const td=Ku.content?"1":"0",nd=Ku.hash?"1":"0",od={...Ku,content:td,hash:nd};Ju+=Ru.URLExt.objectToQueryString(od)}const Yu=this._options.serverSettings,Xu=await Mu.ServerConnection.makeRequest(Ju,{},Yu);if(Xu.status!==200)throw await Mu.ServerConnection.ResponseError.create(Xu);const ed=await Xu.json();return Du.validateContentsModel(ed),ed}async save(Wu,Ku={}){const Ju=this._options.serverSettings,Yu=this._getUrl(Wu),ed={method:"PUT",body:new File([JSON.stringify(Ku)],"data.json",{type:"application/json"})},td=await Mu.ServerConnection.makeRequest(Yu,ed,Ju);if(td.status!==200&&td.status!==201)throw await Mu.ServerConnection.ResponseError.create(td);const nd=await td.json();return Du.validateContentsModel(nd),nd}_getUrl(...Wu){const Ku=Wu.map(Yu=>Ru.URLExt.encodeParts(Yu)),Ju=this._options.serverSettings.baseUrl;return Ru.URLExt.join(Ju,this._options.apiEndpoint,...Ku)}}return contents.RestContentProvider=Vu,contents}var event={};const require$$1$1=getAugmentedNamespace(index_es6$2);var hasRequiredEvent;function requireEvent(){if(hasRequiredEvent)return event;hasRequiredEvent=1,Object.defineProperty(event,"__esModule",{value:!0}),event.EventManager=void 0;const Au=requireLib$b(),lo=require$$1$1,$u=require$$0$3,Ru=requireServerconnection(),Iu="api/events";class Pu{constructor(Mu={}){var Du,Lu;this._socket=null,this.serverSettings=(Du=Mu.serverSettings)!==null&&Du!==void 0?Du:Ru.ServerConnection.makeSettings(),this._poll=new lo.Poll({factory:()=>this._subscribe(),standby:(Lu=Mu.standby)!==null&&Lu!==void 0?Lu:"when-hidden"}),this._stream=new $u.Stream(this),this._poll.start()}get isDisposed(){return this._poll.isDisposed}get stream(){return this._stream}dispose(){if(this.isDisposed)return;this._poll.dispose();const Mu=this._socket;Mu&&(this._socket=null,Mu.onopen=()=>{},Mu.onerror=()=>{},Mu.onmessage=()=>{},Mu.onclose=()=>{},Mu.close()),$u.Signal.clearData(this),this._stream.stop()}async emit(Mu){const{serverSettings:Du}=this,{baseUrl:Lu}=Du,{makeRequest:Bu,ResponseError:ju}=Ru.ServerConnection,Fu=Au.URLExt.join(Lu,Iu),zu={body:JSON.stringify(Mu),method:"POST"},Uu=await Bu(Fu,zu,Du);if(Uu.status!==204)throw new ju(Uu)}_subscribe(){return new Promise((Mu,Du)=>{if(this.isDisposed)return;const{appendToken:Lu,token:Bu,WebSocket:ju,wsUrl:Fu}=this.serverSettings;let zu=Au.URLExt.join(Fu,Iu,"subscribe");Lu&&Bu!==""&&(zu+=`?token=${encodeURIComponent(Bu)}`);const Uu=this._socket=new ju(zu),Hu=this._stream;Uu.onclose=()=>Du(new Error("EventManager socket closed")),Uu.onmessage=Vu=>Vu.data&&Hu.emit(JSON.parse(Vu.data))})}}return event.EventManager=Pu,event}var kernel$1={},comm={},hasRequiredComm;function requireComm(){if(hasRequiredComm)return comm;hasRequiredComm=1;var Au=comm&&comm.__createBinding||(Object.create?(function(Du,Lu,Bu,ju){ju===void 0&&(ju=Bu);var Fu=Object.getOwnPropertyDescriptor(Lu,Bu);(!Fu||("get"in Fu?!Lu.__esModule:Fu.writable||Fu.configurable))&&(Fu={enumerable:!0,get:function(){return Lu[Bu]}}),Object.defineProperty(Du,ju,Fu)}):(function(Du,Lu,Bu,ju){ju===void 0&&(ju=Bu),Du[ju]=Lu[Bu]})),lo=comm&&comm.__setModuleDefault||(Object.create?(function(Du,Lu){Object.defineProperty(Du,"default",{enumerable:!0,value:Lu})}):function(Du,Lu){Du.default=Lu}),$u=comm&&comm.__importStar||(function(){var Du=function(Lu){return Du=Object.getOwnPropertyNames||function(Bu){var ju=[];for(var Fu in Bu)Object.prototype.hasOwnProperty.call(Bu,Fu)&&(ju[ju.length]=Fu);return ju},Du(Lu)};return function(Lu){if(Lu&&Lu.__esModule)return Lu;var Bu={};if(Lu!=null)for(var ju=Du(Lu),Fu=0;Fu<ju.length;Fu++)ju[Fu]!=="default"&&Au(Bu,Lu,ju[Fu]);return lo(Bu,Lu),Bu}})();Object.defineProperty(comm,"__esModule",{value:!0}),comm.CommHandler=comm.CommsOverSubshells=void 0;const Ru=requireDist(),Iu=require$$1$2,Pu=$u(requireMessages());var Ou;(function(Du){Du.Disabled="disabled",Du.PerComm="perComm",Du.PerCommTarget="perCommTarget"})(Ou||(comm.CommsOverSubshells=Ou={}));class Mu extends Iu.DisposableDelegate{constructor(Lu,Bu,ju,Fu,zu){super(Fu),this._subshellStarted=new Ru.PromiseDelegate,this._subshellId=null,this._target="",this._id="",this._id=Bu,this._target=Lu,this._kernel=ju,this._kernel.statusChanged.connect(()=>{this._kernel.status==="restarting"&&this._cleanSubshells()}),this.commsOverSubshells=zu??Ou.PerCommTarget}get commId(){return this._id}get targetName(){return this._target}get subshellId(){return this._subshellId}get subshellStarted(){return this._subshellStarted.promise}get commsOverSubshells(){return this._commsOverSubshells}set commsOverSubshells(Lu){if(Lu===this._commsOverSubshells)return;const Bu=this._maybeCloseSubshell(this._commsOverSubshells);this._commsOverSubshells=Lu,Bu.then(()=>{this._commsOverSubshells!==Ou.Disabled&&this._maybeStartSubshell()}).catch(console.warn)}get onClose(){return this._onClose}set onClose(Lu){this._onClose=Lu}get onMsg(){return this._onMsg}set onMsg(Lu){this._onMsg=Lu}open(Lu,Bu,ju=[]){if(this.isDisposed||this._kernel.isDisposed)throw new Error("Cannot open");const Fu=Pu.createMessage({msgType:"comm_open",channel:"shell",username:this._kernel.username,session:this._kernel.clientId,subshellId:this._subshellId||this._kernel.subshellId,content:{comm_id:this._id,target_name:this._target,data:Lu??{}},metadata:Bu,buffers:ju});return this._kernel.sendShellMessage(Fu,!1,!0)}send(Lu,Bu,ju=[],Fu=!0){if(this.isDisposed||this._kernel.isDisposed)throw new Error("Cannot send");const zu=Pu.createMessage({msgType:"comm_msg",channel:"shell",username:this._kernel.username,session:this._kernel.clientId,subshellId:this._subshellId||this._kernel.subshellId,content:{comm_id:this._id,data:Lu},metadata:Bu,buffers:ju});return this._kernel.sendShellMessage(zu,!1,Fu)}close(Lu,Bu,ju=[]){if(this.isDisposed||this._kernel.isDisposed)throw new Error("Cannot close");const Fu=Pu.createMessage({msgType:"comm_close",channel:"shell",username:this._kernel.username,session:this._kernel.clientId,subshellId:this._subshellId||this._kernel.subshellId,content:{comm_id:this._id,data:Lu??{}},metadata:Bu,buffers:ju}),zu=this._kernel.sendShellMessage(Fu,!1,!0),Uu=this._onClose;if(Uu){const Hu=Pu.createMessage({msgType:"comm_close",channel:"iopub",username:this._kernel.username,session:this._kernel.clientId,subshellId:this._subshellId||this._kernel.subshellId,content:{comm_id:this._id,data:Lu??{}},metadata:Bu,buffers:ju});Uu(Hu)}return this.dispose(),zu}dispose(){this._maybeCloseSubshell(this._commsOverSubshells),super.dispose()}_cleanSubshells(){const Lu=this._kernel.id;Mu._commTargetSubShellsId.hasOwnProperty(Lu)&&delete Mu._commTargetSubShellsId[Lu]}async _maybeStartSubshell(){if(await this._kernel.info,!this._kernel.supportsSubshells)return;if(this._commsOverSubshells===Ou.PerComm){const Uu=await this._kernel.requestCreateSubshell({}).done;this._subshellId=Uu.content.subshell_id,this._subshellStarted.resolve();return}const Lu=this._subshellStarted,Bu=this._kernel.id;Mu._commTargetSubShellsId.hasOwnProperty(Bu)||(Mu._commTargetSubShellsId[Bu]={});const ju=Mu._commTargetSubShellsId[Bu],Fu=ju[this._target];if(Fu){Fu.referenceCount+=1;try{this._subshellId=await Fu.subshellId,Lu.resolve()}catch(Uu){await this._closePerCommTargetSubshell(!1),Lu.reject(`Per comm-target subshell creation failed: ${Uu}`)}return}const zu={subshellId:this._kernel.requestCreateSubshell({}).done.then(Uu=>Uu.content.subshell_id),referenceCount:1};ju[this._target]=zu;try{this._subshellId=await zu.subshellId,Lu.resolve()}catch(Uu){await this._closePerCommTargetSubshell(!1),Lu.reject(`Per comm-target subshell creation failed: ${Uu}`)}}async _closePerCommTargetSubshell(Lu=!0){const Bu=this._kernel.id,ju=this._target;if(Mu._commTargetSubShellsId.hasOwnProperty(Bu)){const Fu=Mu._commTargetSubShellsId[Bu],zu=Fu[ju];if(zu&&(zu.referenceCount-=1,zu.referenceCount<=0)){if(Lu){let Uu=null;try{Uu=await zu.subshellId}catch(Hu){console.warn(`Subshell identifier not available in the closeout sequence, will not request deletion: ${Hu}`)}Uu!==null&&this._kernel.requestDeleteSubshell({subshell_id:Uu},!0)}delete Fu[ju]}Object.keys(Fu).length===0&&delete Mu._commTargetSubShellsId[Bu],this._subshellId=null}this._subshellStarted=new Ru.PromiseDelegate}async _maybeCloseSubshell(Lu){if(this._kernel.status!=="dead")switch(Lu){case Ou.PerComm:{this._subshellId&&(this._kernel.requestDeleteSubshell({subshell_id:this._subshellId},!0),this._subshellId=null),this._subshellStarted=new Ru.PromiseDelegate;break}case Ou.PerCommTarget:{await this._closePerCommTargetSubshell();break}case Ou.Disabled:break}}}return comm.CommHandler=Mu,Mu._commTargetSubShellsId={},comm}var kernel={},hasRequiredKernel$1;function requireKernel$1(){return hasRequiredKernel$1||(hasRequiredKernel$1=1,Object.defineProperty(kernel,"__esModule",{value:!0})),kernel}var restapi$4={},validate$5={},hasRequiredValidate$3;function requireValidate$3(){if(hasRequiredValidate$3)return validate$5;hasRequiredValidate$3=1,Object.defineProperty(validate$5,"__esModule",{value:!0}),validate$5.validateMessage=Iu,validate$5.validateModel=Ou,validate$5.validateModels=Mu;const Au=requireValidate$5(),lo=["username","version","session","msg_id","msg_type"],$u={stream:{name:"string",text:"string"},display_data:{data:"object",metadata:"object"},execute_input:{code:"string",execution_count:"number"},execute_result:{execution_count:"number",data:"object",metadata:"object"},error:{ename:"string",evalue:"string",traceback:"object"},status:{execution_state:["string",["starting","idle","busy","restarting","dead"]]},clear_output:{wait:"boolean"},comm_open:{comm_id:"string",target_name:"string",data:"object"},comm_msg:{comm_id:"string",data:"object"},comm_close:{comm_id:"string"},shutdown_reply:{restart:"boolean"}};function Ru(Du){for(let Lu=0;Lu<lo.length;Lu++)(0,Au.validateProperty)(Du,lo[Lu],"string")}function Iu(Du){(0,Au.validateProperty)(Du,"metadata","object"),(0,Au.validateProperty)(Du,"content","object"),(0,Au.validateProperty)(Du,"channel","string"),Ru(Du.header),Du.channel==="iopub"&&Pu(Du)}function Pu(Du){if(Du.channel==="iopub"){const Lu=$u[Du.header.msg_type];if(Lu===void 0)return;const Bu=Object.keys(Lu),ju=Du.content;for(let Fu=0;Fu<Bu.length;Fu++){let zu=Lu[Bu[Fu]];Array.isArray(zu)||(zu=[zu]),(0,Au.validateProperty)(ju,Bu[Fu],...zu)}}}function Ou(Du){(0,Au.validateProperty)(Du,"name","string"),(0,Au.validateProperty)(Du,"id","string")}function Mu(Du){if(!Array.isArray(Du))throw new Error("Invalid kernel list");Du.forEach(Lu=>Ou(Lu))}return validate$5}var hasRequiredRestapi$4;function requireRestapi$4(){return hasRequiredRestapi$4||(hasRequiredRestapi$4=1,(function(Au){Object.defineProperty(Au,"__esModule",{value:!0}),Au.KernelAPIClient=Au.KERNEL_SERVICE_URL=void 0,Au.listRunning=Iu,Au.startNew=Pu,Au.restartKernel=Ou,Au.interruptKernel=Mu,Au.shutdownKernel=Du,Au.getKernelModel=Lu;const lo=requireServerconnection(),$u=requireLib$b(),Ru=requireValidate$3();Au.KERNEL_SERVICE_URL="api/kernels";async function Iu(ju=lo.ServerConnection.makeSettings()){const Fu=$u.URLExt.join(ju.baseUrl,Au.KERNEL_SERVICE_URL),zu=await lo.ServerConnection.makeRequest(Fu,{},ju);if(zu.status!==200)throw await lo.ServerConnection.ResponseError.create(zu);const Uu=await zu.json();return(0,Ru.validateModels)(Uu),Uu}async function Pu(ju={},Fu=lo.ServerConnection.makeSettings()){const zu=$u.URLExt.join(Fu.baseUrl,Au.KERNEL_SERVICE_URL),Uu={method:"POST",body:JSON.stringify(ju)},Hu=await lo.ServerConnection.makeRequest(zu,Uu,Fu);if(Hu.status!==201)throw await lo.ServerConnection.ResponseError.create(Hu);const Vu=await Hu.json();return(0,Ru.validateModel)(Vu),Vu}async function Ou(ju,Fu=lo.ServerConnection.makeSettings()){const zu=$u.URLExt.join(Fu.baseUrl,Au.KERNEL_SERVICE_URL,encodeURIComponent(ju),"restart"),Uu={method:"POST"},Hu=await lo.ServerConnection.makeRequest(zu,Uu,Fu);if(Hu.status!==200)throw await lo.ServerConnection.ResponseError.create(Hu);const Vu=await Hu.json();(0,Ru.validateModel)(Vu)}async function Mu(ju,Fu=lo.ServerConnection.makeSettings()){const zu=$u.URLExt.join(Fu.baseUrl,Au.KERNEL_SERVICE_URL,encodeURIComponent(ju),"interrupt"),Uu={method:"POST"},Hu=await lo.ServerConnection.makeRequest(zu,Uu,Fu);if(Hu.status!==204)throw await lo.ServerConnection.ResponseError.create(Hu)}async function Du(ju,Fu=lo.ServerConnection.makeSettings()){const zu=$u.URLExt.join(Fu.baseUrl,Au.KERNEL_SERVICE_URL,encodeURIComponent(ju)),Uu={method:"DELETE"},Hu=await lo.ServerConnection.makeRequest(zu,Uu,Fu);if(Hu.status===404){const Vu=`The kernel "${ju}" does not exist on the server`;console.warn(Vu)}else if(Hu.status!==204)throw await lo.ServerConnection.ResponseError.create(Hu)}async function Lu(ju,Fu=lo.ServerConnection.makeSettings()){const zu=$u.URLExt.join(Fu.baseUrl,Au.KERNEL_SERVICE_URL,encodeURIComponent(ju)),Uu=await lo.ServerConnection.makeRequest(zu,{},Fu);if(Uu.status===404)return;if(Uu.status!==200)throw await lo.ServerConnection.ResponseError.create(Uu);const Hu=await Uu.json();return(0,Ru.validateModel)(Hu),Hu}class Bu{constructor(Fu={}){var zu;this.serverSettings=(zu=Fu.serverSettings)!==null&&zu!==void 0?zu:lo.ServerConnection.makeSettings()}async listRunning(){return Iu(this.serverSettings)}async getModel(Fu){return Lu(Fu,this.serverSettings)}async startNew(Fu={}){return Pu(Fu,this.serverSettings)}async restart(Fu){return Ou(Fu,this.serverSettings)}async interrupt(Fu){return Mu(Fu,this.serverSettings)}async shutdown(Fu){return Du(Fu,this.serverSettings)}}Au.KernelAPIClient=Bu})(restapi$4)),restapi$4}var _default$3={},future={},hasRequiredFuture;function requireFuture(){if(hasRequiredFuture)return future;hasRequiredFuture=1;var Au=future&&future.__createBinding||(Object.create?(function(Bu,ju,Fu,zu){zu===void 0&&(zu=Fu);var Uu=Object.getOwnPropertyDescriptor(ju,Fu);(!Uu||("get"in Uu?!ju.__esModule:Uu.writable||Uu.configurable))&&(Uu={enumerable:!0,get:function(){return ju[Fu]}}),Object.defineProperty(Bu,zu,Uu)}):(function(Bu,ju,Fu,zu){zu===void 0&&(zu=Fu),Bu[zu]=ju[Fu]})),lo=future&&future.__setModuleDefault||(Object.create?(function(Bu,ju){Object.defineProperty(Bu,"default",{enumerable:!0,value:ju})}):function(Bu,ju){Bu.default=ju}),$u=future&&future.__importStar||(function(){var Bu=function(ju){return Bu=Object.getOwnPropertyNames||function(Fu){var zu=[];for(var Uu in Fu)Object.prototype.hasOwnProperty.call(Fu,Uu)&&(zu[zu.length]=Uu);return zu},Bu(ju)};return function(ju){if(ju&&ju.__esModule)return ju;var Fu={};if(ju!=null)for(var zu=Bu(ju),Uu=0;Uu<zu.length;Uu++)zu[Uu]!=="default"&&Au(Fu,ju,zu[Uu]);return lo(Fu,ju),Fu}})();Object.defineProperty(future,"__esModule",{value:!0}),future.KernelShellFutureHandler=future.KernelControlFutureHandler=future.KernelFutureHandler=void 0;const Ru=requireDist(),Iu=require$$1$2,Pu=$u(requireMessages());class Ou extends Iu.DisposableDelegate{constructor(ju,Fu,zu,Uu,Hu){super(ju),this._status=0,this._stdin=Lu.noOp,this._iopub=Lu.noOp,this._reply=Lu.noOp,this._done=new Ru.PromiseDelegate,this._hooks=new Lu.HookList,this._disposeOnDone=!0,this._msg=Fu,zu||this._setFlag(Lu.KernelFutureFlag.GotReply),this._disposeOnDone=Uu,this._kernel=Hu}get msg(){return this._msg}get done(){return this._done.promise}get onReply(){return this._reply}set onReply(ju){this._reply=ju}get onIOPub(){return this._iopub}set onIOPub(ju){this._iopub=ju}get onStdin(){return this._stdin}set onStdin(ju){this._stdin=ju}registerMessageHook(ju){if(this.isDisposed)throw new Error("Kernel future is disposed");this._hooks.add(ju)}removeMessageHook(ju){this.isDisposed||this._hooks.remove(ju)}sendInputReply(ju,Fu){this._kernel.sendInputReply(ju,Fu)}dispose(){this._stdin=Lu.noOp,this._iopub=Lu.noOp,this._reply=Lu.noOp,this._hooks=null,this._testFlag(Lu.KernelFutureFlag.IsDone)||(this._done.promise.catch(()=>{}),this._done.reject(new Error(`Canceled future for ${this.msg.header.msg_type} message before replies were done`))),super.dispose()}async handleMsg(ju){switch(ju.channel){case"control":case"shell":ju.channel===this.msg.channel&&ju.parent_header.msg_id===this.msg.header.msg_id&&await this._handleReply(ju);break;case"stdin":await this._handleStdin(ju);break;case"iopub":await this._handleIOPub(ju);break}}async _handleReply(ju){const Fu=this._reply;Fu&&await Fu(ju),this._replyMsg=ju,this._setFlag(Lu.KernelFutureFlag.GotReply),this._testFlag(Lu.KernelFutureFlag.GotIdle)&&this._handleDone()}async _handleStdin(ju){this._kernel.hasPendingInput=!0;const Fu=this._stdin;Fu&&await Fu(ju)}async _handleIOPub(ju){const Fu=await this._hooks.process(ju),zu=this._iopub;Fu&&zu&&await zu(ju),Pu.isStatusMsg(ju)&&ju.content.execution_state==="idle"&&(this._setFlag(Lu.KernelFutureFlag.GotIdle),this._testFlag(Lu.KernelFutureFlag.GotReply)&&this._handleDone())}_handleDone(){this._testFlag(Lu.KernelFutureFlag.IsDone)||(this._setFlag(Lu.KernelFutureFlag.IsDone),this._done.resolve(this._replyMsg),this._disposeOnDone&&this.dispose())}_testFlag(ju){return(this._status&ju)!==0}_setFlag(ju){this._status|=ju}}future.KernelFutureHandler=Ou;class Mu extends Ou{}future.KernelControlFutureHandler=Mu;class Du extends Ou{}future.KernelShellFutureHandler=Du;var Lu;return(function(Bu){Bu.noOp=()=>{};const ju=typeof requestAnimationFrame=="function"?requestAnimationFrame:setImmediate;class Fu{constructor(){this._hooks=[]}add(Uu){this.remove(Uu),this._hooks.push(Uu)}remove(Uu){const Hu=this._hooks.indexOf(Uu);Hu>=0&&(this._hooks[Hu]=null,this._scheduleCompact())}async process(Uu){await this._processing;const Hu=new Ru.PromiseDelegate;this._processing=Hu.promise;let Vu;for(let Gu=this._hooks.length-1;Gu>=0;Gu--){const Wu=this._hooks[Gu];if(Wu!==null){try{Vu=await Wu(Uu)}catch(Ku){Vu=!0,console.error(Ku)}if(Vu===!1)return Hu.resolve(void 0),!1}}return Hu.resolve(void 0),!0}_scheduleCompact(){this._compactScheduled||(this._compactScheduled=!0,ju(()=>{this._processing=this._processing.then(()=>{this._compactScheduled=!1,this._compact()})}))}_compact(){let Uu=0;for(let Hu=0,Vu=this._hooks.length;Hu<Vu;Hu++){const Gu=this._hooks[Hu];this._hooks[Hu]===null?Uu++:this._hooks[Hu-Uu]=Gu}this._hooks.length-=Uu}}Bu.HookList=Fu,(function(zu){zu[zu.GotReply=1]="GotReply",zu[zu.GotIdle=2]="GotIdle",zu[zu.IsDone=4]="IsDone",zu[zu.DisposeOnDone=8]="DisposeOnDone"})(Bu.KernelFutureFlag||(Bu.KernelFutureFlag={}))})(Lu||(Lu={})),future}var restapi$3={},validate$4={},hasRequiredValidate$2;function requireValidate$2(){if(hasRequiredValidate$2)return validate$4;hasRequiredValidate$2=1,Object.defineProperty(validate$4,"__esModule",{value:!0}),validate$4.validateSpecModel=lo,validate$4.validateSpecModels=$u;const Au=requireValidate$5();function lo(Ru){const Iu=Ru.spec;if(!Iu)throw new Error("Invalid kernel spec");(0,Au.validateProperty)(Ru,"name","string"),(0,Au.validateProperty)(Ru,"resources","object"),(0,Au.validateProperty)(Iu,"language","string"),(0,Au.validateProperty)(Iu,"display_name","string"),(0,Au.validateProperty)(Iu,"argv","array");let Pu=null;Iu.hasOwnProperty("metadata")&&((0,Au.validateProperty)(Iu,"metadata","object"),Pu=Iu.metadata);let Ou=null;return Iu.hasOwnProperty("env")&&((0,Au.validateProperty)(Iu,"env","object"),Ou=Iu.env),Iu.hasOwnProperty("interrupt_mode")&&((0,Au.validateProperty)(Iu,"interrupt_mode","string"),Ou=Iu.env),{name:Ru.name,resources:Ru.resources,language:Iu.language,display_name:Iu.display_name,argv:Iu.argv,metadata:Pu,env:Ou}}function $u(Ru){if(!Ru.hasOwnProperty("kernelspecs"))throw new Error("No kernelspecs found");let Iu=Object.keys(Ru.kernelspecs);const Pu=Object.create(null);let Ou=Ru.default;for(let Mu=0;Mu<Iu.length;Mu++){const Du=Ru.kernelspecs[Iu[Mu]];try{Pu[Iu[Mu]]=lo(Du)}catch{console.warn(`Removing errant kernel spec: ${Iu[Mu]}`)}}if(Iu=Object.keys(Pu),!Iu.length)throw new Error("No valid kernelspecs found");return(!Ou||typeof Ou!="string"||!(Ou in Pu))&&(Ou=Iu[0],console.warn(`Default kernel not found, using '${Iu[0]}'`)),{default:Ou,kernelspecs:Pu}}return validate$4}var hasRequiredRestapi$3;function requireRestapi$3(){if(hasRequiredRestapi$3)return restapi$3;hasRequiredRestapi$3=1,Object.defineProperty(restapi$3,"__esModule",{value:!0}),restapi$3.KernelSpecAPIClient=void 0,restapi$3.getSpecs=Iu;const Au=requireServerconnection(),lo=requireValidate$2(),$u=requireLib$b(),Ru="api/kernelspecs";async function Iu(Ou=Au.ServerConnection.makeSettings()){const Mu=$u.URLExt.join(Ou.baseUrl,Ru),Du=await Au.ServerConnection.makeRequest(Mu,{},Ou);if(Du.status!==200)throw await Au.ServerConnection.ResponseError.create(Du);const Lu=await Du.json();return(0,lo.validateSpecModels)(Lu)}class Pu{constructor(Mu={}){var Du;this.serverSettings=(Du=Mu.serverSettings)!==null&&Du!==void 0?Du:Au.ServerConnection.makeSettings()}async get(){return Iu(this.serverSettings)}}return restapi$3.KernelSpecAPIClient=Pu,restapi$3}var hasRequired_default$2;function require_default$2(){return hasRequired_default$2||(hasRequired_default$2=1,(function(Au){var lo=_default$3&&_default$3.__createBinding||(Object.create?(function(Wu,Ku,Ju,Yu){Yu===void 0&&(Yu=Ju);var Xu=Object.getOwnPropertyDescriptor(Ku,Ju);(!Xu||("get"in Xu?!Ku.__esModule:Xu.writable||Xu.configurable))&&(Xu={enumerable:!0,get:function(){return Ku[Ju]}}),Object.defineProperty(Wu,Yu,Xu)}):(function(Wu,Ku,Ju,Yu){Yu===void 0&&(Yu=Ju),Wu[Yu]=Ku[Ju]})),$u=_default$3&&_default$3.__setModuleDefault||(Object.create?(function(Wu,Ku){Object.defineProperty(Wu,"default",{enumerable:!0,value:Ku})}):function(Wu,Ku){Wu.default=Ku}),Ru=_default$3&&_default$3.__importStar||(function(){var Wu=function(Ku){return Wu=Object.getOwnPropertyNames||function(Ju){var Yu=[];for(var Xu in Ju)Object.prototype.hasOwnProperty.call(Ju,Xu)&&(Yu[Yu.length]=Xu);return Yu},Wu(Ku)};return function(Ku){if(Ku&&Ku.__esModule)return Ku;var Ju={};if(Ku!=null)for(var Yu=Wu(Ku),Xu=0;Xu<Yu.length;Xu++)Yu[Xu]!=="default"&&lo(Ju,Ku,Yu[Xu]);return $u(Ju,Ku),Ju}})();Object.defineProperty(Au,"__esModule",{value:!0}),Au.KernelConnection=Au.DEFAULT_KERNEL_INFO_TIMEOUT=void 0;const Iu=requireLib$b(),Pu=requireDist(),Ou=require$$0$3,Mu=requireLib$8(),Du=requireComm(),Lu=Ru(requireMessages()),Bu=requireFuture(),ju=Ru(requireValidate$3()),Fu=requireRestapi$4(),zu=requireRestapi$3(),Uu=requireLib$b();Au.DEFAULT_KERNEL_INFO_TIMEOUT=3e3;const Hu="";class Vu{constructor(Ku){var Ju,Yu,Xu,ed,td,nd,od,sd,ad;this._createSocket=(pd=!0)=>{this._errorIfDisposed(),this._clearSocket(),this._updateConnectionStatus("connecting");const gd=this.serverSettings,Sd=Iu.URLExt.join(gd.wsUrl,Fu.KERNEL_SERVICE_URL,encodeURIComponent(this._id)),_d=Sd.replace(/^((?:\w+:)?\/\/)[^@/]+@/,"$1");console.debug(`Starting WebSocket: ${_d}`);let yd=Iu.URLExt.join(Sd,"channels?session_id="+encodeURIComponent(this._clientId));const wd=gd.token;gd.appendToken&&wd!==""&&(yd=yd+`&token=${encodeURIComponent(wd)}`);const Ad=pd?this._supportedProtocols:[];this._ws=new gd.WebSocket(yd,Ad),this._ws.binaryType="arraybuffer";let md=!1;const dd=async ld=>{var ud,hd;if(!this._isDisposed){this._reason="",this._model=void 0;try{const vd=await this._kernelAPIClient.getModel(this._id);this._model=vd,vd?.execution_state==="dead"?this._updateStatus("dead"):this._onWSClose(ld)}catch(vd){if(vd instanceof Mu.ServerConnection.NetworkError||((ud=vd.response)===null||ud===void 0?void 0:ud.status)===503||((hd=vd.response)===null||hd===void 0?void 0:hd.status)===424){const Ed=Gu.getRandomIntInclusive(10,30)*1e3;setTimeout(dd,Ed,ld)}else this._reason="Kernel died unexpectedly",this._updateStatus("dead")}}},bd=async ld=>{md||(md=!0,await dd(ld))};this._ws.onmessage=this._onWSMessage,this._ws.onopen=this._onWSOpen,this._ws.onclose=bd,this._ws.onerror=bd},this._onWSOpen=pd=>{if(this._ws.protocol!==""&&!this._supportedProtocols.includes(this._ws.protocol))throw console.log("Server selected unknown kernel wire protocol:",this._ws.protocol),this._updateStatus("dead"),new Error(`Unknown kernel wire protocol: ${this._ws.protocol}`);this._selectedProtocol=this._ws.protocol,this._ws.onclose=this._onWSClose,this._ws.onerror=this._onWSClose,this._updateConnectionStatus("connected")},this._onWSMessage=pd=>{let gd;try{gd=this.serverSettings.serializer.deserialize(pd.data,this._ws.protocol),ju.validateMessage(gd)}catch(Sd){throw Sd.message=`Kernel message validation error: ${Sd.message}`,Sd}this._kernelSession=gd.header.session,this._msgChain=this._msgChain.then(()=>this._handleMessage(gd)).catch(Sd=>{Sd.message.startsWith("Canceled future for ")&&console.error(Sd)}),this._anyMessage.emit({msg:gd,direction:"recv"})},this._onWSClose=pd=>{if(!this.isDisposed){if("code"in pd&&(pd.code===1e3||pd.code===1001)){this._updateConnectionStatus("disconnected");return}this._reconnect()}},this._id="",this._name="",this._status="unknown",this._connectionStatus="connecting",this._kernelSession="",this._isRestarting=!1,this._isDisposed=!1,this._ws=null,this._username="",this._reconnectLimit=7,this._reconnectAttempt=0,this._reconnectTimeout=null,this._supportedProtocols=Object.values(Lu.supportedKernelWebSocketProtocols),this._selectedProtocol="",this._commsOverSubshells=Mu.CommsOverSubshells.PerCommTarget,this._futures=new Map,this._comms=new Map,this._targetRegistry=Object.create(null),this._info=new Pu.PromiseDelegate,this._pendingMessages=[],this._statusChanged=new Ou.Signal(this),this._connectionStatusChanged=new Ou.Signal(this),this._disposed=new Ou.Signal(this),this._iopubMessage=new Ou.Signal(this),this._anyMessage=new Ou.Signal(this),this._pendingInput=new Ou.Signal(this),this._unhandledMessage=new Ou.Signal(this),this._displayIdToParentIds=new Map,this._msgIdToDisplayIds=new Map,this._msgChain=Promise.resolve(),this._hasPendingInput=!1,this._reason="",this._noOp=()=>{},this._supportsSubshells=!1,this._kernelInfoTimeout=Au.DEFAULT_KERNEL_INFO_TIMEOUT,this._name=Ku.model.name,this._id=Ku.model.id,this.serverSettings=(Ju=Ku.serverSettings)!==null&&Ju!==void 0?Ju:Mu.ServerConnection.makeSettings(),this._kernelAPIClient=(Yu=Ku.kernelAPIClient)!==null&&Yu!==void 0?Yu:new Fu.KernelAPIClient({serverSettings:this.serverSettings}),this._kernelSpecAPIClient=(Xu=Ku.kernelSpecAPIClient)!==null&&Xu!==void 0?Xu:new zu.KernelSpecAPIClient({serverSettings:this.serverSettings}),this._clientId=(ed=Ku.clientId)!==null&&ed!==void 0?ed:Pu.UUID.uuid4(),this._username=(td=Ku.username)!==null&&td!==void 0?td:"",this.handleComms=(nd=Ku.handleComms)!==null&&nd!==void 0?nd:!0,this._commsOverSubshells=(od=Ku.commsOverSubshells)!==null&&od!==void 0?od:Mu.CommsOverSubshells.PerCommTarget,this._subshellId=(sd=Ku.subshellId)!==null&&sd!==void 0?sd:null,this._createSocket(),this._kernelInfoTimeout=(ad=Ku?.kernelInfoTimeout)!==null&&ad!==void 0?ad:Au.DEFAULT_KERNEL_INFO_TIMEOUT}get disposed(){return this._disposed}get commsOverSubshells(){return this._commsOverSubshells}set commsOverSubshells(Ku){this._commsOverSubshells=Ku;for(const[Ju,Yu]of this._comms)Yu.commsOverSubshells=Ku}get statusChanged(){return this._statusChanged}get connectionStatusChanged(){return this._connectionStatusChanged}get iopubMessage(){return this._iopubMessage}get unhandledMessage(){return this._unhandledMessage}get model(){return this._model||{id:this.id,name:this.name,reason:this._reason}}get anyMessage(){return this._anyMessage}get pendingInput(){return this._pendingInput}get id(){return this._id}get name(){return this._name}get username(){return this._username}get clientId(){return this._clientId}get subshellId(){return this._subshellId}set subshellId(Ku){this._subshellId=Ku}get status(){return this._status}get connectionStatus(){return this._connectionStatus}get isDisposed(){return this._isDisposed}get info(){return this._info.promise}get spec(){return this._specPromise?this._specPromise:(this._specPromise=this._kernelSpecAPIClient.get().then(Ku=>Ku.kernelspecs[this._name]),this._specPromise)}get supportsSubshells(){return this._supportsSubshells}clone(Ku={}){return new Vu({model:this.model,username:this.username,serverSettings:this.serverSettings,handleComms:!1,kernelAPIClient:this._kernelAPIClient,commsOverSubshells:Mu.CommsOverSubshells.Disabled,kernelInfoTimeout:this._kernelInfoTimeout,...Ku})}dispose(){if(this.isDisposed)return;const Ku=()=>{this._isDisposed=!0,this._disposed.emit(),this._updateConnectionStatus("disconnected"),this._clearKernelState(),this._pendingMessages=[],this._clearSocket(),Ou.Signal.clearData(this)};if(this._subshellId!==null){const Ju=this.requestDeleteSubshell({subshell_id:this._subshellId},!0);Ju.onReply=Yu=>{Ku()}}else Ku()}sendShellMessage(Ku,Ju=!1,Yu=!0){return this._sendKernelShellControl(Bu.KernelShellFutureHandler,Ku,Ju,Yu)}sendControlMessage(Ku,Ju=!1,Yu=!0){return this._sendKernelShellControl(Bu.KernelControlFutureHandler,Ku,Ju,Yu)}_sendKernelShellControl(Ku,Ju,Yu=!1,Xu=!0){this._sendMessage(Ju),this._anyMessage.emit({msg:Ju,direction:"send"});const ed=new Ku(()=>{const td=Ju.header.msg_id;this._futures.delete(td);const nd=this._msgIdToDisplayIds.get(td);nd&&(nd.forEach(od=>{const sd=this._displayIdToParentIds.get(od);if(sd){const ad=sd.indexOf(td);if(ad===-1)return;sd.length===1?this._displayIdToParentIds.delete(od):(sd.splice(ad,1),this._displayIdToParentIds.set(od,sd))}}),this._msgIdToDisplayIds.delete(td))},Ju,Yu,Xu,this);return this._futures.set(Ju.header.msg_id,ed),ed}_sendMessage(Ku,Ju=!0){if(this.status==="dead")throw new Error("Kernel is dead");if((this._kernelSession===Hu||this._isRestarting)&&Lu.isInfoRequestMsg(Ku))if(this.connectionStatus==="connected"){this._ws.send(this.serverSettings.serializer.serialize(Ku,this._ws.protocol));return}else throw new Error("Could not send message: status is not connected");if(Ju&&this._pendingMessages.length>0){this._pendingMessages.push(Ku);return}if(this.connectionStatus==="connected"&&!this._isRestarting)this._ws.send(this.serverSettings.serializer.serialize(Ku,this._ws.protocol));else if(Ju)this._pendingMessages.push(Ku);else throw new Error("Could not send message")}async interrupt(){if(this.hasPendingInput=!1,this.status==="dead")throw new Error("Kernel is dead");return this._kernelAPIClient.interrupt(this.id)}async restart(){if(this.status==="dead")throw new Error("Kernel is dead");this._updateStatus("restarting"),this._clearKernelState(),this._isRestarting=!0;try{await this._kernelAPIClient.restart(this.id),await this.reconnect()}catch(Ku){throw this._isRestarting=!1,Ku}this.hasPendingInput=!1}reconnect(){this._errorIfDisposed();const Ku=new Pu.PromiseDelegate,Ju=(Yu,Xu)=>{Xu==="connected"?(Ku.resolve(),this.connectionStatusChanged.disconnect(Ju,this)):Xu==="disconnected"&&(Ku.reject(new Error("Kernel connection disconnected")),this.connectionStatusChanged.disconnect(Ju,this))};return this.connectionStatusChanged.connect(Ju,this),this._reconnectAttempt=0,this._reconnect(),Ku.promise}async shutdown(){this.status!=="dead"&&await this._kernelAPIClient.shutdown(this.id),this.handleShutdown()}handleShutdown(){this._updateStatus("dead"),this.dispose()}async requestKernelInfo(){const Ku=Lu.createMessage({msgType:"kernel_info_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:{}});let Ju;try{Ju=await Gu.handleShellMessage(this,Ku)}catch(Xu){if(this.isDisposed)return;throw Xu}if(this._errorIfDisposed(),!Ju)return;if(Ju.content.status===void 0&&(Ju.content.status="ok"),Ju.content.status!=="ok")return this._info.reject("Kernel info reply errored"),Ju;this._info.resolve(Ju.content),this._kernelSession=Ju.header.session;const Yu=Ju.content.supported_features;return this._supportsSubshells=Yu!==void 0&&Yu.includes("kernel subshells"),Ju}requestComplete(Ku){const Ju=Lu.createMessage({msgType:"complete_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:Ku});return Gu.handleShellMessage(this,Ju)}requestInspect(Ku){const Ju=Lu.createMessage({msgType:"inspect_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:Ku});return Gu.handleShellMessage(this,Ju)}requestHistory(Ku){const Ju=Lu.createMessage({msgType:"history_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:Ku});return Gu.handleShellMessage(this,Ju)}requestExecute(Ku,Ju=!0,Yu){const Xu={silent:!1,store_history:!0,user_expressions:{},allow_stdin:!0,stop_on_error:!1},ed=Lu.createMessage({msgType:"execute_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:{...Xu,...Ku},metadata:Yu});return this.sendShellMessage(ed,!0,Ju)}requestDebug(Ku,Ju=!0){const Yu=Lu.createMessage({msgType:"debug_request",channel:"control",username:this._username,session:this._clientId,content:Ku});return this.sendControlMessage(Yu,!0,Ju)}requestCreateSubshell(Ku,Ju=!0){if(!this.supportsSubshells)throw new Error("Kernel subshells are not supported");const Yu=Lu.createMessage({msgType:"create_subshell_request",channel:"control",username:this._username,session:this._clientId,content:Ku});return this.sendControlMessage(Yu,!0,Ju)}requestDeleteSubshell(Ku,Ju=!0){if(!this.supportsSubshells)throw new Error("Kernel subshells are not supported");const Yu=Lu.createMessage({msgType:"delete_subshell_request",channel:"control",username:this._username,session:this._clientId,content:Ku});return this.sendControlMessage(Yu,!0,Ju)}requestListSubshell(Ku,Ju=!0){if(!this.supportsSubshells)throw new Error("Kernel subshells are not supported");const Yu=Lu.createMessage({msgType:"list_subshell_request",channel:"control",username:this._username,session:this._clientId,content:Ku});return this.sendControlMessage(Yu,!0,Ju)}requestIsComplete(Ku){const Ju=Lu.createMessage({msgType:"is_complete_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:Ku});return Gu.handleShellMessage(this,Ju)}requestCommInfo(Ku){const Ju=Lu.createMessage({msgType:"comm_info_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:Ku});return Gu.handleShellMessage(this,Ju)}sendInputReply(Ku,Ju){const Yu=Lu.createMessage({msgType:"input_reply",channel:"stdin",username:this._username,session:this._clientId,content:Ku});Yu.parent_header=Ju,this._sendMessage(Yu),this._anyMessage.emit({msg:Yu,direction:"send"}),this.hasPendingInput=!1}createComm(Ku,Ju=Pu.UUID.uuid4()){if(!this.handleComms)throw new Error("Comms are disabled on this kernel connection");if(this._comms.has(Ju))throw new Error("Comm is already created");const Yu=new Du.CommHandler(Ku,Ju,this,()=>{this._unregisterComm(Ju)},this._commsOverSubshells);return this._comms.set(Ju,Yu),Yu}hasComm(Ku){return this._comms.has(Ku)}registerCommTarget(Ku,Ju){this.handleComms&&(this._targetRegistry[Ku]=Ju)}removeCommTarget(Ku,Ju){this.handleComms&&!this.isDisposed&&this._targetRegistry[Ku]===Ju&&delete this._targetRegistry[Ku]}registerMessageHook(Ku,Ju){var Yu;const Xu=(Yu=this._futures)===null||Yu===void 0?void 0:Yu.get(Ku);Xu&&Xu.registerMessageHook(Ju)}removeMessageHook(Ku,Ju){var Yu;const Xu=(Yu=this._futures)===null||Yu===void 0?void 0:Yu.get(Ku);Xu&&Xu.removeMessageHook(Ju)}removeInputGuard(){this.hasPendingInput=!1}async _handleDisplayId(Ku,Ju){var Yu,Xu;const ed=Ju.parent_header.msg_id;let td=this._displayIdToParentIds.get(Ku);if(td){const od={header:Pu.JSONExt.deepCopy(Ju.header),parent_header:Pu.JSONExt.deepCopy(Ju.parent_header),metadata:Pu.JSONExt.deepCopy(Ju.metadata),content:Pu.JSONExt.deepCopy(Ju.content),channel:Ju.channel,buffers:Ju.buffers?Ju.buffers.slice():[]};od.header.msg_type="update_display_data",await Promise.all(td.map(async sd=>{const ad=this._futures&&this._futures.get(sd);ad&&await ad.handleMsg(od)}))}if(Ju.header.msg_type==="update_display_data")return!0;td=(Yu=this._displayIdToParentIds.get(Ku))!==null&&Yu!==void 0?Yu:[],td.indexOf(ed)===-1&&td.push(ed),this._displayIdToParentIds.set(Ku,td);const nd=(Xu=this._msgIdToDisplayIds.get(ed))!==null&&Xu!==void 0?Xu:[];return nd.indexOf(ed)===-1&&nd.push(ed),this._msgIdToDisplayIds.set(ed,nd),!1}_clearSocket(){this._ws!==null&&(this._ws.onopen=this._noOp,this._ws.onclose=this._noOp,this._ws.onerror=this._noOp,this._ws.onmessage=this._noOp,this._ws.close(),this._ws=null)}_updateStatus(Ku){this._status===Ku||this._status==="dead"||(this._status=Ku,Gu.logKernelStatus(this),this._statusChanged.emit(Ku),Ku==="dead"&&this.dispose())}_sendPending(){for(;this.connectionStatus==="connected"&&!this._isRestarting&&this._pendingMessages.length>0;)this._sendMessage(this._pendingMessages[0],!1),this._pendingMessages.shift()}_clearKernelState(){this._kernelSession="",this._pendingMessages=[],this._futures.forEach(Ku=>{Ku.dispose()}),this._comms.forEach(Ku=>{Ku.dispose()}),this._msgChain=Promise.resolve(),this._futures=new Map,this._comms=new Map,this._displayIdToParentIds.clear(),this._msgIdToDisplayIds.clear()}_assertCurrentMessage(Ku){if(this._errorIfDisposed(),Ku.header.session!==this._kernelSession)throw new Error(`Canceling handling of old message: ${Ku.header.msg_type}`)}async _handleCommOpen(Ku){this._assertCurrentMessage(Ku);const Ju=Ku.content,Yu=new Du.CommHandler(Ju.target_name,Ju.comm_id,this,()=>{this._unregisterComm(Ju.comm_id)},this.commsOverSubshells);this._comms.set(Ju.comm_id,Yu);try{await(await Gu.loadObject(Ju.target_name,Ju.target_module,this._targetRegistry))(Yu,Ku)}catch(Xu){throw Yu.close(),console.error("Exception opening new comm"),Xu}}async _handleCommClose(Ku){this._assertCurrentMessage(Ku);const Ju=Ku.content,Yu=this._comms.get(Ju.comm_id);if(!Yu){console.error("Comm not found for comm id "+Ju.comm_id);return}this._unregisterComm(Yu.commId);const Xu=Yu.onClose;Xu&&await Xu(Ku),Yu.dispose()}async _handleCommMsg(Ku){this._assertCurrentMessage(Ku);const Ju=Ku.content,Yu=this._comms.get(Ju.comm_id);if(!Yu)return;const Xu=Yu.onMsg;Xu&&await Xu(Ku)}_unregisterComm(Ku){this._comms.delete(Ku)}_updateConnectionStatus(Ku){if(this._connectionStatus!==Ku){if(this._connectionStatus=Ku,Ku!=="connecting"&&(this._reconnectAttempt=0,clearTimeout(this._reconnectTimeout)),this.status!=="dead")if(Ku==="connected"){let Ju=this._isRestarting,Yu=this.requestKernelInfo(),Xu=!1,ed=()=>{Xu||(Xu=!0,Ju&&this._isRestarting&&(this._isRestarting=!1,this._kernelSession=""),clearTimeout(td),this._pendingMessages.length>0&&this._sendPending())};Yu.then(()=>{Ju&&(this._isRestarting=!1),ed()});let td=setTimeout(ed,this._kernelInfoTimeout)}else this._updateStatus("unknown");this._connectionStatusChanged.emit(Ku)}}async _handleMessage(Ku){var Ju,Yu;let Xu=!1;if(Ku.parent_header&&Ku.channel==="iopub"&&(Lu.isDisplayDataMsg(Ku)||Lu.isUpdateDisplayDataMsg(Ku)||Lu.isExecuteResultMsg(Ku))){const td=((Ju=Ku.content.transient)!==null&&Ju!==void 0?Ju:{}).display_id;td&&(Xu=await this._handleDisplayId(td,Ku),this._assertCurrentMessage(Ku))}if(!Xu&&Ku.parent_header){const ed=Ku.parent_header,td=(Yu=this._futures)===null||Yu===void 0?void 0:Yu.get(ed.msg_id);if(td)await td.handleMsg(Ku),this._assertCurrentMessage(Ku);else{const nd=ed.session===this.clientId;Ku.channel!=="iopub"&&nd&&this._unhandledMessage.emit(Ku)}}if(Ku.channel==="iopub"){switch(Ku.header.msg_type){case"status":{const ed=Uu.PageConfig.getOption("untracked_message_types");if(JSON.parse(ed||"[]").includes(Ku.parent_header.msg_type))break;const nd=Ku.content.execution_state;nd==="restarting"&&Promise.resolve().then(async()=>{this._updateStatus("autorestarting"),this._clearKernelState(),await this.reconnect()}),this._updateStatus(nd);break}case"comm_open":this.handleComms&&await this._handleCommOpen(Ku);break;case"comm_msg":this.handleComms&&await this._handleCommMsg(Ku);break;case"comm_close":this.handleComms&&await this._handleCommClose(Ku);break}this.isDisposed||(this._assertCurrentMessage(Ku),this._iopubMessage.emit(Ku))}}_reconnect(){if(this._errorIfDisposed(),clearTimeout(this._reconnectTimeout),this._reconnectAttempt<this._reconnectLimit){this._updateConnectionStatus("connecting");const Ku=Gu.getRandomIntInclusive(0,1e3*(Math.pow(2,this._reconnectAttempt)-1));console.warn(`Connection lost, reconnecting in ${Math.floor(Ku/1e3)} seconds.`);const Ju=this._selectedProtocol!=="";this._reconnectTimeout=setTimeout(this._createSocket,Ku,Ju),this._reconnectAttempt+=1}else this._updateConnectionStatus("disconnected");this._clearSocket()}_errorIfDisposed(){if(this.isDisposed)throw new Error("Kernel connection is disposed")}get hasPendingInput(){return this._hasPendingInput}set hasPendingInput(Ku){this._hasPendingInput=Ku,this._pendingInput.emit(Ku)}}Au.KernelConnection=Vu;var Gu;(function(Wu){function Ku(ed){switch(ed.status){case"idle":case"busy":case"unknown":return;default:console.debug(`Kernel: ${ed.status} (${ed.id})`);break}}Wu.logKernelStatus=Ku;async function Ju(ed,td){return ed.sendShellMessage(td,!0).done}Wu.handleShellMessage=Ju;function Yu(ed,td,nd){return new Promise((od,sd)=>{if(td){if(typeof requirejs>"u")throw new Error("requirejs not found");requirejs([td],ad=>{if(ad[ed]===void 0){const pd=`Object '${ed}' not found in module '${td}'`;sd(new Error(pd))}else od(ad[ed])},sd)}else nd?.[ed]?od(nd[ed]):sd(new Error(`Object '${ed}' not found in registry`))})}Wu.loadObject=Yu;function Xu(ed,td){return ed=Math.ceil(ed),td=Math.floor(td),Math.floor(Math.random()*(td-ed+1))+ed}Wu.getRandomIntInclusive=Xu})(Gu||(Gu={}))})(_default$3)),_default$3}var manager$5={},hasRequiredManager$5;function requireManager$5(){if(hasRequiredManager$5)return manager$5;hasRequiredManager$5=1,Object.defineProperty(manager$5,"__esModule",{value:!0}),manager$5.KernelManager=void 0;const Au=require$$1$1,lo=require$$0$3,$u=requireLib$8(),Ru=requireBasemanager(),Iu=requireRestapi$4(),Pu=require_default$2(),Ou=requireRestapi$3();class Mu extends Ru.BaseManager{constructor(Lu={}){var Bu,ju,Fu;super(Lu),this._commsOverSubshells=$u.CommsOverSubshells.PerCommTarget,this._isReady=!1,this._kernelConnections=new Set,this._models=new Map,this._runningChanged=new lo.Signal(this),this._connectionFailure=new lo.Signal(this),this._kernelInfoTimeout=Pu.DEFAULT_KERNEL_INFO_TIMEOUT,this._kernelAPIClient=(Bu=Lu.kernelAPIClient)!==null&&Bu!==void 0?Bu:new Iu.KernelAPIClient({serverSettings:this.serverSettings}),this._kernelSpecAPIClient=(ju=Lu.kernelSpecAPIClient)!==null&&ju!==void 0?ju:new Ou.KernelSpecAPIClient({serverSettings:this.serverSettings}),this._pollModels=new Au.Poll({auto:!1,factory:()=>this.requestRunning(),frequency:{interval:10*1e3,backoff:!0,max:300*1e3},name:"@jupyterlab/services:KernelManager#models",standby:(Fu=Lu.standby)!==null&&Fu!==void 0?Fu:"when-hidden"}),this._ready=(async()=>{await this._pollModels.start(),await this._pollModels.tick,this._isReady=!0})()}get isReady(){return this._isReady}get ready(){return this._ready}get runningChanged(){return this._runningChanged}get connectionFailure(){return this._connectionFailure}get kernelInfoTimeout(){return this._kernelInfoTimeout}set kernelInfoTimeout(Lu){this._kernelInfoTimeout=Lu}dispose(){this.isDisposed||(this._models.clear(),this._kernelConnections.forEach(Lu=>Lu.dispose()),this._pollModels.dispose(),super.dispose())}connectTo(Lu){var Bu,ju;const{id:Fu}=Lu.model;let zu=(Bu=Lu.handleComms)!==null&&Bu!==void 0?Bu:!0;if(Lu.handleComms===void 0){for(const Hu of this._kernelConnections)if(Hu.id===Fu&&Hu.handleComms){zu=!1;break}}const Uu=new Pu.KernelConnection({handleComms:zu,...Lu,commsOverSubshells:(ju=Lu.commsOverSubshells)!==null&&ju!==void 0?ju:this._commsOverSubshells,serverSettings:this.serverSettings,kernelAPIClient:this._kernelAPIClient,kernelSpecAPIClient:this._kernelSpecAPIClient,kernelInfoTimeout:this._kernelInfoTimeout});return this._onStarted(Uu),this._models.has(Fu)||this.refreshRunning().catch(()=>{}),Uu}running(){return this._models.values()}get runningCount(){return this._models.size}get commsOverSubshells(){return this._commsOverSubshells}set commsOverSubshells(Lu){this._commsOverSubshells=Lu;for(const Bu of this._kernelConnections)Bu.commsOverSubshells=Lu}async refreshRunning(){await this._pollModels.refresh(),await this._pollModels.tick}async startNew(Lu={},Bu={}){const ju=await this._kernelAPIClient.startNew(Lu);return this.connectTo({...Bu,model:ju})}async shutdown(Lu){await this._kernelAPIClient.shutdown(Lu),await this.refreshRunning()}async shutdownAll(){await this.refreshRunning(),await Promise.all([...this._models.keys()].map(Lu=>this._kernelAPIClient.shutdown(Lu))),await this.refreshRunning()}async findById(Lu){return this._models.has(Lu)?this._models.get(Lu):(await this.refreshRunning(),this._models.get(Lu))}async requestRunning(){var Lu,Bu;let ju;try{ju=await this._kernelAPIClient.listRunning()}catch(Fu){throw(Fu instanceof $u.ServerConnection.NetworkError||((Lu=Fu.response)===null||Lu===void 0?void 0:Lu.status)===503||((Bu=Fu.response)===null||Bu===void 0?void 0:Bu.status)===424)&&this._connectionFailure.emit(Fu),Fu}this.isDisposed||this._models.size===ju.length&&ju.every(Fu=>{const zu=this._models.get(Fu.id);return zu?zu.connections===Fu.connections&&zu.execution_state===Fu.execution_state&&zu.last_activity===Fu.last_activity&&zu.name===Fu.name&&zu.reason===Fu.reason&&zu.traceback===Fu.traceback:!1})||(this._models=new Map(ju.map(Fu=>[Fu.id,Fu])),this._kernelConnections.forEach(Fu=>{this._models.has(Fu.id)||Fu.handleShutdown()}),this._runningChanged.emit(ju))}_onStarted(Lu){this._kernelConnections.add(Lu),Lu.statusChanged.connect(this._onStatusChanged,this),Lu.disposed.connect(this._onDisposed,this)}_onDisposed(Lu){this._kernelConnections.delete(Lu),this.refreshRunning().catch(()=>{})}_onStatusChanged(Lu,Bu){Bu==="dead"&&this.refreshRunning().catch(()=>{})}}return manager$5.KernelManager=Mu,(function(Du){class Lu extends Du{constructor(){super(...arguments),this._readyPromise=new Promise(()=>{})}get isActive(){return!1}get parentReady(){return super.ready}async startNew(ju={},Fu={}){return Promise.reject(new Error("Not implemented in no-op Kernel Manager"))}connectTo(ju){throw new Error("Not implemented in no-op Kernel Manager")}async shutdown(ju){return Promise.reject(new Error("Not implemented in no-op Kernel Manager"))}get ready(){return this.parentReady.then(()=>this._readyPromise)}async requestRunning(){return Promise.resolve()}}Du.NoopManager=Lu})(Mu||(manager$5.KernelManager=Mu={})),manager$5}var hasRequiredKernel;function requireKernel(){return hasRequiredKernel||(hasRequiredKernel=1,(function(Au){var lo=kernel$1&&kernel$1.__createBinding||(Object.create?(function(Bu,ju,Fu,zu){zu===void 0&&(zu=Fu);var Uu=Object.getOwnPropertyDescriptor(ju,Fu);(!Uu||("get"in Uu?!ju.__esModule:Uu.writable||Uu.configurable))&&(Uu={enumerable:!0,get:function(){return ju[Fu]}}),Object.defineProperty(Bu,zu,Uu)}):(function(Bu,ju,Fu,zu){zu===void 0&&(zu=Fu),Bu[zu]=ju[Fu]})),$u=kernel$1&&kernel$1.__setModuleDefault||(Object.create?(function(Bu,ju){Object.defineProperty(Bu,"default",{enumerable:!0,value:ju})}):function(Bu,ju){Bu.default=ju}),Ru=kernel$1&&kernel$1.__importStar||(function(){var Bu=function(ju){return Bu=Object.getOwnPropertyNames||function(Fu){var zu=[];for(var Uu in Fu)Object.prototype.hasOwnProperty.call(Fu,Uu)&&(zu[zu.length]=Uu);return zu},Bu(ju)};return function(ju){if(ju&&ju.__esModule)return ju;var Fu={};if(ju!=null)for(var zu=Bu(ju),Uu=0;Uu<zu.length;Uu++)zu[Uu]!=="default"&&lo(Fu,ju,zu[Uu]);return $u(Fu,ju),Fu}})(),Iu=kernel$1&&kernel$1.__exportStar||function(Bu,ju){for(var Fu in Bu)Fu!=="default"&&!Object.prototype.hasOwnProperty.call(ju,Fu)&&lo(ju,Bu,Fu)};Object.defineProperty(Au,"__esModule",{value:!0}),Au.CommsOverSubshells=Au.KernelConnection=Au.KernelAPI=Au.KernelMessage=Au.Kernel=void 0;const Pu=requireComm();Object.defineProperty(Au,"CommsOverSubshells",{enumerable:!0,get:function(){return Pu.CommsOverSubshells}});const Ou=Ru(requireKernel$1());Au.Kernel=Ou;const Mu=Ru(requireMessages());Au.KernelMessage=Mu;const Du=Ru(requireRestapi$4());Au.KernelAPI=Du;const Lu=require_default$2();Object.defineProperty(Au,"KernelConnection",{enumerable:!0,get:function(){return Lu.KernelConnection}}),Iu(requireManager$5(),Au)})(kernel$1)),kernel$1}var kernelspec$1={},kernelspec={},hasRequiredKernelspec$1;function requireKernelspec$1(){return hasRequiredKernelspec$1||(hasRequiredKernelspec$1=1,Object.defineProperty(kernelspec,"__esModule",{value:!0})),kernelspec}var manager$4={},hasRequiredManager$4;function requireManager$4(){if(hasRequiredManager$4)return manager$4;hasRequiredManager$4=1,Object.defineProperty(manager$4,"__esModule",{value:!0}),manager$4.KernelSpecManager=void 0;const Au=requireDist(),lo=require$$1$1,$u=require$$0$3,Ru=requireBasemanager(),Iu=requireRestapi$3();class Pu extends Ru.BaseManager{constructor(Mu={}){var Du,Lu;super(Mu),this._isReady=!1,this._connectionFailure=new $u.Signal(this),this._specs=null,this._specsChanged=new $u.Signal(this),this._kernelSpecAPIClient=(Du=Mu.kernelSpecAPIClient)!==null&&Du!==void 0?Du:new Iu.KernelSpecAPIClient({serverSettings:this.serverSettings}),this._ready=Promise.all([this.requestSpecs()]).then(Bu=>{}).catch(Bu=>{}).then(()=>{this.isDisposed||(this._isReady=!0)}),this._pollSpecs=new lo.Poll({auto:!1,factory:()=>this.requestSpecs(),frequency:{interval:61*1e3,backoff:!0,max:300*1e3},name:"@jupyterlab/services:KernelSpecManager#specs",standby:(Lu=Mu.standby)!==null&&Lu!==void 0?Lu:"when-hidden"}),this.ready.then(()=>{this._pollSpecs.start()})}get isReady(){return this._isReady}get ready(){return this._ready}get specs(){return this._specs}get specsChanged(){return this._specsChanged}get connectionFailure(){return this._connectionFailure}dispose(){this._pollSpecs.dispose(),super.dispose()}async refreshSpecs(){await this._pollSpecs.refresh(),await this._pollSpecs.tick}async requestSpecs(){const Mu=await this._kernelSpecAPIClient.get();this.isDisposed||Au.JSONExt.deepEqual(Mu,this._specs)||(this._specs=Mu,this._specsChanged.emit(Mu))}}return manager$4.KernelSpecManager=Pu,manager$4}var hasRequiredKernelspec;function requireKernelspec(){return hasRequiredKernelspec||(hasRequiredKernelspec=1,(function(Au){var lo=kernelspec$1&&kernelspec$1.__createBinding||(Object.create?(function(Mu,Du,Lu,Bu){Bu===void 0&&(Bu=Lu);var ju=Object.getOwnPropertyDescriptor(Du,Lu);(!ju||("get"in ju?!Du.__esModule:ju.writable||ju.configurable))&&(ju={enumerable:!0,get:function(){return Du[Lu]}}),Object.defineProperty(Mu,Bu,ju)}):(function(Mu,Du,Lu,Bu){Bu===void 0&&(Bu=Lu),Mu[Bu]=Du[Lu]})),$u=kernelspec$1&&kernelspec$1.__setModuleDefault||(Object.create?(function(Mu,Du){Object.defineProperty(Mu,"default",{enumerable:!0,value:Du})}):function(Mu,Du){Mu.default=Du}),Ru=kernelspec$1&&kernelspec$1.__importStar||(function(){var Mu=function(Du){return Mu=Object.getOwnPropertyNames||function(Lu){var Bu=[];for(var ju in Lu)Object.prototype.hasOwnProperty.call(Lu,ju)&&(Bu[Bu.length]=ju);return Bu},Mu(Du)};return function(Du){if(Du&&Du.__esModule)return Du;var Lu={};if(Du!=null)for(var Bu=Mu(Du),ju=0;ju<Bu.length;ju++)Bu[ju]!=="default"&&lo(Lu,Du,Bu[ju]);return $u(Lu,Du),Lu}})(),Iu=kernelspec$1&&kernelspec$1.__exportStar||function(Mu,Du){for(var Lu in Mu)Lu!=="default"&&!Object.prototype.hasOwnProperty.call(Du,Lu)&&lo(Du,Mu,Lu)};Object.defineProperty(Au,"__esModule",{value:!0}),Au.KernelSpecAPI=Au.KernelSpec=void 0;const Pu=Ru(requireKernelspec$1());Au.KernelSpec=Pu;const Ou=Ru(requireRestapi$3());Au.KernelSpecAPI=Ou,Iu(requireManager$4(),Au)})(kernelspec$1)),kernelspec$1}var manager$3={},builder={},hasRequiredBuilder;function requireBuilder(){if(hasRequiredBuilder)return builder;hasRequiredBuilder=1,Object.defineProperty(builder,"__esModule",{value:!0}),builder.BuildManager=void 0;const Au=requireLib$b(),lo=requireServerconnection(),$u="api/build";class Ru{constructor(Pu={}){var Ou;this.serverSettings=(Ou=Pu.serverSettings)!==null&&Ou!==void 0?Ou:lo.ServerConnection.makeSettings()}get isAvailable(){return Au.PageConfig.getOption("buildAvailable").toLowerCase()==="true"}get shouldCheck(){return Au.PageConfig.getOption("buildCheck").toLowerCase()==="true"}getStatus(){const{_url:Pu,serverSettings:Ou}=this;return lo.ServerConnection.makeRequest(Pu,{},Ou).then(Du=>{if(Du.status!==200)throw new lo.ServerConnection.ResponseError(Du);return Du.json()}).then(Du=>{if(typeof Du.status!="string")throw new Error("Invalid data");if(typeof Du.message!="string")throw new Error("Invalid data");return Du})}build(){const{_url:Pu,serverSettings:Ou}=this,Mu={method:"POST"};return lo.ServerConnection.makeRequest(Pu,Mu,Ou).then(Lu=>{if(Lu.status===400)throw new lo.ServerConnection.ResponseError(Lu,"Build aborted");if(Lu.status!==200){const Bu=`Build failed with ${Lu.status}.
|
|
263
263
|
|
|
264
264
|
If you are experiencing the build failure after installing an extension (or trying to include previously installed extension after updating JupyterLab) please check the extension repository for new installation instructions as many extensions migrated to the prebuilt extensions system which no longer requires rebuilding JupyterLab (but uses a different installation procedure, typically involving a package manager such as 'pip' or 'conda').
|
|
265
265
|
|
|
@@ -2101,7 +2101,7 @@ Execution failed: ${Du}`,diff:Pu}}}catch(Pu){const Ou=Pu instanceof Error?Pu.mes
|
|
|
2101
2101
|
`)}function decode$4(Au,lo){return decodeFromLines(Au.split(`
|
|
2102
2102
|
`))}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.
|
|
2103
2103
|
|
|
2104
|
-
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 Sd=resolveTo(Mu,[],Xu.mask?Xu.mask.pathname:"/",!0);Vu!=="/"&&(Sd.pathname=Sd.pathname==="/"?Vu:joinPaths([Vu,Sd.pathname])),ed=Gu.createHref(Sd)}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(Sd){lo&&lo(Sd),Sd.defaultPrevented||sd(Sd)}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:"/platform",agentify:"/agentify",research:"/research",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==="research"||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==="/research"||$u.startsWith("/research/")?"research":$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),iamStore.getState().user&&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-BOGJMsUN.js").then(Au=>Au.r),[],import.meta.url).then(Au=>({default:Au.JupyterReactTheme})));let NotificationApi;isInsideJupyterLab()&&__vitePreload(()=>import("./chunks/index-By5Ku2wm.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(`
|
|
2104
|
+
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 Sd=resolveTo(Mu,[],Xu.mask?Xu.mask.pathname:"/",!0);Vu!=="/"&&(Sd.pathname=Sd.pathname==="/"?Vu:joinPaths([Vu,Sd.pathname])),ed=Gu.createHref(Sd)}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(Sd){lo&&lo(Sd),Sd.defaultPrevented||sd(Sd)}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:"/platform",agentify:"/agentify",research:"/research",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==="research"||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)&&!isHostedAppRoute(Au)}const APPS_SHELL_SECTIONS=new Set(["activity","agents","apps","components","connections","contents","context","deployments","evalsets","examples","home","models","readiness","reports","rules","runs","shared","skills","usage","workspace"]);function isHostedAppRoute(Au){const lo=pathOf(Au).split("/").filter(Boolean);return lo[0]==="apps"&&lo.length>=2&&!APPS_SHELL_SECTIONS.has(lo[1])&&(lo.length===2||lo.length===4&&lo[2]==="preview")}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==="/research"||$u.startsWith("/research/")?"research":$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),iamStore.getState().user&&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-BOGJMsUN.js").then(Au=>Au.r),[],import.meta.url).then(Au=>({default:Au.JupyterReactTheme})));let NotificationApi;isInsideJupyterLab()&&__vitePreload(()=>import("./chunks/index-By5Ku2wm.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(`
|
|
2105
2105
|
`).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(`
|
|
2106
2106
|
[zustand devtools middleware] Unsupported __setState action format.
|
|
2107
2107
|
When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
|
|
@@ -2194,9 +2194,9 @@ ${lo}:`]}}function getResponseMetadata2({id:Au,model:lo,created:$u}){return{id:A
|
|
|
2194
2194
|
`):ju,zu=streamText({model:this.resolveModel(Bu?.model||$u?.model),system:Fu,messages:Iu,tools:this.tools,stopWhen:isStepCount(this.browserConfig.maxSteps??DEFAULT_BROWSER_MAX_STEPS),abortSignal:Ru.signal});for await(const Uu of zu.fullStream){if(Ru.signal.aborted)break;switch(Uu.type){case"text-start":Du();break;case"text-delta":Ou===null&&Du(),Mu+=Uu.text,Lu();break;case"tool-call":this.emit({type:"tool-call",toolCall:{toolCallId:Uu.toolCallId,toolName:Uu.toolName,args:Uu.input??{},argsComplete:!0},timestamp:new Date});break;case"tool-result":this.emit({type:"tool-result",toolResult:{toolCallId:Uu.toolCallId,success:!0,result:Uu.output},timestamp:new Date});break;case"tool-error":this.emit({type:"tool-result",toolResult:{toolCallId:Uu.toolCallId,success:!1,error:Uu.error instanceof Error?Uu.error.message:String(Uu.error)},timestamp:new Date});break;case"error":this.emit({type:"error",error:Uu.error instanceof Error?Uu.error:new Error(String(Uu.error)),timestamp:new Date});break;case"finish":{const Hu=Uu.totalUsage,Vu=Hu?.inputTokens??0,Gu=Hu?.outputTokens??0,Wu=Hu?.totalTokens??(Vu+Gu>0?Vu+Gu:void 0);this.emit({type:"done",usage:{promptTokens:Vu,completionTokens:Gu,totalTokens:Wu},timestamp:new Date});break}default:break}}}catch(Bu){if(Ru.signal.aborted)return;this.emit({type:"error",error:Bu instanceof Error?Bu:new Error(String(Bu)),timestamp:new Date}),this.emit({type:"done",timestamp:new Date})}finally{this.abortController===Ru&&(this.abortController=null)}}}const AGENT_METHODS={authenticate:"authenticate",initialize:"initialize",session_cancel:"session/cancel",session_fork:"session/fork",session_list:"session/list",session_load:"session/load",session_new:"session/new",session_prompt:"session/prompt",session_set_mode:"session/set_mode",session_set_model:"session/set_model"},CLIENT_METHODS={fs_read_text_file:"fs/read_text_file",fs_write_text_file:"fs/write_text_file",session_request_permission:"session/request_permission",session_update:"session/update",terminal_create:"terminal/create",terminal_kill:"terminal/kill",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit"},PROTOCOL_VERSION=1,zAuthMethod=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),description:union([string$2(),_null()]).optional(),id:string$2(),name:string$2()}),zAuthenticateRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),methodId:string$2()}),zAuthenticateResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zBlobResourceContents=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),blob:string$2(),mimeType:union([string$2(),_null()]).optional(),uri:string$2()}),zCreateTerminalResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),terminalId:string$2()}),zDiff=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),newText:string$2(),oldText:union([string$2(),_null()]).optional(),path:string$2()}),zEnvVariable=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),name:string$2(),value:string$2()}),zErrorCode=union([literal(-32700),literal(-32600),literal(-32601),literal(-32602),literal(-32603),literal(-32e3),literal(-32002),number$2().int()]),zError=object({code:zErrorCode,data:unknown$1().optional(),message:string$2()}),zExtNotification=unknown$1(),zExtRequest=unknown$1(),zExtResponse=unknown$1(),zFileSystemCapability=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),readTextFile:boolean$1().optional().default(!1),writeTextFile:boolean$1().optional().default(!1)}),zClientCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),fs:zFileSystemCapability.optional().default({readTextFile:!1,writeTextFile:!1}),terminal:boolean$1().optional().default(!1)}),zHttpHeader=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),name:string$2(),value:string$2()}),zImplementation=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),name:string$2(),title:union([string$2(),_null()]).optional(),version:string$2()}),zKillTerminalCommandResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zListSessionsRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),cursor:union([string$2(),_null()]).optional(),cwd:union([string$2(),_null()]).optional()}),zMcpCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),http:boolean$1().optional().default(!1),sse:boolean$1().optional().default(!1)}),zMcpServerHttp=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),headers:array(zHttpHeader),name:string$2(),url:string$2()}),zMcpServerSse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),headers:array(zHttpHeader),name:string$2(),url:string$2()}),zMcpServerStdio=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),args:array(string$2()),command:string$2(),env:array(zEnvVariable),name:string$2()}),zMcpServer=union([zMcpServerHttp.and(object({type:literal("http")})),zMcpServerSse.and(object({type:literal("sse")})),zMcpServerStdio]),zModelId=string$2(),zModelInfo=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),description:union([string$2(),_null()]).optional(),modelId:zModelId,name:string$2()}),zNewSessionRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),cwd:string$2(),mcpServers:array(zMcpServer)}),zPermissionOptionId=string$2(),zPermissionOptionKind=union([literal("allow_once"),literal("allow_always"),literal("reject_once"),literal("reject_always")]),zPermissionOption=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),kind:zPermissionOptionKind,name:string$2(),optionId:zPermissionOptionId}),zPlanEntryPriority=union([literal("high"),literal("medium"),literal("low")]),zPlanEntryStatus=union([literal("pending"),literal("in_progress"),literal("completed")]),zPlanEntry=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:string$2(),priority:zPlanEntryPriority,status:zPlanEntryStatus}),zPlan=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),entries:array(zPlanEntry)}),zPromptCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),audio:boolean$1().optional().default(!1),embeddedContext:boolean$1().optional().default(!1),image:boolean$1().optional().default(!1)}),zProtocolVersion=number$2().int().gte(0).lte(65535),zInitializeRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),clientCapabilities:zClientCapabilities.optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:union([zImplementation,_null()]).optional(),protocolVersion:zProtocolVersion}),zReadTextFileResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:string$2()}),zReleaseTerminalResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zRequestId=union([_null(),bigint(),string$2()]),zRole=_enum(["assistant","user"]),zAnnotations=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),audience:union([array(zRole),_null()]).optional(),lastModified:union([string$2(),_null()]).optional(),priority:union([number$2(),_null()]).optional()}),zAudioContent=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),annotations:union([zAnnotations,_null()]).optional(),data:string$2(),mimeType:string$2()}),zImageContent=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),annotations:union([zAnnotations,_null()]).optional(),data:string$2(),mimeType:string$2(),uri:union([string$2(),_null()]).optional()}),zResourceLink=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),annotations:union([zAnnotations,_null()]).optional(),description:union([string$2(),_null()]).optional(),mimeType:union([string$2(),_null()]).optional(),name:string$2(),size:union([bigint(),_null()]).optional(),title:union([string$2(),_null()]).optional(),uri:string$2()}),zSelectedPermissionOutcome=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),optionId:zPermissionOptionId}),zRequestPermissionOutcome=union([object({outcome:literal("cancelled")}),zSelectedPermissionOutcome.and(object({outcome:literal("selected")}))]),zRequestPermissionResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),outcome:zRequestPermissionOutcome}),zSessionForkCapabilities=object({_meta:unknown$1().optional()}),zSessionId=string$2(),zCancelNotification=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId});object({method:string$2(),params:union([union([zCancelNotification,zExtNotification]),_null()]).optional()});const zCreateTerminalRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),args:array(string$2()).optional(),command:string$2(),cwd:union([string$2(),_null()]).optional(),env:array(zEnvVariable).optional(),outputByteLimit:union([number$2().int().gte(0),_null()]).optional(),sessionId:zSessionId}),zForkSessionRequest=object({_meta:unknown$1().optional(),sessionId:zSessionId}),zKillTerminalCommandRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId,terminalId:string$2()}),zLoadSessionRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),cwd:string$2(),mcpServers:array(zMcpServer),sessionId:zSessionId}),zReadTextFileRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),limit:union([number$2().int().gte(0),_null()]).optional(),line:union([number$2().int().gte(0),_null()]).optional(),path:string$2(),sessionId:zSessionId}),zReleaseTerminalRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId,terminalId:string$2()}),zSessionInfo=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),cwd:string$2(),sessionId:zSessionId,title:union([string$2(),_null()]).optional(),updatedAt:union([string$2(),_null()]).optional()}),zListSessionsResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),nextCursor:union([string$2(),_null()]).optional(),sessions:array(zSessionInfo)}),zSessionListCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zSessionCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),fork:union([zSessionForkCapabilities,_null()]).optional(),list:union([zSessionListCapabilities,_null()]).optional()}),zAgentCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),loadSession:boolean$1().optional().default(!1),mcpCapabilities:zMcpCapabilities.optional().default({http:!1,sse:!1}),promptCapabilities:zPromptCapabilities.optional().default({audio:!1,embeddedContext:!1,image:!1}),sessionCapabilities:zSessionCapabilities.optional().default({})}),zInitializeResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),agentCapabilities:zAgentCapabilities.optional().default({loadSession:!1,mcpCapabilities:{http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:union([zImplementation,_null()]).optional(),authMethods:array(zAuthMethod).optional().default([]),protocolVersion:zProtocolVersion}),zSessionModeId=string$2(),zCurrentModeUpdate=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),currentModeId:zSessionModeId}),zSessionMode=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),description:union([string$2(),_null()]).optional(),id:zSessionModeId,name:string$2()}),zSessionModeState=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),availableModes:array(zSessionMode),currentModeId:zSessionModeId}),zSessionModelState=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),availableModels:array(zModelInfo),currentModelId:zModelId}),zForkSessionResponse=object({_meta:unknown$1().optional(),models:union([zSessionModelState,_null()]).optional(),modes:union([zSessionModeState,_null()]).optional(),sessionId:zSessionId}),zLoadSessionResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),models:union([zSessionModelState,_null()]).optional(),modes:union([zSessionModeState,_null()]).optional()}),zNewSessionResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),models:union([zSessionModelState,_null()]).optional(),modes:union([zSessionModeState,_null()]).optional(),sessionId:zSessionId}),zSetSessionModeRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),modeId:zSessionModeId,sessionId:zSessionId}),zSetSessionModeResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zSetSessionModelRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),modelId:zModelId,sessionId:zSessionId}),zSetSessionModelResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zStopReason=union([literal("end_turn"),literal("max_tokens"),literal("max_turn_requests"),literal("refusal"),literal("cancelled")]),zPromptResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),stopReason:zStopReason});union([object({id:zRequestId,result:union([zInitializeResponse,zAuthenticateResponse,zNewSessionResponse,zLoadSessionResponse,zListSessionsResponse,zForkSessionResponse,zSetSessionModeResponse,zPromptResponse,zSetSessionModelResponse,zExtResponse])}),object({error:zError,id:zRequestId})]);const zTerminal=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),terminalId:string$2()}),zTerminalExitStatus=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),exitCode:union([number$2().int().gte(0),_null()]).optional(),signal:union([string$2(),_null()]).optional()}),zTerminalOutputRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId,terminalId:string$2()}),zTerminalOutputResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),exitStatus:union([zTerminalExitStatus,_null()]).optional(),output:string$2(),truncated:boolean$1()}),zTextContent=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),annotations:union([zAnnotations,_null()]).optional(),text:string$2()}),zTextResourceContents=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),mimeType:union([string$2(),_null()]).optional(),text:string$2(),uri:string$2()}),zEmbeddedResourceResource=union([zTextResourceContents,zBlobResourceContents]),zEmbeddedResource=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),annotations:union([zAnnotations,_null()]).optional(),resource:zEmbeddedResourceResource}),zContentBlock=union([zTextContent.and(object({type:literal("text")})),zImageContent.and(object({type:literal("image")})),zAudioContent.and(object({type:literal("audio")})),zResourceLink.and(object({type:literal("resource_link")})),zEmbeddedResource.and(object({type:literal("resource")}))]),zContent=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:zContentBlock}),zContentChunk=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:zContentBlock}),zPromptRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),prompt:array(zContentBlock),sessionId:zSessionId});object({id:zRequestId,method:string$2(),params:union([union([zInitializeRequest,zAuthenticateRequest,zNewSessionRequest,zLoadSessionRequest,zListSessionsRequest,zForkSessionRequest,zSetSessionModeRequest,zPromptRequest,zSetSessionModelRequest,zExtRequest]),_null()]).optional()});const zToolCallContent=union([zContent.and(object({type:literal("content")})),zDiff.and(object({type:literal("diff")})),zTerminal.and(object({type:literal("terminal")}))]),zToolCallId=string$2(),zToolCallLocation=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),line:union([number$2().int().gte(0),_null()]).optional(),path:string$2()}),zToolCallStatus=union([literal("pending"),literal("in_progress"),literal("completed"),literal("failed")]),zToolKind=union([literal("read"),literal("edit"),literal("delete"),literal("move"),literal("search"),literal("execute"),literal("think"),literal("fetch"),literal("switch_mode"),literal("other")]),zToolCall=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:array(zToolCallContent).optional(),kind:zToolKind.optional(),locations:array(zToolCallLocation).optional(),rawInput:unknown$1().optional(),rawOutput:unknown$1().optional(),status:zToolCallStatus.optional(),title:string$2(),toolCallId:zToolCallId}),zToolCallUpdate=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:union([array(zToolCallContent),_null()]).optional(),kind:union([zToolKind,_null()]).optional(),locations:union([array(zToolCallLocation),_null()]).optional(),rawInput:unknown$1().optional(),rawOutput:unknown$1().optional(),status:union([zToolCallStatus,_null()]).optional(),title:union([string$2(),_null()]).optional(),toolCallId:zToolCallId}),zRequestPermissionRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),options:array(zPermissionOption),sessionId:zSessionId,toolCall:zToolCallUpdate}),zUnstructuredCommandInput=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),hint:string$2()}),zAvailableCommandInput=zUnstructuredCommandInput,zAvailableCommand=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),description:string$2(),input:union([zAvailableCommandInput,_null()]).optional(),name:string$2()}),zAvailableCommandsUpdate=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),availableCommands:array(zAvailableCommand)}),zSessionUpdate=union([zContentChunk.and(object({sessionUpdate:literal("user_message_chunk")})),zContentChunk.and(object({sessionUpdate:literal("agent_message_chunk")})),zContentChunk.and(object({sessionUpdate:literal("agent_thought_chunk")})),zToolCall.and(object({sessionUpdate:literal("tool_call")})),zToolCallUpdate.and(object({sessionUpdate:literal("tool_call_update")})),zPlan.and(object({sessionUpdate:literal("plan")})),zAvailableCommandsUpdate.and(object({sessionUpdate:literal("available_commands_update")})),zCurrentModeUpdate.and(object({sessionUpdate:literal("current_mode_update")}))]),zSessionNotification=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId,update:zSessionUpdate});object({method:string$2(),params:union([union([zSessionNotification,zExtNotification]),_null()]).optional()});const zWaitForTerminalExitRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId,terminalId:string$2()}),zWaitForTerminalExitResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),exitCode:union([number$2().int().gte(0),_null()]).optional(),signal:union([string$2(),_null()]).optional()}),zWriteTextFileRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:string$2(),path:string$2(),sessionId:zSessionId});object({id:zRequestId,method:string$2(),params:union([union([zWriteTextFileRequest,zReadTextFileRequest,zRequestPermissionRequest,zCreateTerminalRequest,zTerminalOutputRequest,zReleaseTerminalRequest,zWaitForTerminalExitRequest,zKillTerminalCommandRequest,zExtRequest]),_null()]).optional()});const zWriteTextFileResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()});union([object({id:zRequestId,result:union([zWriteTextFileResponse,zReadTextFileResponse,zRequestPermissionResponse,zCreateTerminalResponse,zTerminalOutputResponse,zReleaseTerminalResponse,zWaitForTerminalExitResponse,zKillTerminalCommandResponse,zExtResponse])}),object({error:zError,id:zRequestId})]);class ACPAdapter extends BaseProtocolAdapter{protocol="acp";protocolTransport="websocket";acpConfig;ws=null;session=null;agent=null;streamingContent="";streamingMessageId=null;pendingPermission=null;pendingRequests=new Map;constructor(lo){super(lo),this.acpConfig=lo}getSession(){return this.session}getAgent(){return this.agent}getPendingPermission(){return this.pendingPermission}async connect(){if(this.ws?.readyState!==WebSocket.OPEN)return this.setConnectionState("connecting"),new Promise((lo,$u)=>{try{const Ru=this.acpConfig.wsUrl||this.config.baseUrl,Iu=this.config.agentId,Pu=Iu?`${Ru}/${Iu}`:Ru;this.ws=new WebSocket(Pu),this.ws.onopen=async()=>{this.reconnectAttempts=0;try{const Ou=await this.sendRequest("initialize",{protocolVersion:PROTOCOL_VERSION,clientCapabilities:this.acpConfig.clientCapabilities||{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}});Ou.agentCapabilities?.agent&&(this.agent=Ou.agentCapabilities.agent);const Mu=await this.sendRequest(AGENT_METHODS.session_new,{});Mu.sessionId?this.session={sessionId:Mu.sessionId,agentId:this.config.agentId||"",createdAt:new Date().toISOString(),status:"active"}:Ou.session_id&&(this.session={sessionId:Ou.session_id,agentId:this.config.agentId||"",createdAt:new Date().toISOString(),status:"active"}),this.setConnectionState("connected"),lo()}catch(Ou){console.error("[ACPAdapter] Initialization error:",Ou),this.setConnectionState("connected"),lo()}},this.ws.onmessage=Ou=>{this.handleMessage(Ou)},this.ws.onerror=Ou=>{console.error("[ACPAdapter] WebSocket error:",Ou),this.emit({type:"error",error:new Error("WebSocket error"),timestamp:new Date})},this.ws.onclose=()=>{this.ws=null,this.setConnectionState("disconnected"),this.handleReconnect()}}catch(Ru){this.setConnectionState("error"),this.emit({type:"error",error:Ru instanceof Error?Ru:new Error(String(Ru)),timestamp:new Date}),$u(Ru)}})}disconnect(){this.session&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.terminateSession(this.session.sessionId).catch(lo=>{console.warn("[ACPAdapter] Failed to terminate session:",lo)});for(const[,{reject:lo}]of this.pendingRequests)lo(new Error("Connection closed"));this.pendingRequests.clear(),this.ws&&(this.ws.close(),this.ws=null),this.session=null,this.agent=null,this.pendingPermission=null,this.setConnectionState("disconnected")}async terminateSession(lo){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){console.warn("[ACPAdapter] Cannot terminate: WebSocket not connected");return}try{const $u=lo||this.session?.sessionId;if(!$u){console.warn("[ACPAdapter] Cannot terminate: No session ID");return}const Ru={jsonrpc:"2.0",method:"session/cancel",params:{sessionId:$u}};this.ws.send(JSON.stringify(Ru)),console.debug("[ACPAdapter] Sent session/cancel for:",$u)}catch($u){console.debug("[ACPAdapter] Terminate request error:",$u)}}async sendMessage(lo,$u){if(!this.session)throw new Error("No active session");this.streamingContent="",this.streamingMessageId=generateMessageId();try{const Ru=typeof lo.content=="string"?lo.content:lo.content.filter(Pu=>Pu.type==="text").map(Pu=>Pu.text||"").join("");$u?.model&&console.log("[ACPAdapter] Sending with model:",$u.model),$u?.identities&&$u.identities.length>0&&console.log("[ACPAdapter] Sending with identities:",$u.identities.map(Pu=>Pu.provider));const Iu={};$u?.model&&(Iu.model=$u.model),$u?.identities&&$u.identities.length>0&&(Iu.identities=$u.identities),await this.sendRequest(AGENT_METHODS.session_prompt,{sessionId:this.session.sessionId,prompt:[{type:"text",text:Ru}],...Object.keys(Iu).length>0&&{metadata:Iu}})}catch(Ru){throw this.emit({type:"error",error:Ru instanceof Error?Ru:new Error(String(Ru)),timestamp:new Date}),Ru}}async sendToolResult(lo,$u){if(!this.session)throw new Error("No active session");this.emit({type:"tool-result",toolResult:$u,timestamp:new Date}),this.pendingPermission&&this.grantPermission()}grantPermission(lo){if(this.pendingPermission){const $u=lo||this.pendingPermission.options[0]?.optionId||"allow";this.sendResponse(this.pendingPermission.requestId,{outcome:{outcome:"selected",optionId:$u}}),this.pendingPermission=null}}denyPermission(){this.pendingPermission&&(this.sendResponse(this.pendingPermission.requestId,{outcome:{outcome:"cancelled"}}),this.pendingPermission=null)}supportsFeature(lo){return["streaming","tools","permissions","session-management","bidirectional"].includes(lo)}generateId(){return`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}async sendRequest(lo,$u={}){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("Not connected to agent");const Ru=this.generateId(),Iu={jsonrpc:"2.0",id:Ru,method:lo,params:$u};return new Promise((Pu,Ou)=>{this.pendingRequests.set(Ru,{resolve:Pu,reject:Ou}),this.ws&&this.ws.send(JSON.stringify(Iu)),setTimeout(()=>{this.pendingRequests.has(Ru)&&(this.pendingRequests.delete(Ru),Ou(new Error("Request timeout")))},this.config.timeout||3e4)})}sendResponse(lo,$u){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){console.error("[ACPAdapter] Cannot send response: not connected");return}const Ru={jsonrpc:"2.0",id:lo,result:$u};this.ws.send(JSON.stringify(Ru))}handleMessage(lo){try{const $u=JSON.parse(lo.data);if($u.id&&this.pendingRequests.has($u.id)){const Ru=this.pendingRequests.get($u.id);if(!Ru)return;const{resolve:Iu,reject:Pu}=Ru;this.pendingRequests.delete($u.id),$u.error?Pu(new Error($u.error.message)):Iu($u.result),$u.result&&typeof $u.result=="object"&&"stopReason"in $u.result&&this.handleCompletion($u.result);return}if($u.method==="session/update"){this.handleSessionUpdate($u.params||{});return}if($u.method===CLIENT_METHODS.session_request_permission&&$u.id){this.handlePermissionRequest($u.id,$u.params);return}$u.result&&typeof $u.result=="object"&&"stopReason"in $u.result&&this.handleCompletion($u.result)}catch($u){console.error("[ACPAdapter] Failed to parse message:",$u)}}handleSessionUpdate(lo){const $u=lo.update;if(!$u)return;const Ru=$u.sessionUpdate,Iu=Pu=>Pu&&typeof Pu=="object"&&Pu.type==="text"?String(Pu.text??""):"";if(Ru==="agent_message_chunk"){const Pu=Iu($u.content);if(Pu){this.streamingContent+=Pu;const Ou=createAssistantMessage(this.streamingContent);this.streamingMessageId&&(Ou.id=this.streamingMessageId),this.emit({type:"message",message:Ou,timestamp:new Date})}}if(Ru==="tool_call"){const Pu=$u;this.emit({type:"tool-call",toolCall:{toolCallId:Pu.toolCallId||generateMessageId(),toolName:Pu.title||"",args:Pu.rawInput||{}},timestamp:new Date})}if(Ru==="tool_call_update"){const Pu=$u;(Pu.status==="completed"||Pu.status==="failed")&&this.emit({type:"tool-result",toolResult:{toolCallId:Pu.toolCallId??"",success:Pu.status==="completed",result:Pu.rawOutput},timestamp:new Date})}if(Ru==="agent_thought_chunk"){const Pu=Iu($u.content);Pu&&this.emit({type:"activity",activity:{type:"thought",data:Pu},timestamp:new Date})}}handlePermissionRequest(lo,$u){this.pendingPermission={requestId:lo,sessionId:$u.sessionId,toolCall:$u.toolCall,options:$u.options},this.emit({type:"tool-call",toolCall:{toolCallId:$u.toolCall.toolCallId,toolName:$u.toolCall.title||"",args:$u.toolCall.rawInput||{}},timestamp:new Date}),this.acpConfig.onPermissionRequest?.(this.pendingPermission)}handleCompletion(lo){if(this.streamingContent){const $u=createAssistantMessage(this.streamingContent);$u.id=this.streamingMessageId||generateMessageId(),this.emit({type:"message",message:$u,timestamp:new Date}),this.streamingContent="",this.streamingMessageId=null}this.emit({type:"activity",activity:{type:"completed",data:{stopReason:lo.stopReason}},timestamp:new Date})}}const internalQueryClient=new QueryClient({defaultOptions:{queries:{staleTime:300*1e3,refetchOnWindowFocus:!1}}});function isToolCallMessage(Au){return"type"in Au&&Au.type==="tool-call"}function getMessageText(Au){const lo=typeof Au.content=="string"?Au.content:Au.content.filter($u=>$u.type==="text").map($u=>$u.text).join("");return Au.role==="assistant"?sanitizeAssistantContent(lo):lo}function formatTokenCount(Au){return Au>=1e6?`${(Au/1e6).toFixed(1)}M`:Au>=1e3?`${(Au/1e3).toFixed(1)}K`:Au.toString()}function getApiBaseFromConfig(Au){return Au.replace(/\/(config|configure)\/?$/,"")}function createProtocolAdapter(Au){const lo={protocol:Au.type,baseUrl:Au.endpoint,authToken:Au.authToken,agentId:Au.agentId,...Au.options};switch(Au.type){case"ag-ui":if(Au.ownRoutesOnly&&!Au.appSessions)throw new Error("A chat whose runtime answers only the application’s own routes is an application’s: it needs its sessions (appSessions).");return new AGUIAdapter({...lo,...Au.appSessions?{appSessions:Au.appSessions}:{}});case"a2a":return new A2AAdapter(lo);case"vercel-ai":return new VercelAIAdapter(lo);case"acp":return new ACPAdapter(lo);case"browser-vercel-ai":return new BrowserAgentAdapter(lo);default:return console.warn(`[ChatBase] Unknown protocol type: ${Au.type}`),null}}const PAP_SIGN_IN_WORDS={title:Au=>`Sign in at ${Au}`,titleFor:(Au,lo,$u)=>`Sign in to ${Au} (${lo}) at ${$u}`,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}`,mediatedTitleFor:(Au,lo,$u)=>`Sign in to ${Au} (${lo}) through ${$u}`,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$/,isPapSignInTool=Au=>PAP_SIGN_IN_TOOL.test(Au);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=typeof lo.organization_name=="string"?lo.organization_name.trim().slice(0,200):"",Pu=typeof lo.organization_domain=="string"&&DOMAIN.test(lo.organization_domain.toLowerCase())?lo.organization_domain.toLowerCase():"",Ou=Iu&&Pu?{name:Iu,domain:Pu}:void 0,Mu=Array.isArray(lo.needs)?lo.needs.filter(Du=>typeof Du=="string"&&SCOPE.test(Du)):[];return{mode:lo.mode,open:$u.toString(),host:$u.hostname,...Ru?{company:Ru}:{},...Ou?{organization:Ou}:{},...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}:{},...Mu.length>0?{needs:Mu}:{}}}const PAP_SIGN_IN_TYPE$1="application/vnd.datalayer.pap.sign-in+json",PAP_CONFIRM_TYPE="application/vnd.datalayer.pap.confirm+json",PAP_OUTCOME_TYPE="application/vnd.datalayer.pap.outcome+json",PAP_REPLIES_TYPE="application/vnd.datalayer.pap.replies+json",SHIELD_DIFF_TYPE="application/vnd.datalayer.shield.diff+json",SHIELD_TERMINAL_TYPE="application/vnd.datalayer.shield.terminal+json",DISPLAY_META_KEY="reactor.ui/display",record$1=Au=>Au&&typeof Au=="object"&&!Array.isArray(Au)?Au:null,text$h=Au=>typeof Au=="string"?Au:"",words=Au=>text$h(Au).trim(),count=Au=>typeof Au=="number"&&Number.isInteger(Au)&&Au>=1?Au:0,ACTIONS=["read","write","send","buy","delete","publish"],OUTCOMES=["in_progress","succeeded","failed","cancelled","expired"],STATUSES=["working","idle","queued","closed"],who=Au=>Au==="agent"||Au==="human"?Au:null;function protocolDisplayOf(Au){const lo=record$1(Au);if(!lo||!text$h(lo.type))return null;const $u=text$h(lo.id),Ru=record$1(lo.data)??{},Iu={kind:"unknown",id:$u,type:text$h(lo.type),version:typeof lo.version=="number"?lo.version:0,text:text$h(lo.text)};switch(lo.type){case PAP_SIGN_IN_TYPE$1:{const Pu=readPapSignIn({status:"waiting_for_the_person",...Ru});return Pu?"refused"in Pu?{kind:"sign-in-refused",id:$u,why:Pu.refused}:{kind:"sign-in",id:$u,...Pu}:Iu}case PAP_CONFIRM_TYPE:{const Pu=words(Ru.company),Ou=text$h(Ru.summary),Mu=words(Ru.operation_ref),Du=count(Ru.revision),Lu=record$1(Ru.terms),Bu=record$1(Ru.was),ju=Bu?count(Bu.revision):0;if(!Pu||!Ou.trim()||!Mu||!Du||!Lu||!$u.endsWith("-confirm")||Bu&&(!ju||ju>=Du))return Iu;const Fu=Ru.does===null||Ru.does===void 0?null:ACTIONS.find(Uu=>Uu===Ru.does);if(Fu===void 0)return Iu;const zu=record$1(Ru.session);return{kind:"confirm",id:$u,approvalId:$u.slice(0,-8),company:Pu,summary:Ou,terms:Lu,operationRef:Mu,revision:Du,does:Fu,signedIn:zu&&typeof zu.signed_in=="boolean"?zu.signed_in:null,expiresAt:text$h(Ru.expires_at),was:Bu?{revision:ju,terms:record$1(Bu.terms)??{}}:null,onlyThePerson:Ru.only_the_person===!0}}case PAP_OUTCOME_TYPE:{const Pu=OUTCOMES.find(Lu=>Lu===Ru.state),Ou=words(Ru.company),Mu=text$h(Ru.summary),Du=text$h(Ru.result);return!Pu||!Ou||!Mu.trim()||!words(Ru.operation_ref)||!count(Ru.revision)||Pu==="in_progress"!=!Du.trim()?Iu:{kind:"outcome",id:$u,company:Ou,summary:Mu,operationRef:words(Ru.operation_ref),revision:count(Ru.revision),state:Pu,result:Du,approvedBy:Ru.approved_by==="user"||Ru.approved_by==="standing_permission"?Ru.approved_by:null}}case PAP_REPLIES_TYPE:{const Pu=words(Ru.company),Ou=text$h(Ru.conversation),Mu=Array.isArray(Ru.replies)?Ru.replies.map(record$1).map(Du=>({sender:who(Du?.sender),text:text$h(Du?.text)})):[];return!Pu||!/^[A-Za-z0-9_-]{1,256}$/.test(Ou)||!Mu.length||Mu.some(Du=>!Du.sender||!Du.text.trim())?Iu:{kind:"replies",id:$u,company:Pu,conversation:Ou,replies:Mu,status:STATUSES.find(Du=>Du===Ru.status)??null,responder:who(Ru.responder)}}case SHIELD_DIFF_TYPE:{const Pu=words(Ru.path);return!Pu||typeof Ru.new_text!="string"||!(Ru.old_text===null||Ru.old_text===void 0||typeof Ru.old_text=="string")?Iu:{kind:"diff",id:$u,path:Pu,oldText:typeof Ru.old_text=="string"?Ru.old_text:null,newText:Ru.new_text,language:words(Ru.language)||languageOf$1(Pu)}}case SHIELD_TERMINAL_TYPE:{const Pu=words(Ru.terminal_id);if(!Pu)return Iu;const Ou=typeof Ru.exit_code=="number"&&Number.isInteger(Ru.exit_code)?Ru.exit_code:null;return Ru.exit_code!==null&&Ru.exit_code!==void 0&&Ou===null?Iu:{kind:"terminal",id:$u,terminalId:Pu,command:text$h(Ru.command),output:text$h(Ru.output),exitCode:Ou,released:Ru.released===!0}}default:return Iu}}const PAP_HANDOFF_TOOL=/(^|[_.:\-/])pap_handoff$/;function displayOfToolResult(Au,lo,$u=""){const Ru=record$1(lo),Iu=record$1(Ru?._meta)?.[DISPLAY_META_KEY];if(Iu!==void 0)return protocolDisplayOf(Iu);if(isPapSignInTool(Au)){const Pu=readPapSignIn(lo);return Pu?"refused"in Pu?{kind:"sign-in-refused",id:$u,why:Pu.refused}:{kind:"sign-in",id:$u,...Pu}:null}if(PAP_HANDOFF_TOOL.test(Au)&&Ru){const Pu=text$h(Ru.status);return Pu?{kind:"handoff",id:$u,handed:Pu!=="closed"&&Pu!=="direct_conversation_open",responder:who(Ru.responder),note:text$h(Ru.note)}:null}return null}function displayLine(Au){switch(Au.kind){case"sign-in":return Au.mode==="mediated"?`Sign in through ${Au.host}`:`Sign in at ${Au.company||Au.host}`;case"sign-in-refused":return Au.why;case"confirm":return`${Au.company} asks you to confirm: ${Au.summary} (version ${Au.revision})`;case"outcome":return Au.state==="in_progress"?`Still in progress at ${Au.company}: ${Au.summary}`:`${OUTCOME_LEADS[Au.state]} ${Au.company}: ${Au.result}`;case"replies":return`${Au.company} answered${Au.responder==="human"?": one of its people is answering":""}`;case"handoff":return Au.handed?`Handed to ${Au.responder==="human"?"one of the company’s people":"the company"}`:Au.note||"Nothing was handed over.";case"diff":{const lo=countLines(Au.newText);return Au.oldText===null?`Wrote ${Au.path} (${lo} lines)`:`Changed ${Au.path} (+${lo} −${countLines(Au.oldText)} lines)`}case"terminal":{const lo=Au.command?`Ran \`${Au.command}\``:`Terminal ${Au.terminalId}`;return Au.exitCode===null?`${lo}: running`:`${lo}: exit ${Au.exitCode}`}case"unknown":return Au.text||`A display this app cannot draw (${Au.type})`}}const OUTCOME_LEADS={succeeded:"Done at",failed:"Failed at",cancelled:"Cancelled at",expired:"Expired at"},countLines=Au=>Au===""?0:Au.split(`
|
|
2195
2195
|
`).length-(Au.endsWith(`
|
|
2196
2196
|
`)?1:0),LANGUAGES={py:"python",pyi:"python",ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",mjs:"javascript",json:"json",md:"markdown",mdx:"markdown",yaml:"yaml",yml:"yaml",toml:"toml",sh:"bash",bash:"bash",css:"css",scss:"scss",html:"html",xml:"xml",sql:"sql",rs:"rust",go:"go",java:"java",c:"c",h:"c",cpp:"cpp",rb:"ruby",ipynb:"json",txt:"text"};function languageOf$1(Au){const lo=Au.split("/").pop()??"";if(lo==="Dockerfile"||lo==="Makefile")return lo.toLowerCase();const $u=lo.lastIndexOf(".");return $u>0?LANGUAGES[lo.slice($u+1).toLowerCase()]??"text":"text"}const DIFF_LINES_LIMIT=2e3,lines=Au=>Au===""?[]:Au.replace(/\n$/,"").split(`
|
|
2197
|
-
`);function unifiedDiffLines(Au,lo){const $u=Au===null?[]:lines(Au),Ru=lines(lo);if($u.length>DIFF_LINES_LIMIT||Ru.length>DIFF_LINES_LIMIT)return[...$u.map(Du=>({kind:"remove",text:Du})),...Ru.map(Du=>({kind:"add",text:Du}))];const Iu=[];for(let Du=0;Du<=$u.length;Du++)Iu.push(new Uint32Array(Ru.length+1));for(let Du=$u.length-1;Du>=0;Du--)for(let Lu=Ru.length-1;Lu>=0;Lu--)Iu[Du][Lu]=$u[Du]===Ru[Lu]?Iu[Du+1][Lu+1]+1:Math.max(Iu[Du+1][Lu],Iu[Du][Lu+1]);const Pu=[];let Ou=0,Mu=0;for(;Ou<$u.length&&Mu<Ru.length;)$u[Ou]===Ru[Mu]?(Pu.push({kind:"context",text:$u[Ou]}),Ou++,Mu++):Iu[Ou+1][Mu]>=Iu[Ou][Mu+1]?(Pu.push({kind:"remove",text:$u[Ou]}),Ou++):(Pu.push({kind:"add",text:Ru[Mu]}),Mu++);for(;Ou<$u.length;)Pu.push({kind:"remove",text:$u[Ou++]});for(;Mu<Ru.length;)Pu.push({kind:"add",text:Ru[Mu++]});return Pu}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 (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 ITEM_LIMIT=400,MESSAGE_TEXT_LIMIT=1e5,TOOL_TEXT_LIMIT=4e3,DIAGNOSTIC_LIMIT=50,DEVICE_LIMITS={items:ITEM_LIMIT,messageText:MESSAGE_TEXT_LIMIT,toolText:TOOL_TEXT_LIMIT,diagnostics:DIAGNOSTIC_LIMIT},BROWSER_LIMITS={items:5e3,messageText:1e6,toolText:1e6,diagnostics:DIAGNOSTIC_LIMIT},CUT_MARK="… (cut: too long to keep on this device)",emptyConversation=(Au=DEVICE_LIMITS)=>{for(const[lo,$u]of Object.entries(Au))if(!Number.isInteger($u)||$u<1)throw new Error(`A conversation's ${lo} bound is ${String($u)}: give a whole number of at least 1.`);return{items:[],running:!1,session:null,asking:null,dropped:0,diagnostics:[],turnRows:0,limits:Au}},text$g=Au=>typeof Au=="string"?Au:"",cut=(Au,lo)=>Au.length>lo?`${Au.slice(0,lo)}${CUT_MARK}`:Au,appended=(Au,lo,$u)=>Au.endsWith(CUT_MARK)?Au:cut(Au+lo,$u),isRecord$2=Au=>!!Au&&typeof Au=="object"&&!Array.isArray(Au);function withoutMeta(Au){if(isRecord$2(Au)&&"_meta"in Au){const{_meta:lo,...$u}=Au;return $u}return Au}function said$1(Au){return Au==null?"":typeof Au=="string"?Au:JSON.stringify(Au)}function questionOf$1(Au){if(!Au||typeof Au!="object")return null;const lo=Au,$u=lo.kind;if($u!=="text"&&$u!=="choice"&&$u!=="form"&&$u!=="file")throw new Error(`The application asks something no client knows: ${String($u)}.`);const Ru=Pu=>Array.isArray(Pu)?Pu.filter(Ou=>typeof Ou=="string"):[],Iu=lo.schema;return{kind:$u,prompt:text$g(lo.prompt),options:Ru(lo.options),schema:isRecord$2(Iu)?Iu:null,accept:Ru(lo.accept)}}function withItems(Au,lo,$u=0){const Ru=lo.length-Au.limits.items;return{...Au,items:Ru>0?lo.slice(Ru):lo,dropped:Au.dropped+Math.max(0,Ru),turnRows:Au.turnRows+$u}}function changed$1(Au,lo,$u){const Ru=Au.items.findIndex(Pu=>Pu.id===lo);if(Ru<0)return null;const Iu=Au.items.slice();return Iu[Ru]=$u(Iu[Ru]),{...Au,items:Iu}}function noted(Au,lo){const $u={type:lo.type,name:text$g(lo.name)||text$g(lo.activityType)};return{...Au,diagnostics:[...Au.diagnostics,$u].slice(-Au.limits.diagnostics)}}const HARNESS_TOOL_CALL="datalayer.harness.tool_call";function withRunningDisplay(Au,lo){if(!isRecord$2(lo)||!isRecord$2(lo._meta))return null;const $u=lo._meta[DISPLAY_META_KEY];if($u===void 0)return null;const Ru=protocolDisplayOf($u);if(!Ru)throw new Error(`${HARNESS_TOOL_CALL} of ${text$g(lo.id)} carries a display no client reads.`);return changed$1(Au,text$g(lo.id),Iu=>Iu.kind==="tool"&&Iu.status==="running"?{...Iu,value:{_meta:lo._meta},display:Ru}:Iu)}let rowCount=0;const rowId=Au=>`${Au}-${Date.now().toString(36)}-${rowCount+=1}`;function toolRow(Au,lo){return{kind:"tool",id:Au,name:lo,args:"",input:null,status:"running",awaiting:null,result:"",value:void 0,error:"",executionError:"",codeError:null,exitCode:null,display:null}}function withInput(Au,lo,$u){const Ru=JSON.stringify(lo),Iu=Ru.length<=$u;return{...Au,args:cut(Ru,$u),input:Iu?lo:null}}const asksThePerson=Au=>!!Au&&Array.isArray(Au.steps);function withResult(Au,lo,$u,Ru=!1){const Iu=lo.result,Pu=said$1(withoutMeta(Iu)),Ou=isRecord$2(Iu)?Iu:null,Mu=typeof Ou?.execution_error=="string"?Ou.execution_error:"",Du=isRecord$2(Ou?.code_error)?Ou.code_error:null,Lu=Du?{name:text$g(Du.name)||"Error",value:text$g(Du.value)||"Unknown error",traceback:cut(text$g(Du.traceback),$u)}:null,Bu=Ou&&typeof Ou.exit_code=="number"?Ou.exit_code:null,ju=!lo.success||Mu!==""||Lu!==null||Bu!==null&&Bu!==0||Ou?.execution_ok===!1,Fu=ju||Ru?null:Ou?.pending_approval===!0?"approval":asksThePerson(Au.input)?"person":null;return{...Au,status:ju?"error":Fu?"running":"complete",awaiting:Fu,result:cut(Pu,$u),value:Pu.length<=$u?Iu:void 0,error:lo.error??"",executionError:cut(Mu,$u),codeError:Lu,exitCode:Bu,display:displayOfToolResult(Au.name,Iu,Au.id)}}function rowsOfSnapshot(Au,lo,$u){if(!Array.isArray(Au))throw new Error("A messages snapshot carries no list of messages.");const Ru=[],Iu=new Map;for(const Pu of Au){for(const Ou of messagesOfThread([Pu]))Ru.push({kind:"message",id:Ou.id,role:Ou.role==="user"?"user":"assistant",text:cut(typeof Ou.content=="string"?Ou.content:"",lo.messageText),streaming:!1});if(isRecord$2(Pu)){if(Pu.role==="assistant"&&Pu.toolCalls!==void 0){if(!Array.isArray(Pu.toolCalls))throw new Error(`Message ${String(Pu.id)}'s tool calls are not a list.`);for(const Ou of Pu.toolCalls){const Mu=isRecord$2(Ou)?Ou.function:void 0;if(!isRecord$2(Ou)||typeof Ou.id!="string"||!isRecord$2(Mu))throw new Error(`Message ${String(Pu.id)} holds a tool call without its id and function.`);const Du=text$g(Mu.arguments);let Lu=null;if(Du&&Du.length<=lo.toolText){let Bu;try{Bu=JSON.parse(Du)}catch{Bu=void 0}if(!isRecord$2(Bu))throw new Error(`Tool call ${Ou.id}'s arguments are not a JSON object.`);Lu=Bu}Iu.set(Ou.id,Ru.length),Ru.push({...toolRow(Ou.id,text$g(Mu.name)),args:cut(Du,lo.toolText),input:Du?Lu:{},status:"complete"})}}if(Pu.role==="tool"){const Ou=text$g(Pu.toolCallId),Mu=Iu.get(Ou);if(Mu===void 0){$u.push(Ou||"no call");continue}Ru[Mu]=withResult(Ru[Mu],toolResultOf(Pu.content),lo.toolText,!0)}}}return Ru}function withPrompt(Au,lo,$u){return withItems({...Au,asking:null},[...Au.items,{kind:"message",id:lo,role:"user",text:$u,streaming:!1}])}function withoutItems(Au,lo){const $u=new Set(lo);return{...Au,items:Au.items.filter(Ru=>!$u.has(Ru.id))}}function withTurnEnded(Au,lo){const $u=Au.items.map(Iu=>Iu.kind==="message"&&Iu.streaming?{...Iu,streaming:!1}:Iu.kind==="tool"&&Iu.status==="running"?{...Iu,status:"error",awaiting:null,error:RUN_END_WORDS[lo]}:Iu.kind==="step"&&Iu.status==="running"?{...Iu,status:"complete"}:Iu),Ru={...Au,items:$u,running:!1};return withItems(Ru,[...$u,{kind:"end",id:rowId("end"),end:lo,words:RUN_END_WORDS[lo]}])}function withError(Au,lo){const $u=Au.items.map(Ru=>Ru.kind==="message"&&Ru.streaming?{...Ru,streaming:!1}:Ru.kind==="tool"&&Ru.status==="running"?{...Ru,status:"error",awaiting:null}:Ru.kind==="step"&&Ru.status==="running"?{...Ru,status:"complete"}:Ru);return withItems({...Au,running:!1},[...$u,{kind:"error",id:rowId("error"),text:lo}])}function required(Au,lo){const $u=Au[lo];if(typeof $u!="string"||!$u)throw new Error(`${Au.type} carries no ${lo}.`);return $u}function reduceConversation(Au,lo){const{limits:$u}=Au;switch(lo.type){case"RUN_STARTED":return{...Au,running:!0,asking:null,turnRows:0};case"TEXT_MESSAGE_START":{const Ru=text$g(lo.messageId)||rowId("message");if(Au.items.some(Pu=>Pu.id===Ru))return Au;const Iu=lo.role==="user"?"user":"assistant";return withItems(Au,[...Au.items,{kind:"message",id:Ru,role:Iu,text:"",streaming:!0}],1)}case"TEXT_MESSAGE_CONTENT":case"TEXT_MESSAGE_CHUNK":{const Ru=text$g(lo.delta),Iu=text$g(lo.messageId),Pu=changed$1(Au,Iu,Ou=>Ou.kind==="message"?{...Ou,text:appended(Ou.text,Ru,$u.messageText)}:Ou);return Pu||withItems(Au,[...Au.items,{kind:"message",id:Iu||rowId("message"),role:lo.role==="user"?"user":"assistant",text:cut(Ru,$u.messageText),streaming:lo.type==="TEXT_MESSAGE_CONTENT"}],1)}case"TEXT_MESSAGE_END":return changed$1(Au,text$g(lo.messageId),Ru=>Ru.kind==="message"?{...Ru,streaming:!1}:Ru)??Au;case"MESSAGE_SAID":{const Ru=required(lo,"messageId");if(typeof lo.text!="string")throw new Error(`MESSAGE_SAID of ${Ru} carries no text.`);if(lo.role!=="user"&&lo.role!=="assistant")throw new Error(`MESSAGE_SAID of ${Ru} is said by ${String(lo.role)}: only the person or the assistant speaks here.`);const Iu=lo.role,Pu=cut(lo.text,$u.messageText),Ou=Iu==="assistant"&&lo.streaming!==!1,Mu=Au.items.findIndex(Du=>Du.id===Ru);if(Mu>=0){const Du=Au.items[Mu];if(Du.kind!=="message")throw new Error(`MESSAGE_SAID of ${Ru} names a ${Du.kind} row.`);const Lu=Au.items.slice();return Lu[Mu]={...Du,text:Pu,streaming:Ou},{...Au,items:Lu}}return withItems(Au,[...Au.items,{kind:"message",id:Ru,role:Iu,text:Pu,streaming:Ou}],1)}case"TOOL_CALL_START":{const Ru=text$g(lo.toolCallId)||rowId("tool");return Au.items.some(Iu=>Iu.id===Ru)?Au:withItems(Au,[...Au.items,toolRow(Ru,text$g(lo.toolCallName)||text$g(lo.name))],1)}case"TOOL_CALL_ARGS":return changed$1(Au,text$g(lo.toolCallId),Ru=>Ru.kind==="tool"?{...Ru,args:appended(Ru.args,text$g(lo.delta),$u.toolText)}:Ru)??Au;case"TOOL_CALL_END":return changed$1(Au,text$g(lo.toolCallId),Ru=>{if(Ru.kind!=="tool"||Ru.args.endsWith(CUT_MARK))return Ru;if(!Ru.args)return{...Ru,input:{}};let Iu;try{Iu=JSON.parse(Ru.args)}catch{Iu=void 0}return isRecord$2(Iu)?{...Ru,input:Iu}:{...Ru,status:"error",awaiting:null,error:"Its arguments are not a JSON object."}})??Au;case"TOOL_CALL_SAID":{const Ru=required(lo,"toolCallId"),Iu=required(lo,"toolCallName");if(!isRecord$2(lo.args))throw new Error(`TOOL_CALL_SAID of ${Ru} carries arguments that are not an object.`);const Pu=lo.args,Ou=Au.items.findIndex(Lu=>Lu.id===Ru);if(Ou<0)return withItems(Au,[...Au.items,withInput(toolRow(Ru,Iu),Pu,$u.toolText)],1);const Mu=Au.items[Ou];if(Mu.kind!=="tool")throw new Error(`TOOL_CALL_SAID of ${Ru} names a ${Mu.kind} row.`);const Du=Au.items.slice();return Du[Ou]=withInput(Mu,{...Mu.input??{},...Pu},$u.toolText),{...Au,items:Du}}case"TOOL_CALL_RESULT":{const Ru=toolResultOf(lo.content);return changed$1(Au,text$g(lo.toolCallId),Iu=>Iu.kind==="tool"?withResult(Iu,Ru,$u.toolText):Iu)??noted(Au,lo)}case"TOOL_CALL_DONE":{const Ru=required(lo,"toolCallId");if(typeof lo.success!="boolean")throw new Error(`TOOL_CALL_DONE of ${Ru} does not say whether it succeeded.`);if(lo.error!==void 0&&typeof lo.error!="string")throw new Error(`TOOL_CALL_DONE of ${Ru} says its error in no words.`);const Iu={result:lo.result,success:lo.success,...lo.error!==void 0?{error:lo.error}:{}};return changed$1(Au,Ru,Pu=>Pu.kind==="tool"?withResult(Pu,Iu,$u.toolText,lo.answered===!0):Pu)??noted(Au,lo)}case"STEP_STARTED":{const Ru=text$g(lo.stepName)||text$g(lo.name);return withItems(Au,[...Au.items,{kind:"step",id:rowId("step"),name:Ru,status:"running"}],1)}case"STEP_FINISHED":{const Ru=text$g(lo.stepName)||text$g(lo.name),Iu=Au.items.map((Ou,Mu)=>({item:Ou,index:Mu})).reverse().find(({item:Ou})=>Ou.kind==="step"&&Ou.name===Ru&&Ou.status==="running");if(!Iu)return noted(Au,lo);const Pu=Au.items.slice();return Pu[Iu.index]={...Iu.item,status:"complete"},{...Au,items:Pu}}case"MESSAGES_SNAPSHOT":{const Ru=[],Iu=rowsOfSnapshot(lo.messages,$u,Ru),Pu=withItems({...Au,dropped:0},Iu,1);return Ru.reduce((Ou,Mu)=>noted(Ou,{type:"TOOL_CALL_RESULT",name:`${Mu} (no call)`}),Pu)}case"CUSTOM":{if(lo.name===REACTOR_UI_NAME)return withError(Au,UI_ON_RUN);if(lo.name==="loop.session"&&isRecord$2(lo.value)){const Ru=lo.value;return{...Au,session:Ru,asking:questionOf$1(Ru.asking)??Au.asking}}return lo.name===HARNESS_TOOL_CALL?withRunningDisplay(Au,lo.value)??noted(Au,lo):noted(Au,lo)}case"ACTIVITY_SNAPSHOT":case"ACTIVITY_DELTA":return lo.activityType===REACTOR_UI_NAME?withError(Au,UI_ON_RUN):noted(Au,lo);case"RUN_FINISHED":{const Ru=isRecord$2(lo.result)?lo.result:{},Iu=questionOf$1(Ru.asking),Pu=Au.items.map(Mu=>Mu.kind==="message"&&Mu.streaming?{...Mu,streaming:!1}:Mu),Ou={...Au,items:Pu,running:!1,asking:Iu};return Iu||Au.turnRows>0?Ou:withItems(Ou,[...Pu,{kind:"end",id:rowId("end"),end:"answered",words:RUN_END_WORDS.answered}])}case"RUN_ERROR":return withError(Au,text$g(lo.message)||"Run failed");default:return noted(Au,lo)}}const emptyChatLayer=()=>({extras:new Map,displays:new Map,speakers:new Map,steps:[]}),toolCardId=Au=>`tool-${Au}`,rowIdOf=Au=>"toolCallId"in Au&&Au.id===toolCardId(Au.toolCallId)?Au.toolCallId:Au.id;function cardStatusOf(Au){return Au.status!=="running"?Au.status:Au.awaiting==="approval"?"inProgress":"executing"}function toolCallOf(Au){return{id:toolCardId(Au.id),type:"tool-call",toolCallId:Au.id,toolName:Au.name,args:Au.input??{},...Au.value!==void 0?{result:Au.value}:Au.result?{result:Au.result}:{},status:cardStatusOf(Au),...Au.error?{error:Au.error}:{},...Au.executionError?{executionError:Au.executionError}:{},...Au.codeError?{codeError:{name:Au.codeError.name,value:Au.codeError.value,...Au.codeError.traceback?{traceback:Au.codeError.traceback}:{}}}:{},...Au.exitCode!==null?{exitCode:Au.exitCode}:{}}}function conversationDrawer(Au){const lo=new Map,$u=(Iu,Pu)=>{const Ou=Pu.extras.get(Iu.id),Mu=Pu.displays.get(Iu.id),Du=Pu.speakers.get(Iu.id),Lu=lo.get(Iu.id);if(Lu&&Lu.row===Iu&&Lu.extras===Ou&&Lu.displays===Mu&&Lu.speaker===Du)return Lu.item;const Bu={...Ou,createdAt:Ou?.createdAt??new Date,id:Iu.id,role:Iu.kind==="message"?Iu.role:"assistant",content:Iu.kind==="message"?Iu.text:Au(Iu.text),...Mu?{displays:Mu}:{},...Du?{speaker:Du}:{}};return lo.set(Iu.id,{row:Iu,extras:Ou,displays:Mu,speaker:Du,item:Bu}),Bu},Ru=Iu=>{const Pu=lo.get(Iu.id);if(Pu&&Pu.row===Iu)return Pu.item;const Ou=toolCallOf(Iu);return lo.set(Iu.id,{row:Iu,item:Ou}),Ou};return(Iu,Pu)=>{const Ou=[],Mu=new Map;for(const Lu of Pu.steps)Mu.set(Lu.after,[...Mu.get(Lu.after)??[],Lu.item]);Ou.push(...Mu.get(null)??[]);const Du=new Set;for(const Lu of Iu.items)Du.add(Lu.id),Lu.kind==="message"||Lu.kind==="error"?Ou.push($u(Lu,Pu)):Lu.kind==="tool"&&Ou.push(Ru(Lu)),Ou.push(...Mu.get(Lu.id)??[]);for(const[Lu,Bu]of Mu)Lu!==null&&!Du.has(Lu)&&Ou.push(...Bu);for(const Lu of lo.keys())Du.has(Lu)||lo.delete(Lu);return Ou}}function isSubagentRunOver(Au){return Au.some(lo=>lo.phase==="end"||lo.phase==="error")}function getMonitoringCacheKey(Au,lo){return`${Au||"__unknown_service__"}::${lo||"__unknown_agent__"}`}function getTransportEndpoint(Au,lo,$u){switch(lo){case"vercel-ai":return`${Au}/api/v1/vercel-ai/${$u}`;case"a2a":return`${Au}/api/v1/a2a/agents/${$u}/`;case"acp":return`${Au}/api/v1/acp/ws/${$u}`;default:return`${Au}/api/v1/ag-ui/${$u}/`}}function toAgentRuntimeBaseUrl(Au){const lo=Au.replace(/\/$/,"");return lo.includes("/api/agent-runtimes")?lo:lo.includes("/api/jupyter-server")?lo.replace("/api/jupyter-server","/api/agent-runtimes"):lo.includes("/jupyter/server/")?lo.replace("/jupyter/server/","/agent-runtimes/"):lo.includes("/jupyter-server/")?lo.replace("/jupyter-server/","/agent-runtimes/"):lo.replace("/jupyter/","/agent-runtimes/")}async function createAgentOnRuntime(Au,lo,$u={}){const{iamStore:Ru}=await __vitePreload(async()=>{const{iamStore:Lu}=await import("./chunks/index-D8x0MQWQ.js");return{iamStore:Lu}},[],import.meta.url),Iu=Ru.getState().token||"";if(!$u.protocol&&!$u.agentSpecId)throw new Error("Agent protocol is required. Provide config.protocol from the selected spec/config.");const Pu=$u.protocol||"vercel-ai";if(!$u.model&&!$u.agentSpecId)throw new Error("Agent model is required. Provide config.model from the selected spec/config.");const Ou={name:$u.name||lo,description:$u.description||"AI assistant",agent_library:$u.agentLibrary||"pydantic-ai",transport:Pu,model:$u.model,system_prompt:$u.systemPrompt||"You are a helpful AI assistant."};$u.agentSpecId&&(Ou.agent_spec_id=$u.agentSpecId),typeof $u.enableSkills=="boolean"&&(Ou.enable_skills=$u.enableSkills),Array.isArray($u.backendTools)&&(Ou.backend_tools=$u.backendTools),$u.inferenceProvider&&(Ou.inferenceProvider=$u.inferenceProvider),typeof $u.enableCodemode=="boolean"&&(Ou.enable_codemode=$u.enableCodemode),$u.sandboxVariant&&(Ou.sandbox_variant=$u.sandboxVariant),$u.jupyterSandbox&&(Ou.jupyter_sandbox=$u.jupyterSandbox),$u.createPayload&&typeof $u.createPayload=="object"&&Object.assign(Ou,$u.createPayload);const Mu=await fetch(`${Au}/api/v1/agents`,{method:"POST",headers:{"Content-Type":"application/json",...Iu?{Authorization:`Bearer ${Iu}`}:{}},body:JSON.stringify(Ou)});if(Mu.ok||Mu.status===400||Mu.status===409){const Lu=getTransportEndpoint(Au,Pu,lo);return{agentId:lo,endpoint:Lu,isReady:!0}}const Du=await Mu.json().catch(()=>({}));throw new Error(Du.detail||`Failed to create agent: ${Mu.status}`)}const initialRuntimeState={runtime:null,status:"idle",error:null,isLaunching:!1,historyVersion:0,toolDecisionRequest:null},initialWsState={wsState:"closed",approvals:[],pendingApprovalCount:0,subagentActivity:{},compaction:null,contextSnapshot:null,costUsage:null,mcpStatus:null,codemodeStatus:null,fullContext:null,monitoringCache:{},loadedSkillsByAgentId:{}},initialNotebookState={ephemeralNotebookModels:{},ephemeralDocumentModels:{},editorModeByRuntime:{}},countPendingApprovals=Au=>Au.filter(lo=>lo.status==="pending").length;let _ws=null;const _wsByAgentId=new Map;function _resolveWs(Au){const lo=_wsByAgentId.size>0;if(Au){const $u=_wsByAgentId.get(Au);if($u&&$u.readyState===WebSocket.OPEN)return $u;if(lo)return null}return lo?null:_ws&&_ws.readyState===WebSocket.OPEN?_ws:null}const agentRuntimeStore=createStore$1()(subscribeWithSelector(persist((Au,lo)=>({agents:[],upsertAgent:$u=>{Au(Ru=>{const Iu=Ru.agents.findIndex(Mu=>Mu.id===$u.id),Pu=Date.now();if(Iu>=0){const Mu=[...Ru.agents];return Mu[Iu]={...Mu[Iu],...$u,lastUpdated:Pu},{agents:Mu}}const Ou={name:$u.name||$u.id,description:$u.description||"",status:$u.status||"initializing",lastUpdated:Pu,...$u};return{agents:[...Ru.agents,Ou]}})},getAgentById:$u=>lo().agents.find(Ru=>Ru.id===$u),getAgentByUrl:($u,Ru)=>lo().agents.find(Iu=>Iu.baseUrl===$u&&Iu.protocol===Ru),updateAgentStatus:($u,Ru,Iu=null)=>{Au(Pu=>{const Ou=Pu.agents.findIndex(Mu=>Mu.id===$u);if(Ou>=0){const Mu=[...Pu.agents];return Mu[Ou]={...Mu[Ou],status:Ru,error:Iu,lastUpdated:Date.now()},{agents:Mu}}return{}})},toggleAgentStatus:$u=>{Au(Ru=>{const Iu=Ru.agents.findIndex(Pu=>Pu.id===$u);if(Iu>=0){const Pu=[...Ru.agents],Ou=Pu[Iu].status;return Pu[Iu]={...Pu[Iu],status:Ou==="running"?"paused":"running",lastUpdated:Date.now()},{agents:Pu}}return{}})},deleteAgent:$u=>{Au(Ru=>{const{[$u]:Iu,...Pu}=Ru.loadedSkillsByAgentId;return{agents:Ru.agents.filter(Ou=>Ou.id!==$u),loadedSkillsByAgentId:Pu}})},clearAgents:()=>{Au({agents:[]})},setLoadedSkillsForAgent:($u,Ru)=>{Au(Iu=>({loadedSkillsByAgentId:{...Iu.loadedSkillsByAgentId,[$u]:Ru}}))},getLoadedSkillsForAgent:$u=>lo().loadedSkillsByAgentId[$u]??[],clearLoadedSkillsForAgent:$u=>{Au(Ru=>{if(!($u in Ru.loadedSkillsByAgentId))return{};const{[$u]:Iu,...Pu}=Ru.loadedSkillsByAgentId;return{loadedSkillsByAgentId:Pu}})},setEphemeralNotebookModel:($u,Ru)=>{Au(Iu=>({ephemeralNotebookModels:{...Iu.ephemeralNotebookModels,[$u]:Ru}}))},getEphemeralNotebookModel:$u=>lo().ephemeralNotebookModels[$u]??null,clearEphemeralNotebookModel:$u=>{Au(Ru=>{if(!($u in Ru.ephemeralNotebookModels))return{};const{[$u]:Iu,...Pu}=Ru.ephemeralNotebookModels;return{ephemeralNotebookModels:Pu}})},setEphemeralDocumentModel:($u,Ru)=>{Au(Iu=>({ephemeralDocumentModels:{...Iu.ephemeralDocumentModels,[$u]:Ru}}))},getEphemeralDocumentModel:$u=>lo().ephemeralDocumentModels[$u]??null,clearEphemeralDocumentModel:$u=>{Au(Ru=>{if(!($u in Ru.ephemeralDocumentModels))return{};const{[$u]:Iu,...Pu}=Ru.ephemeralDocumentModels;return{ephemeralDocumentModels:Pu}})},setEditorMode:($u,Ru)=>{$u&&Au(Iu=>({editorModeByRuntime:{...Iu.editorModeByRuntime,[$u]:Ru}}))},getEditorMode:$u=>lo().editorModeByRuntime[$u]??null,...initialRuntimeState,connectAgent:$u=>{const Ru=$u.jupyterBaseUrl||$u.serviceManager?.serverSettings.baseUrl;if(!Ru)throw new Error("connectAgent requires either jupyterBaseUrl or serviceManager");const Iu=toAgentRuntimeBaseUrl(Ru);Au({runtime:{runtimeName:$u.runtimeName,environmentName:$u.environmentName,jupyterBaseUrl:Ru,agentBaseUrl:Iu,serviceManager:$u.serviceManager,status:"ready",kernelId:$u.kernelId},status:"ready",error:null})},launchAgent:async $u=>{Au({status:"launching",error:null,isLaunching:!0});try{const{createRuntime:Ru}=await __vitePreload(async()=>{const{createRuntime:ju}=await Promise.resolve().then(()=>actions);return{createRuntime:ju}},void 0,import.meta.url),{runtimesStore:Iu}=await __vitePreload(async()=>{const{runtimesStore:ju}=await import("./chunks/index-D_vehxcD.js");return{runtimesStore:ju}},[],import.meta.url);$u.runtimesUrl&&Iu.setState({runtimesUrl:$u.runtimesUrl});const{runtimesUrl:Pu,...Ou}=$u,Mu=await Ru({environmentName:Ou.environmentName,creditsLimit:Ou.creditsLimit,type:Ou.type||"notebook",givenName:Ou.givenName,capabilities:Ou.capabilities,snapshot:Ou.snapshot,appSpec:Ou.appSpec,appUid:Ou.appUid,deploymentUid:Ou.deploymentUid});Au({status:"connecting"});const Du=Mu.ingress,Lu=toAgentRuntimeBaseUrl(Du),Bu={runtimeName:Mu.runtime_name,environmentName:Mu.environment.name,jupyterBaseUrl:Du,agentBaseUrl:Lu,status:"ready"};return Au({runtime:Bu,status:"ready",isLaunching:!1}),Bu}catch(Ru){const Iu=Ru instanceof Error?Ru.message:"Failed to launch runtime";throw Au({status:"error",error:Iu,isLaunching:!1}),Ru}},createAgent:async($u={})=>{const{runtime:Ru}=lo();if(!Ru)throw new Error("No runtime connected. Launch or connect to a runtime first.");try{const Iu=$u.name||Ru.runtimeName,Pu=await createAgentOnRuntime(Ru.agentBaseUrl,Iu,$u);return Au({runtime:{...Ru,agentId:Pu.agentId,endpoint:Pu.endpoint,isReady:Pu.isReady}}),Pu}catch(Iu){const Pu=Iu instanceof Error?Iu.message:"Failed to create agent";throw Au({error:Pu}),Iu}},disconnect:()=>{Au({runtime:null,status:"disconnected",error:null})},clearError:()=>Au({error:null}),setError:$u=>Au({error:$u,status:"error"}),...initialWsState,...initialNotebookState,setWsState:$u=>Au({wsState:$u}),setWs:($u,Ru)=>{_ws=$u,Ru&&($u?_wsByAgentId.set(Ru,$u):_wsByAgentId.delete(Ru))},applySnapshot:$u=>Au(Ru=>({approvals:Ru.approvals,pendingApprovalCount:Ru.pendingApprovalCount,contextSnapshot:$u.contextSnapshot??null,costUsage:$u.costUsage??null,mcpStatus:$u.mcpStatus??null,codemodeStatus:$u.codemodeStatus??null,fullContext:$u.fullContext??null})),appendSubagentEvent:$u=>Au(Ru=>{const Iu=$u.toolCallId??$u.subagentName,Pu=Ru.subagentActivity[Iu]??[];return Pu.some(Ou=>Ou.phase==="error"&&Ou.error===SUBAGENT_STOPPED)?{}:{subagentActivity:{...Ru.subagentActivity,[Iu]:[...Pu,$u]}}}),clearSubagentActivity:()=>Au({subagentActivity:{}}),stopSubagentActivity:()=>Au($u=>{let Ru=!1;const Iu={};for(const[Pu,Ou]of Object.entries($u.subagentActivity)){if(Ou.length===0||isSubagentRunOver(Ou)){Iu[Pu]=Ou;continue}Ru=!0,Iu[Pu]=[...Ou,{subagentName:Ou[0].subagentName,toolCallId:Ou[0].toolCallId??Pu,phase:"error",error:SUBAGENT_STOPPED,transport:Ou[0].transport}]}return Ru?{subagentActivity:Iu}:{}}),requestHistoryReload:()=>Au($u=>({historyVersion:$u.historyVersion+1})),requestToolDecision:$u=>Au(Ru=>({toolDecisionRequest:{seq:(Ru.toolDecisionRequest?.seq??0)+1,...$u}})),setCompaction:$u=>Au({compaction:$u}),upsertApproval:$u=>Au(Ru=>{const Iu=Ru.approvals.filter(Ou=>Ou.id!==$u.id),Pu=[$u,...Iu];return{approvals:Pu,pendingApprovalCount:countPendingApprovals(Pu)}}),removeApproval:$u=>Au(Ru=>{const Iu=Ru.approvals.filter(Pu=>Pu.id!==$u);return{approvals:Iu,pendingApprovalCount:countPendingApprovals(Iu)}}),sendDecision:($u,Ru,Iu,Pu,Ou)=>{const Mu=_resolveWs(Ou);return Mu?(Mu.send(JSON.stringify({type:"tool_approval_decision",approvalId:$u,approved:Ru,...Iu?{note:Iu}:{},...Pu?{toolCallId:Pu}:{}})),!0):!1},requestRefresh:$u=>{const Ru=_resolveWs($u);return Ru?(Ru.send(JSON.stringify({type:"request_snapshot"})),Ru.send(JSON.stringify({type:"request_otel_flush"})),!0):!1},sendRawMessage:($u,Ru)=>{const Iu=_resolveWs(Ru);return Iu?(Iu.send(JSON.stringify($u)),!0):!1},appendLocalTokenTurn:({serviceName:$u,agentId:Ru,timestampMs:Iu,promptTokens:Pu,completionTokens:Ou,totalTokens:Mu})=>{Au(Du=>{const Lu=getMonitoringCacheKey($u,Ru),Bu=Du.monitoringCache[Lu]??{tokenTurns:[],costPoints:[]},ju=[...Bu.tokenTurns],Fu=ju[ju.length-1];if(Fu&&Fu.userMessageTokens===Pu&&Fu.aiMessageTokens===Ou&&Fu.systemPromptTokens===0&&Fu.toolsDescriptionTokens===0&&Fu.toolsUsageTokens===0&&Fu.totalTokens===Mu)return ju[ju.length-1]={...Fu,timestampMs:Math.max(Fu.timestampMs,Iu)},{monitoringCache:{...Du.monitoringCache,[Lu]:{...Bu,tokenTurns:ju}}};const zu=(Fu?.turnNumber??0)+1;return ju.push({turnNumber:zu,timestampMs:Iu,systemPromptTokens:0,toolsDescriptionTokens:0,userMessageTokens:Pu,aiMessageTokens:Ou,toolsUsageTokens:0,totalTokens:Mu}),{monitoringCache:{...Du.monitoringCache,[Lu]:{...Bu,tokenTurns:ju}}}})},mergeTokenTurns:({serviceName:$u,agentId:Ru,turns:Iu})=>{Iu.length!==0&&Au(Pu=>{const Ou=getMonitoringCacheKey($u,Ru),Mu=Pu.monitoringCache[Ou]??{tokenTurns:[],costPoints:[]},Du=new Map;for(const Bu of Mu.tokenTurns)Du.set(Bu.turnNumber,Bu);for(const Bu of Iu)Du.set(Bu.turnNumber,Bu);const Lu=Array.from(Du.values()).sort((Bu,ju)=>Bu.turnNumber-ju.turnNumber);return{monitoringCache:{...Pu.monitoringCache,[Ou]:{...Mu,tokenTurns:Lu}}}})},appendLocalTokenTurnFull:({serviceName:$u,agentId:Ru,timestampMs:Iu,systemPromptTokens:Pu,toolsDescriptionTokens:Ou,userMessageTokens:Mu,aiMessageTokens:Du,toolsUsageTokens:Lu,totalTokens:Bu})=>{Au(ju=>{const Fu=getMonitoringCacheKey($u,Ru),zu=ju.monitoringCache[Fu]??{tokenTurns:[],costPoints:[]},Uu=[...zu.tokenTurns],Hu=Uu[Uu.length-1];if(Hu&&Hu.systemPromptTokens===Pu&&Hu.toolsDescriptionTokens===Ou&&Hu.userMessageTokens===Mu&&Hu.aiMessageTokens===Du&&Hu.toolsUsageTokens===Lu&&Hu.totalTokens===Bu)return Uu[Uu.length-1]={...Hu,timestampMs:Math.max(Hu.timestampMs,Iu)},{monitoringCache:{...ju.monitoringCache,[Fu]:{...zu,tokenTurns:Uu}}};const Vu=(Hu?.turnNumber??0)+1;return Uu.push({turnNumber:Vu,timestampMs:Iu,systemPromptTokens:Pu,toolsDescriptionTokens:Ou,userMessageTokens:Mu,aiMessageTokens:Du,toolsUsageTokens:Lu,totalTokens:Bu}),{monitoringCache:{...ju.monitoringCache,[Fu]:{...zu,tokenTurns:Uu}}}})},upsertLocalCostPoint:({serviceName:$u,agentId:Ru,timestampMs:Iu,cumulativeUsd:Pu})=>{Au(Ou=>{const Mu=getMonitoringCacheKey($u,Ru),Du=Ou.monitoringCache[Mu]??{tokenTurns:[],costPoints:[]},Lu=[...Du.costPoints],Bu=Lu.findIndex(ju=>Math.abs(ju.timestampMs-Iu)<1);return Bu>=0?Lu[Bu]={...Lu[Bu],cumulativeUsd:Math.max(Lu[Bu].cumulativeUsd,Pu)}:Lu.push({timestampMs:Iu,cumulativeUsd:Pu}),Lu.sort((ju,Fu)=>ju.timestampMs-Fu.timestampMs),{monitoringCache:{...Ou.monitoringCache,[Mu]:{...Du,costPoints:Lu}}}})},mergeCostPoints:({serviceName:$u,agentId:Ru,points:Iu})=>{Iu.length!==0&&Au(Pu=>{const Ou=getMonitoringCacheKey($u,Ru),Mu=Pu.monitoringCache[Ou]??{tokenTurns:[],costPoints:[]},Du=new Map;for(const Bu of Mu.costPoints)Du.set(Bu.timestampMs,Bu);for(const Bu of Iu){const ju=Du.get(Bu.timestampMs);ju?Du.set(Bu.timestampMs,{timestampMs:Bu.timestampMs,cumulativeUsd:Math.max(ju.cumulativeUsd,Bu.cumulativeUsd)}):Du.set(Bu.timestampMs,Bu)}const Lu=Array.from(Du.values()).sort((Bu,ju)=>Bu.timestampMs-ju.timestampMs);return{monitoringCache:{...Pu.monitoringCache,[Ou]:{...Mu,costPoints:Lu}}}})},reset:()=>{if(_ws)try{_ws.close(1e3,"reset")}catch{}_ws=null,_wsByAgentId.clear(),Au($u=>({...initialRuntimeState,...initialWsState,ephemeralNotebookModels:$u.ephemeralNotebookModels,ephemeralDocumentModels:$u.ephemeralDocumentModels,editorModeByRuntime:$u.editorModeByRuntime}))},resetWs:()=>{if(_ws)try{_ws.close(1e3,"reset")}catch{}_ws=null,_wsByAgentId.clear(),Au($u=>({...initialWsState,ephemeralNotebookModels:$u.ephemeralNotebookModels,ephemeralDocumentModels:$u.ephemeralDocumentModels,editorModeByRuntime:$u.editorModeByRuntime,subagentActivity:$u.subagentActivity}))}}),{name:"agent-runtimes-storage",storage:createJSONStorage(()=>localStorage),partialize:Au=>({agents:Au.agents.map(lo=>({id:lo.id,name:lo.name,description:lo.description,baseUrl:lo.baseUrl,transport:lo.protocol,status:lo.status,lastUpdated:lo.lastUpdated,documentId:lo.documentId,runtimeId:lo.runtimeId})),monitoringCache:Au.monitoringCache,loadedSkillsByAgentId:Au.loadedSkillsByAgentId,ephemeralNotebookModels:Au.ephemeralNotebookModels,ephemeralDocumentModels:Au.ephemeralDocumentModels,editorModeByRuntime:Au.editorModeByRuntime})})));function useAgentRuntimeStore(Au){return useStore$1(agentRuntimeStore,Au||($u=>$u))}const useAgentRuntimeStoreWithStatics=useAgentRuntimeStore;useAgentRuntimeStoreWithStatics.getState=agentRuntimeStore.getState;useAgentRuntimeStoreWithStatics.subscribe=agentRuntimeStore.subscribe;const useAgentRuntimeConnection=()=>useAgentRuntimeStore(Au=>Au.runtime),useAgentRuntimeStatus=()=>useAgentRuntimeStore(Au=>Au.status),useAgentRuntimeError=()=>useAgentRuntimeStore(Au=>Au.error),useAgentRuntimeIsLaunching=()=>useAgentRuntimeStore(Au=>Au.isLaunching),useAgentRuntimeMcpStatus=()=>useAgentRuntimeStore(Au=>Au.mcpStatus),useAgentRuntimeFullContext=()=>useAgentRuntimeStore(Au=>Au.fullContext),useAgentRuntimeContextSnapshot=()=>useAgentRuntimeStore(Au=>Au.contextSnapshot),useAgentRuntimeCodemodeStatus=()=>useAgentRuntimeStore(Au=>Au.codemodeStatus),useAgentRuntimeWsState=()=>useAgentRuntimeStore(Au=>Au.wsState),EMPTY_SUBAGENT_EVENTS=[],useAgentRuntimeSubagentActivity=Au=>useAgentRuntimeStore(lo=>Au?lo.subagentActivity[Au]??EMPTY_SUBAGENT_EVENTS:EMPTY_SUBAGENT_EVENTS),useAgentRuntimeSubagentActivityByToolCall=(Au,lo)=>useAgentRuntimeStore($u=>{if(Au){const Ru=$u.subagentActivity[Au];if(Ru&&Ru.length>0)return Ru}if(lo){const Ru=$u.subagentActivity[lo];if(Ru&&Ru.length>0)return Ru;let Iu;for(const Pu of Object.values($u.subagentActivity))Pu.length>0&&Pu[0]?.subagentName===lo&&(Iu=Pu);if(Iu)return Iu}return EMPTY_SUBAGENT_EVENTS}),useAgentRuntimeActiveSubagentToolCallId=()=>useAgentRuntimeStore(Au=>{let lo=null;for(const[$u,Ru]of Object.entries(Au.subagentActivity))Ru.length!==0&&(isSubagentRunOver(Ru)||(lo=$u));return lo});agentRuntimeStore.subscribe;async function requestAPI(Au="",lo={}){const $u=libExports$3.ServerConnection.makeSettings(),Ru=libExports$5.URLExt.join($u.baseUrl,"agent_runtimes",Au);let Iu;try{Iu=await libExports$3.ServerConnection.makeRequest(Ru,lo,$u)}catch(Ou){throw new libExports$3.ServerConnection.NetworkError(Ou)}let Pu=await Iu.text();if(Pu.length>0)try{Pu=JSON.parse(Pu)}catch{}if(!Iu.ok)throw new libExports$3.ServerConnection.ResponseError(Iu,Pu.message||Pu);return Pu}function useConfig(Au,lo,$u,Ru){return reactExports.useContext(QueryClientContext)?useQuery({queryFn:async()=>{if(lo){const Pu={"Content-Type":"application/json"};$u&&(Pu.Authorization=`Bearer ${$u}`);let Ou=lo;if(Ru){const Du=new URL(lo,window.location.origin);Du.searchParams.set("agent_id",Ru),Ou=Du.toString()}const Mu=await fetch(Ou,{headers:Pu});if(!Mu.ok)throw new Error(`Config fetch failed: ${Mu.statusText}`);return Mu.json()}return requestAPI("configure")},queryKey:["models",lo||"jupyter-server",Ru||"global"],enabled:Au,retry:1}):{data:void 0,isLoading:!1,isError:!1,error:null,refetch:()=>Promise.resolve({data:void 0})}}function parseSkillStatus(Au){return Au==="available"||Au==="enabled"||Au==="loaded"?Au:"available"}function useSkills(Au,lo,$u){const Ru=useAgentRuntimeCodemodeStatus(),Iu=reactExports.useMemo(()=>{if(!Ru)return;const Pu=(Ru.skills??[]).map(Ou=>({id:Ou.id??Ou.name,name:Ou.name,description:Ou.description,tags:Ou.tags,has_scripts:Ou.has_scripts,has_resources:Ou.has_resources,status:parseSkillStatus(Ou.status),approved:Ou.approved!==!1,skill_definition:Ou.skill_definition??null,source_variant:Ou.source_variant,module:Ou.module,package:Ou.package,method:Ou.method,path:Ou.path}));return{skills:Pu,total:Pu.length}},[Ru]);return{data:Iu,isLoading:!1,isError:!1,error:null,refetch:()=>Promise.resolve({data:Iu})}}function useSkillActions(Au){const lo=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_enable",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_enable dropped: websocket not ready"),Ou},[Au]),$u=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_disable",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_disable dropped: websocket not ready"),Ou},[Au]),Ru=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_approve",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_approve dropped: websocket not ready"),Ou},[Au]),Iu=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_unapprove",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_unapprove dropped: websocket not ready"),Ou},[Au]);return{enableSkill:lo,disableSkill:$u,approveSkill:Ru,unapproveSkill:Iu}}function useContextSnapshot(Au,lo,$u,Ru){return{data:useAgentRuntimeContextSnapshot()??void 0,isLoading:!1,isError:!1,error:null}}const RECONNECT_BASE_MS$1=1e3,RECONNECT_MAX_MS$1=3e4;function isRetryableCloseCode(Au){return!new Set([1002,1003,1007,1008,4401,4403]).has(Au)}function useSandbox(Au,lo,$u,Ru){const[Iu,Pu]=reactExports.useState(void 0),Ou=reactExports.useRef(null);reactExports.useEffect(()=>{if(!Au||!lo){Pu(void 0);return}const Du=getApiBaseFromConfig(lo);if(!Du)return;const Lu=Du.replace(/^http/,"ws"),Bu=[];Ru&&Bu.push(`agent_id=${encodeURIComponent(Ru)}`),$u&&Bu.push(`token=${encodeURIComponent($u)}`);const ju=`${Lu}/configure/sandbox/ws${Bu.length?`?${Bu.join("&")}`:""}`;let Fu=!1,zu,Uu=0;const Hu=Gu=>{if(Fu||!isRetryableCloseCode(Gu))return;const Wu=Math.min(RECONNECT_BASE_MS$1*2**Uu,RECONNECT_MAX_MS$1);Uu+=1,zu=setTimeout(Vu,Wu)},Vu=()=>{if(Fu)return;const Gu=new WebSocket(ju);Ou.current=Gu,Gu.onopen=()=>{Uu=0},Gu.onmessage=Wu=>{try{const Ku=JSON.parse(Wu.data);if(Ku&&Ku.action==="interrupt")return;const Ju=typeof Ku?.variant=="string"?Ku.variant:"";Pu({available:Ju!=="unavailable"&&Ju!=="error",sandbox_running:!!Ku?.sandbox_running,is_executing:!!Ku?.is_executing,variant:Ju})}catch{}},Gu.onclose=Wu=>{Ou.current=null,Hu(Wu.code)},Gu.onerror=()=>{Gu.close()}};return Vu(),()=>{Fu=!0,zu&&clearTimeout(zu),Ou.current?.close(),Ou.current=null,Pu(void 0)}},[Au,lo,$u,Ru]);const Mu=reactExports.useCallback(()=>{const Du=Ou.current;Du&&Du.readyState===WebSocket.OPEN&&Du.send(JSON.stringify({action:"interrupt"}))},[]);return{data:Iu,interrupt:Mu}}function _typeof$8(Au){"@babel/helpers - typeof";return _typeof$8=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$8(Au)}function _createClass$8(Au,lo,$u){return Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _classCallCheck$8(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _callSuper$1(Au,lo,$u){return lo=_getPrototypeOf$1(lo),_possibleConstructorReturn$1(Au,_isNativeReflectConstruct$1()?Reflect.construct(lo,$u||[],_getPrototypeOf$1(Au).constructor):lo.apply(Au,$u))}function _possibleConstructorReturn$1(Au,lo){if(lo&&(_typeof$8(lo)==="object"||typeof lo=="function"))return lo;if(lo!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized$1(Au)}function _assertThisInitialized$1(Au){if(Au===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return Au}function _inherits$1(Au,lo){if(typeof lo!="function"&&lo!==null)throw new TypeError("Super expression must either be null or a function");Au.prototype=Object.create(lo&&lo.prototype,{constructor:{value:Au,writable:!0,configurable:!0}}),Object.defineProperty(Au,"prototype",{writable:!1}),lo&&_setPrototypeOf$1(Au,lo)}function _wrapNativeSuper(Au){var lo=typeof Map=="function"?new Map:void 0;return _wrapNativeSuper=function(Ru){if(Ru===null||!_isNativeFunction(Ru))return Ru;if(typeof Ru!="function")throw new TypeError("Super expression must either be null or a function");if(typeof lo<"u"){if(lo.has(Ru))return lo.get(Ru);lo.set(Ru,Iu)}function Iu(){return _construct(Ru,arguments,_getPrototypeOf$1(this).constructor)}return Iu.prototype=Object.create(Ru.prototype,{constructor:{value:Iu,enumerable:!1,writable:!0,configurable:!0}}),_setPrototypeOf$1(Iu,Ru)},_wrapNativeSuper(Au)}function _construct(Au,lo,$u){if(_isNativeReflectConstruct$1())return Reflect.construct.apply(null,arguments);var Ru=[null];Ru.push.apply(Ru,lo);var Iu=new(Au.bind.apply(Au,Ru));return $u&&_setPrototypeOf$1(Iu,$u.prototype),Iu}function _isNativeReflectConstruct$1(){try{var Au=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(_isNativeReflectConstruct$1=function(){return!!Au})()}function _isNativeFunction(Au){try{return Function.toString.call(Au).indexOf("[native code]")!==-1}catch{return typeof Au=="function"}}function _setPrototypeOf$1(Au,lo){return _setPrototypeOf$1=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(Ru,Iu){return Ru.__proto__=Iu,Ru},_setPrototypeOf$1(Au,lo)}function _getPrototypeOf$1(Au){return _getPrototypeOf$1=Object.setPrototypeOf?Object.getPrototypeOf.bind():function($u){return $u.__proto__||Object.getPrototypeOf($u)},_getPrototypeOf$1(Au)}var DetailedError=(function(Au){function lo($u){var Ru,Iu=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,Pu=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,Ou=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null;if(_classCallCheck$8(this,lo),Ru=_callSuper$1(this,lo,[$u]),Ru.originalRequest=Pu,Ru.originalResponse=Ou,Ru.causingError=Iu,Iu!=null&&($u+=", caused by ".concat(Iu.toString())),Pu!=null){var Mu=Pu.getHeader("X-Request-ID")||"n/a",Du=Pu.getMethod(),Lu=Pu.getURL(),Bu=Ou?Ou.getStatus():"n/a",ju=Ou?Ou.getBody()||"":"n/a";$u+=", originated from request (method: ".concat(Du,", url: ").concat(Lu,", response code: ").concat(Bu,", response text: ").concat(ju,", request id: ").concat(Mu,")")}return Ru.message=$u,Ru}return _inherits$1(lo,Au),_createClass$8(lo)})(_wrapNativeSuper(Error));function log(Au){}function _typeof$7(Au){"@babel/helpers - typeof";return _typeof$7=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$7(Au)}function _classCallCheck$7(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$7(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$7(Ru.key),Ru)}}function _createClass$7(Au,lo,$u){return lo&&_defineProperties$7(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$7(Au){var lo=_toPrimitive$7(Au,"string");return _typeof$7(lo)=="symbol"?lo:lo+""}function _toPrimitive$7(Au,lo){if(_typeof$7(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$7(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var NoopUrlStorage=(function(){function Au(){_classCallCheck$7(this,Au)}return _createClass$7(Au,[{key:"listAllUploads",value:function(){return Promise.resolve([])}},{key:"findUploadsByFingerprint",value:function($u){return Promise.resolve([])}},{key:"removeUpload",value:function($u){return Promise.resolve()}},{key:"addUpload",value:function($u,Ru){return Promise.resolve(null)}}])})();const version$1="3.9.4",VERSION=version$1,_TD=typeof TextDecoder=="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,_TE=typeof TextEncoder=="function"?new TextEncoder:void 0,b64ch="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",b64chs=Array.prototype.slice.call(b64ch),b64tab=(Au=>{let lo={};return Au.forEach(($u,Ru)=>lo[$u]=Ru),lo})(b64chs),b64re=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,_fromCC=String.fromCharCode.bind(String),_U8Afrom=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):Au=>new Uint8Array(Array.prototype.slice.call(Au,0)),_mkUriSafe=Au=>Au.replace(/=/g,"").replace(/[+\/]/g,lo=>lo=="+"?"-":"_"),_tidyB64=Au=>Au.replace(/[^A-Za-z0-9\+\/]/g,""),btoaPolyfill=Au=>{let lo,$u,Ru,Iu,Pu="";const Ou=Au.length%3;for(let Mu=0;Mu<Au.length;){if(($u=Au.charCodeAt(Mu++))>255||(Ru=Au.charCodeAt(Mu++))>255||(Iu=Au.charCodeAt(Mu++))>255)throw new TypeError("invalid character found");lo=$u<<16|Ru<<8|Iu,Pu+=b64chs[lo>>18&63]+b64chs[lo>>12&63]+b64chs[lo>>6&63]+b64chs[lo&63]}return Ou?Pu.slice(0,Ou-3)+"===".substring(Ou):Pu},_btoa=typeof btoa=="function"?Au=>btoa(Au):btoaPolyfill,_fromUint8Array=typeof Uint8Array.prototype.toBase64=="function"?Au=>Au.toBase64():Au=>{let $u=[];for(let Ru=0,Iu=Au.length;Ru<Iu;Ru+=4096)$u.push(_fromCC.apply(null,Au.subarray(Ru,Ru+4096)));return _btoa($u.join(""))},fromUint8Array=(Au,lo=!1)=>lo?_mkUriSafe(_fromUint8Array(Au)):_fromUint8Array(Au),cb_utob=Au=>{if(Au.length<2){var lo=Au.charCodeAt(0);return lo<128?Au:lo<2048?_fromCC(192|lo>>>6)+_fromCC(128|lo&63):_fromCC(224|lo>>>12&15)+_fromCC(128|lo>>>6&63)+_fromCC(128|lo&63)}else{var lo=65536+(Au.charCodeAt(0)-55296)*1024+(Au.charCodeAt(1)-56320);return _fromCC(240|lo>>>18&7)+_fromCC(128|lo>>>12&63)+_fromCC(128|lo>>>6&63)+_fromCC(128|lo&63)}},re_utob=/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\x00-\x7F]/g,utob=Au=>Au.replace(re_utob,cb_utob),_encode=_TE?Au=>_fromUint8Array(_TE.encode(Au)):Au=>_btoa(utob(Au)),encode$2=(Au,lo=!1)=>lo?_mkUriSafe(_encode(Au)):_encode(Au),encodeURI$1=Au=>encode$2(Au,!0),re_btou=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,cb_btou=Au=>{switch(Au.length){case 4:var lo=(7&Au.charCodeAt(0))<<18|(63&Au.charCodeAt(1))<<12|(63&Au.charCodeAt(2))<<6|63&Au.charCodeAt(3),$u=lo-65536;return _fromCC(($u>>>10)+55296)+_fromCC(($u&1023)+56320);case 3:return _fromCC((15&Au.charCodeAt(0))<<12|(63&Au.charCodeAt(1))<<6|63&Au.charCodeAt(2));default:return _fromCC((31&Au.charCodeAt(0))<<6|63&Au.charCodeAt(1))}},btou=Au=>Au.replace(re_btou,cb_btou),atobPolyfill=Au=>{if(Au=Au.replace(/\s+/g,""),!b64re.test(Au))throw new TypeError("malformed base64.");Au+="==".slice(2-(Au.length&3));let lo,$u,Ru,Iu=[];for(let Pu=0;Pu<Au.length;)lo=b64tab[Au.charAt(Pu++)]<<18|b64tab[Au.charAt(Pu++)]<<12|($u=b64tab[Au.charAt(Pu++)])<<6|(Ru=b64tab[Au.charAt(Pu++)]),$u===64?Iu.push(_fromCC(lo>>16&255)):Ru===64?Iu.push(_fromCC(lo>>16&255,lo>>8&255)):Iu.push(_fromCC(lo>>16&255,lo>>8&255,lo&255));return Iu.join("")},_atob=typeof atob=="function"?Au=>atob(_tidyB64(Au)):atobPolyfill,_toUint8Array=typeof Uint8Array.fromBase64=="function"?Au=>Uint8Array.fromBase64(Au):Au=>_U8Afrom(_atob(Au).split("").map(lo=>lo.charCodeAt(0))),toUint8Array=Au=>_toUint8Array(_unURI(Au)),_decode=_TD?Au=>_TD.decode(_toUint8Array(Au)):Au=>btou(_atob(Au)),_unURI=Au=>_tidyB64(Au.replace(/[-_]/g,lo=>lo=="-"?"+":"/")),decode$3=Au=>_decode(_unURI(Au)),isValid$1=Au=>{if(typeof Au!="string")return!1;const lo=Au.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(lo)||!/[^\s0-9a-zA-Z\-_]/.test(lo)},_noEnum=Au=>({value:Au,enumerable:!1,writable:!0,configurable:!0}),extendString=function(){const Au=(lo,$u)=>Object.defineProperty(String.prototype,lo,_noEnum($u));Au("fromBase64",function(){return decode$3(this)}),Au("toBase64",function(lo){return encode$2(this,lo)}),Au("toBase64URI",function(){return encode$2(this,!0)}),Au("toBase64URL",function(){return encode$2(this,!0)}),Au("toUint8Array",function(){return toUint8Array(this)})},extendUint8Array=function(){const Au=(lo,$u)=>Object.defineProperty(Uint8Array.prototype,lo,_noEnum($u));Au("toBase64",function(lo){return fromUint8Array(this,lo)}),Au("toBase64URI",function(){return fromUint8Array(this,!0)}),Au("toBase64URL",function(){return fromUint8Array(this,!0)})},extendBuiltins=()=>{extendString(),extendUint8Array()},gBase64={version:version$1,VERSION,atob:_atob,atobPolyfill,btoa:_btoa,btoaPolyfill,fromBase64:decode$3,toBase64:encode$2,encode:encode$2,encodeURI:encodeURI$1,encodeURL:encodeURI$1,utob,btou,decode:decode$3,isValid:isValid$1,fromUint8Array,toUint8Array,extendString,extendUint8Array,extendBuiltins};var urlParseExports=requireUrlParse();const URL$1=getDefaultExportFromCjs(urlParseExports);function uuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(Au){var lo=Math.random()*16|0,$u=Au==="x"?lo:lo&3|8;return $u.toString(16)})}function _regeneratorRuntime$1(){_regeneratorRuntime$1=function(){return lo};var Au,lo={},$u=Object.prototype,Ru=$u.hasOwnProperty,Iu=Object.defineProperty||function(_d,yd,wd){_d[yd]=wd.value},Pu=typeof Symbol=="function"?Symbol:{},Ou=Pu.iterator||"@@iterator",Mu=Pu.asyncIterator||"@@asyncIterator",Du=Pu.toStringTag||"@@toStringTag";function Lu(_d,yd,wd){return Object.defineProperty(_d,yd,{value:wd,enumerable:!0,configurable:!0,writable:!0}),_d[yd]}try{Lu({},"")}catch{Lu=function(wd,Ad,md){return wd[Ad]=md}}function Bu(_d,yd,wd,Ad){var md=yd&&yd.prototype instanceof Gu?yd:Gu,dd=Object.create(md.prototype),bd=new gd(Ad||[]);return Iu(dd,"_invoke",{value:od(_d,wd,bd)}),dd}function ju(_d,yd,wd){try{return{type:"normal",arg:_d.call(yd,wd)}}catch(Ad){return{type:"throw",arg:Ad}}}lo.wrap=Bu;var Fu="suspendedStart",zu="suspendedYield",Uu="executing",Hu="completed",Vu={};function Gu(){}function Wu(){}function Ku(){}var Ju={};Lu(Ju,Ou,function(){return this});var Yu=Object.getPrototypeOf,Xu=Yu&&Yu(Yu(Sd([])));Xu&&Xu!==$u&&Ru.call(Xu,Ou)&&(Ju=Xu);var ed=Ku.prototype=Gu.prototype=Object.create(Ju);function td(_d){["next","throw","return"].forEach(function(yd){Lu(_d,yd,function(wd){return this._invoke(yd,wd)})})}function nd(_d,yd){function wd(md,dd,bd,ld){var ud=ju(_d[md],_d,dd);if(ud.type!=="throw"){var hd=ud.arg,vd=hd.value;return vd&&_typeof$6(vd)=="object"&&Ru.call(vd,"__await")?yd.resolve(vd.__await).then(function(Ed){wd("next",Ed,bd,ld)},function(Ed){wd("throw",Ed,bd,ld)}):yd.resolve(vd).then(function(Ed){hd.value=Ed,bd(hd)},function(Ed){return wd("throw",Ed,bd,ld)})}ld(ud.arg)}var Ad;Iu(this,"_invoke",{value:function(dd,bd){function ld(){return new yd(function(ud,hd){wd(dd,bd,ud,hd)})}return Ad=Ad?Ad.then(ld,ld):ld()}})}function od(_d,yd,wd){var Ad=Fu;return function(md,dd){if(Ad===Uu)throw Error("Generator is already running");if(Ad===Hu){if(md==="throw")throw dd;return{value:Au,done:!0}}for(wd.method=md,wd.arg=dd;;){var bd=wd.delegate;if(bd){var ld=sd(bd,wd);if(ld){if(ld===Vu)continue;return ld}}if(wd.method==="next")wd.sent=wd._sent=wd.arg;else if(wd.method==="throw"){if(Ad===Fu)throw Ad=Hu,wd.arg;wd.dispatchException(wd.arg)}else wd.method==="return"&&wd.abrupt("return",wd.arg);Ad=Uu;var ud=ju(_d,yd,wd);if(ud.type==="normal"){if(Ad=wd.done?Hu:zu,ud.arg===Vu)continue;return{value:ud.arg,done:wd.done}}ud.type==="throw"&&(Ad=Hu,wd.method="throw",wd.arg=ud.arg)}}}function sd(_d,yd){var wd=yd.method,Ad=_d.iterator[wd];if(Ad===Au)return yd.delegate=null,wd==="throw"&&_d.iterator.return&&(yd.method="return",yd.arg=Au,sd(_d,yd),yd.method==="throw")||wd!=="return"&&(yd.method="throw",yd.arg=new TypeError("The iterator does not provide a '"+wd+"' method")),Vu;var md=ju(Ad,_d.iterator,yd.arg);if(md.type==="throw")return yd.method="throw",yd.arg=md.arg,yd.delegate=null,Vu;var dd=md.arg;return dd?dd.done?(yd[_d.resultName]=dd.value,yd.next=_d.nextLoc,yd.method!=="return"&&(yd.method="next",yd.arg=Au),yd.delegate=null,Vu):dd:(yd.method="throw",yd.arg=new TypeError("iterator result is not an object"),yd.delegate=null,Vu)}function ad(_d){var yd={tryLoc:_d[0]};1 in _d&&(yd.catchLoc=_d[1]),2 in _d&&(yd.finallyLoc=_d[2],yd.afterLoc=_d[3]),this.tryEntries.push(yd)}function pd(_d){var yd=_d.completion||{};yd.type="normal",delete yd.arg,_d.completion=yd}function gd(_d){this.tryEntries=[{tryLoc:"root"}],_d.forEach(ad,this),this.reset(!0)}function Sd(_d){if(_d||_d===""){var yd=_d[Ou];if(yd)return yd.call(_d);if(typeof _d.next=="function")return _d;if(!isNaN(_d.length)){var wd=-1,Ad=function md(){for(;++wd<_d.length;)if(Ru.call(_d,wd))return md.value=_d[wd],md.done=!1,md;return md.value=Au,md.done=!0,md};return Ad.next=Ad}}throw new TypeError(_typeof$6(_d)+" is not iterable")}return Wu.prototype=Ku,Iu(ed,"constructor",{value:Ku,configurable:!0}),Iu(Ku,"constructor",{value:Wu,configurable:!0}),Wu.displayName=Lu(Ku,Du,"GeneratorFunction"),lo.isGeneratorFunction=function(_d){var yd=typeof _d=="function"&&_d.constructor;return!!yd&&(yd===Wu||(yd.displayName||yd.name)==="GeneratorFunction")},lo.mark=function(_d){return Object.setPrototypeOf?Object.setPrototypeOf(_d,Ku):(_d.__proto__=Ku,Lu(_d,Du,"GeneratorFunction")),_d.prototype=Object.create(ed),_d},lo.awrap=function(_d){return{__await:_d}},td(nd.prototype),Lu(nd.prototype,Mu,function(){return this}),lo.AsyncIterator=nd,lo.async=function(_d,yd,wd,Ad,md){md===void 0&&(md=Promise);var dd=new nd(Bu(_d,yd,wd,Ad),md);return lo.isGeneratorFunction(yd)?dd:dd.next().then(function(bd){return bd.done?bd.value:dd.next()})},td(ed),Lu(ed,Du,"Generator"),Lu(ed,Ou,function(){return this}),Lu(ed,"toString",function(){return"[object Generator]"}),lo.keys=function(_d){var yd=Object(_d),wd=[];for(var Ad in yd)wd.push(Ad);return wd.reverse(),function md(){for(;wd.length;){var dd=wd.pop();if(dd in yd)return md.value=dd,md.done=!1,md}return md.done=!0,md}},lo.values=Sd,gd.prototype={constructor:gd,reset:function(yd){if(this.prev=0,this.next=0,this.sent=this._sent=Au,this.done=!1,this.delegate=null,this.method="next",this.arg=Au,this.tryEntries.forEach(pd),!yd)for(var wd in this)wd.charAt(0)==="t"&&Ru.call(this,wd)&&!isNaN(+wd.slice(1))&&(this[wd]=Au)},stop:function(){this.done=!0;var yd=this.tryEntries[0].completion;if(yd.type==="throw")throw yd.arg;return this.rval},dispatchException:function(yd){if(this.done)throw yd;var wd=this;function Ad(hd,vd){return bd.type="throw",bd.arg=yd,wd.next=hd,vd&&(wd.method="next",wd.arg=Au),!!vd}for(var md=this.tryEntries.length-1;md>=0;--md){var dd=this.tryEntries[md],bd=dd.completion;if(dd.tryLoc==="root")return Ad("end");if(dd.tryLoc<=this.prev){var ld=Ru.call(dd,"catchLoc"),ud=Ru.call(dd,"finallyLoc");if(ld&&ud){if(this.prev<dd.catchLoc)return Ad(dd.catchLoc,!0);if(this.prev<dd.finallyLoc)return Ad(dd.finallyLoc)}else if(ld){if(this.prev<dd.catchLoc)return Ad(dd.catchLoc,!0)}else{if(!ud)throw Error("try statement without catch or finally");if(this.prev<dd.finallyLoc)return Ad(dd.finallyLoc)}}}},abrupt:function(yd,wd){for(var Ad=this.tryEntries.length-1;Ad>=0;--Ad){var md=this.tryEntries[Ad];if(md.tryLoc<=this.prev&&Ru.call(md,"finallyLoc")&&this.prev<md.finallyLoc){var dd=md;break}}dd&&(yd==="break"||yd==="continue")&&dd.tryLoc<=wd&&wd<=dd.finallyLoc&&(dd=null);var bd=dd?dd.completion:{};return bd.type=yd,bd.arg=wd,dd?(this.method="next",this.next=dd.finallyLoc,Vu):this.complete(bd)},complete:function(yd,wd){if(yd.type==="throw")throw yd.arg;return yd.type==="break"||yd.type==="continue"?this.next=yd.arg:yd.type==="return"?(this.rval=this.arg=yd.arg,this.method="return",this.next="end"):yd.type==="normal"&&wd&&(this.next=wd),Vu},finish:function(yd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ad=this.tryEntries[wd];if(Ad.finallyLoc===yd)return this.complete(Ad.completion,Ad.afterLoc),pd(Ad),Vu}},catch:function(yd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ad=this.tryEntries[wd];if(Ad.tryLoc===yd){var md=Ad.completion;if(md.type==="throw"){var dd=md.arg;pd(Ad)}return dd}}throw Error("illegal catch attempt")},delegateYield:function(yd,wd,Ad){return this.delegate={iterator:Sd(yd),resultName:wd,nextLoc:Ad},this.method==="next"&&(this.arg=Au),Vu}},lo}function asyncGeneratorStep$1(Au,lo,$u,Ru,Iu,Pu,Ou){try{var Mu=Au[Pu](Ou),Du=Mu.value}catch(Lu){$u(Lu);return}Mu.done?lo(Du):Promise.resolve(Du).then(Ru,Iu)}function _asyncToGenerator$1(Au){return function(){var lo=this,$u=arguments;return new Promise(function(Ru,Iu){var Pu=Au.apply(lo,$u);function Ou(Du){asyncGeneratorStep$1(Pu,Ru,Iu,Ou,Mu,"next",Du)}function Mu(Du){asyncGeneratorStep$1(Pu,Ru,Iu,Ou,Mu,"throw",Du)}Ou(void 0)})}}function _slicedToArray$1(Au,lo){return _arrayWithHoles$1(Au)||_iterableToArrayLimit$1(Au,lo)||_unsupportedIterableToArray$1(Au,lo)||_nonIterableRest$1()}function _nonIterableRest$1(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
2197
|
+
`);function unifiedDiffLines(Au,lo){const $u=Au===null?[]:lines(Au),Ru=lines(lo);if($u.length>DIFF_LINES_LIMIT||Ru.length>DIFF_LINES_LIMIT)return[...$u.map(Du=>({kind:"remove",text:Du})),...Ru.map(Du=>({kind:"add",text:Du}))];const Iu=[];for(let Du=0;Du<=$u.length;Du++)Iu.push(new Uint32Array(Ru.length+1));for(let Du=$u.length-1;Du>=0;Du--)for(let Lu=Ru.length-1;Lu>=0;Lu--)Iu[Du][Lu]=$u[Du]===Ru[Lu]?Iu[Du+1][Lu+1]+1:Math.max(Iu[Du+1][Lu],Iu[Du][Lu+1]);const Pu=[];let Ou=0,Mu=0;for(;Ou<$u.length&&Mu<Ru.length;)$u[Ou]===Ru[Mu]?(Pu.push({kind:"context",text:$u[Ou]}),Ou++,Mu++):Iu[Ou+1][Mu]>=Iu[Ou][Mu+1]?(Pu.push({kind:"remove",text:$u[Ou]}),Ou++):(Pu.push({kind:"add",text:Ru[Mu]}),Mu++);for(;Ou<$u.length;)Pu.push({kind:"remove",text:$u[Ou++]});for(;Mu<Ru.length;)Pu.push({kind:"add",text:Ru[Mu++]});return Pu}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 (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 ITEM_LIMIT=400,MESSAGE_TEXT_LIMIT=1e5,TOOL_TEXT_LIMIT=4e3,DIAGNOSTIC_LIMIT=50,DEVICE_LIMITS={items:ITEM_LIMIT,messageText:MESSAGE_TEXT_LIMIT,toolText:TOOL_TEXT_LIMIT,diagnostics:DIAGNOSTIC_LIMIT},BROWSER_LIMITS={items:5e3,messageText:1e6,toolText:1e6,diagnostics:DIAGNOSTIC_LIMIT},CUT_MARK="… (cut: too long to keep on this device)",emptyConversation=(Au=DEVICE_LIMITS)=>{for(const[lo,$u]of Object.entries(Au))if(!Number.isInteger($u)||$u<1)throw new Error(`A conversation's ${lo} bound is ${String($u)}: give a whole number of at least 1.`);return{items:[],running:!1,session:null,asking:null,dropped:0,diagnostics:[],turnRows:0,limits:Au}},text$g=Au=>typeof Au=="string"?Au:"",cut=(Au,lo)=>Au.length>lo?`${Au.slice(0,lo)}${CUT_MARK}`:Au,appended=(Au,lo,$u)=>Au.endsWith(CUT_MARK)?Au:cut(Au+lo,$u),isRecord$2=Au=>!!Au&&typeof Au=="object"&&!Array.isArray(Au);function withoutMeta(Au){if(isRecord$2(Au)&&"_meta"in Au){const{_meta:lo,...$u}=Au;return $u}return Au}function said$1(Au){return Au==null?"":typeof Au=="string"?Au:JSON.stringify(Au)}function questionOf$1(Au){if(!Au||typeof Au!="object")return null;const lo=Au,$u=lo.kind;if($u!=="text"&&$u!=="choice"&&$u!=="form"&&$u!=="file")throw new Error(`The application asks something no client knows: ${String($u)}.`);const Ru=Pu=>Array.isArray(Pu)?Pu.filter(Ou=>typeof Ou=="string"):[],Iu=lo.schema;return{kind:$u,prompt:text$g(lo.prompt),options:Ru(lo.options),schema:isRecord$2(Iu)?Iu:null,accept:Ru(lo.accept)}}function withItems(Au,lo,$u=0){const Ru=lo.length-Au.limits.items;return{...Au,items:Ru>0?lo.slice(Ru):lo,dropped:Au.dropped+Math.max(0,Ru),turnRows:Au.turnRows+$u}}function changed$1(Au,lo,$u){const Ru=Au.items.findIndex(Pu=>Pu.id===lo);if(Ru<0)return null;const Iu=Au.items.slice();return Iu[Ru]=$u(Iu[Ru]),{...Au,items:Iu}}function noted(Au,lo){const $u={type:lo.type,name:text$g(lo.name)||text$g(lo.activityType)};return{...Au,diagnostics:[...Au.diagnostics,$u].slice(-Au.limits.diagnostics)}}const HARNESS_TOOL_CALL="datalayer.harness.tool_call";function withRunningDisplay(Au,lo){if(!isRecord$2(lo)||!isRecord$2(lo._meta))return null;const $u=lo._meta[DISPLAY_META_KEY];if($u===void 0)return null;const Ru=protocolDisplayOf($u);if(!Ru)throw new Error(`${HARNESS_TOOL_CALL} of ${text$g(lo.id)} carries a display no client reads.`);return changed$1(Au,text$g(lo.id),Iu=>Iu.kind==="tool"&&Iu.status==="running"?{...Iu,value:{_meta:lo._meta},display:Ru}:Iu)}let rowCount=0;const rowId=Au=>`${Au}-${Date.now().toString(36)}-${rowCount+=1}`;function toolRow(Au,lo){return{kind:"tool",id:Au,name:lo,args:"",input:null,status:"running",awaiting:null,result:"",value:void 0,error:"",executionError:"",codeError:null,exitCode:null,display:null}}function withInput(Au,lo,$u){const Ru=JSON.stringify(lo),Iu=Ru.length<=$u;return{...Au,args:cut(Ru,$u),input:Iu?lo:null}}const asksThePerson=Au=>!!Au&&Array.isArray(Au.steps);function withResult(Au,lo,$u,Ru=!1){const Iu=lo.result,Pu=said$1(withoutMeta(Iu)),Ou=isRecord$2(Iu)?Iu:null,Mu=typeof Ou?.execution_error=="string"?Ou.execution_error:"",Du=isRecord$2(Ou?.code_error)?Ou.code_error:null,Lu=Du?{name:text$g(Du.name)||"Error",value:text$g(Du.value)||"Unknown error",traceback:cut(text$g(Du.traceback),$u)}:null,Bu=Ou&&typeof Ou.exit_code=="number"?Ou.exit_code:null,ju=!lo.success||Mu!==""||Lu!==null||Bu!==null&&Bu!==0||Ou?.execution_ok===!1,Fu=ju||Ru?null:Ou?.pending_approval===!0?"approval":asksThePerson(Au.input)?"person":null;return{...Au,status:ju?"error":Fu?"running":"complete",awaiting:Fu,result:cut(Pu,$u),value:Pu.length<=$u?Iu:void 0,error:lo.error??"",executionError:cut(Mu,$u),codeError:Lu,exitCode:Bu,display:displayOfToolResult(Au.name,Iu,Au.id)}}function rowsOfSnapshot(Au,lo,$u){if(!Array.isArray(Au))throw new Error("A messages snapshot carries no list of messages.");const Ru=[],Iu=new Map;for(const Pu of Au){for(const Ou of messagesOfThread([Pu]))Ru.push({kind:"message",id:Ou.id,role:Ou.role==="user"?"user":"assistant",text:cut(typeof Ou.content=="string"?Ou.content:"",lo.messageText),streaming:!1});if(isRecord$2(Pu)){if(Pu.role==="assistant"&&Pu.toolCalls!==void 0){if(!Array.isArray(Pu.toolCalls))throw new Error(`Message ${String(Pu.id)}'s tool calls are not a list.`);for(const Ou of Pu.toolCalls){const Mu=isRecord$2(Ou)?Ou.function:void 0;if(!isRecord$2(Ou)||typeof Ou.id!="string"||!isRecord$2(Mu))throw new Error(`Message ${String(Pu.id)} holds a tool call without its id and function.`);const Du=text$g(Mu.arguments);let Lu=null;if(Du&&Du.length<=lo.toolText){let Bu;try{Bu=JSON.parse(Du)}catch{Bu=void 0}if(!isRecord$2(Bu))throw new Error(`Tool call ${Ou.id}'s arguments are not a JSON object.`);Lu=Bu}Iu.set(Ou.id,Ru.length),Ru.push({...toolRow(Ou.id,text$g(Mu.name)),args:cut(Du,lo.toolText),input:Du?Lu:{},status:"complete"})}}if(Pu.role==="tool"){const Ou=text$g(Pu.toolCallId),Mu=Iu.get(Ou);if(Mu===void 0){$u.push(Ou||"no call");continue}Ru[Mu]=withResult(Ru[Mu],toolResultOf(Pu.content),lo.toolText,!0)}}}return Ru}function withPrompt(Au,lo,$u){return withItems({...Au,asking:null},[...Au.items,{kind:"message",id:lo,role:"user",text:$u,streaming:!1}])}function withoutItems(Au,lo){const $u=new Set(lo);return{...Au,items:Au.items.filter(Ru=>!$u.has(Ru.id))}}function withTurnEnded(Au,lo){const $u=Au.items.map(Iu=>Iu.kind==="message"&&Iu.streaming?{...Iu,streaming:!1}:Iu.kind==="tool"&&Iu.status==="running"?{...Iu,status:"error",awaiting:null,error:RUN_END_WORDS[lo]}:Iu.kind==="step"&&Iu.status==="running"?{...Iu,status:"complete"}:Iu),Ru={...Au,items:$u,running:!1};return withItems(Ru,[...$u,{kind:"end",id:rowId("end"),end:lo,words:RUN_END_WORDS[lo]}])}function withError(Au,lo){const $u=Au.items.map(Ru=>Ru.kind==="message"&&Ru.streaming?{...Ru,streaming:!1}:Ru.kind==="tool"&&Ru.status==="running"?{...Ru,status:"error",awaiting:null}:Ru.kind==="step"&&Ru.status==="running"?{...Ru,status:"complete"}:Ru);return withItems({...Au,running:!1},[...$u,{kind:"error",id:rowId("error"),text:lo}])}function required(Au,lo){const $u=Au[lo];if(typeof $u!="string"||!$u)throw new Error(`${Au.type} carries no ${lo}.`);return $u}function reduceConversation(Au,lo){const{limits:$u}=Au;switch(lo.type){case"RUN_STARTED":return{...Au,running:!0,asking:null,turnRows:0};case"TEXT_MESSAGE_START":{const Ru=text$g(lo.messageId)||rowId("message");if(Au.items.some(Pu=>Pu.id===Ru))return Au;const Iu=lo.role==="user"?"user":"assistant";return withItems(Au,[...Au.items,{kind:"message",id:Ru,role:Iu,text:"",streaming:!0}],1)}case"TEXT_MESSAGE_CONTENT":case"TEXT_MESSAGE_CHUNK":{const Ru=text$g(lo.delta),Iu=text$g(lo.messageId),Pu=changed$1(Au,Iu,Ou=>Ou.kind==="message"?{...Ou,text:appended(Ou.text,Ru,$u.messageText)}:Ou);return Pu||withItems(Au,[...Au.items,{kind:"message",id:Iu||rowId("message"),role:lo.role==="user"?"user":"assistant",text:cut(Ru,$u.messageText),streaming:lo.type==="TEXT_MESSAGE_CONTENT"}],1)}case"TEXT_MESSAGE_END":return changed$1(Au,text$g(lo.messageId),Ru=>Ru.kind==="message"?{...Ru,streaming:!1}:Ru)??Au;case"MESSAGE_SAID":{const Ru=required(lo,"messageId");if(typeof lo.text!="string")throw new Error(`MESSAGE_SAID of ${Ru} carries no text.`);if(lo.role!=="user"&&lo.role!=="assistant")throw new Error(`MESSAGE_SAID of ${Ru} is said by ${String(lo.role)}: only the person or the assistant speaks here.`);const Iu=lo.role,Pu=cut(lo.text,$u.messageText),Ou=Iu==="assistant"&&lo.streaming!==!1,Mu=Au.items.findIndex(Du=>Du.id===Ru);if(Mu>=0){const Du=Au.items[Mu];if(Du.kind!=="message")throw new Error(`MESSAGE_SAID of ${Ru} names a ${Du.kind} row.`);const Lu=Au.items.slice();return Lu[Mu]={...Du,text:Pu,streaming:Ou},{...Au,items:Lu}}return withItems(Au,[...Au.items,{kind:"message",id:Ru,role:Iu,text:Pu,streaming:Ou}],1)}case"TOOL_CALL_START":{const Ru=text$g(lo.toolCallId)||rowId("tool");return Au.items.some(Iu=>Iu.id===Ru)?Au:withItems(Au,[...Au.items,toolRow(Ru,text$g(lo.toolCallName)||text$g(lo.name))],1)}case"TOOL_CALL_ARGS":return changed$1(Au,text$g(lo.toolCallId),Ru=>Ru.kind==="tool"?{...Ru,args:appended(Ru.args,text$g(lo.delta),$u.toolText)}:Ru)??Au;case"TOOL_CALL_END":return changed$1(Au,text$g(lo.toolCallId),Ru=>{if(Ru.kind!=="tool"||Ru.args.endsWith(CUT_MARK))return Ru;if(!Ru.args)return{...Ru,input:{}};let Iu;try{Iu=JSON.parse(Ru.args)}catch{Iu=void 0}return isRecord$2(Iu)?{...Ru,input:Iu}:{...Ru,status:"error",awaiting:null,error:"Its arguments are not a JSON object."}})??Au;case"TOOL_CALL_SAID":{const Ru=required(lo,"toolCallId"),Iu=required(lo,"toolCallName");if(!isRecord$2(lo.args))throw new Error(`TOOL_CALL_SAID of ${Ru} carries arguments that are not an object.`);const Pu=lo.args,Ou=Au.items.findIndex(Lu=>Lu.id===Ru);if(Ou<0)return withItems(Au,[...Au.items,withInput(toolRow(Ru,Iu),Pu,$u.toolText)],1);const Mu=Au.items[Ou];if(Mu.kind!=="tool")throw new Error(`TOOL_CALL_SAID of ${Ru} names a ${Mu.kind} row.`);const Du=Au.items.slice();return Du[Ou]=withInput(Mu,{...Mu.input??{},...Pu},$u.toolText),{...Au,items:Du}}case"TOOL_CALL_RESULT":{const Ru=toolResultOf(lo.content);return changed$1(Au,text$g(lo.toolCallId),Iu=>Iu.kind==="tool"?withResult(Iu,Ru,$u.toolText):Iu)??noted(Au,lo)}case"TOOL_CALL_DONE":{const Ru=required(lo,"toolCallId");if(typeof lo.success!="boolean")throw new Error(`TOOL_CALL_DONE of ${Ru} does not say whether it succeeded.`);if(lo.error!==void 0&&typeof lo.error!="string")throw new Error(`TOOL_CALL_DONE of ${Ru} says its error in no words.`);const Iu={result:lo.result,success:lo.success,...lo.error!==void 0?{error:lo.error}:{}};return changed$1(Au,Ru,Pu=>Pu.kind==="tool"?withResult(Pu,Iu,$u.toolText,lo.answered===!0):Pu)??noted(Au,lo)}case"STEP_STARTED":{const Ru=text$g(lo.stepName)||text$g(lo.name);return withItems(Au,[...Au.items,{kind:"step",id:rowId("step"),name:Ru,status:"running"}],1)}case"STEP_FINISHED":{const Ru=text$g(lo.stepName)||text$g(lo.name),Iu=Au.items.map((Ou,Mu)=>({item:Ou,index:Mu})).reverse().find(({item:Ou})=>Ou.kind==="step"&&Ou.name===Ru&&Ou.status==="running");if(!Iu)return noted(Au,lo);const Pu=Au.items.slice();return Pu[Iu.index]={...Iu.item,status:"complete"},{...Au,items:Pu}}case"MESSAGES_SNAPSHOT":{const Ru=[],Iu=rowsOfSnapshot(lo.messages,$u,Ru),Pu=withItems({...Au,dropped:0},Iu,1);return Ru.reduce((Ou,Mu)=>noted(Ou,{type:"TOOL_CALL_RESULT",name:`${Mu} (no call)`}),Pu)}case"CUSTOM":{if(lo.name===REACTOR_UI_NAME)return withError(Au,UI_ON_RUN);if(lo.name==="loop.session"&&isRecord$2(lo.value)){const Ru=lo.value;return{...Au,session:Ru,asking:questionOf$1(Ru.asking)??Au.asking}}return lo.name===HARNESS_TOOL_CALL?withRunningDisplay(Au,lo.value)??noted(Au,lo):noted(Au,lo)}case"ACTIVITY_SNAPSHOT":case"ACTIVITY_DELTA":return lo.activityType===REACTOR_UI_NAME?withError(Au,UI_ON_RUN):noted(Au,lo);case"RUN_FINISHED":{const Ru=isRecord$2(lo.result)?lo.result:{},Iu=questionOf$1(Ru.asking),Pu=Au.items.map(Mu=>Mu.kind==="message"&&Mu.streaming?{...Mu,streaming:!1}:Mu),Ou={...Au,items:Pu,running:!1,asking:Iu};return Iu||Au.turnRows>0?Ou:withItems(Ou,[...Pu,{kind:"end",id:rowId("end"),end:"answered",words:RUN_END_WORDS.answered}])}case"RUN_ERROR":return withError(Au,text$g(lo.message)||"Run failed");default:return noted(Au,lo)}}const emptyChatLayer=()=>({extras:new Map,displays:new Map,speakers:new Map,steps:[]}),toolCardId=Au=>`tool-${Au}`,rowIdOf=Au=>"toolCallId"in Au&&Au.id===toolCardId(Au.toolCallId)?Au.toolCallId:Au.id;function cardStatusOf(Au){return Au.status!=="running"?Au.status:Au.awaiting==="approval"?"inProgress":"executing"}function toolCallOf(Au){return{id:toolCardId(Au.id),type:"tool-call",toolCallId:Au.id,toolName:Au.name,args:Au.input??{},...Au.value!==void 0?{result:Au.value}:Au.result?{result:Au.result}:{},status:cardStatusOf(Au),...Au.error?{error:Au.error}:{},...Au.executionError?{executionError:Au.executionError}:{},...Au.codeError?{codeError:{name:Au.codeError.name,value:Au.codeError.value,...Au.codeError.traceback?{traceback:Au.codeError.traceback}:{}}}:{},...Au.exitCode!==null?{exitCode:Au.exitCode}:{}}}function conversationDrawer(Au){const lo=new Map,$u=(Iu,Pu)=>{const Ou=Pu.extras.get(Iu.id),Mu=Pu.displays.get(Iu.id),Du=Pu.speakers.get(Iu.id),Lu=lo.get(Iu.id);if(Lu&&Lu.row===Iu&&Lu.extras===Ou&&Lu.displays===Mu&&Lu.speaker===Du)return Lu.item;const Bu={...Ou,createdAt:Ou?.createdAt??new Date,id:Iu.id,role:Iu.kind==="message"?Iu.role:"assistant",content:Iu.kind==="message"?Iu.text:Au(Iu.text),...Mu?{displays:Mu}:{},...Du?{speaker:Du}:{}};return lo.set(Iu.id,{row:Iu,extras:Ou,displays:Mu,speaker:Du,item:Bu}),Bu},Ru=Iu=>{const Pu=lo.get(Iu.id);if(Pu&&Pu.row===Iu)return Pu.item;const Ou=toolCallOf(Iu);return lo.set(Iu.id,{row:Iu,item:Ou}),Ou};return(Iu,Pu)=>{const Ou=[],Mu=new Map;for(const Lu of Pu.steps)Mu.set(Lu.after,[...Mu.get(Lu.after)??[],Lu.item]);Ou.push(...Mu.get(null)??[]);const Du=new Set;for(const Lu of Iu.items)Du.add(Lu.id),Lu.kind==="message"||Lu.kind==="error"?Ou.push($u(Lu,Pu)):Lu.kind==="tool"&&Ou.push(Ru(Lu)),Ou.push(...Mu.get(Lu.id)??[]);for(const[Lu,Bu]of Mu)Lu!==null&&!Du.has(Lu)&&Ou.push(...Bu);for(const Lu of lo.keys())Du.has(Lu)||lo.delete(Lu);return Ou}}function isSubagentRunOver(Au){return Au.some(lo=>lo.phase==="end"||lo.phase==="error")}function getMonitoringCacheKey(Au,lo){return`${Au||"__unknown_service__"}::${lo||"__unknown_agent__"}`}function getTransportEndpoint(Au,lo,$u){switch(lo){case"vercel-ai":return`${Au}/api/v1/vercel-ai/${$u}`;case"a2a":return`${Au}/api/v1/a2a/agents/${$u}/`;case"acp":return`${Au}/api/v1/acp/ws/${$u}`;default:return`${Au}/api/v1/ag-ui/${$u}/`}}function toAgentRuntimeBaseUrl(Au){const lo=Au.replace(/\/$/,"");return lo.includes("/api/agent-runtimes")?lo:lo.includes("/api/jupyter-server")?lo.replace("/api/jupyter-server","/api/agent-runtimes"):lo.includes("/jupyter/server/")?lo.replace("/jupyter/server/","/agent-runtimes/"):lo.includes("/jupyter-server/")?lo.replace("/jupyter-server/","/agent-runtimes/"):lo.replace("/jupyter/","/agent-runtimes/")}async function createAgentOnRuntime(Au,lo,$u={}){const{iamStore:Ru}=await __vitePreload(async()=>{const{iamStore:Lu}=await import("./chunks/index-CeTMYE1j.js");return{iamStore:Lu}},[],import.meta.url),Iu=Ru.getState().token||"";if(!$u.protocol&&!$u.agentSpecId)throw new Error("Agent protocol is required. Provide config.protocol from the selected spec/config.");const Pu=$u.protocol||"vercel-ai";if(!$u.model&&!$u.agentSpecId)throw new Error("Agent model is required. Provide config.model from the selected spec/config.");const Ou={name:$u.name||lo,description:$u.description||"AI assistant",agent_library:$u.agentLibrary||"pydantic-ai",transport:Pu,model:$u.model,system_prompt:$u.systemPrompt||"You are a helpful AI assistant."};$u.agentSpecId&&(Ou.agent_spec_id=$u.agentSpecId),typeof $u.enableSkills=="boolean"&&(Ou.enable_skills=$u.enableSkills),Array.isArray($u.backendTools)&&(Ou.backend_tools=$u.backendTools),$u.inferenceProvider&&(Ou.inferenceProvider=$u.inferenceProvider),typeof $u.enableCodemode=="boolean"&&(Ou.enable_codemode=$u.enableCodemode),$u.sandboxVariant&&(Ou.sandbox_variant=$u.sandboxVariant),$u.jupyterSandbox&&(Ou.jupyter_sandbox=$u.jupyterSandbox),$u.createPayload&&typeof $u.createPayload=="object"&&Object.assign(Ou,$u.createPayload);const Mu=await fetch(`${Au}/api/v1/agents`,{method:"POST",headers:{"Content-Type":"application/json",...Iu?{Authorization:`Bearer ${Iu}`}:{}},body:JSON.stringify(Ou)});if(Mu.ok||Mu.status===400||Mu.status===409){const Lu=getTransportEndpoint(Au,Pu,lo);return{agentId:lo,endpoint:Lu,isReady:!0}}const Du=await Mu.json().catch(()=>({}));throw new Error(Du.detail||`Failed to create agent: ${Mu.status}`)}const initialRuntimeState={runtime:null,status:"idle",error:null,isLaunching:!1,historyVersion:0,toolDecisionRequest:null},initialWsState={wsState:"closed",approvals:[],pendingApprovalCount:0,subagentActivity:{},compaction:null,contextSnapshot:null,costUsage:null,mcpStatus:null,codemodeStatus:null,fullContext:null,monitoringCache:{},loadedSkillsByAgentId:{}},initialNotebookState={ephemeralNotebookModels:{},ephemeralDocumentModels:{},editorModeByRuntime:{}},countPendingApprovals=Au=>Au.filter(lo=>lo.status==="pending").length;let _ws=null;const _wsByAgentId=new Map;function _resolveWs(Au){const lo=_wsByAgentId.size>0;if(Au){const $u=_wsByAgentId.get(Au);if($u&&$u.readyState===WebSocket.OPEN)return $u;if(lo)return null}return lo?null:_ws&&_ws.readyState===WebSocket.OPEN?_ws:null}const agentRuntimeStore=createStore$1()(subscribeWithSelector(persist((Au,lo)=>({agents:[],upsertAgent:$u=>{Au(Ru=>{const Iu=Ru.agents.findIndex(Mu=>Mu.id===$u.id),Pu=Date.now();if(Iu>=0){const Mu=[...Ru.agents];return Mu[Iu]={...Mu[Iu],...$u,lastUpdated:Pu},{agents:Mu}}const Ou={name:$u.name||$u.id,description:$u.description||"",status:$u.status||"initializing",lastUpdated:Pu,...$u};return{agents:[...Ru.agents,Ou]}})},getAgentById:$u=>lo().agents.find(Ru=>Ru.id===$u),getAgentByUrl:($u,Ru)=>lo().agents.find(Iu=>Iu.baseUrl===$u&&Iu.protocol===Ru),updateAgentStatus:($u,Ru,Iu=null)=>{Au(Pu=>{const Ou=Pu.agents.findIndex(Mu=>Mu.id===$u);if(Ou>=0){const Mu=[...Pu.agents];return Mu[Ou]={...Mu[Ou],status:Ru,error:Iu,lastUpdated:Date.now()},{agents:Mu}}return{}})},toggleAgentStatus:$u=>{Au(Ru=>{const Iu=Ru.agents.findIndex(Pu=>Pu.id===$u);if(Iu>=0){const Pu=[...Ru.agents],Ou=Pu[Iu].status;return Pu[Iu]={...Pu[Iu],status:Ou==="running"?"paused":"running",lastUpdated:Date.now()},{agents:Pu}}return{}})},deleteAgent:$u=>{Au(Ru=>{const{[$u]:Iu,...Pu}=Ru.loadedSkillsByAgentId;return{agents:Ru.agents.filter(Ou=>Ou.id!==$u),loadedSkillsByAgentId:Pu}})},clearAgents:()=>{Au({agents:[]})},setLoadedSkillsForAgent:($u,Ru)=>{Au(Iu=>({loadedSkillsByAgentId:{...Iu.loadedSkillsByAgentId,[$u]:Ru}}))},getLoadedSkillsForAgent:$u=>lo().loadedSkillsByAgentId[$u]??[],clearLoadedSkillsForAgent:$u=>{Au(Ru=>{if(!($u in Ru.loadedSkillsByAgentId))return{};const{[$u]:Iu,...Pu}=Ru.loadedSkillsByAgentId;return{loadedSkillsByAgentId:Pu}})},setEphemeralNotebookModel:($u,Ru)=>{Au(Iu=>({ephemeralNotebookModels:{...Iu.ephemeralNotebookModels,[$u]:Ru}}))},getEphemeralNotebookModel:$u=>lo().ephemeralNotebookModels[$u]??null,clearEphemeralNotebookModel:$u=>{Au(Ru=>{if(!($u in Ru.ephemeralNotebookModels))return{};const{[$u]:Iu,...Pu}=Ru.ephemeralNotebookModels;return{ephemeralNotebookModels:Pu}})},setEphemeralDocumentModel:($u,Ru)=>{Au(Iu=>({ephemeralDocumentModels:{...Iu.ephemeralDocumentModels,[$u]:Ru}}))},getEphemeralDocumentModel:$u=>lo().ephemeralDocumentModels[$u]??null,clearEphemeralDocumentModel:$u=>{Au(Ru=>{if(!($u in Ru.ephemeralDocumentModels))return{};const{[$u]:Iu,...Pu}=Ru.ephemeralDocumentModels;return{ephemeralDocumentModels:Pu}})},setEditorMode:($u,Ru)=>{$u&&Au(Iu=>({editorModeByRuntime:{...Iu.editorModeByRuntime,[$u]:Ru}}))},getEditorMode:$u=>lo().editorModeByRuntime[$u]??null,...initialRuntimeState,connectAgent:$u=>{const Ru=$u.jupyterBaseUrl||$u.serviceManager?.serverSettings.baseUrl;if(!Ru)throw new Error("connectAgent requires either jupyterBaseUrl or serviceManager");const Iu=toAgentRuntimeBaseUrl(Ru);Au({runtime:{runtimeName:$u.runtimeName,environmentName:$u.environmentName,jupyterBaseUrl:Ru,agentBaseUrl:Iu,serviceManager:$u.serviceManager,status:"ready",kernelId:$u.kernelId},status:"ready",error:null})},launchAgent:async $u=>{Au({status:"launching",error:null,isLaunching:!0});try{const{createRuntime:Ru}=await __vitePreload(async()=>{const{createRuntime:ju}=await Promise.resolve().then(()=>actions);return{createRuntime:ju}},void 0,import.meta.url),{runtimesStore:Iu}=await __vitePreload(async()=>{const{runtimesStore:ju}=await import("./chunks/index-DxN3ZybZ.js");return{runtimesStore:ju}},[],import.meta.url);$u.runtimesUrl&&Iu.setState({runtimesUrl:$u.runtimesUrl});const{runtimesUrl:Pu,...Ou}=$u,Mu=await Ru({environmentName:Ou.environmentName,creditsLimit:Ou.creditsLimit,type:Ou.type||"notebook",givenName:Ou.givenName,capabilities:Ou.capabilities,snapshot:Ou.snapshot,appSpec:Ou.appSpec,appUid:Ou.appUid,deploymentUid:Ou.deploymentUid});Au({status:"connecting"});const Du=Mu.ingress,Lu=toAgentRuntimeBaseUrl(Du),Bu={runtimeName:Mu.runtime_name,environmentName:Mu.environment.name,jupyterBaseUrl:Du,agentBaseUrl:Lu,status:"ready"};return Au({runtime:Bu,status:"ready",isLaunching:!1}),Bu}catch(Ru){const Iu=Ru instanceof Error?Ru.message:"Failed to launch runtime";throw Au({status:"error",error:Iu,isLaunching:!1}),Ru}},createAgent:async($u={})=>{const{runtime:Ru}=lo();if(!Ru)throw new Error("No runtime connected. Launch or connect to a runtime first.");try{const Iu=$u.name||Ru.runtimeName,Pu=await createAgentOnRuntime(Ru.agentBaseUrl,Iu,$u);return Au({runtime:{...Ru,agentId:Pu.agentId,endpoint:Pu.endpoint,isReady:Pu.isReady}}),Pu}catch(Iu){const Pu=Iu instanceof Error?Iu.message:"Failed to create agent";throw Au({error:Pu}),Iu}},disconnect:()=>{Au({runtime:null,status:"disconnected",error:null})},clearError:()=>Au({error:null}),setError:$u=>Au({error:$u,status:"error"}),...initialWsState,...initialNotebookState,setWsState:$u=>Au({wsState:$u}),setWs:($u,Ru)=>{_ws=$u,Ru&&($u?_wsByAgentId.set(Ru,$u):_wsByAgentId.delete(Ru))},applySnapshot:$u=>Au(Ru=>({approvals:Ru.approvals,pendingApprovalCount:Ru.pendingApprovalCount,contextSnapshot:$u.contextSnapshot??null,costUsage:$u.costUsage??null,mcpStatus:$u.mcpStatus??null,codemodeStatus:$u.codemodeStatus??null,fullContext:$u.fullContext??null})),appendSubagentEvent:$u=>Au(Ru=>{const Iu=$u.toolCallId??$u.subagentName,Pu=Ru.subagentActivity[Iu]??[];return Pu.some(Ou=>Ou.phase==="error"&&Ou.error===SUBAGENT_STOPPED)?{}:{subagentActivity:{...Ru.subagentActivity,[Iu]:[...Pu,$u]}}}),clearSubagentActivity:()=>Au({subagentActivity:{}}),stopSubagentActivity:()=>Au($u=>{let Ru=!1;const Iu={};for(const[Pu,Ou]of Object.entries($u.subagentActivity)){if(Ou.length===0||isSubagentRunOver(Ou)){Iu[Pu]=Ou;continue}Ru=!0,Iu[Pu]=[...Ou,{subagentName:Ou[0].subagentName,toolCallId:Ou[0].toolCallId??Pu,phase:"error",error:SUBAGENT_STOPPED,transport:Ou[0].transport}]}return Ru?{subagentActivity:Iu}:{}}),requestHistoryReload:()=>Au($u=>({historyVersion:$u.historyVersion+1})),requestToolDecision:$u=>Au(Ru=>({toolDecisionRequest:{seq:(Ru.toolDecisionRequest?.seq??0)+1,...$u}})),setCompaction:$u=>Au({compaction:$u}),upsertApproval:$u=>Au(Ru=>{const Iu=Ru.approvals.filter(Ou=>Ou.id!==$u.id),Pu=[$u,...Iu];return{approvals:Pu,pendingApprovalCount:countPendingApprovals(Pu)}}),removeApproval:$u=>Au(Ru=>{const Iu=Ru.approvals.filter(Pu=>Pu.id!==$u);return{approvals:Iu,pendingApprovalCount:countPendingApprovals(Iu)}}),sendDecision:($u,Ru,Iu,Pu,Ou)=>{const Mu=_resolveWs(Ou);return Mu?(Mu.send(JSON.stringify({type:"tool_approval_decision",approvalId:$u,approved:Ru,...Iu?{note:Iu}:{},...Pu?{toolCallId:Pu}:{}})),!0):!1},requestRefresh:$u=>{const Ru=_resolveWs($u);return Ru?(Ru.send(JSON.stringify({type:"request_snapshot"})),Ru.send(JSON.stringify({type:"request_otel_flush"})),!0):!1},sendRawMessage:($u,Ru)=>{const Iu=_resolveWs(Ru);return Iu?(Iu.send(JSON.stringify($u)),!0):!1},appendLocalTokenTurn:({serviceName:$u,agentId:Ru,timestampMs:Iu,promptTokens:Pu,completionTokens:Ou,totalTokens:Mu})=>{Au(Du=>{const Lu=getMonitoringCacheKey($u,Ru),Bu=Du.monitoringCache[Lu]??{tokenTurns:[],costPoints:[]},ju=[...Bu.tokenTurns],Fu=ju[ju.length-1];if(Fu&&Fu.userMessageTokens===Pu&&Fu.aiMessageTokens===Ou&&Fu.systemPromptTokens===0&&Fu.toolsDescriptionTokens===0&&Fu.toolsUsageTokens===0&&Fu.totalTokens===Mu)return ju[ju.length-1]={...Fu,timestampMs:Math.max(Fu.timestampMs,Iu)},{monitoringCache:{...Du.monitoringCache,[Lu]:{...Bu,tokenTurns:ju}}};const zu=(Fu?.turnNumber??0)+1;return ju.push({turnNumber:zu,timestampMs:Iu,systemPromptTokens:0,toolsDescriptionTokens:0,userMessageTokens:Pu,aiMessageTokens:Ou,toolsUsageTokens:0,totalTokens:Mu}),{monitoringCache:{...Du.monitoringCache,[Lu]:{...Bu,tokenTurns:ju}}}})},mergeTokenTurns:({serviceName:$u,agentId:Ru,turns:Iu})=>{Iu.length!==0&&Au(Pu=>{const Ou=getMonitoringCacheKey($u,Ru),Mu=Pu.monitoringCache[Ou]??{tokenTurns:[],costPoints:[]},Du=new Map;for(const Bu of Mu.tokenTurns)Du.set(Bu.turnNumber,Bu);for(const Bu of Iu)Du.set(Bu.turnNumber,Bu);const Lu=Array.from(Du.values()).sort((Bu,ju)=>Bu.turnNumber-ju.turnNumber);return{monitoringCache:{...Pu.monitoringCache,[Ou]:{...Mu,tokenTurns:Lu}}}})},appendLocalTokenTurnFull:({serviceName:$u,agentId:Ru,timestampMs:Iu,systemPromptTokens:Pu,toolsDescriptionTokens:Ou,userMessageTokens:Mu,aiMessageTokens:Du,toolsUsageTokens:Lu,totalTokens:Bu})=>{Au(ju=>{const Fu=getMonitoringCacheKey($u,Ru),zu=ju.monitoringCache[Fu]??{tokenTurns:[],costPoints:[]},Uu=[...zu.tokenTurns],Hu=Uu[Uu.length-1];if(Hu&&Hu.systemPromptTokens===Pu&&Hu.toolsDescriptionTokens===Ou&&Hu.userMessageTokens===Mu&&Hu.aiMessageTokens===Du&&Hu.toolsUsageTokens===Lu&&Hu.totalTokens===Bu)return Uu[Uu.length-1]={...Hu,timestampMs:Math.max(Hu.timestampMs,Iu)},{monitoringCache:{...ju.monitoringCache,[Fu]:{...zu,tokenTurns:Uu}}};const Vu=(Hu?.turnNumber??0)+1;return Uu.push({turnNumber:Vu,timestampMs:Iu,systemPromptTokens:Pu,toolsDescriptionTokens:Ou,userMessageTokens:Mu,aiMessageTokens:Du,toolsUsageTokens:Lu,totalTokens:Bu}),{monitoringCache:{...ju.monitoringCache,[Fu]:{...zu,tokenTurns:Uu}}}})},upsertLocalCostPoint:({serviceName:$u,agentId:Ru,timestampMs:Iu,cumulativeUsd:Pu})=>{Au(Ou=>{const Mu=getMonitoringCacheKey($u,Ru),Du=Ou.monitoringCache[Mu]??{tokenTurns:[],costPoints:[]},Lu=[...Du.costPoints],Bu=Lu.findIndex(ju=>Math.abs(ju.timestampMs-Iu)<1);return Bu>=0?Lu[Bu]={...Lu[Bu],cumulativeUsd:Math.max(Lu[Bu].cumulativeUsd,Pu)}:Lu.push({timestampMs:Iu,cumulativeUsd:Pu}),Lu.sort((ju,Fu)=>ju.timestampMs-Fu.timestampMs),{monitoringCache:{...Ou.monitoringCache,[Mu]:{...Du,costPoints:Lu}}}})},mergeCostPoints:({serviceName:$u,agentId:Ru,points:Iu})=>{Iu.length!==0&&Au(Pu=>{const Ou=getMonitoringCacheKey($u,Ru),Mu=Pu.monitoringCache[Ou]??{tokenTurns:[],costPoints:[]},Du=new Map;for(const Bu of Mu.costPoints)Du.set(Bu.timestampMs,Bu);for(const Bu of Iu){const ju=Du.get(Bu.timestampMs);ju?Du.set(Bu.timestampMs,{timestampMs:Bu.timestampMs,cumulativeUsd:Math.max(ju.cumulativeUsd,Bu.cumulativeUsd)}):Du.set(Bu.timestampMs,Bu)}const Lu=Array.from(Du.values()).sort((Bu,ju)=>Bu.timestampMs-ju.timestampMs);return{monitoringCache:{...Pu.monitoringCache,[Ou]:{...Mu,costPoints:Lu}}}})},reset:()=>{if(_ws)try{_ws.close(1e3,"reset")}catch{}_ws=null,_wsByAgentId.clear(),Au($u=>({...initialRuntimeState,...initialWsState,ephemeralNotebookModels:$u.ephemeralNotebookModels,ephemeralDocumentModels:$u.ephemeralDocumentModels,editorModeByRuntime:$u.editorModeByRuntime}))},resetWs:()=>{if(_ws)try{_ws.close(1e3,"reset")}catch{}_ws=null,_wsByAgentId.clear(),Au($u=>({...initialWsState,ephemeralNotebookModels:$u.ephemeralNotebookModels,ephemeralDocumentModels:$u.ephemeralDocumentModels,editorModeByRuntime:$u.editorModeByRuntime,subagentActivity:$u.subagentActivity}))}}),{name:"agent-runtimes-storage",storage:createJSONStorage(()=>localStorage),partialize:Au=>({agents:Au.agents.map(lo=>({id:lo.id,name:lo.name,description:lo.description,baseUrl:lo.baseUrl,transport:lo.protocol,status:lo.status,lastUpdated:lo.lastUpdated,documentId:lo.documentId,runtimeId:lo.runtimeId})),monitoringCache:Au.monitoringCache,loadedSkillsByAgentId:Au.loadedSkillsByAgentId,ephemeralNotebookModels:Au.ephemeralNotebookModels,ephemeralDocumentModels:Au.ephemeralDocumentModels,editorModeByRuntime:Au.editorModeByRuntime})})));function useAgentRuntimeStore(Au){return useStore$1(agentRuntimeStore,Au||($u=>$u))}const useAgentRuntimeStoreWithStatics=useAgentRuntimeStore;useAgentRuntimeStoreWithStatics.getState=agentRuntimeStore.getState;useAgentRuntimeStoreWithStatics.subscribe=agentRuntimeStore.subscribe;const useAgentRuntimeConnection=()=>useAgentRuntimeStore(Au=>Au.runtime),useAgentRuntimeStatus=()=>useAgentRuntimeStore(Au=>Au.status),useAgentRuntimeError=()=>useAgentRuntimeStore(Au=>Au.error),useAgentRuntimeIsLaunching=()=>useAgentRuntimeStore(Au=>Au.isLaunching),useAgentRuntimeMcpStatus=()=>useAgentRuntimeStore(Au=>Au.mcpStatus),useAgentRuntimeFullContext=()=>useAgentRuntimeStore(Au=>Au.fullContext),useAgentRuntimeContextSnapshot=()=>useAgentRuntimeStore(Au=>Au.contextSnapshot),useAgentRuntimeCodemodeStatus=()=>useAgentRuntimeStore(Au=>Au.codemodeStatus),useAgentRuntimeWsState=()=>useAgentRuntimeStore(Au=>Au.wsState),EMPTY_SUBAGENT_EVENTS=[],useAgentRuntimeSubagentActivity=Au=>useAgentRuntimeStore(lo=>Au?lo.subagentActivity[Au]??EMPTY_SUBAGENT_EVENTS:EMPTY_SUBAGENT_EVENTS),useAgentRuntimeSubagentActivityByToolCall=(Au,lo)=>useAgentRuntimeStore($u=>{if(Au){const Ru=$u.subagentActivity[Au];if(Ru&&Ru.length>0)return Ru}if(lo){const Ru=$u.subagentActivity[lo];if(Ru&&Ru.length>0)return Ru;let Iu;for(const Pu of Object.values($u.subagentActivity))Pu.length>0&&Pu[0]?.subagentName===lo&&(Iu=Pu);if(Iu)return Iu}return EMPTY_SUBAGENT_EVENTS}),useAgentRuntimeActiveSubagentToolCallId=()=>useAgentRuntimeStore(Au=>{let lo=null;for(const[$u,Ru]of Object.entries(Au.subagentActivity))Ru.length!==0&&(isSubagentRunOver(Ru)||(lo=$u));return lo});agentRuntimeStore.subscribe;async function requestAPI(Au="",lo={}){const $u=libExports$3.ServerConnection.makeSettings(),Ru=libExports$5.URLExt.join($u.baseUrl,"agent_runtimes",Au);let Iu;try{Iu=await libExports$3.ServerConnection.makeRequest(Ru,lo,$u)}catch(Ou){throw new libExports$3.ServerConnection.NetworkError(Ou)}let Pu=await Iu.text();if(Pu.length>0)try{Pu=JSON.parse(Pu)}catch{}if(!Iu.ok)throw new libExports$3.ServerConnection.ResponseError(Iu,Pu.message||Pu);return Pu}function useConfig(Au,lo,$u,Ru){return reactExports.useContext(QueryClientContext)?useQuery({queryFn:async()=>{if(lo){const Pu={"Content-Type":"application/json"};$u&&(Pu.Authorization=`Bearer ${$u}`);let Ou=lo;if(Ru){const Du=new URL(lo,window.location.origin);Du.searchParams.set("agent_id",Ru),Ou=Du.toString()}const Mu=await fetch(Ou,{headers:Pu});if(!Mu.ok)throw new Error(`Config fetch failed: ${Mu.statusText}`);return Mu.json()}return requestAPI("configure")},queryKey:["models",lo||"jupyter-server",Ru||"global"],enabled:Au,retry:1}):{data:void 0,isLoading:!1,isError:!1,error:null,refetch:()=>Promise.resolve({data:void 0})}}function parseSkillStatus(Au){return Au==="available"||Au==="enabled"||Au==="loaded"?Au:"available"}function useSkills(Au,lo,$u){const Ru=useAgentRuntimeCodemodeStatus(),Iu=reactExports.useMemo(()=>{if(!Ru)return;const Pu=(Ru.skills??[]).map(Ou=>({id:Ou.id??Ou.name,name:Ou.name,description:Ou.description,tags:Ou.tags,has_scripts:Ou.has_scripts,has_resources:Ou.has_resources,status:parseSkillStatus(Ou.status),approved:Ou.approved!==!1,skill_definition:Ou.skill_definition??null,source_variant:Ou.source_variant,module:Ou.module,package:Ou.package,method:Ou.method,path:Ou.path}));return{skills:Pu,total:Pu.length}},[Ru]);return{data:Iu,isLoading:!1,isError:!1,error:null,refetch:()=>Promise.resolve({data:Iu})}}function useSkillActions(Au){const lo=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_enable",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_enable dropped: websocket not ready"),Ou},[Au]),$u=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_disable",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_disable dropped: websocket not ready"),Ou},[Au]),Ru=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_approve",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_approve dropped: websocket not ready"),Ou},[Au]),Iu=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_unapprove",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_unapprove dropped: websocket not ready"),Ou},[Au]);return{enableSkill:lo,disableSkill:$u,approveSkill:Ru,unapproveSkill:Iu}}function useContextSnapshot(Au,lo,$u,Ru){return{data:useAgentRuntimeContextSnapshot()??void 0,isLoading:!1,isError:!1,error:null}}const RECONNECT_BASE_MS$1=1e3,RECONNECT_MAX_MS$1=3e4;function isRetryableCloseCode(Au){return!new Set([1002,1003,1007,1008,4401,4403]).has(Au)}function useSandbox(Au,lo,$u,Ru){const[Iu,Pu]=reactExports.useState(void 0),Ou=reactExports.useRef(null);reactExports.useEffect(()=>{if(!Au||!lo){Pu(void 0);return}const Du=getApiBaseFromConfig(lo);if(!Du)return;const Lu=Du.replace(/^http/,"ws"),Bu=[];Ru&&Bu.push(`agent_id=${encodeURIComponent(Ru)}`),$u&&Bu.push(`token=${encodeURIComponent($u)}`);const ju=`${Lu}/configure/sandbox/ws${Bu.length?`?${Bu.join("&")}`:""}`;let Fu=!1,zu,Uu=0;const Hu=Gu=>{if(Fu||!isRetryableCloseCode(Gu))return;const Wu=Math.min(RECONNECT_BASE_MS$1*2**Uu,RECONNECT_MAX_MS$1);Uu+=1,zu=setTimeout(Vu,Wu)},Vu=()=>{if(Fu)return;const Gu=new WebSocket(ju);Ou.current=Gu,Gu.onopen=()=>{Uu=0},Gu.onmessage=Wu=>{try{const Ku=JSON.parse(Wu.data);if(Ku&&Ku.action==="interrupt")return;const Ju=typeof Ku?.variant=="string"?Ku.variant:"";Pu({available:Ju!=="unavailable"&&Ju!=="error",sandbox_running:!!Ku?.sandbox_running,is_executing:!!Ku?.is_executing,variant:Ju})}catch{}},Gu.onclose=Wu=>{Ou.current=null,Hu(Wu.code)},Gu.onerror=()=>{Gu.close()}};return Vu(),()=>{Fu=!0,zu&&clearTimeout(zu),Ou.current?.close(),Ou.current=null,Pu(void 0)}},[Au,lo,$u,Ru]);const Mu=reactExports.useCallback(()=>{const Du=Ou.current;Du&&Du.readyState===WebSocket.OPEN&&Du.send(JSON.stringify({action:"interrupt"}))},[]);return{data:Iu,interrupt:Mu}}function _typeof$8(Au){"@babel/helpers - typeof";return _typeof$8=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$8(Au)}function _createClass$8(Au,lo,$u){return Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _classCallCheck$8(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _callSuper$1(Au,lo,$u){return lo=_getPrototypeOf$1(lo),_possibleConstructorReturn$1(Au,_isNativeReflectConstruct$1()?Reflect.construct(lo,$u||[],_getPrototypeOf$1(Au).constructor):lo.apply(Au,$u))}function _possibleConstructorReturn$1(Au,lo){if(lo&&(_typeof$8(lo)==="object"||typeof lo=="function"))return lo;if(lo!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized$1(Au)}function _assertThisInitialized$1(Au){if(Au===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return Au}function _inherits$1(Au,lo){if(typeof lo!="function"&&lo!==null)throw new TypeError("Super expression must either be null or a function");Au.prototype=Object.create(lo&&lo.prototype,{constructor:{value:Au,writable:!0,configurable:!0}}),Object.defineProperty(Au,"prototype",{writable:!1}),lo&&_setPrototypeOf$1(Au,lo)}function _wrapNativeSuper(Au){var lo=typeof Map=="function"?new Map:void 0;return _wrapNativeSuper=function(Ru){if(Ru===null||!_isNativeFunction(Ru))return Ru;if(typeof Ru!="function")throw new TypeError("Super expression must either be null or a function");if(typeof lo<"u"){if(lo.has(Ru))return lo.get(Ru);lo.set(Ru,Iu)}function Iu(){return _construct(Ru,arguments,_getPrototypeOf$1(this).constructor)}return Iu.prototype=Object.create(Ru.prototype,{constructor:{value:Iu,enumerable:!1,writable:!0,configurable:!0}}),_setPrototypeOf$1(Iu,Ru)},_wrapNativeSuper(Au)}function _construct(Au,lo,$u){if(_isNativeReflectConstruct$1())return Reflect.construct.apply(null,arguments);var Ru=[null];Ru.push.apply(Ru,lo);var Iu=new(Au.bind.apply(Au,Ru));return $u&&_setPrototypeOf$1(Iu,$u.prototype),Iu}function _isNativeReflectConstruct$1(){try{var Au=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(_isNativeReflectConstruct$1=function(){return!!Au})()}function _isNativeFunction(Au){try{return Function.toString.call(Au).indexOf("[native code]")!==-1}catch{return typeof Au=="function"}}function _setPrototypeOf$1(Au,lo){return _setPrototypeOf$1=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(Ru,Iu){return Ru.__proto__=Iu,Ru},_setPrototypeOf$1(Au,lo)}function _getPrototypeOf$1(Au){return _getPrototypeOf$1=Object.setPrototypeOf?Object.getPrototypeOf.bind():function($u){return $u.__proto__||Object.getPrototypeOf($u)},_getPrototypeOf$1(Au)}var DetailedError=(function(Au){function lo($u){var Ru,Iu=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,Pu=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,Ou=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null;if(_classCallCheck$8(this,lo),Ru=_callSuper$1(this,lo,[$u]),Ru.originalRequest=Pu,Ru.originalResponse=Ou,Ru.causingError=Iu,Iu!=null&&($u+=", caused by ".concat(Iu.toString())),Pu!=null){var Mu=Pu.getHeader("X-Request-ID")||"n/a",Du=Pu.getMethod(),Lu=Pu.getURL(),Bu=Ou?Ou.getStatus():"n/a",ju=Ou?Ou.getBody()||"":"n/a";$u+=", originated from request (method: ".concat(Du,", url: ").concat(Lu,", response code: ").concat(Bu,", response text: ").concat(ju,", request id: ").concat(Mu,")")}return Ru.message=$u,Ru}return _inherits$1(lo,Au),_createClass$8(lo)})(_wrapNativeSuper(Error));function log(Au){}function _typeof$7(Au){"@babel/helpers - typeof";return _typeof$7=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$7(Au)}function _classCallCheck$7(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$7(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$7(Ru.key),Ru)}}function _createClass$7(Au,lo,$u){return lo&&_defineProperties$7(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$7(Au){var lo=_toPrimitive$7(Au,"string");return _typeof$7(lo)=="symbol"?lo:lo+""}function _toPrimitive$7(Au,lo){if(_typeof$7(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$7(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var NoopUrlStorage=(function(){function Au(){_classCallCheck$7(this,Au)}return _createClass$7(Au,[{key:"listAllUploads",value:function(){return Promise.resolve([])}},{key:"findUploadsByFingerprint",value:function($u){return Promise.resolve([])}},{key:"removeUpload",value:function($u){return Promise.resolve()}},{key:"addUpload",value:function($u,Ru){return Promise.resolve(null)}}])})();const version$1="3.9.4",VERSION=version$1,_TD=typeof TextDecoder=="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,_TE=typeof TextEncoder=="function"?new TextEncoder:void 0,b64ch="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",b64chs=Array.prototype.slice.call(b64ch),b64tab=(Au=>{let lo={};return Au.forEach(($u,Ru)=>lo[$u]=Ru),lo})(b64chs),b64re=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,_fromCC=String.fromCharCode.bind(String),_U8Afrom=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):Au=>new Uint8Array(Array.prototype.slice.call(Au,0)),_mkUriSafe=Au=>Au.replace(/=/g,"").replace(/[+\/]/g,lo=>lo=="+"?"-":"_"),_tidyB64=Au=>Au.replace(/[^A-Za-z0-9\+\/]/g,""),btoaPolyfill=Au=>{let lo,$u,Ru,Iu,Pu="";const Ou=Au.length%3;for(let Mu=0;Mu<Au.length;){if(($u=Au.charCodeAt(Mu++))>255||(Ru=Au.charCodeAt(Mu++))>255||(Iu=Au.charCodeAt(Mu++))>255)throw new TypeError("invalid character found");lo=$u<<16|Ru<<8|Iu,Pu+=b64chs[lo>>18&63]+b64chs[lo>>12&63]+b64chs[lo>>6&63]+b64chs[lo&63]}return Ou?Pu.slice(0,Ou-3)+"===".substring(Ou):Pu},_btoa=typeof btoa=="function"?Au=>btoa(Au):btoaPolyfill,_fromUint8Array=typeof Uint8Array.prototype.toBase64=="function"?Au=>Au.toBase64():Au=>{let $u=[];for(let Ru=0,Iu=Au.length;Ru<Iu;Ru+=4096)$u.push(_fromCC.apply(null,Au.subarray(Ru,Ru+4096)));return _btoa($u.join(""))},fromUint8Array=(Au,lo=!1)=>lo?_mkUriSafe(_fromUint8Array(Au)):_fromUint8Array(Au),cb_utob=Au=>{if(Au.length<2){var lo=Au.charCodeAt(0);return lo<128?Au:lo<2048?_fromCC(192|lo>>>6)+_fromCC(128|lo&63):_fromCC(224|lo>>>12&15)+_fromCC(128|lo>>>6&63)+_fromCC(128|lo&63)}else{var lo=65536+(Au.charCodeAt(0)-55296)*1024+(Au.charCodeAt(1)-56320);return _fromCC(240|lo>>>18&7)+_fromCC(128|lo>>>12&63)+_fromCC(128|lo>>>6&63)+_fromCC(128|lo&63)}},re_utob=/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\x00-\x7F]/g,utob=Au=>Au.replace(re_utob,cb_utob),_encode=_TE?Au=>_fromUint8Array(_TE.encode(Au)):Au=>_btoa(utob(Au)),encode$2=(Au,lo=!1)=>lo?_mkUriSafe(_encode(Au)):_encode(Au),encodeURI$1=Au=>encode$2(Au,!0),re_btou=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,cb_btou=Au=>{switch(Au.length){case 4:var lo=(7&Au.charCodeAt(0))<<18|(63&Au.charCodeAt(1))<<12|(63&Au.charCodeAt(2))<<6|63&Au.charCodeAt(3),$u=lo-65536;return _fromCC(($u>>>10)+55296)+_fromCC(($u&1023)+56320);case 3:return _fromCC((15&Au.charCodeAt(0))<<12|(63&Au.charCodeAt(1))<<6|63&Au.charCodeAt(2));default:return _fromCC((31&Au.charCodeAt(0))<<6|63&Au.charCodeAt(1))}},btou=Au=>Au.replace(re_btou,cb_btou),atobPolyfill=Au=>{if(Au=Au.replace(/\s+/g,""),!b64re.test(Au))throw new TypeError("malformed base64.");Au+="==".slice(2-(Au.length&3));let lo,$u,Ru,Iu=[];for(let Pu=0;Pu<Au.length;)lo=b64tab[Au.charAt(Pu++)]<<18|b64tab[Au.charAt(Pu++)]<<12|($u=b64tab[Au.charAt(Pu++)])<<6|(Ru=b64tab[Au.charAt(Pu++)]),$u===64?Iu.push(_fromCC(lo>>16&255)):Ru===64?Iu.push(_fromCC(lo>>16&255,lo>>8&255)):Iu.push(_fromCC(lo>>16&255,lo>>8&255,lo&255));return Iu.join("")},_atob=typeof atob=="function"?Au=>atob(_tidyB64(Au)):atobPolyfill,_toUint8Array=typeof Uint8Array.fromBase64=="function"?Au=>Uint8Array.fromBase64(Au):Au=>_U8Afrom(_atob(Au).split("").map(lo=>lo.charCodeAt(0))),toUint8Array=Au=>_toUint8Array(_unURI(Au)),_decode=_TD?Au=>_TD.decode(_toUint8Array(Au)):Au=>btou(_atob(Au)),_unURI=Au=>_tidyB64(Au.replace(/[-_]/g,lo=>lo=="-"?"+":"/")),decode$3=Au=>_decode(_unURI(Au)),isValid$1=Au=>{if(typeof Au!="string")return!1;const lo=Au.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(lo)||!/[^\s0-9a-zA-Z\-_]/.test(lo)},_noEnum=Au=>({value:Au,enumerable:!1,writable:!0,configurable:!0}),extendString=function(){const Au=(lo,$u)=>Object.defineProperty(String.prototype,lo,_noEnum($u));Au("fromBase64",function(){return decode$3(this)}),Au("toBase64",function(lo){return encode$2(this,lo)}),Au("toBase64URI",function(){return encode$2(this,!0)}),Au("toBase64URL",function(){return encode$2(this,!0)}),Au("toUint8Array",function(){return toUint8Array(this)})},extendUint8Array=function(){const Au=(lo,$u)=>Object.defineProperty(Uint8Array.prototype,lo,_noEnum($u));Au("toBase64",function(lo){return fromUint8Array(this,lo)}),Au("toBase64URI",function(){return fromUint8Array(this,!0)}),Au("toBase64URL",function(){return fromUint8Array(this,!0)})},extendBuiltins=()=>{extendString(),extendUint8Array()},gBase64={version:version$1,VERSION,atob:_atob,atobPolyfill,btoa:_btoa,btoaPolyfill,fromBase64:decode$3,toBase64:encode$2,encode:encode$2,encodeURI:encodeURI$1,encodeURL:encodeURI$1,utob,btou,decode:decode$3,isValid:isValid$1,fromUint8Array,toUint8Array,extendString,extendUint8Array,extendBuiltins};var urlParseExports=requireUrlParse();const URL$1=getDefaultExportFromCjs(urlParseExports);function uuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(Au){var lo=Math.random()*16|0,$u=Au==="x"?lo:lo&3|8;return $u.toString(16)})}function _regeneratorRuntime$1(){_regeneratorRuntime$1=function(){return lo};var Au,lo={},$u=Object.prototype,Ru=$u.hasOwnProperty,Iu=Object.defineProperty||function(_d,yd,wd){_d[yd]=wd.value},Pu=typeof Symbol=="function"?Symbol:{},Ou=Pu.iterator||"@@iterator",Mu=Pu.asyncIterator||"@@asyncIterator",Du=Pu.toStringTag||"@@toStringTag";function Lu(_d,yd,wd){return Object.defineProperty(_d,yd,{value:wd,enumerable:!0,configurable:!0,writable:!0}),_d[yd]}try{Lu({},"")}catch{Lu=function(wd,Ad,md){return wd[Ad]=md}}function Bu(_d,yd,wd,Ad){var md=yd&&yd.prototype instanceof Gu?yd:Gu,dd=Object.create(md.prototype),bd=new gd(Ad||[]);return Iu(dd,"_invoke",{value:od(_d,wd,bd)}),dd}function ju(_d,yd,wd){try{return{type:"normal",arg:_d.call(yd,wd)}}catch(Ad){return{type:"throw",arg:Ad}}}lo.wrap=Bu;var Fu="suspendedStart",zu="suspendedYield",Uu="executing",Hu="completed",Vu={};function Gu(){}function Wu(){}function Ku(){}var Ju={};Lu(Ju,Ou,function(){return this});var Yu=Object.getPrototypeOf,Xu=Yu&&Yu(Yu(Sd([])));Xu&&Xu!==$u&&Ru.call(Xu,Ou)&&(Ju=Xu);var ed=Ku.prototype=Gu.prototype=Object.create(Ju);function td(_d){["next","throw","return"].forEach(function(yd){Lu(_d,yd,function(wd){return this._invoke(yd,wd)})})}function nd(_d,yd){function wd(md,dd,bd,ld){var ud=ju(_d[md],_d,dd);if(ud.type!=="throw"){var hd=ud.arg,vd=hd.value;return vd&&_typeof$6(vd)=="object"&&Ru.call(vd,"__await")?yd.resolve(vd.__await).then(function(Ed){wd("next",Ed,bd,ld)},function(Ed){wd("throw",Ed,bd,ld)}):yd.resolve(vd).then(function(Ed){hd.value=Ed,bd(hd)},function(Ed){return wd("throw",Ed,bd,ld)})}ld(ud.arg)}var Ad;Iu(this,"_invoke",{value:function(dd,bd){function ld(){return new yd(function(ud,hd){wd(dd,bd,ud,hd)})}return Ad=Ad?Ad.then(ld,ld):ld()}})}function od(_d,yd,wd){var Ad=Fu;return function(md,dd){if(Ad===Uu)throw Error("Generator is already running");if(Ad===Hu){if(md==="throw")throw dd;return{value:Au,done:!0}}for(wd.method=md,wd.arg=dd;;){var bd=wd.delegate;if(bd){var ld=sd(bd,wd);if(ld){if(ld===Vu)continue;return ld}}if(wd.method==="next")wd.sent=wd._sent=wd.arg;else if(wd.method==="throw"){if(Ad===Fu)throw Ad=Hu,wd.arg;wd.dispatchException(wd.arg)}else wd.method==="return"&&wd.abrupt("return",wd.arg);Ad=Uu;var ud=ju(_d,yd,wd);if(ud.type==="normal"){if(Ad=wd.done?Hu:zu,ud.arg===Vu)continue;return{value:ud.arg,done:wd.done}}ud.type==="throw"&&(Ad=Hu,wd.method="throw",wd.arg=ud.arg)}}}function sd(_d,yd){var wd=yd.method,Ad=_d.iterator[wd];if(Ad===Au)return yd.delegate=null,wd==="throw"&&_d.iterator.return&&(yd.method="return",yd.arg=Au,sd(_d,yd),yd.method==="throw")||wd!=="return"&&(yd.method="throw",yd.arg=new TypeError("The iterator does not provide a '"+wd+"' method")),Vu;var md=ju(Ad,_d.iterator,yd.arg);if(md.type==="throw")return yd.method="throw",yd.arg=md.arg,yd.delegate=null,Vu;var dd=md.arg;return dd?dd.done?(yd[_d.resultName]=dd.value,yd.next=_d.nextLoc,yd.method!=="return"&&(yd.method="next",yd.arg=Au),yd.delegate=null,Vu):dd:(yd.method="throw",yd.arg=new TypeError("iterator result is not an object"),yd.delegate=null,Vu)}function ad(_d){var yd={tryLoc:_d[0]};1 in _d&&(yd.catchLoc=_d[1]),2 in _d&&(yd.finallyLoc=_d[2],yd.afterLoc=_d[3]),this.tryEntries.push(yd)}function pd(_d){var yd=_d.completion||{};yd.type="normal",delete yd.arg,_d.completion=yd}function gd(_d){this.tryEntries=[{tryLoc:"root"}],_d.forEach(ad,this),this.reset(!0)}function Sd(_d){if(_d||_d===""){var yd=_d[Ou];if(yd)return yd.call(_d);if(typeof _d.next=="function")return _d;if(!isNaN(_d.length)){var wd=-1,Ad=function md(){for(;++wd<_d.length;)if(Ru.call(_d,wd))return md.value=_d[wd],md.done=!1,md;return md.value=Au,md.done=!0,md};return Ad.next=Ad}}throw new TypeError(_typeof$6(_d)+" is not iterable")}return Wu.prototype=Ku,Iu(ed,"constructor",{value:Ku,configurable:!0}),Iu(Ku,"constructor",{value:Wu,configurable:!0}),Wu.displayName=Lu(Ku,Du,"GeneratorFunction"),lo.isGeneratorFunction=function(_d){var yd=typeof _d=="function"&&_d.constructor;return!!yd&&(yd===Wu||(yd.displayName||yd.name)==="GeneratorFunction")},lo.mark=function(_d){return Object.setPrototypeOf?Object.setPrototypeOf(_d,Ku):(_d.__proto__=Ku,Lu(_d,Du,"GeneratorFunction")),_d.prototype=Object.create(ed),_d},lo.awrap=function(_d){return{__await:_d}},td(nd.prototype),Lu(nd.prototype,Mu,function(){return this}),lo.AsyncIterator=nd,lo.async=function(_d,yd,wd,Ad,md){md===void 0&&(md=Promise);var dd=new nd(Bu(_d,yd,wd,Ad),md);return lo.isGeneratorFunction(yd)?dd:dd.next().then(function(bd){return bd.done?bd.value:dd.next()})},td(ed),Lu(ed,Du,"Generator"),Lu(ed,Ou,function(){return this}),Lu(ed,"toString",function(){return"[object Generator]"}),lo.keys=function(_d){var yd=Object(_d),wd=[];for(var Ad in yd)wd.push(Ad);return wd.reverse(),function md(){for(;wd.length;){var dd=wd.pop();if(dd in yd)return md.value=dd,md.done=!1,md}return md.done=!0,md}},lo.values=Sd,gd.prototype={constructor:gd,reset:function(yd){if(this.prev=0,this.next=0,this.sent=this._sent=Au,this.done=!1,this.delegate=null,this.method="next",this.arg=Au,this.tryEntries.forEach(pd),!yd)for(var wd in this)wd.charAt(0)==="t"&&Ru.call(this,wd)&&!isNaN(+wd.slice(1))&&(this[wd]=Au)},stop:function(){this.done=!0;var yd=this.tryEntries[0].completion;if(yd.type==="throw")throw yd.arg;return this.rval},dispatchException:function(yd){if(this.done)throw yd;var wd=this;function Ad(hd,vd){return bd.type="throw",bd.arg=yd,wd.next=hd,vd&&(wd.method="next",wd.arg=Au),!!vd}for(var md=this.tryEntries.length-1;md>=0;--md){var dd=this.tryEntries[md],bd=dd.completion;if(dd.tryLoc==="root")return Ad("end");if(dd.tryLoc<=this.prev){var ld=Ru.call(dd,"catchLoc"),ud=Ru.call(dd,"finallyLoc");if(ld&&ud){if(this.prev<dd.catchLoc)return Ad(dd.catchLoc,!0);if(this.prev<dd.finallyLoc)return Ad(dd.finallyLoc)}else if(ld){if(this.prev<dd.catchLoc)return Ad(dd.catchLoc,!0)}else{if(!ud)throw Error("try statement without catch or finally");if(this.prev<dd.finallyLoc)return Ad(dd.finallyLoc)}}}},abrupt:function(yd,wd){for(var Ad=this.tryEntries.length-1;Ad>=0;--Ad){var md=this.tryEntries[Ad];if(md.tryLoc<=this.prev&&Ru.call(md,"finallyLoc")&&this.prev<md.finallyLoc){var dd=md;break}}dd&&(yd==="break"||yd==="continue")&&dd.tryLoc<=wd&&wd<=dd.finallyLoc&&(dd=null);var bd=dd?dd.completion:{};return bd.type=yd,bd.arg=wd,dd?(this.method="next",this.next=dd.finallyLoc,Vu):this.complete(bd)},complete:function(yd,wd){if(yd.type==="throw")throw yd.arg;return yd.type==="break"||yd.type==="continue"?this.next=yd.arg:yd.type==="return"?(this.rval=this.arg=yd.arg,this.method="return",this.next="end"):yd.type==="normal"&&wd&&(this.next=wd),Vu},finish:function(yd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ad=this.tryEntries[wd];if(Ad.finallyLoc===yd)return this.complete(Ad.completion,Ad.afterLoc),pd(Ad),Vu}},catch:function(yd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ad=this.tryEntries[wd];if(Ad.tryLoc===yd){var md=Ad.completion;if(md.type==="throw"){var dd=md.arg;pd(Ad)}return dd}}throw Error("illegal catch attempt")},delegateYield:function(yd,wd,Ad){return this.delegate={iterator:Sd(yd),resultName:wd,nextLoc:Ad},this.method==="next"&&(this.arg=Au),Vu}},lo}function asyncGeneratorStep$1(Au,lo,$u,Ru,Iu,Pu,Ou){try{var Mu=Au[Pu](Ou),Du=Mu.value}catch(Lu){$u(Lu);return}Mu.done?lo(Du):Promise.resolve(Du).then(Ru,Iu)}function _asyncToGenerator$1(Au){return function(){var lo=this,$u=arguments;return new Promise(function(Ru,Iu){var Pu=Au.apply(lo,$u);function Ou(Du){asyncGeneratorStep$1(Pu,Ru,Iu,Ou,Mu,"next",Du)}function Mu(Du){asyncGeneratorStep$1(Pu,Ru,Iu,Ou,Mu,"throw",Du)}Ou(void 0)})}}function _slicedToArray$1(Au,lo){return _arrayWithHoles$1(Au)||_iterableToArrayLimit$1(Au,lo)||_unsupportedIterableToArray$1(Au,lo)||_nonIterableRest$1()}function _nonIterableRest$1(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
2198
2198
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _iterableToArrayLimit$1(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 _arrayWithHoles$1(Au){if(Array.isArray(Au))return Au}function _typeof$6(Au){"@babel/helpers - typeof";return _typeof$6=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$6(Au)}function _createForOfIteratorHelper(Au,lo){var $u=typeof Symbol<"u"&&Au[Symbol.iterator]||Au["@@iterator"];if(!$u){if(Array.isArray(Au)||($u=_unsupportedIterableToArray$1(Au))||lo){$u&&(Au=$u);var Ru=0,Iu=function(){};return{s:Iu,n:function(){return Ru>=Au.length?{done:!0}:{done:!1,value:Au[Ru++]}},e:function(Lu){throw Lu},f:Iu}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
2199
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var Pu=!0,Ou=!1,Mu;return{s:function(){$u=$u.call(Au)},n:function(){var Lu=$u.next();return Pu=Lu.done,Lu},e:function(Lu){Ou=!0,Mu=Lu},f:function(){try{!Pu&&$u.return!=null&&$u.return()}finally{if(Ou)throw Mu}}}}function _unsupportedIterableToArray$1(Au,lo){if(Au){if(typeof Au=="string")return _arrayLikeToArray$1(Au,lo);var $u=Object.prototype.toString.call(Au).slice(8,-1);if($u==="Object"&&Au.constructor&&($u=Au.constructor.name),$u==="Map"||$u==="Set")return Array.from(Au);if($u==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test($u))return _arrayLikeToArray$1(Au,lo)}}function _arrayLikeToArray$1(Au,lo){(lo==null||lo>Au.length)&&(lo=Au.length);for(var $u=0,Ru=new Array(lo);$u<lo;$u++)Ru[$u]=Au[$u];return Ru}function ownKeys$1(Au,lo){var $u=Object.keys(Au);if(Object.getOwnPropertySymbols){var Ru=Object.getOwnPropertySymbols(Au);lo&&(Ru=Ru.filter(function(Iu){return Object.getOwnPropertyDescriptor(Au,Iu).enumerable})),$u.push.apply($u,Ru)}return $u}function _objectSpread$1(Au){for(var lo=1;lo<arguments.length;lo++){var $u=arguments[lo]!=null?arguments[lo]:{};lo%2?ownKeys$1(Object($u),!0).forEach(function(Ru){_defineProperty$1(Au,Ru,$u[Ru])}):Object.getOwnPropertyDescriptors?Object.defineProperties(Au,Object.getOwnPropertyDescriptors($u)):ownKeys$1(Object($u)).forEach(function(Ru){Object.defineProperty(Au,Ru,Object.getOwnPropertyDescriptor($u,Ru))})}return Au}function _defineProperty$1(Au,lo,$u){return lo=_toPropertyKey$6(lo),lo in Au?Object.defineProperty(Au,lo,{value:$u,enumerable:!0,configurable:!0,writable:!0}):Au[lo]=$u,Au}function _classCallCheck$6(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$6(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$6(Ru.key),Ru)}}function _createClass$6(Au,lo,$u){return lo&&_defineProperties$6(Au.prototype,lo),$u&&_defineProperties$6(Au,$u),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$6(Au){var lo=_toPrimitive$6(Au,"string");return _typeof$6(lo)=="symbol"?lo:lo+""}function _toPrimitive$6(Au,lo){if(_typeof$6(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$6(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var PROTOCOL_TUS_V1="tus-v1",PROTOCOL_IETF_DRAFT_03="ietf-draft-03",PROTOCOL_IETF_DRAFT_05="ietf-draft-05",defaultOptions$2={endpoint:null,uploadUrl:null,metadata:{},metadataForPartialUploads:{},fingerprint:null,uploadSize:null,onProgress:null,onChunkComplete:null,onSuccess:null,onError:null,onUploadUrlAvailable:null,overridePatchMethod:!1,headers:{},addRequestId:!1,onBeforeRequest:null,onAfterResponse:null,onShouldRetry:defaultOnShouldRetry,chunkSize:Number.POSITIVE_INFINITY,retryDelays:[0,1e3,3e3,5e3],parallelUploads:1,parallelUploadBoundaries:null,storeFingerprintForResuming:!0,removeFingerprintOnSuccess:!1,uploadLengthDeferred:!1,uploadDataDuringCreation:!1,urlStorage:null,fileReader:null,httpStack:null,protocol:PROTOCOL_TUS_V1},BaseUpload=(function(){function Au(lo,$u){_classCallCheck$6(this,Au),"resume"in $u&&console.log("tus: The `resume` option has been removed in tus-js-client v2. Please use the URL storage API instead."),this.options=$u,this.options.chunkSize=Number(this.options.chunkSize),this._urlStorage=this.options.urlStorage,this.file=lo,this.url=null,this._req=null,this._fingerprint=null,this._urlStorageKey=null,this._offset=null,this._aborted=!1,this._size=null,this._source=null,this._retryAttempt=0,this._retryTimeout=null,this._offsetBeforeRetry=0,this._parallelUploads=null,this._parallelUploadUrls=null}return _createClass$6(Au,[{key:"findPreviousUploads",value:function(){var $u=this;return this.options.fingerprint(this.file,this.options).then(function(Ru){return $u._urlStorage.findUploadsByFingerprint(Ru)})}},{key:"resumeFromPreviousUpload",value:function($u){this.url=$u.uploadUrl||null,this._parallelUploadUrls=$u.parallelUploadUrls||null,this._urlStorageKey=$u.urlStorageKey}},{key:"start",value:function(){var $u=this,Ru=this.file;if(!Ru){this._emitError(new Error("tus: no file or stream to upload provided"));return}if(![PROTOCOL_TUS_V1,PROTOCOL_IETF_DRAFT_03,PROTOCOL_IETF_DRAFT_05].includes(this.options.protocol)){this._emitError(new Error("tus: unsupported protocol ".concat(this.options.protocol)));return}if(!this.options.endpoint&&!this.options.uploadUrl&&!this.url){this._emitError(new Error("tus: neither an endpoint or an upload URL is provided"));return}var Iu=this.options.retryDelays;if(Iu!=null&&Object.prototype.toString.call(Iu)!=="[object Array]"){this._emitError(new Error("tus: the `retryDelays` option must either be an array or null"));return}if(this.options.parallelUploads>1)for(var Pu=0,Ou=["uploadUrl","uploadSize","uploadLengthDeferred"];Pu<Ou.length;Pu++){var Mu=Ou[Pu];if(this.options[Mu]){this._emitError(new Error("tus: cannot use the ".concat(Mu," option when parallelUploads is enabled")));return}}if(this.options.parallelUploadBoundaries){if(this.options.parallelUploads<=1){this._emitError(new Error("tus: cannot use the `parallelUploadBoundaries` option when `parallelUploads` is disabled"));return}if(this.options.parallelUploads!==this.options.parallelUploadBoundaries.length){this._emitError(new Error("tus: the `parallelUploadBoundaries` must have the same length as the value of `parallelUploads`"));return}}this.options.fingerprint(Ru,this.options).then(function(Du){return $u._fingerprint=Du,$u._source?$u._source:$u.options.fileReader.openFile(Ru,$u.options.chunkSize)}).then(function(Du){if($u._source=Du,$u.options.uploadLengthDeferred)$u._size=null;else if($u.options.uploadSize!=null){if($u._size=Number($u.options.uploadSize),Number.isNaN($u._size)){$u._emitError(new Error("tus: cannot convert `uploadSize` option into a number"));return}}else if($u._size=$u._source.size,$u._size==null){$u._emitError(new Error("tus: cannot automatically derive upload's size from input. Specify it manually using the `uploadSize` option or use the `uploadLengthDeferred` option"));return}$u.options.parallelUploads>1||$u._parallelUploadUrls!=null?$u._startParallelUpload():$u._startSingleUpload()}).catch(function(Du){$u._emitError(Du)})}},{key:"_startParallelUpload",value:function(){var $u,Ru=this,Iu=this._size,Pu=0;this._parallelUploads=[];var Ou=this._parallelUploadUrls!=null?this._parallelUploadUrls.length:this.options.parallelUploads,Mu=($u=this.options.parallelUploadBoundaries)!==null&&$u!==void 0?$u:splitSizeIntoParts(this._source.size,Ou);this._parallelUploadUrls&&Mu.forEach(function(Bu,ju){Bu.uploadUrl=Ru._parallelUploadUrls[ju]||null}),this._parallelUploadUrls=new Array(Mu.length);var Du=Mu.map(function(Bu,ju){var Fu=0;return Ru._source.slice(Bu.start,Bu.end).then(function(zu){var Uu=zu.value;return new Promise(function(Hu,Vu){var Gu=_objectSpread$1(_objectSpread$1({},Ru.options),{},{uploadUrl:Bu.uploadUrl||null,storeFingerprintForResuming:!1,removeFingerprintOnSuccess:!1,parallelUploads:1,parallelUploadBoundaries:null,metadata:Ru.options.metadataForPartialUploads,headers:_objectSpread$1(_objectSpread$1({},Ru.options.headers),{},{"Upload-Concat":"partial"}),onSuccess:Hu,onError:Vu,onProgress:function(Ju){Pu=Pu-Fu+Ju,Fu=Ju,Ru._emitProgress(Pu,Iu)},onUploadUrlAvailable:function(){Ru._parallelUploadUrls[ju]=Wu.url,Ru._parallelUploadUrls.filter(function(Ju){return!!Ju}).length===Mu.length&&Ru._saveUploadInUrlStorage()}}),Wu=new Au(Uu,Gu);Wu.start(),Ru._parallelUploads.push(Wu)})})}),Lu;Promise.all(Du).then(function(){Lu=Ru._openRequest("POST",Ru.options.endpoint),Lu.setHeader("Upload-Concat","final;".concat(Ru._parallelUploadUrls.join(" ")));var Bu=encodeMetadata(Ru.options.metadata);return Bu!==""&&Lu.setHeader("Upload-Metadata",Bu),Ru._sendRequest(Lu,null)}).then(function(Bu){if(!inStatusCategory(Bu.getStatus(),200)){Ru._emitHttpError(Lu,Bu,"tus: unexpected response while creating upload");return}var ju=Bu.getHeader("Location");if(ju==null){Ru._emitHttpError(Lu,Bu,"tus: invalid or missing Location header");return}Ru.url=resolveUrl(Ru.options.endpoint,ju),"Created upload at ".concat(Ru.url),Ru._emitSuccess(Bu)}).catch(function(Bu){Ru._emitError(Bu)})}},{key:"_startSingleUpload",value:function(){if(this._aborted=!1,this.url!=null){"Resuming upload from previous URL: ".concat(this.url),this._resumeUpload();return}if(this.options.uploadUrl!=null){"Resuming upload from provided URL: ".concat(this.options.uploadUrl),this.url=this.options.uploadUrl,this._resumeUpload();return}this._createUpload()}},{key:"abort",value:function($u){var Ru=this;if(this._parallelUploads!=null){var Iu=_createForOfIteratorHelper(this._parallelUploads),Pu;try{for(Iu.s();!(Pu=Iu.n()).done;){var Ou=Pu.value;Ou.abort($u)}}catch(Mu){Iu.e(Mu)}finally{Iu.f()}}return this._req!==null&&this._req.abort(),this._aborted=!0,this._retryTimeout!=null&&(clearTimeout(this._retryTimeout),this._retryTimeout=null),!$u||this.url==null?Promise.resolve():Au.terminate(this.url,this.options).then(function(){return Ru._removeFromUrlStorage()})}},{key:"_emitHttpError",value:function($u,Ru,Iu,Pu){this._emitError(new DetailedError(Iu,Pu,$u,Ru))}},{key:"_emitError",value:function($u){var Ru=this;if(!this._aborted){if(this.options.retryDelays!=null){var Iu=this._offset!=null&&this._offset>this._offsetBeforeRetry;if(Iu&&(this._retryAttempt=0),shouldRetry($u,this._retryAttempt,this.options)){var Pu=this.options.retryDelays[this._retryAttempt++];this._offsetBeforeRetry=this._offset,this._retryTimeout=setTimeout(function(){Ru.start()},Pu);return}}if(typeof this.options.onError=="function")this.options.onError($u);else throw $u}}},{key:"_emitSuccess",value:function($u){this.options.removeFingerprintOnSuccess&&this._removeFromUrlStorage(),typeof this.options.onSuccess=="function"&&this.options.onSuccess({lastResponse:$u})}},{key:"_emitProgress",value:function($u,Ru){typeof this.options.onProgress=="function"&&this.options.onProgress($u,Ru)}},{key:"_emitChunkComplete",value:function($u,Ru,Iu){typeof this.options.onChunkComplete=="function"&&this.options.onChunkComplete($u,Ru,Iu)}},{key:"_createUpload",value:function(){var $u=this;if(!this.options.endpoint){this._emitError(new Error("tus: unable to create upload because no endpoint is provided"));return}var Ru=this._openRequest("POST",this.options.endpoint);this.options.uploadLengthDeferred?Ru.setHeader("Upload-Defer-Length","1"):Ru.setHeader("Upload-Length","".concat(this._size));var Iu=encodeMetadata(this.options.metadata);Iu!==""&&Ru.setHeader("Upload-Metadata",Iu);var Pu;this.options.uploadDataDuringCreation&&!this.options.uploadLengthDeferred?(this._offset=0,Pu=this._addChunkToRequest(Ru)):((this.options.protocol===PROTOCOL_IETF_DRAFT_03||this.options.protocol===PROTOCOL_IETF_DRAFT_05)&&Ru.setHeader("Upload-Complete","?0"),Pu=this._sendRequest(Ru,null)),Pu.then(function(Ou){if(!inStatusCategory(Ou.getStatus(),200)){$u._emitHttpError(Ru,Ou,"tus: unexpected response while creating upload");return}var Mu=Ou.getHeader("Location");if(Mu==null){$u._emitHttpError(Ru,Ou,"tus: invalid or missing Location header");return}if($u.url=resolveUrl($u.options.endpoint,Mu),"Created upload at ".concat($u.url),typeof $u.options.onUploadUrlAvailable=="function"&&$u.options.onUploadUrlAvailable(),$u._size===0){$u._emitSuccess(Ou),$u._source.close();return}$u._saveUploadInUrlStorage().then(function(){$u.options.uploadDataDuringCreation?$u._handleUploadResponse(Ru,Ou):($u._offset=0,$u._performUpload())})}).catch(function(Ou){$u._emitHttpError(Ru,null,"tus: failed to create upload",Ou)})}},{key:"_resumeUpload",value:function(){var $u=this,Ru=this._openRequest("HEAD",this.url),Iu=this._sendRequest(Ru,null);Iu.then(function(Pu){var Ou=Pu.getStatus();if(!inStatusCategory(Ou,200)){if(Ou===423){$u._emitHttpError(Ru,Pu,"tus: upload is currently locked; retry later");return}if(inStatusCategory(Ou,400)&&$u._removeFromUrlStorage(),!$u.options.endpoint){$u._emitHttpError(Ru,Pu,"tus: unable to resume upload (new upload cannot be created without an endpoint)");return}$u.url=null,$u._createUpload();return}var Mu=Number.parseInt(Pu.getHeader("Upload-Offset"),10);if(Number.isNaN(Mu)){$u._emitHttpError(Ru,Pu,"tus: invalid or missing offset value");return}var Du=Number.parseInt(Pu.getHeader("Upload-Length"),10);if(Number.isNaN(Du)&&!$u.options.uploadLengthDeferred&&$u.options.protocol===PROTOCOL_TUS_V1){$u._emitHttpError(Ru,Pu,"tus: invalid or missing length value");return}typeof $u.options.onUploadUrlAvailable=="function"&&$u.options.onUploadUrlAvailable(),$u._saveUploadInUrlStorage().then(function(){if(Mu===Du){$u._emitProgress(Du,Du),$u._emitSuccess(Pu);return}$u._offset=Mu,$u._performUpload()})}).catch(function(Pu){$u._emitHttpError(Ru,null,"tus: failed to resume upload",Pu)})}},{key:"_performUpload",value:function(){var $u=this;if(!this._aborted){var Ru;this.options.overridePatchMethod?(Ru=this._openRequest("POST",this.url),Ru.setHeader("X-HTTP-Method-Override","PATCH")):Ru=this._openRequest("PATCH",this.url),Ru.setHeader("Upload-Offset","".concat(this._offset));var Iu=this._addChunkToRequest(Ru);Iu.then(function(Pu){if(!inStatusCategory(Pu.getStatus(),200)){$u._emitHttpError(Ru,Pu,"tus: unexpected response while uploading chunk");return}$u._handleUploadResponse(Ru,Pu)}).catch(function(Pu){$u._aborted||$u._emitHttpError(Ru,null,"tus: failed to upload chunk at offset ".concat($u._offset),Pu)})}}},{key:"_addChunkToRequest",value:function($u){var Ru=this,Iu=this._offset,Pu=this._offset+this.options.chunkSize;return $u.setProgressHandler(function(Ou){Ru._emitProgress(Iu+Ou,Ru._size)}),this.options.protocol===PROTOCOL_TUS_V1?$u.setHeader("Content-Type","application/offset+octet-stream"):this.options.protocol===PROTOCOL_IETF_DRAFT_05&&$u.setHeader("Content-Type","application/partial-upload"),(Pu===Number.POSITIVE_INFINITY||Pu>this._size)&&!this.options.uploadLengthDeferred&&(Pu=this._size),this._source.slice(Iu,Pu).then(function(Ou){var Mu=Ou.value,Du=Ou.done,Lu=Mu!=null&&Mu.size?Mu.size:0;Ru.options.uploadLengthDeferred&&Du&&(Ru._size=Ru._offset+Lu,$u.setHeader("Upload-Length","".concat(Ru._size)));var Bu=Ru._offset+Lu;return!Ru.options.uploadLengthDeferred&&Du&&Bu!==Ru._size?Promise.reject(new Error("upload was configured with a size of ".concat(Ru._size," bytes, but the source is done after ").concat(Bu," bytes"))):Mu===null?Ru._sendRequest($u):((Ru.options.protocol===PROTOCOL_IETF_DRAFT_03||Ru.options.protocol===PROTOCOL_IETF_DRAFT_05)&&$u.setHeader("Upload-Complete",Du?"?1":"?0"),Ru._emitProgress(Ru._offset,Ru._size),Ru._sendRequest($u,Mu))})}},{key:"_handleUploadResponse",value:function($u,Ru){var Iu=Number.parseInt(Ru.getHeader("Upload-Offset"),10);if(Number.isNaN(Iu)){this._emitHttpError($u,Ru,"tus: invalid or missing offset value");return}if(this._emitProgress(Iu,this._size),this._emitChunkComplete(Iu-this._offset,Iu,this._size),this._offset=Iu,Iu===this._size){this._emitSuccess(Ru),this._source.close();return}this._performUpload()}},{key:"_openRequest",value:function($u,Ru){var Iu=openRequest($u,Ru,this.options);return this._req=Iu,Iu}},{key:"_removeFromUrlStorage",value:function(){var $u=this;this._urlStorageKey&&(this._urlStorage.removeUpload(this._urlStorageKey).catch(function(Ru){$u._emitError(Ru)}),this._urlStorageKey=null)}},{key:"_saveUploadInUrlStorage",value:function(){var $u=this;if(!this.options.storeFingerprintForResuming||!this._fingerprint||this._urlStorageKey!==null)return Promise.resolve();var Ru={size:this._size,metadata:this.options.metadata,creationTime:new Date().toString()};return this._parallelUploads?Ru.parallelUploadUrls=this._parallelUploadUrls:Ru.uploadUrl=this.url,this._urlStorage.addUpload(this._fingerprint,Ru).then(function(Iu){$u._urlStorageKey=Iu})}},{key:"_sendRequest",value:function($u){var Ru=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;return sendRequest($u,Ru,this.options)}}],[{key:"terminate",value:function($u){var Ru=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Iu=openRequest("DELETE",$u,Ru);return sendRequest(Iu,null,Ru).then(function(Pu){if(Pu.getStatus()!==204)throw new DetailedError("tus: unexpected response while terminating upload",null,Iu,Pu)}).catch(function(Pu){if(Pu instanceof DetailedError||(Pu=new DetailedError("tus: failed to terminate upload",Pu,Iu,null)),!shouldRetry(Pu,0,Ru))throw Pu;var Ou=Ru.retryDelays[0],Mu=Ru.retryDelays.slice(1),Du=_objectSpread$1(_objectSpread$1({},Ru),{},{retryDelays:Mu});return new Promise(function(Lu){return setTimeout(Lu,Ou)}).then(function(){return Au.terminate($u,Du)})})}}])})();function encodeMetadata(Au){return Object.entries(Au).map(function(lo){var $u=_slicedToArray$1(lo,2),Ru=$u[0],Iu=$u[1];return"".concat(Ru," ").concat(gBase64.encode(String(Iu)))}).join(",")}function inStatusCategory(Au,lo){return Au>=lo&&Au<lo+100}function openRequest(Au,lo,$u){var Ru=$u.httpStack.createRequest(Au,lo);$u.protocol===PROTOCOL_IETF_DRAFT_03?Ru.setHeader("Upload-Draft-Interop-Version","5"):$u.protocol===PROTOCOL_IETF_DRAFT_05?Ru.setHeader("Upload-Draft-Interop-Version","6"):Ru.setHeader("Tus-Resumable","1.0.0");for(var Iu=$u.headers||{},Pu=0,Ou=Object.entries(Iu);Pu<Ou.length;Pu++){var Mu=_slicedToArray$1(Ou[Pu],2),Du=Mu[0],Lu=Mu[1];Ru.setHeader(Du,Lu)}if($u.addRequestId){var Bu=uuid();Ru.setHeader("X-Request-ID",Bu)}return Ru}function sendRequest(Au,lo,$u){return _sendRequest2.apply(this,arguments)}function _sendRequest2(){return _sendRequest2=_asyncToGenerator$1(_regeneratorRuntime$1().mark(function Au(lo,$u,Ru){var Iu;return _regeneratorRuntime$1().wrap(function(Ou){for(;;)switch(Ou.prev=Ou.next){case 0:if(typeof Ru.onBeforeRequest!="function"){Ou.next=3;break}return Ou.next=3,Ru.onBeforeRequest(lo);case 3:return Ou.next=5,lo.send($u);case 5:if(Iu=Ou.sent,typeof Ru.onAfterResponse!="function"){Ou.next=9;break}return Ou.next=9,Ru.onAfterResponse(lo,Iu);case 9:return Ou.abrupt("return",Iu);case 10:case"end":return Ou.stop()}},Au)})),_sendRequest2.apply(this,arguments)}function isOnline(){var Au=!0;return typeof navigator<"u"&&navigator.onLine===!1&&(Au=!1),Au}function shouldRetry(Au,lo,$u){return $u.retryDelays==null||lo>=$u.retryDelays.length||Au.originalRequest==null?!1:$u&&typeof $u.onShouldRetry=="function"?$u.onShouldRetry(Au,lo,$u):defaultOnShouldRetry(Au)}function defaultOnShouldRetry(Au){var lo=Au.originalResponse?Au.originalResponse.getStatus():0;return(!inStatusCategory(lo,400)||lo===409||lo===423)&&isOnline()}function resolveUrl(Au,lo){return new URL$1(lo,Au).toString()}function splitSizeIntoParts(Au,lo){for(var $u=Math.floor(Au/lo),Ru=[],Iu=0;Iu<lo;Iu++)Ru.push({start:$u*Iu,end:$u*(Iu+1)});return Ru[lo-1].end=Au,Ru}BaseUpload.defaultOptions=defaultOptions$2;var isReactNative=function Au(){return typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative"};function uriToBlob(Au){return new Promise(function(lo,$u){var Ru=new XMLHttpRequest;Ru.responseType="blob",Ru.onload=function(){var Iu=Ru.response;lo(Iu)},Ru.onerror=function(Iu){$u(Iu)},Ru.open("GET",Au),Ru.send()})}var isCordova=function Au(){return typeof window<"u"&&(typeof window.PhoneGap<"u"||typeof window.Cordova<"u"||typeof window.cordova<"u")};function readAsByteArray(Au){return new Promise(function(lo,$u){var Ru=new FileReader;Ru.onload=function(){var Iu=new Uint8Array(Ru.result);lo({value:Iu})},Ru.onerror=function(Iu){$u(Iu)},Ru.readAsArrayBuffer(Au)})}function _typeof$5(Au){"@babel/helpers - typeof";return _typeof$5=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$5(Au)}function _classCallCheck$5(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$5(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$5(Ru.key),Ru)}}function _createClass$5(Au,lo,$u){return lo&&_defineProperties$5(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$5(Au){var lo=_toPrimitive$5(Au,"string");return _typeof$5(lo)=="symbol"?lo:lo+""}function _toPrimitive$5(Au,lo){if(_typeof$5(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$5(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var FileSource=(function(){function Au(lo){_classCallCheck$5(this,Au),this._file=lo,this.size=lo.size}return _createClass$5(Au,[{key:"slice",value:function($u,Ru){if(isCordova())return readAsByteArray(this._file.slice($u,Ru));var Iu=this._file.slice($u,Ru),Pu=Ru>=this.size;return Promise.resolve({value:Iu,done:Pu})}},{key:"close",value:function(){}}])})();function _typeof$4(Au){"@babel/helpers - typeof";return _typeof$4=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$4(Au)}function _classCallCheck$4(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$4(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$4(Ru.key),Ru)}}function _createClass$4(Au,lo,$u){return lo&&_defineProperties$4(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$4(Au){var lo=_toPrimitive$4(Au,"string");return _typeof$4(lo)=="symbol"?lo:lo+""}function _toPrimitive$4(Au,lo){if(_typeof$4(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$4(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}function len(Au){return Au===void 0?0:Au.size!==void 0?Au.size:Au.length}function concat(Au,lo){if(Au.concat)return Au.concat(lo);if(Au instanceof Blob)return new Blob([Au,lo],{type:Au.type});if(Au.set){var $u=new Au.constructor(Au.length+lo.length);return $u.set(Au),$u.set(lo,Au.length),$u}throw new Error("Unknown data type")}var StreamSource=(function(){function Au(lo){_classCallCheck$4(this,Au),this._buffer=void 0,this._bufferOffset=0,this._reader=lo,this._done=!1}return _createClass$4(Au,[{key:"slice",value:function($u,Ru){return $u<this._bufferOffset?Promise.reject(new Error("Requested data is before the reader's current offset")):this._readUntilEnoughDataOrDone($u,Ru)}},{key:"_readUntilEnoughDataOrDone",value:function($u,Ru){var Iu=this,Pu=Ru<=this._bufferOffset+len(this._buffer);if(this._done||Pu){var Ou=this._getDataFromBuffer($u,Ru),Mu=Ou==null?this._done:!1;return Promise.resolve({value:Ou,done:Mu})}return this._reader.read().then(function(Du){var Lu=Du.value,Bu=Du.done;return Bu?Iu._done=!0:Iu._buffer===void 0?Iu._buffer=Lu:Iu._buffer=concat(Iu._buffer,Lu),Iu._readUntilEnoughDataOrDone($u,Ru)})}},{key:"_getDataFromBuffer",value:function($u,Ru){$u>this._bufferOffset&&(this._buffer=this._buffer.slice($u-this._bufferOffset),this._bufferOffset=$u);var Iu=len(this._buffer)===0;return this._done&&Iu?null:this._buffer.slice(0,Ru-$u)}},{key:"close",value:function(){this._reader.cancel&&this._reader.cancel()}}])})();function _typeof$3(Au){"@babel/helpers - typeof";return _typeof$3=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$3(Au)}function _regeneratorRuntime(){_regeneratorRuntime=function(){return lo};var Au,lo={},$u=Object.prototype,Ru=$u.hasOwnProperty,Iu=Object.defineProperty||function(_d,yd,wd){_d[yd]=wd.value},Pu=typeof Symbol=="function"?Symbol:{},Ou=Pu.iterator||"@@iterator",Mu=Pu.asyncIterator||"@@asyncIterator",Du=Pu.toStringTag||"@@toStringTag";function Lu(_d,yd,wd){return Object.defineProperty(_d,yd,{value:wd,enumerable:!0,configurable:!0,writable:!0}),_d[yd]}try{Lu({},"")}catch{Lu=function(wd,Ad,md){return wd[Ad]=md}}function Bu(_d,yd,wd,Ad){var md=yd&&yd.prototype instanceof Gu?yd:Gu,dd=Object.create(md.prototype),bd=new gd(Ad||[]);return Iu(dd,"_invoke",{value:od(_d,wd,bd)}),dd}function ju(_d,yd,wd){try{return{type:"normal",arg:_d.call(yd,wd)}}catch(Ad){return{type:"throw",arg:Ad}}}lo.wrap=Bu;var Fu="suspendedStart",zu="suspendedYield",Uu="executing",Hu="completed",Vu={};function Gu(){}function Wu(){}function Ku(){}var Ju={};Lu(Ju,Ou,function(){return this});var Yu=Object.getPrototypeOf,Xu=Yu&&Yu(Yu(Sd([])));Xu&&Xu!==$u&&Ru.call(Xu,Ou)&&(Ju=Xu);var ed=Ku.prototype=Gu.prototype=Object.create(Ju);function td(_d){["next","throw","return"].forEach(function(yd){Lu(_d,yd,function(wd){return this._invoke(yd,wd)})})}function nd(_d,yd){function wd(md,dd,bd,ld){var ud=ju(_d[md],_d,dd);if(ud.type!=="throw"){var hd=ud.arg,vd=hd.value;return vd&&_typeof$3(vd)=="object"&&Ru.call(vd,"__await")?yd.resolve(vd.__await).then(function(Ed){wd("next",Ed,bd,ld)},function(Ed){wd("throw",Ed,bd,ld)}):yd.resolve(vd).then(function(Ed){hd.value=Ed,bd(hd)},function(Ed){return wd("throw",Ed,bd,ld)})}ld(ud.arg)}var Ad;Iu(this,"_invoke",{value:function(dd,bd){function ld(){return new yd(function(ud,hd){wd(dd,bd,ud,hd)})}return Ad=Ad?Ad.then(ld,ld):ld()}})}function od(_d,yd,wd){var Ad=Fu;return function(md,dd){if(Ad===Uu)throw Error("Generator is already running");if(Ad===Hu){if(md==="throw")throw dd;return{value:Au,done:!0}}for(wd.method=md,wd.arg=dd;;){var bd=wd.delegate;if(bd){var ld=sd(bd,wd);if(ld){if(ld===Vu)continue;return ld}}if(wd.method==="next")wd.sent=wd._sent=wd.arg;else if(wd.method==="throw"){if(Ad===Fu)throw Ad=Hu,wd.arg;wd.dispatchException(wd.arg)}else wd.method==="return"&&wd.abrupt("return",wd.arg);Ad=Uu;var ud=ju(_d,yd,wd);if(ud.type==="normal"){if(Ad=wd.done?Hu:zu,ud.arg===Vu)continue;return{value:ud.arg,done:wd.done}}ud.type==="throw"&&(Ad=Hu,wd.method="throw",wd.arg=ud.arg)}}}function sd(_d,yd){var wd=yd.method,Ad=_d.iterator[wd];if(Ad===Au)return yd.delegate=null,wd==="throw"&&_d.iterator.return&&(yd.method="return",yd.arg=Au,sd(_d,yd),yd.method==="throw")||wd!=="return"&&(yd.method="throw",yd.arg=new TypeError("The iterator does not provide a '"+wd+"' method")),Vu;var md=ju(Ad,_d.iterator,yd.arg);if(md.type==="throw")return yd.method="throw",yd.arg=md.arg,yd.delegate=null,Vu;var dd=md.arg;return dd?dd.done?(yd[_d.resultName]=dd.value,yd.next=_d.nextLoc,yd.method!=="return"&&(yd.method="next",yd.arg=Au),yd.delegate=null,Vu):dd:(yd.method="throw",yd.arg=new TypeError("iterator result is not an object"),yd.delegate=null,Vu)}function ad(_d){var yd={tryLoc:_d[0]};1 in _d&&(yd.catchLoc=_d[1]),2 in _d&&(yd.finallyLoc=_d[2],yd.afterLoc=_d[3]),this.tryEntries.push(yd)}function pd(_d){var yd=_d.completion||{};yd.type="normal",delete yd.arg,_d.completion=yd}function gd(_d){this.tryEntries=[{tryLoc:"root"}],_d.forEach(ad,this),this.reset(!0)}function Sd(_d){if(_d||_d===""){var yd=_d[Ou];if(yd)return yd.call(_d);if(typeof _d.next=="function")return _d;if(!isNaN(_d.length)){var wd=-1,Ad=function md(){for(;++wd<_d.length;)if(Ru.call(_d,wd))return md.value=_d[wd],md.done=!1,md;return md.value=Au,md.done=!0,md};return Ad.next=Ad}}throw new TypeError(_typeof$3(_d)+" is not iterable")}return Wu.prototype=Ku,Iu(ed,"constructor",{value:Ku,configurable:!0}),Iu(Ku,"constructor",{value:Wu,configurable:!0}),Wu.displayName=Lu(Ku,Du,"GeneratorFunction"),lo.isGeneratorFunction=function(_d){var yd=typeof _d=="function"&&_d.constructor;return!!yd&&(yd===Wu||(yd.displayName||yd.name)==="GeneratorFunction")},lo.mark=function(_d){return Object.setPrototypeOf?Object.setPrototypeOf(_d,Ku):(_d.__proto__=Ku,Lu(_d,Du,"GeneratorFunction")),_d.prototype=Object.create(ed),_d},lo.awrap=function(_d){return{__await:_d}},td(nd.prototype),Lu(nd.prototype,Mu,function(){return this}),lo.AsyncIterator=nd,lo.async=function(_d,yd,wd,Ad,md){md===void 0&&(md=Promise);var dd=new nd(Bu(_d,yd,wd,Ad),md);return lo.isGeneratorFunction(yd)?dd:dd.next().then(function(bd){return bd.done?bd.value:dd.next()})},td(ed),Lu(ed,Du,"Generator"),Lu(ed,Ou,function(){return this}),Lu(ed,"toString",function(){return"[object Generator]"}),lo.keys=function(_d){var yd=Object(_d),wd=[];for(var Ad in yd)wd.push(Ad);return wd.reverse(),function md(){for(;wd.length;){var dd=wd.pop();if(dd in yd)return md.value=dd,md.done=!1,md}return md.done=!0,md}},lo.values=Sd,gd.prototype={constructor:gd,reset:function(yd){if(this.prev=0,this.next=0,this.sent=this._sent=Au,this.done=!1,this.delegate=null,this.method="next",this.arg=Au,this.tryEntries.forEach(pd),!yd)for(var wd in this)wd.charAt(0)==="t"&&Ru.call(this,wd)&&!isNaN(+wd.slice(1))&&(this[wd]=Au)},stop:function(){this.done=!0;var yd=this.tryEntries[0].completion;if(yd.type==="throw")throw yd.arg;return this.rval},dispatchException:function(yd){if(this.done)throw yd;var wd=this;function Ad(hd,vd){return bd.type="throw",bd.arg=yd,wd.next=hd,vd&&(wd.method="next",wd.arg=Au),!!vd}for(var md=this.tryEntries.length-1;md>=0;--md){var dd=this.tryEntries[md],bd=dd.completion;if(dd.tryLoc==="root")return Ad("end");if(dd.tryLoc<=this.prev){var ld=Ru.call(dd,"catchLoc"),ud=Ru.call(dd,"finallyLoc");if(ld&&ud){if(this.prev<dd.catchLoc)return Ad(dd.catchLoc,!0);if(this.prev<dd.finallyLoc)return Ad(dd.finallyLoc)}else if(ld){if(this.prev<dd.catchLoc)return Ad(dd.catchLoc,!0)}else{if(!ud)throw Error("try statement without catch or finally");if(this.prev<dd.finallyLoc)return Ad(dd.finallyLoc)}}}},abrupt:function(yd,wd){for(var Ad=this.tryEntries.length-1;Ad>=0;--Ad){var md=this.tryEntries[Ad];if(md.tryLoc<=this.prev&&Ru.call(md,"finallyLoc")&&this.prev<md.finallyLoc){var dd=md;break}}dd&&(yd==="break"||yd==="continue")&&dd.tryLoc<=wd&&wd<=dd.finallyLoc&&(dd=null);var bd=dd?dd.completion:{};return bd.type=yd,bd.arg=wd,dd?(this.method="next",this.next=dd.finallyLoc,Vu):this.complete(bd)},complete:function(yd,wd){if(yd.type==="throw")throw yd.arg;return yd.type==="break"||yd.type==="continue"?this.next=yd.arg:yd.type==="return"?(this.rval=this.arg=yd.arg,this.method="return",this.next="end"):yd.type==="normal"&&wd&&(this.next=wd),Vu},finish:function(yd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ad=this.tryEntries[wd];if(Ad.finallyLoc===yd)return this.complete(Ad.completion,Ad.afterLoc),pd(Ad),Vu}},catch:function(yd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ad=this.tryEntries[wd];if(Ad.tryLoc===yd){var md=Ad.completion;if(md.type==="throw"){var dd=md.arg;pd(Ad)}return dd}}throw Error("illegal catch attempt")},delegateYield:function(yd,wd,Ad){return this.delegate={iterator:Sd(yd),resultName:wd,nextLoc:Ad},this.method==="next"&&(this.arg=Au),Vu}},lo}function asyncGeneratorStep(Au,lo,$u,Ru,Iu,Pu,Ou){try{var Mu=Au[Pu](Ou),Du=Mu.value}catch(Lu){$u(Lu);return}Mu.done?lo(Du):Promise.resolve(Du).then(Ru,Iu)}function _asyncToGenerator(Au){return function(){var lo=this,$u=arguments;return new Promise(function(Ru,Iu){var Pu=Au.apply(lo,$u);function Ou(Du){asyncGeneratorStep(Pu,Ru,Iu,Ou,Mu,"next",Du)}function Mu(Du){asyncGeneratorStep(Pu,Ru,Iu,Ou,Mu,"throw",Du)}Ou(void 0)})}}function _classCallCheck$3(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$3(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$3(Ru.key),Ru)}}function _createClass$3(Au,lo,$u){return lo&&_defineProperties$3(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$3(Au){var lo=_toPrimitive$3(Au,"string");return _typeof$3(lo)=="symbol"?lo:lo+""}function _toPrimitive$3(Au,lo){if(_typeof$3(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$3(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var FileReader$1=(function(){function Au(){_classCallCheck$3(this,Au)}return _createClass$3(Au,[{key:"openFile",value:(function(){var lo=_asyncToGenerator(_regeneratorRuntime().mark(function Ru(Iu,Pu){var Ou;return _regeneratorRuntime().wrap(function(Du){for(;;)switch(Du.prev=Du.next){case 0:if(!(isReactNative()&&Iu&&typeof Iu.uri<"u")){Du.next=11;break}return Du.prev=1,Du.next=4,uriToBlob(Iu.uri);case 4:return Ou=Du.sent,Du.abrupt("return",new FileSource(Ou));case 8:throw Du.prev=8,Du.t0=Du.catch(1),new Error("tus: cannot fetch `file.uri` as Blob, make sure the uri is correct and accessible. ".concat(Du.t0));case 11:if(!(typeof Iu.slice=="function"&&typeof Iu.size<"u")){Du.next=13;break}return Du.abrupt("return",Promise.resolve(new FileSource(Iu)));case 13:if(typeof Iu.read!="function"){Du.next=18;break}if(Pu=Number(Pu),Number.isFinite(Pu)){Du.next=17;break}return Du.abrupt("return",Promise.reject(new Error("cannot create source for stream without a finite value for the `chunkSize` option")));case 17:return Du.abrupt("return",Promise.resolve(new StreamSource(Iu,Pu)));case 18:return Du.abrupt("return",Promise.reject(new Error("source object may only be an instance of File, Blob, or Reader in this environment")));case 19:case"end":return Du.stop()}},Ru,null,[[1,8]])}));function $u(Ru,Iu){return lo.apply(this,arguments)}return $u})()}])})();function fingerprint(Au,lo){return isReactNative()?Promise.resolve(reactNativeFingerprint(Au,lo)):Promise.resolve(["tus-br",Au.name,Au.type,Au.size,Au.lastModified,lo.endpoint].join("-"))}function reactNativeFingerprint(Au,lo){var $u=Au.exif?hashCode(JSON.stringify(Au.exif)):"noexif";return["tus-rn",Au.name||"noname",Au.size||"nosize",$u,lo.endpoint].join("/")}function hashCode(Au){var lo=0;if(Au.length===0)return lo;for(var $u=0;$u<Au.length;$u++){var Ru=Au.charCodeAt($u);lo=(lo<<5)-lo+Ru,lo&=lo}return lo}function _typeof$2(Au){"@babel/helpers - typeof";return _typeof$2=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$2(Au)}function _classCallCheck$2(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$2(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$2(Ru.key),Ru)}}function _createClass$2(Au,lo,$u){return lo&&_defineProperties$2(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$2(Au){var lo=_toPrimitive$2(Au,"string");return _typeof$2(lo)=="symbol"?lo:lo+""}function _toPrimitive$2(Au,lo){if(_typeof$2(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$2(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var XHRHttpStack=(function(){function Au(){_classCallCheck$2(this,Au)}return _createClass$2(Au,[{key:"createRequest",value:function($u,Ru){return new Request$1($u,Ru)}},{key:"getName",value:function(){return"XHRHttpStack"}}])})(),Request$1=(function(){function Au(lo,$u){_classCallCheck$2(this,Au),this._xhr=new XMLHttpRequest,this._xhr.open(lo,$u,!0),this._method=lo,this._url=$u,this._headers={}}return _createClass$2(Au,[{key:"getMethod",value:function(){return this._method}},{key:"getURL",value:function(){return this._url}},{key:"setHeader",value:function($u,Ru){this._xhr.setRequestHeader($u,Ru),this._headers[$u]=Ru}},{key:"getHeader",value:function($u){return this._headers[$u]}},{key:"setProgressHandler",value:function($u){"upload"in this._xhr&&(this._xhr.upload.onprogress=function(Ru){Ru.lengthComputable&&$u(Ru.loaded)})}},{key:"send",value:function(){var $u=this,Ru=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null;return new Promise(function(Iu,Pu){$u._xhr.onload=function(){Iu(new Response$1($u._xhr))},$u._xhr.onerror=function(Ou){Pu(Ou)},$u._xhr.send(Ru)})}},{key:"abort",value:function(){return this._xhr.abort(),Promise.resolve()}},{key:"getUnderlyingObject",value:function(){return this._xhr}}])})(),Response$1=(function(){function Au(lo){_classCallCheck$2(this,Au),this._xhr=lo}return _createClass$2(Au,[{key:"getStatus",value:function(){return this._xhr.status}},{key:"getHeader",value:function($u){return this._xhr.getResponseHeader($u)}},{key:"getBody",value:function(){return this._xhr.responseText}},{key:"getUnderlyingObject",value:function(){return this._xhr}}])})();function _typeof$1(Au){"@babel/helpers - typeof";return _typeof$1=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$1(Au)}function _classCallCheck$1(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$1(Ru.key),Ru)}}function _createClass$1(Au,lo,$u){return lo&&_defineProperties$1(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$1(Au){var lo=_toPrimitive$1(Au,"string");return _typeof$1(lo)=="symbol"?lo:lo+""}function _toPrimitive$1(Au,lo){if(_typeof$1(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$1(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var hasStorage=!1;try{hasStorage="localStorage"in window;var key="tusSupport",originalValue=localStorage.getItem(key);localStorage.setItem(key,originalValue),originalValue===null&&localStorage.removeItem(key)}catch(Au){if(Au.code===Au.SECURITY_ERR||Au.code===Au.QUOTA_EXCEEDED_ERR)hasStorage=!1;else throw Au}var canStoreURLs=hasStorage,WebStorageUrlStorage=(function(){function Au(){_classCallCheck$1(this,Au)}return _createClass$1(Au,[{key:"findAllUploads",value:function(){var $u=this._findEntries("tus::");return Promise.resolve($u)}},{key:"findUploadsByFingerprint",value:function($u){var Ru=this._findEntries("tus::".concat($u,"::"));return Promise.resolve(Ru)}},{key:"removeUpload",value:function($u){return localStorage.removeItem($u),Promise.resolve()}},{key:"addUpload",value:function($u,Ru){var Iu=Math.round(Math.random()*1e12),Pu="tus::".concat($u,"::").concat(Iu);return localStorage.setItem(Pu,JSON.stringify(Ru)),Promise.resolve(Pu)}},{key:"_findEntries",value:function($u){for(var Ru=[],Iu=0;Iu<localStorage.length;Iu++){var Pu=localStorage.key(Iu);if(Pu.indexOf($u)===0)try{var Ou=JSON.parse(localStorage.getItem(Pu));Ou.urlStorageKey=Pu,Ru.push(Ou)}catch{}}return Ru}}])})();function _typeof(Au){"@babel/helpers - typeof";return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof(Au)}function _classCallCheck(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey(Ru.key),Ru)}}function _createClass(Au,lo,$u){return $u&&_defineProperties(Au,$u),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _callSuper(Au,lo,$u){return lo=_getPrototypeOf(lo),_possibleConstructorReturn(Au,_isNativeReflectConstruct()?Reflect.construct(lo,$u||[],_getPrototypeOf(Au).constructor):lo.apply(Au,$u))}function _possibleConstructorReturn(Au,lo){if(lo&&(_typeof(lo)==="object"||typeof lo=="function"))return lo;if(lo!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized(Au)}function _assertThisInitialized(Au){if(Au===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return Au}function _isNativeReflectConstruct(){try{var Au=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(_isNativeReflectConstruct=function(){return!!Au})()}function _getPrototypeOf(Au){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function($u){return $u.__proto__||Object.getPrototypeOf($u)},_getPrototypeOf(Au)}function _inherits(Au,lo){if(typeof lo!="function"&&lo!==null)throw new TypeError("Super expression must either be null or a function");Au.prototype=Object.create(lo&&lo.prototype,{constructor:{value:Au,writable:!0,configurable:!0}}),Object.defineProperty(Au,"prototype",{writable:!1}),lo&&_setPrototypeOf(Au,lo)}function _setPrototypeOf(Au,lo){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(Ru,Iu){return Ru.__proto__=Iu,Ru},_setPrototypeOf(Au,lo)}function ownKeys(Au,lo){var $u=Object.keys(Au);if(Object.getOwnPropertySymbols){var Ru=Object.getOwnPropertySymbols(Au);lo&&(Ru=Ru.filter(function(Iu){return Object.getOwnPropertyDescriptor(Au,Iu).enumerable})),$u.push.apply($u,Ru)}return $u}function _objectSpread(Au){for(var lo=1;lo<arguments.length;lo++){var $u=arguments[lo]!=null?arguments[lo]:{};lo%2?ownKeys(Object($u),!0).forEach(function(Ru){_defineProperty(Au,Ru,$u[Ru])}):Object.getOwnPropertyDescriptors?Object.defineProperties(Au,Object.getOwnPropertyDescriptors($u)):ownKeys(Object($u)).forEach(function(Ru){Object.defineProperty(Au,Ru,Object.getOwnPropertyDescriptor($u,Ru))})}return Au}function _defineProperty(Au,lo,$u){return lo=_toPropertyKey(lo),lo in Au?Object.defineProperty(Au,lo,{value:$u,enumerable:!0,configurable:!0,writable:!0}):Au[lo]=$u,Au}function _toPropertyKey(Au){var lo=_toPrimitive(Au,"string");return _typeof(lo)=="symbol"?lo:lo+""}function _toPrimitive(Au,lo){if(_typeof(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var defaultOptions$1=_objectSpread(_objectSpread({},BaseUpload.defaultOptions),{},{httpStack:new XHRHttpStack,fileReader:new FileReader$1,urlStorage:canStoreURLs?new WebStorageUrlStorage:new NoopUrlStorage,fingerprint}),Upload=(function(Au){function lo(){var $u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,Ru=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return _classCallCheck(this,lo),Ru=_objectSpread(_objectSpread({},defaultOptions$1),Ru),_callSuper(this,lo,[$u,Ru])}return _inherits(lo,Au),_createClass(lo,null,[{key:"terminate",value:function(Ru){var Iu=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return Iu=_objectSpread(_objectSpread({},defaultOptions$1),Iu),BaseUpload.terminate(Ru,Iu)}}])})(BaseUpload);const RUNTIMES_API_PREFIX="api/runtimes/v1";function join$1(Au,lo){return`${Au.replace(/\/+$/,"")}/${lo.replace(/^\/+/,"")}`}function runtimesUrl(Au){return join$1(Au,`${RUNTIMES_API_PREFIX}/runtimes`)}function runtimeUrl(Au,lo){return`${runtimesUrl(Au)}/${lo}`}function sandboxSnapshotsUrl(Au){return join$1(Au,`${RUNTIMES_API_PREFIX}/sandbox-snapshots`)}function sandboxSnapshotUrl(Au,lo){return`${sandboxSnapshotsUrl(Au)}/${lo}`}function asCodeSandboxSnapshot(Au){const{uid:lo,updated_at:$u,format_version:Ru,...Iu}=Au;return{...Iu,id:lo,updatedAt:new Date($u),formatVersion:Ru}}async function getEnvironments(){const Au=await requestDatalayerAPI({url:libExports$5.URLExt.join(runtimesStore.getState().runtimesUrl,"api/runtimes/v1/environments"),token:iamStore.getState().token});return Au.success?Au.environments??[]:(console.error("Failed to fetch available environments.",Au),[])}async function createRuntime(Au){const{externalToken:lo,token:$u}=iamStore.getState();if(typeof Au.creditsLimit!="number"||!Number.isFinite(Au.creditsLimit)||Au.creditsLimit<0)throw new Error(`Invalid runtime creditsLimit for environment ${Au.environmentName}. A number of zero or more is required.`);if(Au.deploymentUid&&!Au.appUid)throw new Error(`Deployment ${Au.deploymentUid} is named without its application: give appUid.`);if(Au.appUid&&!Au.appSpec)throw new Error(`Application ${Au.appUid} is launched without its Appspec: give appSpec, so its runtime is given the secrets its connections declare.`);const Ru={name:Au.environmentName};Au.environmentVersion!==void 0&&Au.environmentVersion!==""&&(Ru.version=Au.environmentVersion);const Iu={environment:Ru,type:Au.type??"notebook",given_name:Au.givenName,credits_limit:Au.creditsLimit};Au.capabilities&&(Iu.capabilities=Au.capabilities),Au.snapshot&&(Iu.from=Au.snapshot),Au.appUid&&(Iu.app_uid=Au.appUid),Au.deploymentUid&&(Iu.deployment_uid=Au.deploymentUid),Au.appSpec&&(Iu.app_spec=Au.appSpec);const Pu=await requestDatalayerAPI({url:runtimesUrl(runtimesStore.getState().runtimesUrl),method:"POST",body:Iu,token:$u,headers:lo?{"X-External-Token":lo}:void 0});if(!Pu.success||!Pu.runtime){const Ou=`Failed to create a kernel for the environment ${Au.environmentName}.`;throw console.error(Ou,Pu),new Error(Ou)}return Pu.runtime}async function getRuntimes(){const Au=await requestDatalayerAPI({url:runtimesUrl(runtimesStore.getState().runtimesUrl),token:iamStore.getState().token});if(!Au.success){const lo="Failed to list the running kernels.";throw console.error(lo,Au),new Error(lo)}return Au.runtimes??[]}async function getRuntimeRecord(Au){try{return(await requestDatalayerAPI({url:runtimeUrl(runtimesStore.getState().runtimesUrl,Au),token:iamStore.getState().token})).runtime??null}catch(lo){if(lo.response?.status===404)return null;throw lo}}async function deleteRuntime(Au){const lo=iamStore.getState().externalToken;await requestDatalayerAPI({url:runtimeUrl(runtimesStore.getState().runtimesUrl,Au.id)+libExports$5.URLExt.objectToQueryString(Au.reason?{reason:Au.reason}:{}),method:"DELETE",token:iamStore.getState().token,headers:lo?{"X-External-Token":lo}:void 0})}async function snapshotRuntime(Au){const lo=await requestDatalayerAPI({url:sandboxSnapshotsUrl(runtimesStore.getState().runtimesUrl),method:"POST",body:{runtime_name:Au.id,name:Au.name,description:Au.description,stop:Au.stop},token:iamStore.getState().token});if(!lo.success)throw new Error(`Failed to take the code sandbox snapshot ${Au.id} - ${lo}`);if(lo.snapshot)return asCodeSandboxSnapshot(lo.snapshot)}async function getSandboxSnapshots(){const Au=await requestDatalayerAPI({url:sandboxSnapshotsUrl(runtimesStore.getState().runtimesUrl),token:iamStore.getState().token});return Au.success?(Au.snapshots??[]).map(asCodeSandboxSnapshot):(console.error("Failed to fetch code sandbox snapshots.",Au),[])}async function loadSandboxSnapshot(Au){const lo=await requestDatalayerAPI({url:runtimeUrl(runtimesStore.getState().runtimesUrl,Au.id),method:"PUT",body:{from:Au.from},token:iamStore.getState().token});if(!lo.success)throw new Error(`Failed to load the code sandbox snapshot; ${lo.message}`)}function createSandboxSnapshotDownloadURL(Au){return sandboxSnapshotUrl(runtimesStore.getState().runtimesUrl,Au)+libExports$5.URLExt.objectToQueryString({download:"1",token:iamStore.getState().token??""})}function exportCodeSandboxSnapshot(Au){const lo=createSandboxSnapshotDownloadURL(Au),$u=document.createElement("a");$u.href=lo,$u.download="",document.body.appendChild($u),$u.click(),document.body.removeChild($u)}async function deleteCodeSandboxSnapshot(Au){await requestDatalayerAPI({url:sandboxSnapshotUrl(runtimesStore.getState().runtimesUrl,Au),method:"DELETE",token:iamStore.getState().token})}async function updateCodeSandboxSnapshot(Au,lo){(lo.name||lo.description)&&await requestDatalayerAPI({url:sandboxSnapshotUrl(runtimesStore.getState().runtimesUrl,Au),method:"PATCH",body:{...lo},token:iamStore.getState().token})}async function uploadCodeSandboxSnapshot(Au){if(Au.file.size===0)return Promise.reject("Empty Code Sandbox Snapshot.");const lo=new PromiseDelegate,$u=new Upload(Au.file,{endpoint:`${sandboxSnapshotsUrl(runtimesStore.getState().runtimesUrl)}/upload`,headers:{Authorization:`Bearer ${iamStore.getState().token}`},retryDelays:null,metadata:Au.metadata,onError:Iu=>{console.error(`Failed to upload ${Au.metadata.filename}.`,Iu),lo.reject(Iu)},onProgress:Au.onProgress,onSuccess:()=>{lo.resolve()}}),Ru=await $u.findPreviousUploads();return Ru.length&&$u.resumeFromPreviousUpload(Ru[0]),$u.start(),lo.promise}const actions=Object.freeze(Object.defineProperty({__proto__:null,createRuntime,createSandboxSnapshotDownloadURL,deleteCodeSandboxSnapshot,deleteRuntime,exportCodeSandboxSnapshot,getEnvironments,getRuntimeRecord,getRuntimes,getSandboxSnapshots,loadSandboxSnapshot,snapshotRuntime,updateCodeSandboxSnapshot,uploadCodeSandboxSnapshot},Symbol.toStringTag,{value:"Module"})),CLAUDE_CODE_HARNESS_0_0_1={id:"claude-code",version:"0.0.1",name:"Claude Code",description:"Anthropic's coding agent, driven over ACP through the Agent Client Protocol project's adapter on the Claude Agent SDK.",enabled:!0,tags:["harness"],docs:"https://github.com/agentclientprotocol/claude-agent-acp",acp:{command:"npx",args:["-y","@agentclientprotocol/claude-agent-acp@0.91.0"],protocolVersion:1,loadSession:!0,mcp:"lend",modes:["default","plan","acceptEdits","bypassPermissions"],env:{},nativeSession:"none"},requires:{secrets:["ANTHROPIC_API_KEY"],binaries:["node","git"]},terms:{servedToThirdParties:"api_key_only",licence:"Apache-2.0 (adapter); Anthropic Commercial Terms of Service (the agent)"},skills:{format:"skill-md",dir:".claude/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"load",forkHistory:"replay",interrupt:!0,steering:!1,images:!0,compaction:"own",modes:["default","plan","acceptEdits","bypassPermissions"],autoRun:["^(cal|uptime|cat|head|tail|wc|stat|strings|hexdump|od|nl|id|uname|free|df|du|locale|groups|nproc|basename|dirname|realpath|cut|paste|tr|column|tac|rev|fold|expand|unexpand|fmt|comm|cmp|numfmt|readlink|diff|true|false|sleep|which|type|expr|seq|tsort|pr)(\\s|$)","^(pwd|whoami|alias|history|arch|ifconfig|ip addr)(\\s|$)","^(claude (-h|--help)|node (-v|--version)|python3? --version)$","^(echo|uniq|jq|cd|ls|find)(\\s|$)","^(xargs|file|sed|sort|man|help|netstat|ps|base64|grep|egrep|fgrep|rg|sha256sum|sha1sum|md5sum|tree|date|hostname|lsof|pgrep|tput|ss|fd|fdfind|test)(\\s|$)","^git (diff|log|show|shortlog|reflog|stash (list|show)|ls-remote|status|blame|ls-files|config --get|remote( show)?|merge-base|rev-parse|rev-list|describe|cat-file|for-each-ref|grep|worktree list|tag|branch)(\\s|$)","^gh (pr (view|list|diff|checks|status)|issue (view|list|status)|repo view|run (list|view)|auth status|release (list|view)|workflow (list|view)|label list|search (repos|issues|prs|commits|code))(\\s|$)","^docker (ps|images|logs|inspect)(\\s|$)"]},instructionsFile:"CLAUDE.md",registered:{adapter:"@agentclientprotocol/claude-agent-acp",version:"0.91.0",licenceSource:"https://www.npmjs.com/package/@agentclientprotocol/claude-agent-acp",termsSource:"https://code.claude.com/docs/en/legal-and-compliance",credential:"An Anthropic API key (ANTHROPIC_API_KEY), the person's own",binaries:"Node 22 (engines.node >=22 on npm), git",note:"Anthropic's legal page (read 2026-10-15): running Claude Code in hosted sandboxes or agent infrastructure requires the Commercial Terms; each end user authenticates with their own API key or subscription; developers may not route requests through Free, Pro or Max plan credentials on behalf of their users, nor collect or intermediate Claude.ai credentials. So only API keys are taken; a subscription login is refused. The npm package moved from @zed-industries (0.23.1, March 2026) to @agentclientprotocol."}},CODEX_HARNESS_0_0_1={id:"codex",version:"0.0.1",name:"Codex",description:"OpenAI's coding agent, driven over ACP through the Agent Client Protocol project's adapter, which ships the Codex binary it drives.",enabled:!0,tags:["harness"],docs:"https://github.com/agentclientprotocol/codex-acp",acp:{command:"npx",args:["-y","@agentclientprotocol/codex-acp@2.2.2"],protocolVersion:1,loadSession:!0,mcp:"lend",modes:["read-only","workspace-write","agent","agent-full-access"],env:{NO_BROWSER:"1"},nativeSession:"none"},requires:{secrets:["OPENAI_API_KEY"],binaries:["node","git"]},terms:{servedToThirdParties:"api_key_only",licence:"Apache-2.0 (adapter); OpenAI Terms of Use (the agent)"},skills:{format:"skill-md",dir:".agents/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"load",forkHistory:"replay",interrupt:!0,steering:!1,images:!0,compaction:"own",modes:["read-only","workspace-write","agent","agent-full-access"],autoRun:[]},instructionsFile:"AGENTS.md",registered:{adapter:"@agentclientprotocol/codex-acp",version:"2.2.2",licenceSource:"https://www.npmjs.com/package/@agentclientprotocol/codex-acp",termsSource:"https://learn.chatgpt.com/docs/auth",credential:"An OpenAI API key (OPENAI_API_KEY or CODEX_API_KEY), the person's own",binaries:"Node 22 (as the Agent Client Protocol project's adapters; unstated on npm), git",note:"Codex's authentication page (read 2026-10-15) recommends API keys for automation and device-code login for headless machines; a ChatGPT login needs a browser and is hidden with NO_BROWSER=1 in the adapter. Only API keys are taken; a ChatGPT login is refused. The Zed-scoped package was archived on 22 July 2026 and names this one."}},CUSTOM_HARNESS_0_0_1={id:"custom",version:"0.0.1",name:"Custom harness",description:"An organization's own ACP agent, its command named by the organization's own harness spec and never typed into a form.",enabled:!1,tags:["harness"],docs:"",requires:{secrets:[],binaries:[]},terms:{servedToThirdParties:"organizations_own",licence:"The organization's own"},skills:{format:"none",dir:""},honours:{model:!1,subagents:!1},capabilities:{resume:"none",forkHistory:"none",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:[],autoRun:[]},instructionsFile:"",registered:{adapter:"The organization's own",version:"0",licenceSource:"https://agentspecs.datalayer.tech/harnesses",termsSource:"https://agentspecs.datalayer.tech/harnesses",credential:"The organization's own",binaries:"",note:"Not launchable from the shared catalogue; an organization's own harness spec names the command and answers for its terms."}},FAST_AGENT_HARNESS_0_0_1={id:"fast-agent",version:"0.0.1",name:"fast-agent",description:"llmindset's agent framework served over ACP; each agent it defines is a session mode, with any model provider it is configured with.",enabled:!0,tags:["harness","framework"],docs:"https://github.com/evalstate/fast-agent/blob/main/docs/docs/acp/index.md",acp:{command:"uvx",args:["fast-agent-acp==0.10.45"],protocolVersion:1,loadSession:!0,mcp:"lend",modes:[],env:{},nativeSession:"none"},requires:{secrets:["ANTHROPIC_API_KEY"],binaries:["uvx"]},terms:{servedToThirdParties:"permitted",licence:"Apache-2.0"},skills:{format:"skill-md",dir:".agents/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"load",forkHistory:"replay",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:[],autoRun:[]},instructionsFile:"AGENTS.md",registered:{adapter:"fast-agent-acp",version:"0.10.45",licenceSource:"https://pypi.org/project/fast-agent-acp/",termsSource:"https://github.com/evalstate/fast-agent/blob/main/LICENSE",credential:"The provider's key fast-agent is given (ANTHROPIC_API_KEY, OPENAI_API_KEY or HF_TOKEN); ANTHROPIC_API_KEY declared",binaries:"uv (uvx), Python 3.12 to 3.15 (requires_python on PyPI)",note:"A framework, not a coding agent: each agent it defines is an ACP mode; the client's MCP servers are attached; sessions are listed. Launched with uvx fast-agent-acp (docs/docs/acp/index.md); reads skills from .fast-agent/skills, .agents/skills and .claude/skills; its default prompt reads AGENTS.md."}},GEMINI_CLI_HARNESS_0_0_1={id:"gemini-cli",version:"0.0.1",name:"Gemini CLI",description:"Google's coding agent, which speaks ACP itself when started with --experimental-acp.",enabled:!0,tags:["harness"],docs:"https://github.com/google-gemini/gemini-cli/blob/main/docs/cli/cli-reference.md",acp:{command:"npx",args:["-y","@google/gemini-cli@0.64.0","--experimental-acp"],protocolVersion:1,loadSession:!1,mcp:"lend",modes:["default","auto_edit","yolo","plan"],env:{},nativeSession:"none"},requires:{secrets:["GEMINI_API_KEY"],binaries:["node","git"]},terms:{servedToThirdParties:"api_key_only",licence:"Apache-2.0 (the agent); Gemini API or Gemini Code Assist terms (the model)",tierRestrictions:"Gemini Code Assist Standard or Enterprise for a Google login (the individuals tier stopped being served on 18 June 2026); a Gemini API key otherwise"},skills:{format:"skill-md",dir:".gemini/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"none",forkHistory:"replay",interrupt:!0,steering:!1,images:!0,compaction:"own",modes:["default","auto_edit","yolo","plan"],autoRun:[]},instructionsFile:"GEMINI.md",registered:{adapter:"@google/gemini-cli",version:"0.64.0",licenceSource:"https://www.npmjs.com/package/@google/gemini-cli",termsSource:"https://developers.google.com/gemini-code-assist/resources/privacy-notice-gemini-code-assist-individuals",credential:"A Gemini API key (GEMINI_API_KEY), the person's own; or a Google login on a Code Assist Standard or Enterprise subscription",binaries:"Node 20 or later (engines.node >=20 on npm), git",note:`Google's notice (read 2026-10-15): "Starting June 18, 2026, Gemini Code Assist IDE extensions stopped serving requests for the Gemini Code Assist for individuals"; Standard and Enterprise follow a separate schedule. The ACP flag is --experimental-acp in the CLI reference (docs/cli/cli-reference.md).`}},GOOSE_HARNESS_0_0_1={id:"goose",version:"0.0.1",name:"goose",description:"Block's open agent (now the Agentic AI Foundation's), which speaks ACP itself with goose acp; any model provider it is configured with.",enabled:!0,tags:["harness"],docs:"https://block.github.io/goose/docs/gdk/acp/",acp:{command:"goose",args:["acp"],protocolVersion:1,loadSession:!1,mcp:"lend",modes:[],env:{GOOSE_PROVIDER:"anthropic"},nativeSession:"none"},requires:{secrets:["ANTHROPIC_API_KEY"],binaries:["goose@1.54.0","git"]},terms:{servedToThirdParties:"permitted",licence:"Apache-2.0"},skills:{format:"skill-md",dir:".agents/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"none",forkHistory:"replay",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:[],autoRun:[]},instructionsFile:".goosehints",registered:{adapter:"goose",version:"1.54.0",licenceSource:"https://github.com/aaif-goose/goose",termsSource:"https://github.com/aaif-goose/goose/blob/main/LICENSE",credential:"The provider's key goose is configured with (GOOSE_PROVIDER); ANTHROPIC_API_KEY declared",binaries:"The goose CLI (release v1.54.0 of 8 October 2026), git",note:"Open source under Apache-2.0, no vendor terms of its own; the model provider's terms apply to the key. Launched as goose acp (documentation/docs/gdk/acp/index.md)."}},OPENCODE_HARNESS_0_0_1={id:"opencode",version:"0.0.1",name:"OpenCode",description:"Anomaly's open coding agent, which speaks ACP itself with opencode acp; any model provider it is configured with.",enabled:!0,tags:["harness"],docs:"https://opencode.ai/docs/acp/",acp:{command:"npx",args:["-y","opencode-ai@1.19.0","acp"],protocolVersion:1,loadSession:!1,mcp:"lend",modes:[],env:{},nativeSession:"none"},requires:{secrets:["ANTHROPIC_API_KEY"],binaries:["node","git"]},terms:{servedToThirdParties:"permitted",licence:"MIT"},skills:{format:"skill-md",dir:".opencode/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"none",forkHistory:"replay",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:[],autoRun:[]},instructionsFile:"AGENTS.md",registered:{adapter:"opencode-ai",version:"1.19.0",licenceSource:"https://www.npmjs.com/package/opencode-ai",termsSource:"https://github.com/anomalyco/opencode/blob/dev/LICENSE",credential:"The provider's key OpenCode is configured with; ANTHROPIC_API_KEY declared",binaries:"Node (the opencode-ai package), git",note:"Open source under MIT, no vendor terms of its own; the model provider's terms apply to the key. Launched as opencode acp (opencode.ai/docs/acp); reads skills from .opencode/skills, .claude/skills and .agents/skills."}},OPENHANDS_HARNESS_0_0_1={id:"openhands",version:"0.0.1",name:"OpenHands",description:"The OpenHands CLI, which speaks ACP itself with openhands acp; any model provider it is configured with.",enabled:!0,tags:["harness"],docs:"https://docs.openhands.dev/openhands/usage/run-openhands/acp",acp:{command:"uvx",args:["--from","openhands==1.16.0","openhands","acp","--override-with-envs"],protocolVersion:1,loadSession:!0,mcp:"lend",modes:["always-ask","always-approve","llm-approve"],env:{},nativeSession:"none"},requires:{secrets:["LLM_API_KEY"],binaries:["uvx","git"]},terms:{servedToThirdParties:"permitted",licence:"MIT"},skills:{format:"skill-md",dir:".agents/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"load",forkHistory:"replay",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:["always-ask","always-approve","llm-approve"],autoRun:[]},instructionsFile:"AGENTS.md",registered:{adapter:"openhands",version:"1.16.0",licenceSource:"https://pypi.org/project/openhands/",termsSource:"https://github.com/OpenHands/OpenHands-CLI/blob/main/LICENSE",credential:"The provider's key OpenHands reads as LLM_API_KEY, with LLM_MODEL, under --override-with-envs",binaries:"uv (uvx), Python 3.12 or later, git",note:"Open source under MIT, no vendor terms of its own; the model provider's terms apply to the key. Launched as openhands acp (OpenHands-CLI README; docs.openhands.dev's ACP page); resumes with --resume; reads skills from .agents/skills (.openhands/skills is legacy)."}},HARNESS_CATALOGUE={"claude-code":CLAUDE_CODE_HARNESS_0_0_1,codex:CODEX_HARNESS_0_0_1,custom:CUSTOM_HARNESS_0_0_1,"fast-agent":FAST_AGENT_HARNESS_0_0_1,"gemini-cli":GEMINI_CLI_HARNESS_0_0_1,goose:GOOSE_HARNESS_0_0_1,opencode:OPENCODE_HARNESS_0_0_1,openhands:OPENHANDS_HARNESS_0_0_1};function listHarnesses(){return Object.values(HARNESS_CATALOGUE)}const AGENT_RUNTIME_VARIANTS=["browser-vercelai","local-pydanticai","cloud-pydanticai"],DEFAULT_AGENT_RUNTIME_VARIANT="cloud-pydanticai",VARIANT_BY_LEGACY_TARGET={"backend-services":"cloud-pydanticai","local-agent-runtimes":"local-pydanticai"};function isAgentRuntimeVariant(Au){return typeof Au=="string"&&AGENT_RUNTIME_VARIANTS.includes(Au)}function toAgentRuntimeVariant(Au,lo=DEFAULT_AGENT_RUNTIME_VARIANT){return Au?isAgentRuntimeVariant(Au)?Au:VARIANT_BY_LEGACY_TARGET[Au]??lo:lo}function locationOf(Au){return Au.slice(0,Au.indexOf("-"))}function runsInBrowser(Au){return locationOf(Au)==="browser"}function legacyTargetOf(Au){return locationOf(Au)==="cloud"?"backend-services":"local-agent-runtimes"}const runtimesStore=createStore$1((Au,lo)=>({configuration:{maxNotebookRuntimes:5,maxCellRuntimes:3},setConfiguration:$u=>{Au(Ru=>JSONExt.deepEqual(Ru.configuration,$u)?{}:{configuration:{...$u}})},runtimesUrl:coreStore.getState().configuration?.runtimesUrl,tab:0,getIntTab:()=>Math.floor(lo().tab),setTab:$u=>Au(Ru=>({tab:$u})),runtimes:[],refreshRuntimes:async()=>{const $u=await getRuntimes();JSONExt.deepEqual(lo().runtimes,$u)||Au({runtimes:[...$u]})},removeRuntime:$u=>{if(!$u)return;const Ru=lo().runtimes,Iu=Ru.filter(Pu=>Pu.runtime_name!==$u);Iu.length!==Ru.length&&Au({runtimes:Iu})},runtimeModels:[],addRuntimeModel:$u=>{const Ru=lo().runtimeModels;Ru.findIndex(Pu=>$u.id&&$u.id===Pu.id||!!$u.uid&&$u.uid===Pu.uid)<0&&Au({runtimeModels:[...Ru,$u]})},removeRuntimeModel:$u=>{const Ru=[...lo().runtimeModels],Iu=Ru?.findIndex(Pu=>!!Pu.id&&$u===Pu.id||$u===Pu.runtime_name)??-1;Iu>=0&&(Ru.splice(Iu,1),Au({runtimeModels:Ru}))},setRuntimeModels:$u=>{JSONExt.deepEqual(lo().runtimeModels,$u)||Au({runtimeModels:[...$u]})},multiServiceManager:void 0,setMultiServiceManager:$u=>{Au(Ru=>({multiServiceManager:$u}))},showDisclaimer:!1,setShowDisclaimer:$u=>{Au(Ru=>({showDisclaimer:$u}))},runtimeSnapshots:[],addSandboxSnapshot:$u=>{const Ru=lo().runtimeSnapshots,Iu=Ru.findIndex(Pu=>Pu.id===$u.id);if(Iu<0){const Pu=[...Ru,$u];Au({runtimeSnapshots:Pu})}else if(!JSONExt.deepEqual(Ru[Iu],$u)){const Pu=[...Ru];Pu.splice(Iu,1,$u),Au({runtimeSnapshots:Pu})}},removeSandboxSnapshot:$u=>{const Ru=lo().runtimeSnapshots,Iu=Ru.findIndex(Pu=>Pu.id===$u);if(Iu>=0){const Pu=[...Ru];Pu.splice(Iu,1),Au({runtimeSnapshots:Pu})}},setSandboxSnapshots:$u=>{JSONExt.deepEqual(lo().runtimeSnapshots,$u)||Au({runtimeSnapshots:[...$u]})},version:"",setVersion:$u=>{$u&&!lo().version&&Au(Ru=>({version:$u}))}})),kernelsPoll=new Poll({auto:!0,factory:()=>runtimesStore.getState().refreshRuntimes(),frequency:{interval:61*1e3,backoff:!0,max:300*1e3},name:"@datalayer/jupyter-kernels:KernelsManager#kernels",standby:()=>iamStore.getState().token||runtimesStore.getState().runtimesUrl?"when-hidden":!0});runtimesStore.subscribe((Au,lo)=>{if(!JSONExt.deepEqual(Au.runtimes,lo.runtimes)){const $u=Date.now(),Ru=Math.min(...Au.runtimes.map(Iu=>Iu.expired_at?parseFloat(Iu.expired_at):1/0))*1e3;$u+kernelsPoll.frequency.interval>Ru+2e3&&setTimeout(()=>{kernelsPoll.refresh()},Ru+2e3-$u)}});coreStore.subscribe((Au,lo)=>{if(Au.configuration.runtimesUrl&&Au.configuration.runtimesUrl!==lo.configuration.runtimesUrl){const $u=Au.configuration.runtimesUrl;console.log(`Updating runtimesUrl with new value ${$u}`),runtimesStore.setState({runtimesUrl:$u}),kernelsPoll.refresh().then(()=>kernelsPoll.tick).catch(Ru=>{console.error("Failed to refresh kernel servers list following service URL changed.",Ru)})}});function useRuntimesStore(Au){return useStore$1(runtimesStore,Au)}const DEFAULT_AGENT_CONFIG={name:"ai-agent",description:"AI Assistant",model:"",systemPrompt:"You are a helpful AI assistant.",agentLibrary:"pydantic-ai",protocol:"vercel-ai"};requireManager();const sandboxManagersByRuntime=new Map;function registerSandboxServiceManager(Au,lo){const $u=String(Au||"").trim();if(!$u||!lo)return()=>{};let Ru=sandboxManagersByRuntime.get($u);return Ru||(Ru=new Set,sandboxManagersByRuntime.set($u,Ru)),Ru.add(lo),()=>{const Iu=sandboxManagersByRuntime.get($u);Iu&&(Iu.delete(lo),Iu.size===0&&sandboxManagersByRuntime.delete($u))}}function disposeSandboxServiceManagers(Au){const lo=String(Au||"").trim();if(!lo)return;const $u=sandboxManagersByRuntime.get(lo);$u&&(sandboxManagersByRuntime.delete(lo),$u.forEach(Ru=>{try{disposeServiceManager(Ru)}catch(Iu){console.warn(`[sandboxServiceManagers] Failed disposing service manager for pod ${lo}`,Iu)}}))}function launchesOwnRoutesOnly(Au){return!!Au?.deploymentUid}const base$2=Au=>Au.trim().replace(/\/$/,"");function agentDeletionUrl(Au,lo,$u){if(!$u)return`${base$2(Au)}/api/v1/agents/${encodeURIComponent(lo)}`}function runtimeModelsUrl(Au,lo,$u){if(!$u)return`${base$2(Au)}/api/v1/configure/models?agent_id=${encodeURIComponent(lo)}`}const EMPTY_RUNTIMES=[],BROWSER_AGENT_CONNECTION=Object.freeze({runtimeName:"",environmentName:"",jupyterBaseUrl:"",agentBaseUrl:"",status:"ready",isReady:!0}),AGENT_QUERY_OPTIONS={staleTime:300*1e3,gcTime:600*1e3},agentQueryKeys={agentRuntimes:{all:()=>["agentRuntimes"],lists:()=>[...agentQueryKeys.agentRuntimes.all(),"list"],details:()=>[...agentQueryKeys.agentRuntimes.all(),"detail"],detail:Au=>[...agentQueryKeys.agentRuntimes.details(),Au]},checkpoints:{all:()=>["checkpoints"],lists:()=>[...agentQueryKeys.checkpoints.all(),"list"]}},DELETED_POD_TOMBSTONE_TTL_MS=300*1e3,deletedRuntimeTombstones=new Map;function markRuntimeDeleted(Au){const lo=String(Au||"").trim();lo&&(deletedRuntimeTombstones.set(lo,Date.now()),disposeSandboxServiceManagers(lo))}function clearRuntimeDeleted(Au){deletedRuntimeTombstones.delete(String(Au||"").trim())}const LIVE_RUNTIME_STATUSES=new Set(["running","resumed","starting","resuming"]);function isStaleDeletedRuntime(Au){const lo=String(Au?.runtime_name||"").trim(),$u=deletedRuntimeTombstones.get(lo);return $u===void 0?!1:Date.now()-$u>DELETED_POD_TOMBSTONE_TTL_MS?(deletedRuntimeTombstones.delete(lo),!1):LIVE_RUNTIME_STATUSES.has(Au.status)}const RUNTIME_STATUS_MAP={resume:"resumed",resumed:"resumed",resuming:"resuming",pausing:"pausing",paused:"paused",starting:"starting",pending:"starting",launching:"starting",terminated:"terminated",archived:"archived",running:"running"};function toAgentRuntimeData(Au){const lo=typeof Au.status=="string"?Au.status.toLowerCase():"",$u=RUNTIME_STATUS_MAP[lo]??"running",Ru=Au.environment;return{...Au,environment:{name:String(Ru?.name||"").trim(),title:String(Ru?.title||"").trim()||void 0,cpu:String(Ru?.cpu||"").trim()||void 0,memory:String(Ru?.memory||"").trim()||void 0,gpu:String(Ru?.gpu||"").trim()||void 0,resources:Ru?.resources},status:$u,name:Au.given_name||Au.runtime_name,id:Au.runtime_name,url:Au.ingress,messageCount:0,agent_spec_id:Au.agent_spec_id||void 0,content_attachments:Array.isArray(Au.content_attachments)?Au.content_attachments:[]}}function useAgentRuntimes(Au={}){const{agentSpecId:lo,agentConfig:$u,autoCreateAgent:Ru=!0,autoStart:Iu=!1,agentSpec:Pu,variant:Ou,runtimeCreationTarget:Mu,runtimeCreationBaseUrl:Du,runtimeConnection:Lu,appLaunch:Bu}=Au,ju=toAgentRuntimeVariant(Ou??Mu),Fu=launchesOwnRoutesOnly(Bu),{configuration:zu}=useCoreStore(),Uu=useAgentRuntimeConnection(),Hu=useAgentRuntimeStatus(),Vu=useAgentRuntimeError(),Gu=useAgentRuntimeIsLaunching(),Wu=useAgentRuntimeStore($d=>$d.launchAgent),Ku=useAgentRuntimeStore($d=>$d.connectAgent),Ju=useAgentRuntimeStore($d=>$d.createAgent),Yu=useAgentRuntimeStore($d=>$d.disconnect),[Xu,ed]=reactExports.useState("idle"),[td,nd]=reactExports.useState(null),[od,sd]=reactExports.useState(!1),ad=reactExports.useRef(!1),[pd,gd]=reactExports.useState(!1),Sd=reactExports.useRef(!1),_d=reactExports.useRef(null),yd=reactExports.useRef(!1),wd=reactExports.useRef($u);wd.current=$u;const Ad=!!lo&&locationOf(ju)==="cloud",md=Lu?[Lu.runtimeName,Lu.environmentName,Lu.jupyterBaseUrl||Lu.serviceManager?.serverSettings.baseUrl||"",Lu.kernelId||""].join(":"):null,dd=reactExports.useMemo(()=>Du||(runsInBrowser(ju)?"":locationOf(ju)==="local"?"http://localhost:8765":zu?.runtimesUrl||void 0||"https://r1.datalayer.run"),[zu?.runtimesUrl,Du,ju]),bd=reactExports.useCallback(async()=>{try{const{iamStore:$d,coreStore:Id}=await __vitePreload(async()=>{const{iamStore:Yd,coreStore:mh}=await import("./chunks/index-D8x0MQWQ.js");return{iamStore:Yd,coreStore:mh}},[],import.meta.url),qd=$d.getState().token||"",Wd=Id.getState().configuration?.aiAgentsUrl||"";return{token:qd,aiAgentsUrl:Wd,runtimesUrl:dd}}catch{return{token:"",aiAgentsUrl:"",runtimesUrl:""}}},[dd]);reactExports.useEffect(()=>{!Lu||!md||(Uu?[Uu.runtimeName,Uu.environmentName,Uu.jupyterBaseUrl||"",Uu.kernelId||""].join(":"):null)===md||(Sd.current=!1,Ku(Lu))},[Lu,md,Uu,Ku]);const ld=reactExports.useCallback(async $d=>{if(runsInBrowser(ju))return BROWSER_AGENT_CONNECTION;if(Ad){ed("launching"),nd(null);try{const qd=(typeof $u?.name=="string"&&$u.name||typeof Pu?.name=="string"&&Pu.name||`${lo}`).replace(/\//g,"-").replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,63),Md=await Wu($d?{...$d,...Bu,runtimesUrl:dd}:{environmentName:"ai-agents-env",creditsLimit:10,givenName:qd,...Bu,runtimesUrl:dd});return ed("ready"),Md}catch(Id){const qd=Id instanceof Error?Id.message:String(Id);throw nd(qd),ed("error"),Id}}else{if(!$d)throw new Error("Runtime options are required in connect mode");return Wu({...$d,runtimesUrl:dd})}},[$u?.name,Pu?.name,lo,Bu,Ad,dd,Wu,ju]),ud=reactExports.useCallback(async $d=>{if(yd.current)throw new Error("Agent creation already in progress");yd.current=!0,sd(!0);try{const Id={};Pu&&(Pu.model&&(Id.model=Pu.model),Pu.protocol&&(Id.protocol=Pu.protocol),Pu.systemPrompt&&(Id.systemPrompt=Pu.systemPrompt),Pu.description&&(Id.description=Pu.description),Pu.name&&(Id.name=Pu.name));const qd={...DEFAULT_AGENT_CONFIG,...Id,...$u,...$d,name:$d?.name||$u?.name||(Ad&&lo?lo:Uu?.runtimeName)};return await Ju(qd)}catch(Id){const qd=Id instanceof Error?Id.message:String(Id);throw Ad&&(nd(qd),ed("error")),Id}finally{yd.current=!1,sd(!1)}},[lo,$u,Pu,Ad,Uu,Ju]),hd=reactExports.useCallback(async()=>{const $d=Uu?.agentId,Id=Uu?.agentBaseUrl,qd=$d&&Id?agentDeletionUrl(Id,$d,Fu):void 0;if(qd)try{const{token:Md}=await bd();await fetch(qd,{method:"DELETE",headers:Md?{Authorization:`Bearer ${Md}`}:{}})}catch{}Sd.current=!1,ad.current=!1,ed("idle"),nd(null),agentRuntimeStore.getState().reset()},[Uu?.agentId,Uu?.agentBaseUrl,bd,Fu]);reactExports.useEffect(()=>{!Ad&&Ru&&Uu&&Hu==="ready"&&!Uu.isReady&&!Sd.current&&(Sd.current=!0,Ju(wd.current).catch($d=>{console.error("[useAgent] Failed to auto-create agent:",$d),Sd.current=!1}))},[Ad,Ru,Uu,Hu,Ju]),reactExports.useEffect(()=>{Ad&&Ru&&Uu&&(Xu==="ready"||Xu==="resumed")&&!Uu.isReady&&!Sd.current&&(Sd.current=!0,ud(wd.current).catch($d=>{console.error("[useAgents] Failed to auto-create agent:",$d);const Id=$d instanceof Error?$d.message:String($d);nd(Id),ed("error"),Sd.current=!1}))},[Ad,Ru,Uu,Xu,ud]),reactExports.useEffect(()=>{const $d=Uu?.runtimeName||null;if(!$d){_d.current=null;return}_d.current&&_d.current!==$d&&(Sd.current=!1),_d.current=$d},[Uu?.runtimeName]),reactExports.useEffect(()=>{if(!Ad||Uu||Xu!=="idle")return;if(Bu){gd(!0);return}let $d=!1;return(async()=>{try{const{token:qd,runtimesUrl:Md}=await bd();if(!qd)return;const{listRuntimes:Wd}=await __vitePreload(async()=>{const{listRuntimes:ah}=await import("./chunks/runtimes-DGW2aYMb.js");return{listRuntimes:ah}},[],import.meta.url),oh=((await Wd(qd,Md)).runtimes||[]).filter(ah=>ah.environment?.name!=="ai-agents-env"?!1:lo?ah.agent_spec_id===lo:!0).slice().sort((ah,Oh)=>{const Gd=Number(ah.started_at||0);return Number(Oh.started_at||0)-Gd})[0];if($d||!oh?.runtime_name||!oh?.ingress)return;Ku({runtimeName:oh.runtime_name,environmentName:oh.environment.name,jupyterBaseUrl:oh.ingress}),Sd.current=!1;const yh=oh,gh=typeof yh.status=="string"?yh.status.toLowerCase():"",Xd=RUNTIME_STATUS_MAP[gh]??"running",eh=Xd==="paused"?"paused":Xd==="resuming"||Xd==="resumed"?"resumed":"running";ed(eh==="paused"?"paused":eh==="resumed"?"resumed":"ready")}catch(qd){console.warn("[useAgents] Failed to find existing runtime:",qd)}finally{$d||gd(!0)}})(),()=>{$d=!0}},[Ad,Uu,Iu,Xu,bd,lo,Bu,Ku]),reactExports.useEffect(()=>{(Hu==="disconnected"||Hu==="idle")&&(Sd.current=!1)},[Hu]),reactExports.useEffect(()=>{Ad&&Iu&&pd&&!Uu&&!ad.current&&Xu==="idle"&&(ad.current=!0,ld())},[Ad,Iu,pd,Uu,Xu,ld]),reactExports.useEffect(()=>{Vu&&Ad&&Xu!=="error"&&(nd(Vu),ed("error"))},[Vu,Ad,Xu]);const vd=runsInBrowser(ju),Ed=vd?"ready":Ad?Xu:Hu,Cd=vd?null:Ad&&td||Vu,Rd=vd?!0:Ad?(Xu==="ready"||Xu==="resumed")&&!!Uu?.isReady:Hu==="ready"&&!!Uu?.isReady,jd=Uu?.endpoint||null,Td=Uu?.serviceManager||null;return{runtime:Uu,status:Ed,isLaunching:Gu,launchRuntime:ld,connectToRuntime:Ku,disconnect:Yu,endpoint:jd,serviceManager:Td,createAgent:ud,teardown:hd,isCreating:od,isReady:Rd,error:Cd,variant:ju,runtimeCreationTarget:legacyTargetOf(ju),runtimeCreationBaseUrl:dd}}function useAgentRuntimesQuery(Au,lo){const{configuration:$u}=useCoreStore(),{requestDatalayer:Ru}=useDatalayer({notifyOnError:!1}),{user:Iu}=useIAMStore(),Pu=useQueryClient();return useQuery({queryKey:[...agentQueryKeys.agentRuntimes.lists(),"","","",""],queryFn:async()=>{const Mu=new URLSearchParams().toString(),Du=await Ru({url:`${runtimesUrl($u.runtimesUrl)}${Mu?`?${Mu}`:""}`,method:"GET"});if(Du.success&&Du.runtimes){const Lu=Du.runtimes.filter(Bu=>Bu.environment?.name==="ai-agents-env").map(toAgentRuntimeData).filter(Bu=>!isStaleDeletedRuntime(Bu));return Lu.forEach(Bu=>{Pu.setQueryData(agentQueryKeys.agentRuntimes.detail(Bu.runtime_name),Bu)}),Lu}return[]},...AGENT_QUERY_OPTIONS,refetchInterval:lo?.refetchInterval??1e4,refetchOnMount:!0,refetchOnWindowFocus:!0,enabled:(lo?.enabled??!0)&&!!Iu})}function useCreateAgentRuntime(){const{configuration:Au}=useCoreStore(),{requestDatalayer:lo}=useDatalayer({notifyOnError:!1}),$u=useQueryClient();return useMutation({mutationFn:async Ru=>{const Iu=(Ru.contentAttachmentUids??[]).map(Pu=>String(Pu||"").trim()).filter(Boolean);return lo({url:runtimesUrl(Au.runtimesUrl),method:"POST",body:{environment:{name:Ru.environmentName||"ai-agents-env"},given_name:Ru.givenName||"Agent",credits_limit:Ru.creditsLimit||10,type:Ru.type||"notebook",editor_variant:Ru.editorVariant||"none",enable_codemode:Ru.enableCodemode??!1,agent_spec_id:Ru.agentSpecId||void 0,agent_spec:Ru.agentSpec||void 0,user_account_handle:Ru.userAccountHandle||void 0,billing_entity_uid:Ru.billingEntityUid||void 0,billing_entity_type:Ru.billingEntityType||void 0,billing_entity_handle:Ru.billingEntityHandle||void 0,billing_source_organization_uid:Ru.billingSourceOrganizationUid||void 0,billing_source_organization_handle:Ru.billingSourceOrganizationHandle||void 0,runtime_name:Ru.runtimeName||void 0,content_attachment_uids:Iu.length?Iu:void 0}})},onSuccess:Ru=>{if(Ru.success&&Ru.runtime){const Iu=toAgentRuntimeData(Ru.runtime);clearRuntimeDeleted(Iu.runtime_name),$u.setQueryData(agentQueryKeys.agentRuntimes.detail(Iu.runtime_name),Iu),$u.invalidateQueries({queryKey:agentQueryKeys.agentRuntimes.all()})}}})}function useDeleteAgentRuntime(){const{configuration:Au}=useCoreStore(),{requestDatalayer:lo}=useDatalayer({notifyOnError:!1}),$u=useQueryClient(),Ru=Pu=>{if(!Pu||typeof Pu!="object")return;const Ou=Pu.response;return typeof Ou?.status=="number"?Ou.status:void 0},Iu=Pu=>{if(!Pu||typeof Pu!="object")return"";const Ou=Pu.response?.data;return String(Ou?.detail||Ou?.message||Pu.message||"").toLowerCase()};return useMutation({mutationFn:async Pu=>{try{return await lo({url:runtimeUrl(Au.runtimesUrl,Pu),method:"DELETE"})}catch(Ou){const Mu=Ru(Ou),Du=Iu(Ou);if(!(Mu===404||Du.includes("no reservation")||Du.includes("unknown reservation")||Du.includes("not found")))throw Ou;try{throw await lo({url:runtimeUrl(Au.runtimesUrl,Pu),method:"GET"}),Ou}catch(Bu){if(Ru(Bu)===404)return{success:!0,recovered:!0};throw Ou}}},onSuccess:(Pu,Ou)=>{markRuntimeDeleted(Ou),runtimesStore.getState().removeRuntime(Ou),$u.setQueriesData({queryKey:agentQueryKeys.agentRuntimes.lists()},Mu=>Array.isArray(Mu)?Mu.filter(Du=>Du.runtime_name!==Ou):Mu),$u.cancelQueries({queryKey:agentQueryKeys.agentRuntimes.detail(Ou)}),$u.removeQueries({queryKey:agentQueryKeys.agentRuntimes.detail(Ou)}),$u.invalidateQueries({queryKey:agentQueryKeys.agentRuntimes.lists()}),$u.refetchQueries({queryKey:agentQueryKeys.agentRuntimes.lists(),type:"active"}),$u.invalidateQueries({queryKey:agentQueryKeys.checkpoints.all()})}})}function useRefreshAgentRuntimes(){const Au=useQueryClient();return reactExports.useCallback(()=>{Au.invalidateQueries({queryKey:agentQueryKeys.agentRuntimes.all()})},[Au])}const DEFAULT_LIFECYCLE_RECORD={resumePending:!1,pauseLockedForResumed:!1};create$g()(persist((Au,lo)=>({byRuntimeKey:{},markResumePending:$u=>{$u&&Au(Ru=>({byRuntimeKey:{...Ru.byRuntimeKey,[$u]:{...DEFAULT_LIFECYCLE_RECORD,...Ru.byRuntimeKey[$u]??{},resumePending:!0}}}))},markResumeFailed:$u=>{$u&&Au(Ru=>({byRuntimeKey:{...Ru.byRuntimeKey,[$u]:{...DEFAULT_LIFECYCLE_RECORD,...Ru.byRuntimeKey[$u]??{},resumePending:!1,pauseLockedForResumed:!1}}}))},markResumeSettled:$u=>{$u&&Au(Ru=>({byRuntimeKey:{...Ru.byRuntimeKey,[$u]:{...DEFAULT_LIFECYCLE_RECORD,...Ru.byRuntimeKey[$u]??{},resumePending:!1,pauseLockedForResumed:!0}}}))},clearRuntimeLifecycle:$u=>{if(!$u)return;const Ru={...lo().byRuntimeKey};delete Ru[$u],Au({byRuntimeKey:Ru})}}),{name:"datalayer-agent-lifecycle",storage:createJSONStorage(()=>localStorage),partialize:Au=>({byRuntimeKey:Au.byRuntimeKey})}));function useAgentsRuntimes(Au,lo){const $u=useAgentRuntimesQuery(Au,lo),Ru=useCreateAgentRuntime(),Iu=useDeleteAgentRuntime(),Pu=useRefreshAgentRuntimes(),Ou=reactExports.useCallback(async(Mu,Du)=>{const Lu=String(Mu||"").trim();if(Lu)return Du?.beforeStop&&await Du.beforeStop(),Iu.mutateAsync(Lu)},[Iu]);return reactExports.useMemo(()=>({runtimes:$u.data??EMPTY_RUNTIMES,isRuntimesLoading:$u.isLoading,isRuntimesError:$u.isError,runtimesError:$u.error,refetchRuntimes:()=>$u.refetch(),refreshRuntimes:Pu,stopRuntimeByName:Ou,createRuntime:async Mu=>Ru.mutateAsync(Mu)}),[$u.data,$u.isLoading,$u.isError,$u.error,$u.refetch,Pu,Ou,Ru,Iu])}const DEFAULT_WS_PATH="/api/v1/tool-approvals/ws",DEFAULT_RECONNECT_DELAY_MS=3e3;function useAgentRuntimeWebSocket(Au){const{enabled:lo=!0,baseUrl:$u,authToken:Ru,agentId:Iu,autoReconnect:Pu=!0,reconnectDelayMs:Ou=DEFAULT_RECONNECT_DELAY_MS,maxReconnectAttempts:Mu}=Au,Du=reactExports.useRef(Au.onMessage);Du.current=Au.onMessage,reactExports.useEffect(()=>{if(!lo||!$u){agentRuntimeStore.getState().setWsState("closed");return}let Lu=!1,Bu=0,ju=null;function Fu(){const Uu=`${$u}${DEFAULT_WS_PATH}`,Hu=new URL(Uu.replace(/^http/,"ws"));return Ru&&Hu.searchParams.set("token",Ru),Iu&&Hu.searchParams.set("agent_id",Iu),Hu.toString()}function zu(){if(Lu)return;const Uu=Fu();agentRuntimeStore.getState().setWsState("connecting");const Hu=new WebSocket(Uu);agentRuntimeStore.getState().setWs(Hu,Iu),Hu.onopen=()=>{Bu=0,agentRuntimeStore.getState().setWsState("connected")},Hu.onmessage=Vu=>{let Gu;try{Gu=JSON.parse(String(Vu.data))}catch{return}const Wu=parseAgentStreamMessage(Gu);if(Du.current?.({type:Wu?.type,payload:Wu?.payload,raw:Gu}),!Wu)return;const Ku=agentRuntimeStore.getState();if(Wu.type==="agent.snapshot"){Ku.applySnapshot(Wu.payload);return}if(Wu.type==="agent.subagent"){Ku.appendSubagentEvent(Wu.payload);return}if(Wu.type==="agent.compaction"){Ku.setCompaction(Wu.payload);return}},Hu.onclose=()=>{if(agentRuntimeStore.getState().setWs(null,Iu),agentRuntimeStore.getState().setWsState("closed"),Lu||!Pu||(Bu+=1,typeof Mu=="number"&&Bu>Mu))return;const Vu=typeof Ou=="function"?Ou(Bu):Ou;ju=setTimeout(zu,Math.max(0,Vu))},Hu.onerror=()=>{(Hu.readyState===WebSocket.CONNECTING||Hu.readyState===WebSocket.OPEN)&&Hu.close()}}return zu(),()=>{Lu=!0,ju&&clearTimeout(ju),agentRuntimeStore.getState().setWs(null,Iu),agentRuntimeStore.getState().resetWs()}},[lo,$u,Ru,Iu,Pu,Ou,Mu])}const ALPHAVANTAGE_MCP_SERVER_0_0_1={id:"alphavantage",version:"0.0.1",name:"Alpha Vantage",description:"Financial market data and stock information",icon:"@primer/octicons-react:graph",emoji:"💹",url:"",command:"uvx",args:["av-mcp==0.2.1","${ALPHAVANTAGE_API_KEY}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["ALPHAVANTAGE_API_KEY:0.0.1"]},CHART_MCP_SERVER_0_0_1={id:"chart",version:"0.0.1",name:"Chart Generator",description:"Generate charts and visualizations",icon:"@datalayer/icons-react:chart-bar",emoji:"📊",url:"",command:"npx",args:["-y","@antv/mcp-server-chart"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},DATALAYER_MCP_SERVER_0_0_1={id:"datalayer",version:"0.0.1",name:"Datalayer",description:"Read, edit and run Jupyter notebooks on Datalayer, with sandboxes and data",icon:"@datalayer/icons-react:datalayer",emoji:"🚀",url:"",command:"npx",args:["-y","mcp-remote","https://mcp.datalayer.run/mcp","--header","Authorization: Bearer ${DATALAYER_API_KEY}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["DATALAYER_API_KEY:0.0.1"]},EARTHDATA_MCP_SERVER_0_0_1={id:"earthdata",version:"0.0.1",name:"Earthdata MCP",description:"Access NASA Earthdata search and metadata capabilities",icon:"@datalayer/icons-react:globe-americas",emoji:"🌍",url:"",command:"npx",args:["-y","mcp-remote","https://mcp.datalayer.run/mcp?only=earthdata","--header","Authorization: Bearer ${DATALAYER_API_KEY}"],transport:"stdio",enabled:!0,isAvailable:!1,tools:[],requiredEnvVars:["DATALAYER_API_KEY:0.0.1"]},EURUS_MCP_SERVER_0_0_1={id:"eurus",version:"0.0.1",name:"Eurus Climate MCP",description:"Climate and reanalysis analysis tools for spatial workflows",icon:"@primer/octicons-react:cloud",emoji:"🌦️",url:"",command:"eurus-mcp",args:[],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},FILESYSTEM_MCP_SERVER_0_0_1={id:"filesystem",version:"0.0.1",name:"Filesystem",description:"Local filesystem read/write operations",icon:"@primer/octicons-react:file-directory",emoji:"📁",url:"",command:"npx",args:["-y","@modelcontextprotocol/server-filesystem","${TMPDIR}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},GITHUB_MCP_SERVER_0_0_1={id:"github",version:"0.0.1",name:"GitHub",description:"GitHub repository operations (issues, PRs, code search)",icon:"@datalayer/icons-react:github-mark",emoji:"🐙",url:"",command:"docker",args:["run","-i","--rm","-e","GITHUB_PERSONAL_ACCESS_TOKEN","ghcr.io/github/github-mcp-server"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["GITHUB_TOKEN:0.0.1"]},GOOGLE_WORKSPACE_MCP_SERVER_0_0_1={id:"google-workspace",version:"0.0.1",name:"Google Workspace",description:"Gmail of the person an application acts for, read or read and send, with a token Datalayer mints per call",icon:"@datalayer/icons-react:google",emoji:"📧",url:"http://127.0.0.1:9711/mcp",command:"uvx",args:["workspace-mcp","--transport","streamable-http","--permissions","gmail:send"],transport:"streamable-http",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},HUGGINGFACE_MCP_SERVER_0_0_1={id:"huggingface",version:"0.0.1",name:"Hugging Face",description:"Hugging Face models, datasets, spaces, and papers access",icon:"@primer/octicons-react:hubot",emoji:"🤗",url:"",command:"npx",args:["-y","mcp-remote","https://huggingface.co/mcp","--header","Authorization: Bearer ${HF_TOKEN}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["HF_TOKEN:0.0.1"]},KAGGLE_MCP_SERVER_0_0_1={id:"kaggle",version:"0.0.1",name:"Kaggle",description:"Kaggle datasets, models, competitions, and notebooks access",icon:"@datalayer/icons-react:kaggle",emoji:"🏆",url:"",command:"npx",args:["-y","mcp-remote","https://www.kaggle.com/mcp","--header","Authorization: Bearer ${KAGGLE_API_TOKEN}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["KAGGLE_API_TOKEN:0.0.1"]},ODOO_ACCOUNTING_MCP_SERVER_0_0_1={id:"odoo-accounting",version:"0.0.1",name:"Odoo Accounting",description:"An accountant's day in Odoo — invoices, bills, journal entries, reconciliations, bank lines and tax returns — through the Datalayer MCP server",icon:"@datalayer/icons-react:odoo",emoji:"🧮",url:"",command:"npx",args:["-y","mcp-remote","https://mcp.datalayer.run/mcp?only=odoo-accounting","--header","Authorization: Bearer ${DATALAYER_API_KEY}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["DATALAYER_API_KEY:0.0.1"]},ODOO_MCP_SERVER_0_0_1={id:"odoo",version:"0.0.1",name:"Odoo",description:"Odoo ERP operations (search, invoices, journals, reconciliations)",icon:"@datalayer/icons-react:odoo",emoji:"🧾",url:"",command:"uvx",args:["mcp-server-odoo"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},SALESFORCE_MCP_SERVER_0_0_1={id:"salesforce",version:"0.0.1",name:"Salesforce",description:"Salesforce CRM operations (queries, reports, objects, SOQL)",icon:"@primer/octicons-react:briefcase",emoji:"☁️",url:"",command:"npx",args:["-y","@anthropic/salesforce-mcp-server"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["SALESFORCE_ACCESS_TOKEN:0.0.1","SALESFORCE_INSTANCE_URL:0.0.1"]},SLACK_MCP_SERVER_0_0_1={id:"slack",version:"0.0.1",name:"Slack",description:"Slack messaging and channel operations",icon:"@datalayer/icons-react:slack",emoji:"💬",url:"",command:"npx",args:["-y","@datalayer/slack-mcp-server"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["SLACK_BOT_TOKEN:0.0.1","SLACK_TEAM_ID:0.0.1","SLACK_CHANNEL_IDS:0.0.1"]},TAVILY_MCP_SERVER_0_0_1={id:"tavily",version:"0.0.1",name:"Tavily Search",description:"Web search and research capabilities via Tavily API",icon:"@primer/octicons-react:search",emoji:"🔍",url:"",command:"npx",args:["-y","tavily-mcp"],transport:"stdio",enabled:!0,isAvailable:!1,tools:[],requiredEnvVars:["TAVILY_API_KEY:0.0.1"]},MCP_SERVER_LIBRARY={alphavantage:ALPHAVANTAGE_MCP_SERVER_0_0_1,chart:CHART_MCP_SERVER_0_0_1,datalayer:DATALAYER_MCP_SERVER_0_0_1,earthdata:EARTHDATA_MCP_SERVER_0_0_1,eurus:EURUS_MCP_SERVER_0_0_1,filesystem:FILESYSTEM_MCP_SERVER_0_0_1,github:GITHUB_MCP_SERVER_0_0_1,"google-workspace":GOOGLE_WORKSPACE_MCP_SERVER_0_0_1,huggingface:HUGGINGFACE_MCP_SERVER_0_0_1,kaggle:KAGGLE_MCP_SERVER_0_0_1,"odoo-accounting":ODOO_ACCOUNTING_MCP_SERVER_0_0_1,odoo:ODOO_MCP_SERVER_0_0_1,salesforce:SALESFORCE_MCP_SERVER_0_0_1,slack:SLACK_MCP_SERVER_0_0_1,tavily:TAVILY_MCP_SERVER_0_0_1},ACCOUNTING_SKILL_SPEC_0_0_1={id:"accounting",version:"0.0.1",name:"Accounting Skill",description:"Accounting analysis workflows for reconciliation, close, variance, and audit-ready summaries",module:"agent_skills.skills.accounting",package:void 0,method:void 0,path:void 0,requiredEnvVars:[],optionalEnvVars:[],dependencies:["pandas>=2.0.0"],tags:["accounting","finance","reconciliation","close"],icon:"@primer/octicons-react:book",emoji:"🧮",enabled:!1},CRAWL_SKILL_SPEC_0_0_1={id:"crawl",version:"0.0.1",name:"Web Crawl Skill",description:"Web crawling and content extraction capabilities",module:"agent_skills.skills.crawl",package:void 0,method:void 0,path:void 0,requiredEnvVars:["TAVILY_API_KEY:0.0.1"],optionalEnvVars:[],dependencies:["requests>=2.31.0","beautifulsoup4>=4.12.0"],tags:["web","crawl","scraping"],icon:"@primer/octicons-react:globe",emoji:"🌐",enabled:!0},EVENTS_SKILL_SPEC_0_0_1={id:"events",version:"0.0.1",name:"Events Skill",description:"Event generation, enrichment, and lifecycle orchestration",module:"agent_skills.skills.events",package:void 0,method:void 0,path:void 0,requiredEnvVars:[],optionalEnvVars:[],dependencies:["httpx>=0.27.0"],tags:["events","orchestration","automation"],icon:"@primer/octicons-react:calendar",emoji:"📅",enabled:!1},GITHUB_SKILL_SPEC_0_0_1={id:"github",version:"0.0.1",name:"GitHub Skill",description:"GitHub repository management and code operations",module:"agent_skills.skills.github",package:void 0,method:void 0,path:void 0,requiredEnvVars:["GITHUB_TOKEN:0.0.1"],optionalEnvVars:[],dependencies:["PyGithub>=2.1.0"],tags:["github","git","code"],icon:"@datalayer/icons-react:github-mark",emoji:"🐙",enabled:!1},JOKES_SKILL_SPEC_0_0_1={id:"jokes",version:"0.0.1",name:"Jokes Skill",description:"Return random jokes from a local path-based skill.",module:void 0,package:void 0,method:void 0,path:"jokes",requiredEnvVars:[],optionalEnvVars:[],dependencies:[],tags:["fun","humor","demo"],icon:"@primer/octicons-react:smiley",emoji:"😄",enabled:!1},PDF_SKILL_SPEC_0_0_1={id:"pdf",version:"0.0.1",name:"PDF Processing Skill",description:"PDF document reading, parsing, and extraction",module:"agent_skills.skills.pdf",package:void 0,method:void 0,path:void 0,requiredEnvVars:[],optionalEnvVars:[],dependencies:["PyPDF2>=3.0.0","pdfplumber>=0.10.0"],tags:["pdf","documents","extraction"],icon:"@primer/octicons-react:file",emoji:"📄",enabled:!1},TEXT_SUMMARIZER_SKILL_SPEC_0_0_1={id:"text-summarizer",version:"0.0.1",name:"Text Summarizer Skill",description:"Summarize text content using extractive and abstractive techniques. Use when the user asks for summaries, key points, or condensed versions of documents.",module:void 0,package:"agent_skills.skills.text_summarizer",method:"summarize_text",path:void 0,requiredEnvVars:[],optionalEnvVars:[],dependencies:["agent-skills>=0.0.1"],tags:["nlp","summarization","text-processing"],icon:"@primer/octicons-react:note",emoji:"📝",enabled:!1},SKILLS_CATALOG={accounting:ACCOUNTING_SKILL_SPEC_0_0_1,crawl:CRAWL_SKILL_SPEC_0_0_1,events:EVENTS_SKILL_SPEC_0_0_1,github:GITHUB_SKILL_SPEC_0_0_1,jokes:JOKES_SKILL_SPEC_0_0_1,pdf:PDF_SKILL_SPEC_0_0_1,"text-summarizer":TEXT_SUMMARIZER_SKILL_SPEC_0_0_1},CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1={id:"create-plan",version:"0.0.1",name:"Create Plan",description:"Create a plan with multiple steps and emit an AG-UI state snapshot.",tags:["example","ag-ui","state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"create_plan"},icon:"@primer/octicons-react:list-unordered",emoji:"📋"},CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1={id:"current-time",version:"0.0.1",name:"Current Time",description:"Return the current time in ISO format for a given timezone.",tags:["example","ag-ui","time"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"current_time"},icon:"@primer/octicons-react:clock",emoji:"🕒"},DECIDE_BACKEND_TOOL_SPEC_0_0_1={id:"decide",version:"0.0.1",name:"Decide",description:"Ask Jev typed questions about a text — noul (does a statement hold, with its probability), choice (one of named options) or score (a step on a rubric) — and get the typed answers back, through datalayer-ai-inference.",tags:["runtime","decisions","jev"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.tools.decisions",method:"decide"},icon:"@primer/octicons-react:law",emoji:"⚖️"},DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1={id:"display-recipe",version:"0.0.1",name:"Display Recipe",description:"Update the shared recipe state and emit an AG-UI state snapshot.",tags:["example","ag-ui","shared-state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"display_recipe"},icon:"@primer/octicons-react:book",emoji:"🍳"},EXAMPLE_CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1={id:"example-create-plan",version:"0.0.1",name:"Create Plan",description:"Create a plan with multiple steps and emit an AG-UI state snapshot.",tags:["example","ag-ui","state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"create_plan"},icon:"@primer/octicons-react:list-unordered",emoji:"📋"},EXAMPLE_CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1={id:"example-current-time",version:"0.0.1",name:"Current Time",description:"Return the current time in ISO format for a given timezone.",tags:["example","ag-ui","time"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"current_time"},icon:"@primer/octicons-react:clock",emoji:"🕒"},EXAMPLE_DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1={id:"example-display-recipe",version:"0.0.1",name:"Display Recipe",description:"Update the shared recipe state and emit an AG-UI state snapshot.",tags:["example","ag-ui","shared-state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"display_recipe"},icon:"@primer/octicons-react:book",emoji:"🍳"},EXAMPLE_GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1={id:"example-generate-haiku",version:"0.0.1",name:"Generate Haiku",description:"Generate a haiku (Japanese + English + gradient) rendered as a card by the frontend.",tags:["example","ag-ui","generative-ui"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"generate_haiku"},icon:"@primer/octicons-react:pencil",emoji:"🖋️"},EXAMPLE_GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1={id:"example-generate-task-steps",version:"0.0.1",name:"Generate Task Steps",description:"Generate task steps for human review and emit an AG-UI state snapshot.",tags:["example","ag-ui","human-in-the-loop"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"generate_task_steps"},icon:"@primer/octicons-react:tasklist",emoji:"🙋"},EXAMPLE_GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1={id:"example-get-weather",version:"0.0.1",name:"Get Weather",description:"Fetch current weather for a location from the Open-Meteo API for frontend rendering.",tags:["example","ag-ui","weather"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"get_weather"},icon:"@primer/octicons-react:sun",emoji:"🌤️"},EXAMPLE_RENDER_A2UI_SURFACE_BACKEND_TOOL_SPEC_0_0_1={id:"example-render-a2ui-surface",version:"0.0.1",name:"Render A2UI Surface",description:"Turn a declarative field spec into a validated A2UI v0.9 surface rendered live by the frontend as an interactive form/card.",tags:["example","ag-ui","a2ui","generative-ui"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.a2ui",method:"render_a2ui_surface"},icon:"@primer/octicons-react:browser",emoji:"🎛️"},EXAMPLE_UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1={id:"example-update-plan-step",version:"0.0.1",name:"Update Plan Step",description:"Update a plan step and emit an AG-UI state delta (JSON Patch RFC 6902).",tags:["example","ag-ui","state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"update_plan_step"},icon:"@primer/octicons-react:checklist",emoji:"✅"},GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1={id:"generate-haiku",version:"0.0.1",name:"Generate Haiku",description:"Generate a haiku (Japanese + English + gradient) rendered as a card by the frontend.",tags:["example","ag-ui","generative-ui"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"generate_haiku"},icon:"@primer/octicons-react:pencil",emoji:"🖋️"},GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1={id:"generate-task-steps",version:"0.0.1",name:"Generate Task Steps",description:"Generate task steps for human review and emit an AG-UI state snapshot.",tags:["example","ag-ui","human-in-the-loop"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"generate_task_steps"},icon:"@primer/octicons-react:tasklist",emoji:"🙋"},GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1={id:"get-weather",version:"0.0.1",name:"Get Weather",description:"Fetch current weather for a location from the Open-Meteo API for frontend rendering.",tags:["example","ag-ui","weather"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"get_weather"},icon:"@primer/octicons-react:sun",emoji:"🌤️"},RUNTIME_ECHO_BACKEND_TOOL_SPEC_0_0_1={id:"runtime-echo",version:"0.0.1",name:"Runtime Echo",description:"Echo text back to the caller for quick runtime verification.",tags:["runtime","utility"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools",method:"runtime_echo"},icon:"@primer/octicons-react:comment",emoji:"💬"},RUNTIME_SEND_MAIL_BACKEND_TOOL_SPEC_0_0_1={id:"runtime-send-mail",version:"0.0.1",name:"Runtime Send Mail (Fake)",description:"Fake mail sender for tool approval demos; returns a simulated send receipt.",tags:["runtime","approval","mail"],enabled:!0,approval:"manual",timeout:void 0,requiresApproval:!0,runtime:{language:"python",package:"agent_runtimes.examples.tools",method:"runtime_send_mail"},icon:"@primer/octicons-react:mail",emoji:"📧"},RUNTIME_SENSITIVE_ECHO_BACKEND_TOOL_SPEC_0_0_1={id:"runtime-sensitive-echo",version:"0.0.1",name:"Runtime Sensitive Echo",description:"Echo text with a manual approval checkpoint before execution.",tags:["runtime","approval"],enabled:!0,approval:"manual",timeout:void 0,requiresApproval:!0,runtime:{language:"python",package:"agent_runtimes.examples.tools",method:"runtime_sensitive_echo"},icon:"@primer/octicons-react:shield",emoji:"🛡️"},UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1={id:"update-plan-step",version:"0.0.1",name:"Update Plan Step",description:"Update a plan step and emit an AG-UI state delta (JSON Patch RFC 6902).",tags:["example","ag-ui","state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"update_plan_step"},icon:"@primer/octicons-react:checklist",emoji:"✅"},BACKEND_TOOL_CATALOG={"create-plan":CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1,"current-time":CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1,decide:DECIDE_BACKEND_TOOL_SPEC_0_0_1,"display-recipe":DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1,"example-create-plan":EXAMPLE_CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1,"example-current-time":EXAMPLE_CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1,"example-display-recipe":EXAMPLE_DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1,"example-generate-haiku":EXAMPLE_GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1,"example-generate-task-steps":EXAMPLE_GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1,"example-get-weather":EXAMPLE_GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1,"example-render-a2ui-surface":EXAMPLE_RENDER_A2UI_SURFACE_BACKEND_TOOL_SPEC_0_0_1,"example-update-plan-step":EXAMPLE_UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1,"generate-haiku":GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1,"generate-task-steps":GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1,"get-weather":GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1,"runtime-echo":RUNTIME_ECHO_BACKEND_TOOL_SPEC_0_0_1,"runtime-send-mail":RUNTIME_SEND_MAIL_BACKEND_TOOL_SPEC_0_0_1,"runtime-sensitive-echo":RUNTIME_SENSITIVE_ECHO_BACKEND_TOOL_SPEC_0_0_1,"update-plan-step":UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1},DECKS_FRONTEND_TOOL_SPEC_0_0_1={id:"decks",version:"0.0.1",name:"Decks",description:"Read, write and drive presentations kept as data — a deck, its slides, and the one on screen.",tags:["frontend","decks","presentations"],enabled:!0,toolset:["decks_list_decks","decks_get_deck","decks_create_deck","decks_update_deck","decks_update_slide","decks_insert_slide","decks_delete_slide","decks_list_slides","decks_get_slide","decks_add_slide","decks_delete_deck","decks_list","decks_open","decks_go_to_slide","decks_next_slide","decks_previous_slide","decks_present","decks_print"],icon:"@primer/octicons-react:project",emoji:"🃏"},JUPYTER_NOTEBOOK_EDIT_FRONTEND_TOOL_SPEC_0_0_1={id:"jupyter-notebook-edit",version:"0.0.1",name:"Jupyter Notebook (edit)",description:"Read and edit a notebook, and run cells — but never delete from it.",tags:["frontend","notebook","edit"],enabled:!0,toolset:["readCell","readAllCells","insertCell","updateCell","runCell","executeCode"],icon:"@datalayer/icons-react:jupyter",emoji:"📓"},JUPYTER_NOTEBOOK_PROPOSE_FRONTEND_TOOL_SPEC_0_0_1={id:"jupyter-notebook-propose",version:"0.0.1",name:"Jupyter Notebook (propose)",description:"Read a notebook and propose changes for a person to accept, never applying them.",tags:["frontend","notebook","propose"],enabled:!0,toolset:["readCell","readAllCells","proposeCellUpdate","runCell"],icon:"@datalayer/icons-react:jupyter",emoji:"📓"},JUPYTER_NOTEBOOK_READ_FRONTEND_TOOL_SPEC_0_0_1={id:"jupyter-notebook-read",version:"0.0.1",name:"Jupyter Notebook (read only)",description:"Read a notebook without changing it — cells, outputs and errors.",tags:["frontend","notebook","read"],enabled:!0,toolset:["readCell","readAllCells"],icon:"@datalayer/icons-react:jupyter",emoji:"📓"},JUPYTER_NOTEBOOK_FRONTEND_TOOL_SPEC_0_0_1={id:"jupyter-notebook",version:"0.0.1",name:"Jupyter Notebook",description:"Frontend tools for interacting with Jupyter notebooks.",tags:["frontend","notebook","jupyter-server"],enabled:!0,toolset:"all",icon:"@datalayer/icons-react:jupyter",emoji:"📓"},LEXICAL_DOCUMENT_FRONTEND_TOOL_SPEC_0_0_1={id:"lexical-document",version:"0.0.1",name:"Lexical Document",description:"Frontend tools for interacting with Lexical documents: reading and writing blocks, running Jupyter cells in the page, and drawing diagrams into the document with Excalidraw.",tags:["frontend","document","lexical","drawing","diagram"],enabled:!0,toolset:"all",icon:"@primer/octicons-react:file",emoji:"📄"},FRONTEND_TOOL_CATALOG={decks:DECKS_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-edit":JUPYTER_NOTEBOOK_EDIT_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-propose":JUPYTER_NOTEBOOK_PROPOSE_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-read":JUPYTER_NOTEBOOK_READ_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook":JUPYTER_NOTEBOOK_FRONTEND_TOOL_SPEC_0_0_1,"lexical-document":LEXICAL_DOCUMENT_FRONTEND_TOOL_SPEC_0_0_1},MCP_SERVER_MAP$1={"alphavantage:0.0.1":ALPHAVANTAGE_MCP_SERVER_0_0_1,"chart:0.0.1":CHART_MCP_SERVER_0_0_1,"earthdata:0.0.1":EARTHDATA_MCP_SERVER_0_0_1,"eurus:0.0.1":EURUS_MCP_SERVER_0_0_1,"filesystem:0.0.1":FILESYSTEM_MCP_SERVER_0_0_1,"github:0.0.1":GITHUB_MCP_SERVER_0_0_1,"google-workspace:0.0.1":GOOGLE_WORKSPACE_MCP_SERVER_0_0_1,"huggingface:0.0.1":HUGGINGFACE_MCP_SERVER_0_0_1,"kaggle:0.0.1":KAGGLE_MCP_SERVER_0_0_1,"odoo:0.0.1":ODOO_MCP_SERVER_0_0_1,"salesforce:0.0.1":SALESFORCE_MCP_SERVER_0_0_1,"slack:0.0.1":SLACK_MCP_SERVER_0_0_1,"tavily:0.0.1":TAVILY_MCP_SERVER_0_0_1},SKILL_MAP$1={"accounting:0.0.1":ACCOUNTING_SKILL_SPEC_0_0_1,"crawl:0.0.1":CRAWL_SKILL_SPEC_0_0_1,"events:0.0.1":EVENTS_SKILL_SPEC_0_0_1,"github:0.0.1":GITHUB_SKILL_SPEC_0_0_1,"jokes:0.0.1":JOKES_SKILL_SPEC_0_0_1,"pdf:0.0.1":PDF_SKILL_SPEC_0_0_1,"text-summarizer:0.0.1":TEXT_SUMMARIZER_SKILL_SPEC_0_0_1};function toAgentSkillSpec$1(Au){return{id:Au.id,name:Au.name,description:Au.description,version:Au.version??"0.0.1",tags:Au.tags,enabled:Au.enabled,requiredEnvVars:Au.requiredEnvVars}}const TOOL_MAP$1={"decide:0.0.1":DECIDE_BACKEND_TOOL_SPEC_0_0_1,"example-create-plan:0.0.1":EXAMPLE_CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1,"example-current-time:0.0.1":EXAMPLE_CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1,"example-display-recipe:0.0.1":EXAMPLE_DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1,"example-generate-haiku:0.0.1":EXAMPLE_GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1,"example-generate-task-steps:0.0.1":EXAMPLE_GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1,"example-get-weather:0.0.1":EXAMPLE_GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1,"example-render-a2ui-surface:0.0.1":EXAMPLE_RENDER_A2UI_SURFACE_BACKEND_TOOL_SPEC_0_0_1,"example-update-plan-step:0.0.1":EXAMPLE_UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1,"runtime-echo:0.0.1":RUNTIME_ECHO_BACKEND_TOOL_SPEC_0_0_1,"runtime-send-mail:0.0.1":RUNTIME_SEND_MAIL_BACKEND_TOOL_SPEC_0_0_1,"runtime-sensitive-echo:0.0.1":RUNTIME_SENSITIVE_ECHO_BACKEND_TOOL_SPEC_0_0_1},FRONTEND_TOOL_MAP$1={"decks:0.0.1":DECKS_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-edit:0.0.1":JUPYTER_NOTEBOOK_EDIT_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-propose:0.0.1":JUPYTER_NOTEBOOK_PROPOSE_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-read:0.0.1":JUPYTER_NOTEBOOK_READ_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook:0.0.1":JUPYTER_NOTEBOOK_FRONTEND_TOOL_SPEC_0_0_1,"lexical-document:0.0.1":LEXICAL_DOCUMENT_FRONTEND_TOOL_SPEC_0_0_1},EXAMPLE_A2A_RESEARCHER_AGENTSPEC_0_0_1={id:"example-a2a-researcher",version:"0.0.1",name:"Example A2A Researcher",description:"A research specialist served over the A2A protocol. Given a topic, gathers the key facts and returns concise, source-aware notes.",tags:["research","a2a"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],frontendTools:[],environmentName:"ai-agents-env",icon:"search",emoji:"🔎",color:"#0EA5E9",suggestions:[{text:"Gather the key facts on a topic, with sources",summary:"Key facts with sources"}],welcomeMessage:"A2A researcher ready.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:void 0,harness:"pydantic-ai",systemPrompt:"You are a meticulous research specialist, reached by other agents over the A2A protocol. Given a topic, gather the key facts and return concise, source-aware notes. Prefer verifiable claims and flag anything uncertain. Answer with the notes themselves: no preamble, no questions back. You have no tools and no web access: work from what you know, and say when something should be checked.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"a2a",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_A2A_WRITER_AGENTSPEC_0_0_1={id:"example-a2a-writer",version:"0.0.1",name:"Example A2A Writer",description:"A writing specialist served over the A2A protocol. Given notes or instructions, produces clear, well-structured prose.",tags:["writing","a2a"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],frontendTools:[],environmentName:"ai-agents-env",icon:"pencil",emoji:"✍️",color:"#F59E0B",suggestions:[{text:"Turn a set of notes into a short, structured write-up",summary:"Notes into a write-up"}],welcomeMessage:"A2A writer ready.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:void 0,harness:"pydantic-ai",systemPrompt:"You are a concise writing specialist, reached by other agents over the A2A protocol. Given notes or findings, produce clear, well-structured prose. Keep it focused and free of filler. Answer with the text itself: no preamble, no questions back. You have no tools: work from the notes and instructions you are given.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"a2a",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_A2A_AGENTSPEC_0_0_1={id:"example-a2a",version:"0.0.1",name:"Example A2A Agent",description:"Demonstrates delegation to separate agents over the A2A protocol. The orchestrator hands research and writing to a researcher and a writer that run as agents of their own — launched beside it on the local server, or on Datalayer runtimes when it runs in the cloud — and talks to them over A2A.",tags:["research","workflow","a2a"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],frontendTools:[],environmentName:"ai-agents-env",icon:"broadcast",emoji:"📡",color:"#7C3AED",suggestions:[{text:"Research three key facts about the A2A protocol through the researcher, then have the writer turn them into one short paragraph.",summary:"Research then write over A2A"},{text:"Have the researcher gather five source-backed notes on Jupyter kernels and report them to me as they are.",summary:"Research via the A2A researcher"},{text:"Have the writer draft a short guide to naming variables from these points: be specific, prefer words to abbreviations, keep units in the name.",summary:"Draft via the A2A writer"}],welcomeMessage:"A2A example agent ready. Ask me to delegate research and writing to the agents I reach over A2A.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:'You are the A2A Orchestrator. You do not research or write yourself: you split a request into specialist tasks and hand each to a separate agent reached over the A2A protocol, then synthesize their answers into one coherent reply.\nYour agents are `researcher` — facts, background, source-backed notes — and `writer` — clear, structured prose from notes or instructions. Reach them with `delegate_task`, naming the agent; a request to "research and write" is two delegations, the researcher\'s notes handed to the writer. Give each a task it can carry out without the rest of this conversation. The first delegation to an agent may take a moment while it is launched.\nAnswer in the conversation, and only with the tools you actually have; never call a tool you were not given.',systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:{includeGeneralPurpose:!1,subagents:[{name:"researcher",description:"A separate research agent, reached over A2A. Gathers facts and source-backed notes on a topic; use for research, fact-finding and background gathering.",ref:"example-a2a-researcher:0.0.1",a2a:{launch:"auto"}},{name:"writer",description:"A separate writing agent, reached over A2A. Turns notes into clear, well-structured prose; use for summaries, drafts and final write-ups.",ref:"example-a2a-writer:0.0.1",a2a:{launch:"auto"}}]}},EXAMPLE_A2UI_AGENT_SPEC_0_0_1={id:"example-a2ui-agent",version:"0.0.1",name:"A2UI Agent",description:"An AG-UI agent that generates interactive A2UI surfaces on demand. Describe a form, intake, configurator, survey or booking flow and the agent renders a validated, themeable A2UI surface you can fill in.",tags:["workflow","automation","analysis"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[TOOL_MAP$1["example-render-a2ui-surface:0.0.1"]],frontendTools:[],frontendRenderTools:[{tool:"render_a2ui_surface",renderer:"a2ui-surface"}],environmentName:"ai-agents-env",icon:"browser",emoji:"🎛️",color:"#6366F1",suggestions:[{text:"Build a support ticket intake form with category, priority and a description.",summary:"Support ticket form"},{text:"Create a trip booking form with destination, dates, travelers and budget.",summary:"Trip booking form"},{text:"Generate a customer feedback survey with a rating slider and comments.",summary:"Feedback survey"},{text:"Make a product configurator for a laptop with CPU, RAM and add-ons.",summary:"Laptop configurator"}],welcomeMessage:`Hi! I turn requests into interactive A2UI surfaces. Ask me to build a form, survey, configurator or booking flow and I'll render it live for you.
|
|
2199
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var Pu=!0,Ou=!1,Mu;return{s:function(){$u=$u.call(Au)},n:function(){var Lu=$u.next();return Pu=Lu.done,Lu},e:function(Lu){Ou=!0,Mu=Lu},f:function(){try{!Pu&&$u.return!=null&&$u.return()}finally{if(Ou)throw Mu}}}}function _unsupportedIterableToArray$1(Au,lo){if(Au){if(typeof Au=="string")return _arrayLikeToArray$1(Au,lo);var $u=Object.prototype.toString.call(Au).slice(8,-1);if($u==="Object"&&Au.constructor&&($u=Au.constructor.name),$u==="Map"||$u==="Set")return Array.from(Au);if($u==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test($u))return _arrayLikeToArray$1(Au,lo)}}function _arrayLikeToArray$1(Au,lo){(lo==null||lo>Au.length)&&(lo=Au.length);for(var $u=0,Ru=new Array(lo);$u<lo;$u++)Ru[$u]=Au[$u];return Ru}function ownKeys$1(Au,lo){var $u=Object.keys(Au);if(Object.getOwnPropertySymbols){var Ru=Object.getOwnPropertySymbols(Au);lo&&(Ru=Ru.filter(function(Iu){return Object.getOwnPropertyDescriptor(Au,Iu).enumerable})),$u.push.apply($u,Ru)}return $u}function _objectSpread$1(Au){for(var lo=1;lo<arguments.length;lo++){var $u=arguments[lo]!=null?arguments[lo]:{};lo%2?ownKeys$1(Object($u),!0).forEach(function(Ru){_defineProperty$1(Au,Ru,$u[Ru])}):Object.getOwnPropertyDescriptors?Object.defineProperties(Au,Object.getOwnPropertyDescriptors($u)):ownKeys$1(Object($u)).forEach(function(Ru){Object.defineProperty(Au,Ru,Object.getOwnPropertyDescriptor($u,Ru))})}return Au}function _defineProperty$1(Au,lo,$u){return lo=_toPropertyKey$6(lo),lo in Au?Object.defineProperty(Au,lo,{value:$u,enumerable:!0,configurable:!0,writable:!0}):Au[lo]=$u,Au}function _classCallCheck$6(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$6(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$6(Ru.key),Ru)}}function _createClass$6(Au,lo,$u){return lo&&_defineProperties$6(Au.prototype,lo),$u&&_defineProperties$6(Au,$u),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$6(Au){var lo=_toPrimitive$6(Au,"string");return _typeof$6(lo)=="symbol"?lo:lo+""}function _toPrimitive$6(Au,lo){if(_typeof$6(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$6(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var PROTOCOL_TUS_V1="tus-v1",PROTOCOL_IETF_DRAFT_03="ietf-draft-03",PROTOCOL_IETF_DRAFT_05="ietf-draft-05",defaultOptions$2={endpoint:null,uploadUrl:null,metadata:{},metadataForPartialUploads:{},fingerprint:null,uploadSize:null,onProgress:null,onChunkComplete:null,onSuccess:null,onError:null,onUploadUrlAvailable:null,overridePatchMethod:!1,headers:{},addRequestId:!1,onBeforeRequest:null,onAfterResponse:null,onShouldRetry:defaultOnShouldRetry,chunkSize:Number.POSITIVE_INFINITY,retryDelays:[0,1e3,3e3,5e3],parallelUploads:1,parallelUploadBoundaries:null,storeFingerprintForResuming:!0,removeFingerprintOnSuccess:!1,uploadLengthDeferred:!1,uploadDataDuringCreation:!1,urlStorage:null,fileReader:null,httpStack:null,protocol:PROTOCOL_TUS_V1},BaseUpload=(function(){function Au(lo,$u){_classCallCheck$6(this,Au),"resume"in $u&&console.log("tus: The `resume` option has been removed in tus-js-client v2. Please use the URL storage API instead."),this.options=$u,this.options.chunkSize=Number(this.options.chunkSize),this._urlStorage=this.options.urlStorage,this.file=lo,this.url=null,this._req=null,this._fingerprint=null,this._urlStorageKey=null,this._offset=null,this._aborted=!1,this._size=null,this._source=null,this._retryAttempt=0,this._retryTimeout=null,this._offsetBeforeRetry=0,this._parallelUploads=null,this._parallelUploadUrls=null}return _createClass$6(Au,[{key:"findPreviousUploads",value:function(){var $u=this;return this.options.fingerprint(this.file,this.options).then(function(Ru){return $u._urlStorage.findUploadsByFingerprint(Ru)})}},{key:"resumeFromPreviousUpload",value:function($u){this.url=$u.uploadUrl||null,this._parallelUploadUrls=$u.parallelUploadUrls||null,this._urlStorageKey=$u.urlStorageKey}},{key:"start",value:function(){var $u=this,Ru=this.file;if(!Ru){this._emitError(new Error("tus: no file or stream to upload provided"));return}if(![PROTOCOL_TUS_V1,PROTOCOL_IETF_DRAFT_03,PROTOCOL_IETF_DRAFT_05].includes(this.options.protocol)){this._emitError(new Error("tus: unsupported protocol ".concat(this.options.protocol)));return}if(!this.options.endpoint&&!this.options.uploadUrl&&!this.url){this._emitError(new Error("tus: neither an endpoint or an upload URL is provided"));return}var Iu=this.options.retryDelays;if(Iu!=null&&Object.prototype.toString.call(Iu)!=="[object Array]"){this._emitError(new Error("tus: the `retryDelays` option must either be an array or null"));return}if(this.options.parallelUploads>1)for(var Pu=0,Ou=["uploadUrl","uploadSize","uploadLengthDeferred"];Pu<Ou.length;Pu++){var Mu=Ou[Pu];if(this.options[Mu]){this._emitError(new Error("tus: cannot use the ".concat(Mu," option when parallelUploads is enabled")));return}}if(this.options.parallelUploadBoundaries){if(this.options.parallelUploads<=1){this._emitError(new Error("tus: cannot use the `parallelUploadBoundaries` option when `parallelUploads` is disabled"));return}if(this.options.parallelUploads!==this.options.parallelUploadBoundaries.length){this._emitError(new Error("tus: the `parallelUploadBoundaries` must have the same length as the value of `parallelUploads`"));return}}this.options.fingerprint(Ru,this.options).then(function(Du){return $u._fingerprint=Du,$u._source?$u._source:$u.options.fileReader.openFile(Ru,$u.options.chunkSize)}).then(function(Du){if($u._source=Du,$u.options.uploadLengthDeferred)$u._size=null;else if($u.options.uploadSize!=null){if($u._size=Number($u.options.uploadSize),Number.isNaN($u._size)){$u._emitError(new Error("tus: cannot convert `uploadSize` option into a number"));return}}else if($u._size=$u._source.size,$u._size==null){$u._emitError(new Error("tus: cannot automatically derive upload's size from input. Specify it manually using the `uploadSize` option or use the `uploadLengthDeferred` option"));return}$u.options.parallelUploads>1||$u._parallelUploadUrls!=null?$u._startParallelUpload():$u._startSingleUpload()}).catch(function(Du){$u._emitError(Du)})}},{key:"_startParallelUpload",value:function(){var $u,Ru=this,Iu=this._size,Pu=0;this._parallelUploads=[];var Ou=this._parallelUploadUrls!=null?this._parallelUploadUrls.length:this.options.parallelUploads,Mu=($u=this.options.parallelUploadBoundaries)!==null&&$u!==void 0?$u:splitSizeIntoParts(this._source.size,Ou);this._parallelUploadUrls&&Mu.forEach(function(Bu,ju){Bu.uploadUrl=Ru._parallelUploadUrls[ju]||null}),this._parallelUploadUrls=new Array(Mu.length);var Du=Mu.map(function(Bu,ju){var Fu=0;return Ru._source.slice(Bu.start,Bu.end).then(function(zu){var Uu=zu.value;return new Promise(function(Hu,Vu){var Gu=_objectSpread$1(_objectSpread$1({},Ru.options),{},{uploadUrl:Bu.uploadUrl||null,storeFingerprintForResuming:!1,removeFingerprintOnSuccess:!1,parallelUploads:1,parallelUploadBoundaries:null,metadata:Ru.options.metadataForPartialUploads,headers:_objectSpread$1(_objectSpread$1({},Ru.options.headers),{},{"Upload-Concat":"partial"}),onSuccess:Hu,onError:Vu,onProgress:function(Ju){Pu=Pu-Fu+Ju,Fu=Ju,Ru._emitProgress(Pu,Iu)},onUploadUrlAvailable:function(){Ru._parallelUploadUrls[ju]=Wu.url,Ru._parallelUploadUrls.filter(function(Ju){return!!Ju}).length===Mu.length&&Ru._saveUploadInUrlStorage()}}),Wu=new Au(Uu,Gu);Wu.start(),Ru._parallelUploads.push(Wu)})})}),Lu;Promise.all(Du).then(function(){Lu=Ru._openRequest("POST",Ru.options.endpoint),Lu.setHeader("Upload-Concat","final;".concat(Ru._parallelUploadUrls.join(" ")));var Bu=encodeMetadata(Ru.options.metadata);return Bu!==""&&Lu.setHeader("Upload-Metadata",Bu),Ru._sendRequest(Lu,null)}).then(function(Bu){if(!inStatusCategory(Bu.getStatus(),200)){Ru._emitHttpError(Lu,Bu,"tus: unexpected response while creating upload");return}var ju=Bu.getHeader("Location");if(ju==null){Ru._emitHttpError(Lu,Bu,"tus: invalid or missing Location header");return}Ru.url=resolveUrl(Ru.options.endpoint,ju),"Created upload at ".concat(Ru.url),Ru._emitSuccess(Bu)}).catch(function(Bu){Ru._emitError(Bu)})}},{key:"_startSingleUpload",value:function(){if(this._aborted=!1,this.url!=null){"Resuming upload from previous URL: ".concat(this.url),this._resumeUpload();return}if(this.options.uploadUrl!=null){"Resuming upload from provided URL: ".concat(this.options.uploadUrl),this.url=this.options.uploadUrl,this._resumeUpload();return}this._createUpload()}},{key:"abort",value:function($u){var Ru=this;if(this._parallelUploads!=null){var Iu=_createForOfIteratorHelper(this._parallelUploads),Pu;try{for(Iu.s();!(Pu=Iu.n()).done;){var Ou=Pu.value;Ou.abort($u)}}catch(Mu){Iu.e(Mu)}finally{Iu.f()}}return this._req!==null&&this._req.abort(),this._aborted=!0,this._retryTimeout!=null&&(clearTimeout(this._retryTimeout),this._retryTimeout=null),!$u||this.url==null?Promise.resolve():Au.terminate(this.url,this.options).then(function(){return Ru._removeFromUrlStorage()})}},{key:"_emitHttpError",value:function($u,Ru,Iu,Pu){this._emitError(new DetailedError(Iu,Pu,$u,Ru))}},{key:"_emitError",value:function($u){var Ru=this;if(!this._aborted){if(this.options.retryDelays!=null){var Iu=this._offset!=null&&this._offset>this._offsetBeforeRetry;if(Iu&&(this._retryAttempt=0),shouldRetry($u,this._retryAttempt,this.options)){var Pu=this.options.retryDelays[this._retryAttempt++];this._offsetBeforeRetry=this._offset,this._retryTimeout=setTimeout(function(){Ru.start()},Pu);return}}if(typeof this.options.onError=="function")this.options.onError($u);else throw $u}}},{key:"_emitSuccess",value:function($u){this.options.removeFingerprintOnSuccess&&this._removeFromUrlStorage(),typeof this.options.onSuccess=="function"&&this.options.onSuccess({lastResponse:$u})}},{key:"_emitProgress",value:function($u,Ru){typeof this.options.onProgress=="function"&&this.options.onProgress($u,Ru)}},{key:"_emitChunkComplete",value:function($u,Ru,Iu){typeof this.options.onChunkComplete=="function"&&this.options.onChunkComplete($u,Ru,Iu)}},{key:"_createUpload",value:function(){var $u=this;if(!this.options.endpoint){this._emitError(new Error("tus: unable to create upload because no endpoint is provided"));return}var Ru=this._openRequest("POST",this.options.endpoint);this.options.uploadLengthDeferred?Ru.setHeader("Upload-Defer-Length","1"):Ru.setHeader("Upload-Length","".concat(this._size));var Iu=encodeMetadata(this.options.metadata);Iu!==""&&Ru.setHeader("Upload-Metadata",Iu);var Pu;this.options.uploadDataDuringCreation&&!this.options.uploadLengthDeferred?(this._offset=0,Pu=this._addChunkToRequest(Ru)):((this.options.protocol===PROTOCOL_IETF_DRAFT_03||this.options.protocol===PROTOCOL_IETF_DRAFT_05)&&Ru.setHeader("Upload-Complete","?0"),Pu=this._sendRequest(Ru,null)),Pu.then(function(Ou){if(!inStatusCategory(Ou.getStatus(),200)){$u._emitHttpError(Ru,Ou,"tus: unexpected response while creating upload");return}var Mu=Ou.getHeader("Location");if(Mu==null){$u._emitHttpError(Ru,Ou,"tus: invalid or missing Location header");return}if($u.url=resolveUrl($u.options.endpoint,Mu),"Created upload at ".concat($u.url),typeof $u.options.onUploadUrlAvailable=="function"&&$u.options.onUploadUrlAvailable(),$u._size===0){$u._emitSuccess(Ou),$u._source.close();return}$u._saveUploadInUrlStorage().then(function(){$u.options.uploadDataDuringCreation?$u._handleUploadResponse(Ru,Ou):($u._offset=0,$u._performUpload())})}).catch(function(Ou){$u._emitHttpError(Ru,null,"tus: failed to create upload",Ou)})}},{key:"_resumeUpload",value:function(){var $u=this,Ru=this._openRequest("HEAD",this.url),Iu=this._sendRequest(Ru,null);Iu.then(function(Pu){var Ou=Pu.getStatus();if(!inStatusCategory(Ou,200)){if(Ou===423){$u._emitHttpError(Ru,Pu,"tus: upload is currently locked; retry later");return}if(inStatusCategory(Ou,400)&&$u._removeFromUrlStorage(),!$u.options.endpoint){$u._emitHttpError(Ru,Pu,"tus: unable to resume upload (new upload cannot be created without an endpoint)");return}$u.url=null,$u._createUpload();return}var Mu=Number.parseInt(Pu.getHeader("Upload-Offset"),10);if(Number.isNaN(Mu)){$u._emitHttpError(Ru,Pu,"tus: invalid or missing offset value");return}var Du=Number.parseInt(Pu.getHeader("Upload-Length"),10);if(Number.isNaN(Du)&&!$u.options.uploadLengthDeferred&&$u.options.protocol===PROTOCOL_TUS_V1){$u._emitHttpError(Ru,Pu,"tus: invalid or missing length value");return}typeof $u.options.onUploadUrlAvailable=="function"&&$u.options.onUploadUrlAvailable(),$u._saveUploadInUrlStorage().then(function(){if(Mu===Du){$u._emitProgress(Du,Du),$u._emitSuccess(Pu);return}$u._offset=Mu,$u._performUpload()})}).catch(function(Pu){$u._emitHttpError(Ru,null,"tus: failed to resume upload",Pu)})}},{key:"_performUpload",value:function(){var $u=this;if(!this._aborted){var Ru;this.options.overridePatchMethod?(Ru=this._openRequest("POST",this.url),Ru.setHeader("X-HTTP-Method-Override","PATCH")):Ru=this._openRequest("PATCH",this.url),Ru.setHeader("Upload-Offset","".concat(this._offset));var Iu=this._addChunkToRequest(Ru);Iu.then(function(Pu){if(!inStatusCategory(Pu.getStatus(),200)){$u._emitHttpError(Ru,Pu,"tus: unexpected response while uploading chunk");return}$u._handleUploadResponse(Ru,Pu)}).catch(function(Pu){$u._aborted||$u._emitHttpError(Ru,null,"tus: failed to upload chunk at offset ".concat($u._offset),Pu)})}}},{key:"_addChunkToRequest",value:function($u){var Ru=this,Iu=this._offset,Pu=this._offset+this.options.chunkSize;return $u.setProgressHandler(function(Ou){Ru._emitProgress(Iu+Ou,Ru._size)}),this.options.protocol===PROTOCOL_TUS_V1?$u.setHeader("Content-Type","application/offset+octet-stream"):this.options.protocol===PROTOCOL_IETF_DRAFT_05&&$u.setHeader("Content-Type","application/partial-upload"),(Pu===Number.POSITIVE_INFINITY||Pu>this._size)&&!this.options.uploadLengthDeferred&&(Pu=this._size),this._source.slice(Iu,Pu).then(function(Ou){var Mu=Ou.value,Du=Ou.done,Lu=Mu!=null&&Mu.size?Mu.size:0;Ru.options.uploadLengthDeferred&&Du&&(Ru._size=Ru._offset+Lu,$u.setHeader("Upload-Length","".concat(Ru._size)));var Bu=Ru._offset+Lu;return!Ru.options.uploadLengthDeferred&&Du&&Bu!==Ru._size?Promise.reject(new Error("upload was configured with a size of ".concat(Ru._size," bytes, but the source is done after ").concat(Bu," bytes"))):Mu===null?Ru._sendRequest($u):((Ru.options.protocol===PROTOCOL_IETF_DRAFT_03||Ru.options.protocol===PROTOCOL_IETF_DRAFT_05)&&$u.setHeader("Upload-Complete",Du?"?1":"?0"),Ru._emitProgress(Ru._offset,Ru._size),Ru._sendRequest($u,Mu))})}},{key:"_handleUploadResponse",value:function($u,Ru){var Iu=Number.parseInt(Ru.getHeader("Upload-Offset"),10);if(Number.isNaN(Iu)){this._emitHttpError($u,Ru,"tus: invalid or missing offset value");return}if(this._emitProgress(Iu,this._size),this._emitChunkComplete(Iu-this._offset,Iu,this._size),this._offset=Iu,Iu===this._size){this._emitSuccess(Ru),this._source.close();return}this._performUpload()}},{key:"_openRequest",value:function($u,Ru){var Iu=openRequest($u,Ru,this.options);return this._req=Iu,Iu}},{key:"_removeFromUrlStorage",value:function(){var $u=this;this._urlStorageKey&&(this._urlStorage.removeUpload(this._urlStorageKey).catch(function(Ru){$u._emitError(Ru)}),this._urlStorageKey=null)}},{key:"_saveUploadInUrlStorage",value:function(){var $u=this;if(!this.options.storeFingerprintForResuming||!this._fingerprint||this._urlStorageKey!==null)return Promise.resolve();var Ru={size:this._size,metadata:this.options.metadata,creationTime:new Date().toString()};return this._parallelUploads?Ru.parallelUploadUrls=this._parallelUploadUrls:Ru.uploadUrl=this.url,this._urlStorage.addUpload(this._fingerprint,Ru).then(function(Iu){$u._urlStorageKey=Iu})}},{key:"_sendRequest",value:function($u){var Ru=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;return sendRequest($u,Ru,this.options)}}],[{key:"terminate",value:function($u){var Ru=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Iu=openRequest("DELETE",$u,Ru);return sendRequest(Iu,null,Ru).then(function(Pu){if(Pu.getStatus()!==204)throw new DetailedError("tus: unexpected response while terminating upload",null,Iu,Pu)}).catch(function(Pu){if(Pu instanceof DetailedError||(Pu=new DetailedError("tus: failed to terminate upload",Pu,Iu,null)),!shouldRetry(Pu,0,Ru))throw Pu;var Ou=Ru.retryDelays[0],Mu=Ru.retryDelays.slice(1),Du=_objectSpread$1(_objectSpread$1({},Ru),{},{retryDelays:Mu});return new Promise(function(Lu){return setTimeout(Lu,Ou)}).then(function(){return Au.terminate($u,Du)})})}}])})();function encodeMetadata(Au){return Object.entries(Au).map(function(lo){var $u=_slicedToArray$1(lo,2),Ru=$u[0],Iu=$u[1];return"".concat(Ru," ").concat(gBase64.encode(String(Iu)))}).join(",")}function inStatusCategory(Au,lo){return Au>=lo&&Au<lo+100}function openRequest(Au,lo,$u){var Ru=$u.httpStack.createRequest(Au,lo);$u.protocol===PROTOCOL_IETF_DRAFT_03?Ru.setHeader("Upload-Draft-Interop-Version","5"):$u.protocol===PROTOCOL_IETF_DRAFT_05?Ru.setHeader("Upload-Draft-Interop-Version","6"):Ru.setHeader("Tus-Resumable","1.0.0");for(var Iu=$u.headers||{},Pu=0,Ou=Object.entries(Iu);Pu<Ou.length;Pu++){var Mu=_slicedToArray$1(Ou[Pu],2),Du=Mu[0],Lu=Mu[1];Ru.setHeader(Du,Lu)}if($u.addRequestId){var Bu=uuid();Ru.setHeader("X-Request-ID",Bu)}return Ru}function sendRequest(Au,lo,$u){return _sendRequest2.apply(this,arguments)}function _sendRequest2(){return _sendRequest2=_asyncToGenerator$1(_regeneratorRuntime$1().mark(function Au(lo,$u,Ru){var Iu;return _regeneratorRuntime$1().wrap(function(Ou){for(;;)switch(Ou.prev=Ou.next){case 0:if(typeof Ru.onBeforeRequest!="function"){Ou.next=3;break}return Ou.next=3,Ru.onBeforeRequest(lo);case 3:return Ou.next=5,lo.send($u);case 5:if(Iu=Ou.sent,typeof Ru.onAfterResponse!="function"){Ou.next=9;break}return Ou.next=9,Ru.onAfterResponse(lo,Iu);case 9:return Ou.abrupt("return",Iu);case 10:case"end":return Ou.stop()}},Au)})),_sendRequest2.apply(this,arguments)}function isOnline(){var Au=!0;return typeof navigator<"u"&&navigator.onLine===!1&&(Au=!1),Au}function shouldRetry(Au,lo,$u){return $u.retryDelays==null||lo>=$u.retryDelays.length||Au.originalRequest==null?!1:$u&&typeof $u.onShouldRetry=="function"?$u.onShouldRetry(Au,lo,$u):defaultOnShouldRetry(Au)}function defaultOnShouldRetry(Au){var lo=Au.originalResponse?Au.originalResponse.getStatus():0;return(!inStatusCategory(lo,400)||lo===409||lo===423)&&isOnline()}function resolveUrl(Au,lo){return new URL$1(lo,Au).toString()}function splitSizeIntoParts(Au,lo){for(var $u=Math.floor(Au/lo),Ru=[],Iu=0;Iu<lo;Iu++)Ru.push({start:$u*Iu,end:$u*(Iu+1)});return Ru[lo-1].end=Au,Ru}BaseUpload.defaultOptions=defaultOptions$2;var isReactNative=function Au(){return typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative"};function uriToBlob(Au){return new Promise(function(lo,$u){var Ru=new XMLHttpRequest;Ru.responseType="blob",Ru.onload=function(){var Iu=Ru.response;lo(Iu)},Ru.onerror=function(Iu){$u(Iu)},Ru.open("GET",Au),Ru.send()})}var isCordova=function Au(){return typeof window<"u"&&(typeof window.PhoneGap<"u"||typeof window.Cordova<"u"||typeof window.cordova<"u")};function readAsByteArray(Au){return new Promise(function(lo,$u){var Ru=new FileReader;Ru.onload=function(){var Iu=new Uint8Array(Ru.result);lo({value:Iu})},Ru.onerror=function(Iu){$u(Iu)},Ru.readAsArrayBuffer(Au)})}function _typeof$5(Au){"@babel/helpers - typeof";return _typeof$5=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$5(Au)}function _classCallCheck$5(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$5(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$5(Ru.key),Ru)}}function _createClass$5(Au,lo,$u){return lo&&_defineProperties$5(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$5(Au){var lo=_toPrimitive$5(Au,"string");return _typeof$5(lo)=="symbol"?lo:lo+""}function _toPrimitive$5(Au,lo){if(_typeof$5(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$5(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var FileSource=(function(){function Au(lo){_classCallCheck$5(this,Au),this._file=lo,this.size=lo.size}return _createClass$5(Au,[{key:"slice",value:function($u,Ru){if(isCordova())return readAsByteArray(this._file.slice($u,Ru));var Iu=this._file.slice($u,Ru),Pu=Ru>=this.size;return Promise.resolve({value:Iu,done:Pu})}},{key:"close",value:function(){}}])})();function _typeof$4(Au){"@babel/helpers - typeof";return _typeof$4=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$4(Au)}function _classCallCheck$4(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$4(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$4(Ru.key),Ru)}}function _createClass$4(Au,lo,$u){return lo&&_defineProperties$4(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$4(Au){var lo=_toPrimitive$4(Au,"string");return _typeof$4(lo)=="symbol"?lo:lo+""}function _toPrimitive$4(Au,lo){if(_typeof$4(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$4(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}function len(Au){return Au===void 0?0:Au.size!==void 0?Au.size:Au.length}function concat(Au,lo){if(Au.concat)return Au.concat(lo);if(Au instanceof Blob)return new Blob([Au,lo],{type:Au.type});if(Au.set){var $u=new Au.constructor(Au.length+lo.length);return $u.set(Au),$u.set(lo,Au.length),$u}throw new Error("Unknown data type")}var StreamSource=(function(){function Au(lo){_classCallCheck$4(this,Au),this._buffer=void 0,this._bufferOffset=0,this._reader=lo,this._done=!1}return _createClass$4(Au,[{key:"slice",value:function($u,Ru){return $u<this._bufferOffset?Promise.reject(new Error("Requested data is before the reader's current offset")):this._readUntilEnoughDataOrDone($u,Ru)}},{key:"_readUntilEnoughDataOrDone",value:function($u,Ru){var Iu=this,Pu=Ru<=this._bufferOffset+len(this._buffer);if(this._done||Pu){var Ou=this._getDataFromBuffer($u,Ru),Mu=Ou==null?this._done:!1;return Promise.resolve({value:Ou,done:Mu})}return this._reader.read().then(function(Du){var Lu=Du.value,Bu=Du.done;return Bu?Iu._done=!0:Iu._buffer===void 0?Iu._buffer=Lu:Iu._buffer=concat(Iu._buffer,Lu),Iu._readUntilEnoughDataOrDone($u,Ru)})}},{key:"_getDataFromBuffer",value:function($u,Ru){$u>this._bufferOffset&&(this._buffer=this._buffer.slice($u-this._bufferOffset),this._bufferOffset=$u);var Iu=len(this._buffer)===0;return this._done&&Iu?null:this._buffer.slice(0,Ru-$u)}},{key:"close",value:function(){this._reader.cancel&&this._reader.cancel()}}])})();function _typeof$3(Au){"@babel/helpers - typeof";return _typeof$3=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$3(Au)}function _regeneratorRuntime(){_regeneratorRuntime=function(){return lo};var Au,lo={},$u=Object.prototype,Ru=$u.hasOwnProperty,Iu=Object.defineProperty||function(_d,yd,wd){_d[yd]=wd.value},Pu=typeof Symbol=="function"?Symbol:{},Ou=Pu.iterator||"@@iterator",Mu=Pu.asyncIterator||"@@asyncIterator",Du=Pu.toStringTag||"@@toStringTag";function Lu(_d,yd,wd){return Object.defineProperty(_d,yd,{value:wd,enumerable:!0,configurable:!0,writable:!0}),_d[yd]}try{Lu({},"")}catch{Lu=function(wd,Ad,md){return wd[Ad]=md}}function Bu(_d,yd,wd,Ad){var md=yd&&yd.prototype instanceof Gu?yd:Gu,dd=Object.create(md.prototype),bd=new gd(Ad||[]);return Iu(dd,"_invoke",{value:od(_d,wd,bd)}),dd}function ju(_d,yd,wd){try{return{type:"normal",arg:_d.call(yd,wd)}}catch(Ad){return{type:"throw",arg:Ad}}}lo.wrap=Bu;var Fu="suspendedStart",zu="suspendedYield",Uu="executing",Hu="completed",Vu={};function Gu(){}function Wu(){}function Ku(){}var Ju={};Lu(Ju,Ou,function(){return this});var Yu=Object.getPrototypeOf,Xu=Yu&&Yu(Yu(Sd([])));Xu&&Xu!==$u&&Ru.call(Xu,Ou)&&(Ju=Xu);var ed=Ku.prototype=Gu.prototype=Object.create(Ju);function td(_d){["next","throw","return"].forEach(function(yd){Lu(_d,yd,function(wd){return this._invoke(yd,wd)})})}function nd(_d,yd){function wd(md,dd,bd,ld){var ud=ju(_d[md],_d,dd);if(ud.type!=="throw"){var hd=ud.arg,vd=hd.value;return vd&&_typeof$3(vd)=="object"&&Ru.call(vd,"__await")?yd.resolve(vd.__await).then(function(Ed){wd("next",Ed,bd,ld)},function(Ed){wd("throw",Ed,bd,ld)}):yd.resolve(vd).then(function(Ed){hd.value=Ed,bd(hd)},function(Ed){return wd("throw",Ed,bd,ld)})}ld(ud.arg)}var Ad;Iu(this,"_invoke",{value:function(dd,bd){function ld(){return new yd(function(ud,hd){wd(dd,bd,ud,hd)})}return Ad=Ad?Ad.then(ld,ld):ld()}})}function od(_d,yd,wd){var Ad=Fu;return function(md,dd){if(Ad===Uu)throw Error("Generator is already running");if(Ad===Hu){if(md==="throw")throw dd;return{value:Au,done:!0}}for(wd.method=md,wd.arg=dd;;){var bd=wd.delegate;if(bd){var ld=sd(bd,wd);if(ld){if(ld===Vu)continue;return ld}}if(wd.method==="next")wd.sent=wd._sent=wd.arg;else if(wd.method==="throw"){if(Ad===Fu)throw Ad=Hu,wd.arg;wd.dispatchException(wd.arg)}else wd.method==="return"&&wd.abrupt("return",wd.arg);Ad=Uu;var ud=ju(_d,yd,wd);if(ud.type==="normal"){if(Ad=wd.done?Hu:zu,ud.arg===Vu)continue;return{value:ud.arg,done:wd.done}}ud.type==="throw"&&(Ad=Hu,wd.method="throw",wd.arg=ud.arg)}}}function sd(_d,yd){var wd=yd.method,Ad=_d.iterator[wd];if(Ad===Au)return yd.delegate=null,wd==="throw"&&_d.iterator.return&&(yd.method="return",yd.arg=Au,sd(_d,yd),yd.method==="throw")||wd!=="return"&&(yd.method="throw",yd.arg=new TypeError("The iterator does not provide a '"+wd+"' method")),Vu;var md=ju(Ad,_d.iterator,yd.arg);if(md.type==="throw")return yd.method="throw",yd.arg=md.arg,yd.delegate=null,Vu;var dd=md.arg;return dd?dd.done?(yd[_d.resultName]=dd.value,yd.next=_d.nextLoc,yd.method!=="return"&&(yd.method="next",yd.arg=Au),yd.delegate=null,Vu):dd:(yd.method="throw",yd.arg=new TypeError("iterator result is not an object"),yd.delegate=null,Vu)}function ad(_d){var yd={tryLoc:_d[0]};1 in _d&&(yd.catchLoc=_d[1]),2 in _d&&(yd.finallyLoc=_d[2],yd.afterLoc=_d[3]),this.tryEntries.push(yd)}function pd(_d){var yd=_d.completion||{};yd.type="normal",delete yd.arg,_d.completion=yd}function gd(_d){this.tryEntries=[{tryLoc:"root"}],_d.forEach(ad,this),this.reset(!0)}function Sd(_d){if(_d||_d===""){var yd=_d[Ou];if(yd)return yd.call(_d);if(typeof _d.next=="function")return _d;if(!isNaN(_d.length)){var wd=-1,Ad=function md(){for(;++wd<_d.length;)if(Ru.call(_d,wd))return md.value=_d[wd],md.done=!1,md;return md.value=Au,md.done=!0,md};return Ad.next=Ad}}throw new TypeError(_typeof$3(_d)+" is not iterable")}return Wu.prototype=Ku,Iu(ed,"constructor",{value:Ku,configurable:!0}),Iu(Ku,"constructor",{value:Wu,configurable:!0}),Wu.displayName=Lu(Ku,Du,"GeneratorFunction"),lo.isGeneratorFunction=function(_d){var yd=typeof _d=="function"&&_d.constructor;return!!yd&&(yd===Wu||(yd.displayName||yd.name)==="GeneratorFunction")},lo.mark=function(_d){return Object.setPrototypeOf?Object.setPrototypeOf(_d,Ku):(_d.__proto__=Ku,Lu(_d,Du,"GeneratorFunction")),_d.prototype=Object.create(ed),_d},lo.awrap=function(_d){return{__await:_d}},td(nd.prototype),Lu(nd.prototype,Mu,function(){return this}),lo.AsyncIterator=nd,lo.async=function(_d,yd,wd,Ad,md){md===void 0&&(md=Promise);var dd=new nd(Bu(_d,yd,wd,Ad),md);return lo.isGeneratorFunction(yd)?dd:dd.next().then(function(bd){return bd.done?bd.value:dd.next()})},td(ed),Lu(ed,Du,"Generator"),Lu(ed,Ou,function(){return this}),Lu(ed,"toString",function(){return"[object Generator]"}),lo.keys=function(_d){var yd=Object(_d),wd=[];for(var Ad in yd)wd.push(Ad);return wd.reverse(),function md(){for(;wd.length;){var dd=wd.pop();if(dd in yd)return md.value=dd,md.done=!1,md}return md.done=!0,md}},lo.values=Sd,gd.prototype={constructor:gd,reset:function(yd){if(this.prev=0,this.next=0,this.sent=this._sent=Au,this.done=!1,this.delegate=null,this.method="next",this.arg=Au,this.tryEntries.forEach(pd),!yd)for(var wd in this)wd.charAt(0)==="t"&&Ru.call(this,wd)&&!isNaN(+wd.slice(1))&&(this[wd]=Au)},stop:function(){this.done=!0;var yd=this.tryEntries[0].completion;if(yd.type==="throw")throw yd.arg;return this.rval},dispatchException:function(yd){if(this.done)throw yd;var wd=this;function Ad(hd,vd){return bd.type="throw",bd.arg=yd,wd.next=hd,vd&&(wd.method="next",wd.arg=Au),!!vd}for(var md=this.tryEntries.length-1;md>=0;--md){var dd=this.tryEntries[md],bd=dd.completion;if(dd.tryLoc==="root")return Ad("end");if(dd.tryLoc<=this.prev){var ld=Ru.call(dd,"catchLoc"),ud=Ru.call(dd,"finallyLoc");if(ld&&ud){if(this.prev<dd.catchLoc)return Ad(dd.catchLoc,!0);if(this.prev<dd.finallyLoc)return Ad(dd.finallyLoc)}else if(ld){if(this.prev<dd.catchLoc)return Ad(dd.catchLoc,!0)}else{if(!ud)throw Error("try statement without catch or finally");if(this.prev<dd.finallyLoc)return Ad(dd.finallyLoc)}}}},abrupt:function(yd,wd){for(var Ad=this.tryEntries.length-1;Ad>=0;--Ad){var md=this.tryEntries[Ad];if(md.tryLoc<=this.prev&&Ru.call(md,"finallyLoc")&&this.prev<md.finallyLoc){var dd=md;break}}dd&&(yd==="break"||yd==="continue")&&dd.tryLoc<=wd&&wd<=dd.finallyLoc&&(dd=null);var bd=dd?dd.completion:{};return bd.type=yd,bd.arg=wd,dd?(this.method="next",this.next=dd.finallyLoc,Vu):this.complete(bd)},complete:function(yd,wd){if(yd.type==="throw")throw yd.arg;return yd.type==="break"||yd.type==="continue"?this.next=yd.arg:yd.type==="return"?(this.rval=this.arg=yd.arg,this.method="return",this.next="end"):yd.type==="normal"&&wd&&(this.next=wd),Vu},finish:function(yd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ad=this.tryEntries[wd];if(Ad.finallyLoc===yd)return this.complete(Ad.completion,Ad.afterLoc),pd(Ad),Vu}},catch:function(yd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ad=this.tryEntries[wd];if(Ad.tryLoc===yd){var md=Ad.completion;if(md.type==="throw"){var dd=md.arg;pd(Ad)}return dd}}throw Error("illegal catch attempt")},delegateYield:function(yd,wd,Ad){return this.delegate={iterator:Sd(yd),resultName:wd,nextLoc:Ad},this.method==="next"&&(this.arg=Au),Vu}},lo}function asyncGeneratorStep(Au,lo,$u,Ru,Iu,Pu,Ou){try{var Mu=Au[Pu](Ou),Du=Mu.value}catch(Lu){$u(Lu);return}Mu.done?lo(Du):Promise.resolve(Du).then(Ru,Iu)}function _asyncToGenerator(Au){return function(){var lo=this,$u=arguments;return new Promise(function(Ru,Iu){var Pu=Au.apply(lo,$u);function Ou(Du){asyncGeneratorStep(Pu,Ru,Iu,Ou,Mu,"next",Du)}function Mu(Du){asyncGeneratorStep(Pu,Ru,Iu,Ou,Mu,"throw",Du)}Ou(void 0)})}}function _classCallCheck$3(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$3(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$3(Ru.key),Ru)}}function _createClass$3(Au,lo,$u){return lo&&_defineProperties$3(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$3(Au){var lo=_toPrimitive$3(Au,"string");return _typeof$3(lo)=="symbol"?lo:lo+""}function _toPrimitive$3(Au,lo){if(_typeof$3(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$3(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var FileReader$1=(function(){function Au(){_classCallCheck$3(this,Au)}return _createClass$3(Au,[{key:"openFile",value:(function(){var lo=_asyncToGenerator(_regeneratorRuntime().mark(function Ru(Iu,Pu){var Ou;return _regeneratorRuntime().wrap(function(Du){for(;;)switch(Du.prev=Du.next){case 0:if(!(isReactNative()&&Iu&&typeof Iu.uri<"u")){Du.next=11;break}return Du.prev=1,Du.next=4,uriToBlob(Iu.uri);case 4:return Ou=Du.sent,Du.abrupt("return",new FileSource(Ou));case 8:throw Du.prev=8,Du.t0=Du.catch(1),new Error("tus: cannot fetch `file.uri` as Blob, make sure the uri is correct and accessible. ".concat(Du.t0));case 11:if(!(typeof Iu.slice=="function"&&typeof Iu.size<"u")){Du.next=13;break}return Du.abrupt("return",Promise.resolve(new FileSource(Iu)));case 13:if(typeof Iu.read!="function"){Du.next=18;break}if(Pu=Number(Pu),Number.isFinite(Pu)){Du.next=17;break}return Du.abrupt("return",Promise.reject(new Error("cannot create source for stream without a finite value for the `chunkSize` option")));case 17:return Du.abrupt("return",Promise.resolve(new StreamSource(Iu,Pu)));case 18:return Du.abrupt("return",Promise.reject(new Error("source object may only be an instance of File, Blob, or Reader in this environment")));case 19:case"end":return Du.stop()}},Ru,null,[[1,8]])}));function $u(Ru,Iu){return lo.apply(this,arguments)}return $u})()}])})();function fingerprint(Au,lo){return isReactNative()?Promise.resolve(reactNativeFingerprint(Au,lo)):Promise.resolve(["tus-br",Au.name,Au.type,Au.size,Au.lastModified,lo.endpoint].join("-"))}function reactNativeFingerprint(Au,lo){var $u=Au.exif?hashCode(JSON.stringify(Au.exif)):"noexif";return["tus-rn",Au.name||"noname",Au.size||"nosize",$u,lo.endpoint].join("/")}function hashCode(Au){var lo=0;if(Au.length===0)return lo;for(var $u=0;$u<Au.length;$u++){var Ru=Au.charCodeAt($u);lo=(lo<<5)-lo+Ru,lo&=lo}return lo}function _typeof$2(Au){"@babel/helpers - typeof";return _typeof$2=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$2(Au)}function _classCallCheck$2(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$2(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$2(Ru.key),Ru)}}function _createClass$2(Au,lo,$u){return lo&&_defineProperties$2(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$2(Au){var lo=_toPrimitive$2(Au,"string");return _typeof$2(lo)=="symbol"?lo:lo+""}function _toPrimitive$2(Au,lo){if(_typeof$2(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$2(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var XHRHttpStack=(function(){function Au(){_classCallCheck$2(this,Au)}return _createClass$2(Au,[{key:"createRequest",value:function($u,Ru){return new Request$1($u,Ru)}},{key:"getName",value:function(){return"XHRHttpStack"}}])})(),Request$1=(function(){function Au(lo,$u){_classCallCheck$2(this,Au),this._xhr=new XMLHttpRequest,this._xhr.open(lo,$u,!0),this._method=lo,this._url=$u,this._headers={}}return _createClass$2(Au,[{key:"getMethod",value:function(){return this._method}},{key:"getURL",value:function(){return this._url}},{key:"setHeader",value:function($u,Ru){this._xhr.setRequestHeader($u,Ru),this._headers[$u]=Ru}},{key:"getHeader",value:function($u){return this._headers[$u]}},{key:"setProgressHandler",value:function($u){"upload"in this._xhr&&(this._xhr.upload.onprogress=function(Ru){Ru.lengthComputable&&$u(Ru.loaded)})}},{key:"send",value:function(){var $u=this,Ru=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null;return new Promise(function(Iu,Pu){$u._xhr.onload=function(){Iu(new Response$1($u._xhr))},$u._xhr.onerror=function(Ou){Pu(Ou)},$u._xhr.send(Ru)})}},{key:"abort",value:function(){return this._xhr.abort(),Promise.resolve()}},{key:"getUnderlyingObject",value:function(){return this._xhr}}])})(),Response$1=(function(){function Au(lo){_classCallCheck$2(this,Au),this._xhr=lo}return _createClass$2(Au,[{key:"getStatus",value:function(){return this._xhr.status}},{key:"getHeader",value:function($u){return this._xhr.getResponseHeader($u)}},{key:"getBody",value:function(){return this._xhr.responseText}},{key:"getUnderlyingObject",value:function(){return this._xhr}}])})();function _typeof$1(Au){"@babel/helpers - typeof";return _typeof$1=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$1(Au)}function _classCallCheck$1(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$1(Ru.key),Ru)}}function _createClass$1(Au,lo,$u){return lo&&_defineProperties$1(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$1(Au){var lo=_toPrimitive$1(Au,"string");return _typeof$1(lo)=="symbol"?lo:lo+""}function _toPrimitive$1(Au,lo){if(_typeof$1(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$1(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var hasStorage=!1;try{hasStorage="localStorage"in window;var key="tusSupport",originalValue=localStorage.getItem(key);localStorage.setItem(key,originalValue),originalValue===null&&localStorage.removeItem(key)}catch(Au){if(Au.code===Au.SECURITY_ERR||Au.code===Au.QUOTA_EXCEEDED_ERR)hasStorage=!1;else throw Au}var canStoreURLs=hasStorage,WebStorageUrlStorage=(function(){function Au(){_classCallCheck$1(this,Au)}return _createClass$1(Au,[{key:"findAllUploads",value:function(){var $u=this._findEntries("tus::");return Promise.resolve($u)}},{key:"findUploadsByFingerprint",value:function($u){var Ru=this._findEntries("tus::".concat($u,"::"));return Promise.resolve(Ru)}},{key:"removeUpload",value:function($u){return localStorage.removeItem($u),Promise.resolve()}},{key:"addUpload",value:function($u,Ru){var Iu=Math.round(Math.random()*1e12),Pu="tus::".concat($u,"::").concat(Iu);return localStorage.setItem(Pu,JSON.stringify(Ru)),Promise.resolve(Pu)}},{key:"_findEntries",value:function($u){for(var Ru=[],Iu=0;Iu<localStorage.length;Iu++){var Pu=localStorage.key(Iu);if(Pu.indexOf($u)===0)try{var Ou=JSON.parse(localStorage.getItem(Pu));Ou.urlStorageKey=Pu,Ru.push(Ou)}catch{}}return Ru}}])})();function _typeof(Au){"@babel/helpers - typeof";return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof(Au)}function _classCallCheck(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey(Ru.key),Ru)}}function _createClass(Au,lo,$u){return $u&&_defineProperties(Au,$u),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _callSuper(Au,lo,$u){return lo=_getPrototypeOf(lo),_possibleConstructorReturn(Au,_isNativeReflectConstruct()?Reflect.construct(lo,$u||[],_getPrototypeOf(Au).constructor):lo.apply(Au,$u))}function _possibleConstructorReturn(Au,lo){if(lo&&(_typeof(lo)==="object"||typeof lo=="function"))return lo;if(lo!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized(Au)}function _assertThisInitialized(Au){if(Au===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return Au}function _isNativeReflectConstruct(){try{var Au=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(_isNativeReflectConstruct=function(){return!!Au})()}function _getPrototypeOf(Au){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function($u){return $u.__proto__||Object.getPrototypeOf($u)},_getPrototypeOf(Au)}function _inherits(Au,lo){if(typeof lo!="function"&&lo!==null)throw new TypeError("Super expression must either be null or a function");Au.prototype=Object.create(lo&&lo.prototype,{constructor:{value:Au,writable:!0,configurable:!0}}),Object.defineProperty(Au,"prototype",{writable:!1}),lo&&_setPrototypeOf(Au,lo)}function _setPrototypeOf(Au,lo){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(Ru,Iu){return Ru.__proto__=Iu,Ru},_setPrototypeOf(Au,lo)}function ownKeys(Au,lo){var $u=Object.keys(Au);if(Object.getOwnPropertySymbols){var Ru=Object.getOwnPropertySymbols(Au);lo&&(Ru=Ru.filter(function(Iu){return Object.getOwnPropertyDescriptor(Au,Iu).enumerable})),$u.push.apply($u,Ru)}return $u}function _objectSpread(Au){for(var lo=1;lo<arguments.length;lo++){var $u=arguments[lo]!=null?arguments[lo]:{};lo%2?ownKeys(Object($u),!0).forEach(function(Ru){_defineProperty(Au,Ru,$u[Ru])}):Object.getOwnPropertyDescriptors?Object.defineProperties(Au,Object.getOwnPropertyDescriptors($u)):ownKeys(Object($u)).forEach(function(Ru){Object.defineProperty(Au,Ru,Object.getOwnPropertyDescriptor($u,Ru))})}return Au}function _defineProperty(Au,lo,$u){return lo=_toPropertyKey(lo),lo in Au?Object.defineProperty(Au,lo,{value:$u,enumerable:!0,configurable:!0,writable:!0}):Au[lo]=$u,Au}function _toPropertyKey(Au){var lo=_toPrimitive(Au,"string");return _typeof(lo)=="symbol"?lo:lo+""}function _toPrimitive(Au,lo){if(_typeof(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var defaultOptions$1=_objectSpread(_objectSpread({},BaseUpload.defaultOptions),{},{httpStack:new XHRHttpStack,fileReader:new FileReader$1,urlStorage:canStoreURLs?new WebStorageUrlStorage:new NoopUrlStorage,fingerprint}),Upload=(function(Au){function lo(){var $u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,Ru=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return _classCallCheck(this,lo),Ru=_objectSpread(_objectSpread({},defaultOptions$1),Ru),_callSuper(this,lo,[$u,Ru])}return _inherits(lo,Au),_createClass(lo,null,[{key:"terminate",value:function(Ru){var Iu=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return Iu=_objectSpread(_objectSpread({},defaultOptions$1),Iu),BaseUpload.terminate(Ru,Iu)}}])})(BaseUpload);const RUNTIMES_API_PREFIX="api/runtimes/v1";function join$1(Au,lo){return`${Au.replace(/\/+$/,"")}/${lo.replace(/^\/+/,"")}`}function runtimesUrl(Au){return join$1(Au,`${RUNTIMES_API_PREFIX}/runtimes`)}function runtimeUrl(Au,lo){return`${runtimesUrl(Au)}/${lo}`}function sandboxSnapshotsUrl(Au){return join$1(Au,`${RUNTIMES_API_PREFIX}/sandbox-snapshots`)}function sandboxSnapshotUrl(Au,lo){return`${sandboxSnapshotsUrl(Au)}/${lo}`}function asCodeSandboxSnapshot(Au){const{uid:lo,updated_at:$u,format_version:Ru,...Iu}=Au;return{...Iu,id:lo,updatedAt:new Date($u),formatVersion:Ru}}async function getEnvironments(){const Au=await requestDatalayerAPI({url:libExports$5.URLExt.join(runtimesStore.getState().runtimesUrl,"api/runtimes/v1/environments"),token:iamStore.getState().token});return Au.success?Au.environments??[]:(console.error("Failed to fetch available environments.",Au),[])}async function createRuntime(Au){const{externalToken:lo,token:$u}=iamStore.getState();if(typeof Au.creditsLimit!="number"||!Number.isFinite(Au.creditsLimit)||Au.creditsLimit<0)throw new Error(`Invalid runtime creditsLimit for environment ${Au.environmentName}. A number of zero or more is required.`);if(Au.deploymentUid&&!Au.appUid)throw new Error(`Deployment ${Au.deploymentUid} is named without its application: give appUid.`);if(Au.appUid&&!Au.appSpec)throw new Error(`Application ${Au.appUid} is launched without its Appspec: give appSpec, so its runtime is given the secrets its connections declare.`);const Ru={name:Au.environmentName};Au.environmentVersion!==void 0&&Au.environmentVersion!==""&&(Ru.version=Au.environmentVersion);const Iu={environment:Ru,type:Au.type??"notebook",given_name:Au.givenName,credits_limit:Au.creditsLimit};Au.capabilities&&(Iu.capabilities=Au.capabilities),Au.snapshot&&(Iu.from=Au.snapshot),Au.appUid&&(Iu.app_uid=Au.appUid),Au.deploymentUid&&(Iu.deployment_uid=Au.deploymentUid),Au.appSpec&&(Iu.app_spec=Au.appSpec);const Pu=await requestDatalayerAPI({url:runtimesUrl(runtimesStore.getState().runtimesUrl),method:"POST",body:Iu,token:$u,headers:lo?{"X-External-Token":lo}:void 0});if(!Pu.success||!Pu.runtime){const Ou=`Failed to create a kernel for the environment ${Au.environmentName}.`;throw console.error(Ou,Pu),new Error(Ou)}return Pu.runtime}async function getRuntimes(){const Au=await requestDatalayerAPI({url:runtimesUrl(runtimesStore.getState().runtimesUrl),token:iamStore.getState().token});if(!Au.success){const lo="Failed to list the running kernels.";throw console.error(lo,Au),new Error(lo)}return Au.runtimes??[]}async function getRuntimeRecord(Au){try{return(await requestDatalayerAPI({url:runtimeUrl(runtimesStore.getState().runtimesUrl,Au),token:iamStore.getState().token})).runtime??null}catch(lo){if(lo.response?.status===404)return null;throw lo}}async function deleteRuntime(Au){const lo=iamStore.getState().externalToken;await requestDatalayerAPI({url:runtimeUrl(runtimesStore.getState().runtimesUrl,Au.id)+libExports$5.URLExt.objectToQueryString(Au.reason?{reason:Au.reason}:{}),method:"DELETE",token:iamStore.getState().token,headers:lo?{"X-External-Token":lo}:void 0})}async function snapshotRuntime(Au){const lo=await requestDatalayerAPI({url:sandboxSnapshotsUrl(runtimesStore.getState().runtimesUrl),method:"POST",body:{runtime_name:Au.id,name:Au.name,description:Au.description,stop:Au.stop},token:iamStore.getState().token});if(!lo.success)throw new Error(`Failed to take the code sandbox snapshot ${Au.id} - ${lo}`);if(lo.snapshot)return asCodeSandboxSnapshot(lo.snapshot)}async function getSandboxSnapshots(){const Au=await requestDatalayerAPI({url:sandboxSnapshotsUrl(runtimesStore.getState().runtimesUrl),token:iamStore.getState().token});return Au.success?(Au.snapshots??[]).map(asCodeSandboxSnapshot):(console.error("Failed to fetch code sandbox snapshots.",Au),[])}async function loadSandboxSnapshot(Au){const lo=await requestDatalayerAPI({url:runtimeUrl(runtimesStore.getState().runtimesUrl,Au.id),method:"PUT",body:{from:Au.from},token:iamStore.getState().token});if(!lo.success)throw new Error(`Failed to load the code sandbox snapshot; ${lo.message}`)}function createSandboxSnapshotDownloadURL(Au){return sandboxSnapshotUrl(runtimesStore.getState().runtimesUrl,Au)+libExports$5.URLExt.objectToQueryString({download:"1",token:iamStore.getState().token??""})}function exportCodeSandboxSnapshot(Au){const lo=createSandboxSnapshotDownloadURL(Au),$u=document.createElement("a");$u.href=lo,$u.download="",document.body.appendChild($u),$u.click(),document.body.removeChild($u)}async function deleteCodeSandboxSnapshot(Au){await requestDatalayerAPI({url:sandboxSnapshotUrl(runtimesStore.getState().runtimesUrl,Au),method:"DELETE",token:iamStore.getState().token})}async function updateCodeSandboxSnapshot(Au,lo){(lo.name||lo.description)&&await requestDatalayerAPI({url:sandboxSnapshotUrl(runtimesStore.getState().runtimesUrl,Au),method:"PATCH",body:{...lo},token:iamStore.getState().token})}async function uploadCodeSandboxSnapshot(Au){if(Au.file.size===0)return Promise.reject("Empty Code Sandbox Snapshot.");const lo=new PromiseDelegate,$u=new Upload(Au.file,{endpoint:`${sandboxSnapshotsUrl(runtimesStore.getState().runtimesUrl)}/upload`,headers:{Authorization:`Bearer ${iamStore.getState().token}`},retryDelays:null,metadata:Au.metadata,onError:Iu=>{console.error(`Failed to upload ${Au.metadata.filename}.`,Iu),lo.reject(Iu)},onProgress:Au.onProgress,onSuccess:()=>{lo.resolve()}}),Ru=await $u.findPreviousUploads();return Ru.length&&$u.resumeFromPreviousUpload(Ru[0]),$u.start(),lo.promise}const actions=Object.freeze(Object.defineProperty({__proto__:null,createRuntime,createSandboxSnapshotDownloadURL,deleteCodeSandboxSnapshot,deleteRuntime,exportCodeSandboxSnapshot,getEnvironments,getRuntimeRecord,getRuntimes,getSandboxSnapshots,loadSandboxSnapshot,snapshotRuntime,updateCodeSandboxSnapshot,uploadCodeSandboxSnapshot},Symbol.toStringTag,{value:"Module"})),CLAUDE_CODE_HARNESS_0_0_1={id:"claude-code",version:"0.0.1",name:"Claude Code",description:"Anthropic's coding agent, driven over ACP through the Agent Client Protocol project's adapter on the Claude Agent SDK.",enabled:!0,tags:["harness"],docs:"https://github.com/agentclientprotocol/claude-agent-acp",acp:{command:"npx",args:["-y","@agentclientprotocol/claude-agent-acp@0.91.0"],protocolVersion:1,loadSession:!0,mcp:"lend",modes:["default","plan","acceptEdits","bypassPermissions"],env:{},nativeSession:"none"},requires:{secrets:["ANTHROPIC_API_KEY"],binaries:["node","git"]},terms:{servedToThirdParties:"api_key_only",licence:"Apache-2.0 (adapter); Anthropic Commercial Terms of Service (the agent)"},skills:{format:"skill-md",dir:".claude/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"load",forkHistory:"replay",interrupt:!0,steering:!1,images:!0,compaction:"own",modes:["default","plan","acceptEdits","bypassPermissions"],autoRun:["^(cal|uptime|cat|head|tail|wc|stat|strings|hexdump|od|nl|id|uname|free|df|du|locale|groups|nproc|basename|dirname|realpath|cut|paste|tr|column|tac|rev|fold|expand|unexpand|fmt|comm|cmp|numfmt|readlink|diff|true|false|sleep|which|type|expr|seq|tsort|pr)(\\s|$)","^(pwd|whoami|alias|history|arch|ifconfig|ip addr)(\\s|$)","^(claude (-h|--help)|node (-v|--version)|python3? --version)$","^(echo|uniq|jq|cd|ls|find)(\\s|$)","^(xargs|file|sed|sort|man|help|netstat|ps|base64|grep|egrep|fgrep|rg|sha256sum|sha1sum|md5sum|tree|date|hostname|lsof|pgrep|tput|ss|fd|fdfind|test)(\\s|$)","^git (diff|log|show|shortlog|reflog|stash (list|show)|ls-remote|status|blame|ls-files|config --get|remote( show)?|merge-base|rev-parse|rev-list|describe|cat-file|for-each-ref|grep|worktree list|tag|branch)(\\s|$)","^gh (pr (view|list|diff|checks|status)|issue (view|list|status)|repo view|run (list|view)|auth status|release (list|view)|workflow (list|view)|label list|search (repos|issues|prs|commits|code))(\\s|$)","^docker (ps|images|logs|inspect)(\\s|$)"]},instructionsFile:"CLAUDE.md",registered:{adapter:"@agentclientprotocol/claude-agent-acp",version:"0.91.0",licenceSource:"https://www.npmjs.com/package/@agentclientprotocol/claude-agent-acp",termsSource:"https://code.claude.com/docs/en/legal-and-compliance",credential:"An Anthropic API key (ANTHROPIC_API_KEY), the person's own",binaries:"Node 22 (engines.node >=22 on npm), git",note:"Anthropic's legal page (read 2026-10-15): running Claude Code in hosted sandboxes or agent infrastructure requires the Commercial Terms; each end user authenticates with their own API key or subscription; developers may not route requests through Free, Pro or Max plan credentials on behalf of their users, nor collect or intermediate Claude.ai credentials. So only API keys are taken; a subscription login is refused. The npm package moved from @zed-industries (0.23.1, March 2026) to @agentclientprotocol."}},CODEX_HARNESS_0_0_1={id:"codex",version:"0.0.1",name:"Codex",description:"OpenAI's coding agent, driven over ACP through the Agent Client Protocol project's adapter, which ships the Codex binary it drives.",enabled:!0,tags:["harness"],docs:"https://github.com/agentclientprotocol/codex-acp",acp:{command:"npx",args:["-y","@agentclientprotocol/codex-acp@2.2.2"],protocolVersion:1,loadSession:!0,mcp:"lend",modes:["read-only","workspace-write","agent","agent-full-access"],env:{NO_BROWSER:"1"},nativeSession:"none"},requires:{secrets:["OPENAI_API_KEY"],binaries:["node","git"]},terms:{servedToThirdParties:"api_key_only",licence:"Apache-2.0 (adapter); OpenAI Terms of Use (the agent)"},skills:{format:"skill-md",dir:".agents/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"load",forkHistory:"replay",interrupt:!0,steering:!1,images:!0,compaction:"own",modes:["read-only","workspace-write","agent","agent-full-access"],autoRun:[]},instructionsFile:"AGENTS.md",registered:{adapter:"@agentclientprotocol/codex-acp",version:"2.2.2",licenceSource:"https://www.npmjs.com/package/@agentclientprotocol/codex-acp",termsSource:"https://learn.chatgpt.com/docs/auth",credential:"An OpenAI API key (OPENAI_API_KEY or CODEX_API_KEY), the person's own",binaries:"Node 22 (as the Agent Client Protocol project's adapters; unstated on npm), git",note:"Codex's authentication page (read 2026-10-15) recommends API keys for automation and device-code login for headless machines; a ChatGPT login needs a browser and is hidden with NO_BROWSER=1 in the adapter. Only API keys are taken; a ChatGPT login is refused. The Zed-scoped package was archived on 22 July 2026 and names this one."}},CUSTOM_HARNESS_0_0_1={id:"custom",version:"0.0.1",name:"Custom harness",description:"An organization's own ACP agent, its command named by the organization's own harness spec and never typed into a form.",enabled:!1,tags:["harness"],docs:"",requires:{secrets:[],binaries:[]},terms:{servedToThirdParties:"organizations_own",licence:"The organization's own"},skills:{format:"none",dir:""},honours:{model:!1,subagents:!1},capabilities:{resume:"none",forkHistory:"none",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:[],autoRun:[]},instructionsFile:"",registered:{adapter:"The organization's own",version:"0",licenceSource:"https://agentspecs.datalayer.tech/harnesses",termsSource:"https://agentspecs.datalayer.tech/harnesses",credential:"The organization's own",binaries:"",note:"Not launchable from the shared catalogue; an organization's own harness spec names the command and answers for its terms."}},FAST_AGENT_HARNESS_0_0_1={id:"fast-agent",version:"0.0.1",name:"fast-agent",description:"llmindset's agent framework served over ACP; each agent it defines is a session mode, with any model provider it is configured with.",enabled:!0,tags:["harness","framework"],docs:"https://github.com/evalstate/fast-agent/blob/main/docs/docs/acp/index.md",acp:{command:"uvx",args:["fast-agent-acp==0.10.45"],protocolVersion:1,loadSession:!0,mcp:"lend",modes:[],env:{},nativeSession:"none"},requires:{secrets:["ANTHROPIC_API_KEY"],binaries:["uvx"]},terms:{servedToThirdParties:"permitted",licence:"Apache-2.0"},skills:{format:"skill-md",dir:".agents/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"load",forkHistory:"replay",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:[],autoRun:[]},instructionsFile:"AGENTS.md",registered:{adapter:"fast-agent-acp",version:"0.10.45",licenceSource:"https://pypi.org/project/fast-agent-acp/",termsSource:"https://github.com/evalstate/fast-agent/blob/main/LICENSE",credential:"The provider's key fast-agent is given (ANTHROPIC_API_KEY, OPENAI_API_KEY or HF_TOKEN); ANTHROPIC_API_KEY declared",binaries:"uv (uvx), Python 3.12 to 3.15 (requires_python on PyPI)",note:"A framework, not a coding agent: each agent it defines is an ACP mode; the client's MCP servers are attached; sessions are listed. Launched with uvx fast-agent-acp (docs/docs/acp/index.md); reads skills from .fast-agent/skills, .agents/skills and .claude/skills; its default prompt reads AGENTS.md."}},GEMINI_CLI_HARNESS_0_0_1={id:"gemini-cli",version:"0.0.1",name:"Gemini CLI",description:"Google's coding agent, which speaks ACP itself when started with --experimental-acp.",enabled:!0,tags:["harness"],docs:"https://github.com/google-gemini/gemini-cli/blob/main/docs/cli/cli-reference.md",acp:{command:"npx",args:["-y","@google/gemini-cli@0.64.0","--experimental-acp"],protocolVersion:1,loadSession:!1,mcp:"lend",modes:["default","auto_edit","yolo","plan"],env:{},nativeSession:"none"},requires:{secrets:["GEMINI_API_KEY"],binaries:["node","git"]},terms:{servedToThirdParties:"api_key_only",licence:"Apache-2.0 (the agent); Gemini API or Gemini Code Assist terms (the model)",tierRestrictions:"Gemini Code Assist Standard or Enterprise for a Google login (the individuals tier stopped being served on 18 June 2026); a Gemini API key otherwise"},skills:{format:"skill-md",dir:".gemini/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"none",forkHistory:"replay",interrupt:!0,steering:!1,images:!0,compaction:"own",modes:["default","auto_edit","yolo","plan"],autoRun:[]},instructionsFile:"GEMINI.md",registered:{adapter:"@google/gemini-cli",version:"0.64.0",licenceSource:"https://www.npmjs.com/package/@google/gemini-cli",termsSource:"https://developers.google.com/gemini-code-assist/resources/privacy-notice-gemini-code-assist-individuals",credential:"A Gemini API key (GEMINI_API_KEY), the person's own; or a Google login on a Code Assist Standard or Enterprise subscription",binaries:"Node 20 or later (engines.node >=20 on npm), git",note:`Google's notice (read 2026-10-15): "Starting June 18, 2026, Gemini Code Assist IDE extensions stopped serving requests for the Gemini Code Assist for individuals"; Standard and Enterprise follow a separate schedule. The ACP flag is --experimental-acp in the CLI reference (docs/cli/cli-reference.md).`}},GOOSE_HARNESS_0_0_1={id:"goose",version:"0.0.1",name:"goose",description:"Block's open agent (now the Agentic AI Foundation's), which speaks ACP itself with goose acp; any model provider it is configured with.",enabled:!0,tags:["harness"],docs:"https://block.github.io/goose/docs/gdk/acp/",acp:{command:"goose",args:["acp"],protocolVersion:1,loadSession:!1,mcp:"lend",modes:[],env:{GOOSE_PROVIDER:"anthropic"},nativeSession:"none"},requires:{secrets:["ANTHROPIC_API_KEY"],binaries:["goose@1.54.0","git"]},terms:{servedToThirdParties:"permitted",licence:"Apache-2.0"},skills:{format:"skill-md",dir:".agents/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"none",forkHistory:"replay",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:[],autoRun:[]},instructionsFile:".goosehints",registered:{adapter:"goose",version:"1.54.0",licenceSource:"https://github.com/aaif-goose/goose",termsSource:"https://github.com/aaif-goose/goose/blob/main/LICENSE",credential:"The provider's key goose is configured with (GOOSE_PROVIDER); ANTHROPIC_API_KEY declared",binaries:"The goose CLI (release v1.54.0 of 8 October 2026), git",note:"Open source under Apache-2.0, no vendor terms of its own; the model provider's terms apply to the key. Launched as goose acp (documentation/docs/gdk/acp/index.md)."}},OPENCODE_HARNESS_0_0_1={id:"opencode",version:"0.0.1",name:"OpenCode",description:"Anomaly's open coding agent, which speaks ACP itself with opencode acp; any model provider it is configured with.",enabled:!0,tags:["harness"],docs:"https://opencode.ai/docs/acp/",acp:{command:"npx",args:["-y","opencode-ai@1.19.0","acp"],protocolVersion:1,loadSession:!1,mcp:"lend",modes:[],env:{},nativeSession:"none"},requires:{secrets:["ANTHROPIC_API_KEY"],binaries:["node","git"]},terms:{servedToThirdParties:"permitted",licence:"MIT"},skills:{format:"skill-md",dir:".opencode/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"none",forkHistory:"replay",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:[],autoRun:[]},instructionsFile:"AGENTS.md",registered:{adapter:"opencode-ai",version:"1.19.0",licenceSource:"https://www.npmjs.com/package/opencode-ai",termsSource:"https://github.com/anomalyco/opencode/blob/dev/LICENSE",credential:"The provider's key OpenCode is configured with; ANTHROPIC_API_KEY declared",binaries:"Node (the opencode-ai package), git",note:"Open source under MIT, no vendor terms of its own; the model provider's terms apply to the key. Launched as opencode acp (opencode.ai/docs/acp); reads skills from .opencode/skills, .claude/skills and .agents/skills."}},OPENHANDS_HARNESS_0_0_1={id:"openhands",version:"0.0.1",name:"OpenHands",description:"The OpenHands CLI, which speaks ACP itself with openhands acp; any model provider it is configured with.",enabled:!0,tags:["harness"],docs:"https://docs.openhands.dev/openhands/usage/run-openhands/acp",acp:{command:"uvx",args:["--from","openhands==1.16.0","openhands","acp","--override-with-envs"],protocolVersion:1,loadSession:!0,mcp:"lend",modes:["always-ask","always-approve","llm-approve"],env:{},nativeSession:"none"},requires:{secrets:["LLM_API_KEY"],binaries:["uvx","git"]},terms:{servedToThirdParties:"permitted",licence:"MIT"},skills:{format:"skill-md",dir:".agents/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"load",forkHistory:"replay",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:["always-ask","always-approve","llm-approve"],autoRun:[]},instructionsFile:"AGENTS.md",registered:{adapter:"openhands",version:"1.16.0",licenceSource:"https://pypi.org/project/openhands/",termsSource:"https://github.com/OpenHands/OpenHands-CLI/blob/main/LICENSE",credential:"The provider's key OpenHands reads as LLM_API_KEY, with LLM_MODEL, under --override-with-envs",binaries:"uv (uvx), Python 3.12 or later, git",note:"Open source under MIT, no vendor terms of its own; the model provider's terms apply to the key. Launched as openhands acp (OpenHands-CLI README; docs.openhands.dev's ACP page); resumes with --resume; reads skills from .agents/skills (.openhands/skills is legacy)."}},HARNESS_CATALOGUE={"claude-code":CLAUDE_CODE_HARNESS_0_0_1,codex:CODEX_HARNESS_0_0_1,custom:CUSTOM_HARNESS_0_0_1,"fast-agent":FAST_AGENT_HARNESS_0_0_1,"gemini-cli":GEMINI_CLI_HARNESS_0_0_1,goose:GOOSE_HARNESS_0_0_1,opencode:OPENCODE_HARNESS_0_0_1,openhands:OPENHANDS_HARNESS_0_0_1};function listHarnesses(){return Object.values(HARNESS_CATALOGUE)}const AGENT_RUNTIME_VARIANTS=["browser-vercelai","local-pydanticai","cloud-pydanticai"],DEFAULT_AGENT_RUNTIME_VARIANT="cloud-pydanticai",VARIANT_BY_LEGACY_TARGET={"backend-services":"cloud-pydanticai","local-agent-runtimes":"local-pydanticai"};function isAgentRuntimeVariant(Au){return typeof Au=="string"&&AGENT_RUNTIME_VARIANTS.includes(Au)}function toAgentRuntimeVariant(Au,lo=DEFAULT_AGENT_RUNTIME_VARIANT){return Au?isAgentRuntimeVariant(Au)?Au:VARIANT_BY_LEGACY_TARGET[Au]??lo:lo}function locationOf(Au){return Au.slice(0,Au.indexOf("-"))}function runsInBrowser(Au){return locationOf(Au)==="browser"}function legacyTargetOf(Au){return locationOf(Au)==="cloud"?"backend-services":"local-agent-runtimes"}const runtimesStore=createStore$1((Au,lo)=>({configuration:{maxNotebookRuntimes:5,maxCellRuntimes:3},setConfiguration:$u=>{Au(Ru=>JSONExt.deepEqual(Ru.configuration,$u)?{}:{configuration:{...$u}})},runtimesUrl:coreStore.getState().configuration?.runtimesUrl,tab:0,getIntTab:()=>Math.floor(lo().tab),setTab:$u=>Au(Ru=>({tab:$u})),runtimes:[],refreshRuntimes:async()=>{const $u=await getRuntimes();JSONExt.deepEqual(lo().runtimes,$u)||Au({runtimes:[...$u]})},removeRuntime:$u=>{if(!$u)return;const Ru=lo().runtimes,Iu=Ru.filter(Pu=>Pu.runtime_name!==$u);Iu.length!==Ru.length&&Au({runtimes:Iu})},runtimeModels:[],addRuntimeModel:$u=>{const Ru=lo().runtimeModels;Ru.findIndex(Pu=>$u.id&&$u.id===Pu.id||!!$u.uid&&$u.uid===Pu.uid)<0&&Au({runtimeModels:[...Ru,$u]})},removeRuntimeModel:$u=>{const Ru=[...lo().runtimeModels],Iu=Ru?.findIndex(Pu=>!!Pu.id&&$u===Pu.id||$u===Pu.runtime_name)??-1;Iu>=0&&(Ru.splice(Iu,1),Au({runtimeModels:Ru}))},setRuntimeModels:$u=>{JSONExt.deepEqual(lo().runtimeModels,$u)||Au({runtimeModels:[...$u]})},multiServiceManager:void 0,setMultiServiceManager:$u=>{Au(Ru=>({multiServiceManager:$u}))},showDisclaimer:!1,setShowDisclaimer:$u=>{Au(Ru=>({showDisclaimer:$u}))},runtimeSnapshots:[],addSandboxSnapshot:$u=>{const Ru=lo().runtimeSnapshots,Iu=Ru.findIndex(Pu=>Pu.id===$u.id);if(Iu<0){const Pu=[...Ru,$u];Au({runtimeSnapshots:Pu})}else if(!JSONExt.deepEqual(Ru[Iu],$u)){const Pu=[...Ru];Pu.splice(Iu,1,$u),Au({runtimeSnapshots:Pu})}},removeSandboxSnapshot:$u=>{const Ru=lo().runtimeSnapshots,Iu=Ru.findIndex(Pu=>Pu.id===$u);if(Iu>=0){const Pu=[...Ru];Pu.splice(Iu,1),Au({runtimeSnapshots:Pu})}},setSandboxSnapshots:$u=>{JSONExt.deepEqual(lo().runtimeSnapshots,$u)||Au({runtimeSnapshots:[...$u]})},version:"",setVersion:$u=>{$u&&!lo().version&&Au(Ru=>({version:$u}))}})),kernelsPoll=new Poll({auto:!0,factory:()=>runtimesStore.getState().refreshRuntimes(),frequency:{interval:61*1e3,backoff:!0,max:300*1e3},name:"@datalayer/jupyter-kernels:KernelsManager#kernels",standby:()=>iamStore.getState().token||runtimesStore.getState().runtimesUrl?"when-hidden":!0});runtimesStore.subscribe((Au,lo)=>{if(!JSONExt.deepEqual(Au.runtimes,lo.runtimes)){const $u=Date.now(),Ru=Math.min(...Au.runtimes.map(Iu=>Iu.expired_at?parseFloat(Iu.expired_at):1/0))*1e3;$u+kernelsPoll.frequency.interval>Ru+2e3&&setTimeout(()=>{kernelsPoll.refresh()},Ru+2e3-$u)}});coreStore.subscribe((Au,lo)=>{if(Au.configuration.runtimesUrl&&Au.configuration.runtimesUrl!==lo.configuration.runtimesUrl){const $u=Au.configuration.runtimesUrl;console.log(`Updating runtimesUrl with new value ${$u}`),runtimesStore.setState({runtimesUrl:$u}),kernelsPoll.refresh().then(()=>kernelsPoll.tick).catch(Ru=>{console.error("Failed to refresh kernel servers list following service URL changed.",Ru)})}});function useRuntimesStore(Au){return useStore$1(runtimesStore,Au)}const DEFAULT_AGENT_CONFIG={name:"ai-agent",description:"AI Assistant",model:"",systemPrompt:"You are a helpful AI assistant.",agentLibrary:"pydantic-ai",protocol:"vercel-ai"};requireManager();const sandboxManagersByRuntime=new Map;function registerSandboxServiceManager(Au,lo){const $u=String(Au||"").trim();if(!$u||!lo)return()=>{};let Ru=sandboxManagersByRuntime.get($u);return Ru||(Ru=new Set,sandboxManagersByRuntime.set($u,Ru)),Ru.add(lo),()=>{const Iu=sandboxManagersByRuntime.get($u);Iu&&(Iu.delete(lo),Iu.size===0&&sandboxManagersByRuntime.delete($u))}}function disposeSandboxServiceManagers(Au){const lo=String(Au||"").trim();if(!lo)return;const $u=sandboxManagersByRuntime.get(lo);$u&&(sandboxManagersByRuntime.delete(lo),$u.forEach(Ru=>{try{disposeServiceManager(Ru)}catch(Iu){console.warn(`[sandboxServiceManagers] Failed disposing service manager for pod ${lo}`,Iu)}}))}function launchesOwnRoutesOnly(Au){return!!Au?.deploymentUid}const base$2=Au=>Au.trim().replace(/\/$/,"");function agentDeletionUrl(Au,lo,$u){if(!$u)return`${base$2(Au)}/api/v1/agents/${encodeURIComponent(lo)}`}function runtimeModelsUrl(Au,lo,$u){if(!$u)return`${base$2(Au)}/api/v1/configure/models?agent_id=${encodeURIComponent(lo)}`}const EMPTY_RUNTIMES=[],BROWSER_AGENT_CONNECTION=Object.freeze({runtimeName:"",environmentName:"",jupyterBaseUrl:"",agentBaseUrl:"",status:"ready",isReady:!0}),AGENT_QUERY_OPTIONS={staleTime:300*1e3,gcTime:600*1e3},agentQueryKeys={agentRuntimes:{all:()=>["agentRuntimes"],lists:()=>[...agentQueryKeys.agentRuntimes.all(),"list"],details:()=>[...agentQueryKeys.agentRuntimes.all(),"detail"],detail:Au=>[...agentQueryKeys.agentRuntimes.details(),Au]},checkpoints:{all:()=>["checkpoints"],lists:()=>[...agentQueryKeys.checkpoints.all(),"list"]}},DELETED_POD_TOMBSTONE_TTL_MS=300*1e3,deletedRuntimeTombstones=new Map;function markRuntimeDeleted(Au){const lo=String(Au||"").trim();lo&&(deletedRuntimeTombstones.set(lo,Date.now()),disposeSandboxServiceManagers(lo))}function clearRuntimeDeleted(Au){deletedRuntimeTombstones.delete(String(Au||"").trim())}const LIVE_RUNTIME_STATUSES=new Set(["running","resumed","starting","resuming"]);function isStaleDeletedRuntime(Au){const lo=String(Au?.runtime_name||"").trim(),$u=deletedRuntimeTombstones.get(lo);return $u===void 0?!1:Date.now()-$u>DELETED_POD_TOMBSTONE_TTL_MS?(deletedRuntimeTombstones.delete(lo),!1):LIVE_RUNTIME_STATUSES.has(Au.status)}const RUNTIME_STATUS_MAP={resume:"resumed",resumed:"resumed",resuming:"resuming",pausing:"pausing",paused:"paused",starting:"starting",pending:"starting",launching:"starting",terminated:"terminated",archived:"archived",running:"running"};function toAgentRuntimeData(Au){const lo=typeof Au.status=="string"?Au.status.toLowerCase():"",$u=RUNTIME_STATUS_MAP[lo]??"running",Ru=Au.environment;return{...Au,environment:{name:String(Ru?.name||"").trim(),title:String(Ru?.title||"").trim()||void 0,cpu:String(Ru?.cpu||"").trim()||void 0,memory:String(Ru?.memory||"").trim()||void 0,gpu:String(Ru?.gpu||"").trim()||void 0,resources:Ru?.resources},status:$u,name:Au.given_name||Au.runtime_name,id:Au.runtime_name,url:Au.ingress,messageCount:0,agent_spec_id:Au.agent_spec_id||void 0,content_attachments:Array.isArray(Au.content_attachments)?Au.content_attachments:[]}}function useAgentRuntimes(Au={}){const{agentSpecId:lo,agentConfig:$u,autoCreateAgent:Ru=!0,autoStart:Iu=!1,agentSpec:Pu,variant:Ou,runtimeCreationTarget:Mu,runtimeCreationBaseUrl:Du,runtimeConnection:Lu,appLaunch:Bu}=Au,ju=toAgentRuntimeVariant(Ou??Mu),Fu=launchesOwnRoutesOnly(Bu),{configuration:zu}=useCoreStore(),Uu=useAgentRuntimeConnection(),Hu=useAgentRuntimeStatus(),Vu=useAgentRuntimeError(),Gu=useAgentRuntimeIsLaunching(),Wu=useAgentRuntimeStore($d=>$d.launchAgent),Ku=useAgentRuntimeStore($d=>$d.connectAgent),Ju=useAgentRuntimeStore($d=>$d.createAgent),Yu=useAgentRuntimeStore($d=>$d.disconnect),[Xu,ed]=reactExports.useState("idle"),[td,nd]=reactExports.useState(null),[od,sd]=reactExports.useState(!1),ad=reactExports.useRef(!1),[pd,gd]=reactExports.useState(!1),Sd=reactExports.useRef(!1),_d=reactExports.useRef(null),yd=reactExports.useRef(!1),wd=reactExports.useRef($u);wd.current=$u;const Ad=!!lo&&locationOf(ju)==="cloud",md=Lu?[Lu.runtimeName,Lu.environmentName,Lu.jupyterBaseUrl||Lu.serviceManager?.serverSettings.baseUrl||"",Lu.kernelId||""].join(":"):null,dd=reactExports.useMemo(()=>Du||(runsInBrowser(ju)?"":locationOf(ju)==="local"?"http://localhost:8765":zu?.runtimesUrl||void 0||"https://r1.datalayer.run"),[zu?.runtimesUrl,Du,ju]),bd=reactExports.useCallback(async()=>{try{const{iamStore:$d,coreStore:Id}=await __vitePreload(async()=>{const{iamStore:Yd,coreStore:mh}=await import("./chunks/index-CeTMYE1j.js");return{iamStore:Yd,coreStore:mh}},[],import.meta.url),qd=$d.getState().token||"",Wd=Id.getState().configuration?.aiAgentsUrl||"";return{token:qd,aiAgentsUrl:Wd,runtimesUrl:dd}}catch{return{token:"",aiAgentsUrl:"",runtimesUrl:""}}},[dd]);reactExports.useEffect(()=>{!Lu||!md||(Uu?[Uu.runtimeName,Uu.environmentName,Uu.jupyterBaseUrl||"",Uu.kernelId||""].join(":"):null)===md||(Sd.current=!1,Ku(Lu))},[Lu,md,Uu,Ku]);const ld=reactExports.useCallback(async $d=>{if(runsInBrowser(ju))return BROWSER_AGENT_CONNECTION;if(Ad){ed("launching"),nd(null);try{const qd=(typeof $u?.name=="string"&&$u.name||typeof Pu?.name=="string"&&Pu.name||`${lo}`).replace(/\//g,"-").replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,63),Md=await Wu($d?{...$d,...Bu,runtimesUrl:dd}:{environmentName:"ai-agents-env",creditsLimit:10,givenName:qd,...Bu,runtimesUrl:dd});return ed("ready"),Md}catch(Id){const qd=Id instanceof Error?Id.message:String(Id);throw nd(qd),ed("error"),Id}}else{if(!$d)throw new Error("Runtime options are required in connect mode");return Wu({...$d,runtimesUrl:dd})}},[$u?.name,Pu?.name,lo,Bu,Ad,dd,Wu,ju]),ud=reactExports.useCallback(async $d=>{if(yd.current)throw new Error("Agent creation already in progress");yd.current=!0,sd(!0);try{const Id={};Pu&&(Pu.model&&(Id.model=Pu.model),Pu.protocol&&(Id.protocol=Pu.protocol),Pu.systemPrompt&&(Id.systemPrompt=Pu.systemPrompt),Pu.description&&(Id.description=Pu.description),Pu.name&&(Id.name=Pu.name));const qd={...DEFAULT_AGENT_CONFIG,...Id,...$u,...$d,name:$d?.name||$u?.name||(Ad&&lo?lo:Uu?.runtimeName)};return await Ju(qd)}catch(Id){const qd=Id instanceof Error?Id.message:String(Id);throw Ad&&(nd(qd),ed("error")),Id}finally{yd.current=!1,sd(!1)}},[lo,$u,Pu,Ad,Uu,Ju]),hd=reactExports.useCallback(async()=>{const $d=Uu?.agentId,Id=Uu?.agentBaseUrl,qd=$d&&Id?agentDeletionUrl(Id,$d,Fu):void 0;if(qd)try{const{token:Md}=await bd();await fetch(qd,{method:"DELETE",headers:Md?{Authorization:`Bearer ${Md}`}:{}})}catch{}Sd.current=!1,ad.current=!1,ed("idle"),nd(null),agentRuntimeStore.getState().reset()},[Uu?.agentId,Uu?.agentBaseUrl,bd,Fu]);reactExports.useEffect(()=>{!Ad&&Ru&&Uu&&Hu==="ready"&&!Uu.isReady&&!Sd.current&&(Sd.current=!0,Ju(wd.current).catch($d=>{console.error("[useAgent] Failed to auto-create agent:",$d),Sd.current=!1}))},[Ad,Ru,Uu,Hu,Ju]),reactExports.useEffect(()=>{Ad&&Ru&&Uu&&(Xu==="ready"||Xu==="resumed")&&!Uu.isReady&&!Sd.current&&(Sd.current=!0,ud(wd.current).catch($d=>{console.error("[useAgents] Failed to auto-create agent:",$d);const Id=$d instanceof Error?$d.message:String($d);nd(Id),ed("error"),Sd.current=!1}))},[Ad,Ru,Uu,Xu,ud]),reactExports.useEffect(()=>{const $d=Uu?.runtimeName||null;if(!$d){_d.current=null;return}_d.current&&_d.current!==$d&&(Sd.current=!1),_d.current=$d},[Uu?.runtimeName]),reactExports.useEffect(()=>{if(!Ad||Uu||Xu!=="idle")return;if(Bu){gd(!0);return}let $d=!1;return(async()=>{try{const{token:qd,runtimesUrl:Md}=await bd();if(!qd)return;const{listRuntimes:Wd}=await __vitePreload(async()=>{const{listRuntimes:ah}=await import("./chunks/runtimes-DGW2aYMb.js");return{listRuntimes:ah}},[],import.meta.url),oh=((await Wd(qd,Md)).runtimes||[]).filter(ah=>ah.environment?.name!=="ai-agents-env"?!1:lo?ah.agent_spec_id===lo:!0).slice().sort((ah,Oh)=>{const Gd=Number(ah.started_at||0);return Number(Oh.started_at||0)-Gd})[0];if($d||!oh?.runtime_name||!oh?.ingress)return;Ku({runtimeName:oh.runtime_name,environmentName:oh.environment.name,jupyterBaseUrl:oh.ingress}),Sd.current=!1;const yh=oh,gh=typeof yh.status=="string"?yh.status.toLowerCase():"",Xd=RUNTIME_STATUS_MAP[gh]??"running",eh=Xd==="paused"?"paused":Xd==="resuming"||Xd==="resumed"?"resumed":"running";ed(eh==="paused"?"paused":eh==="resumed"?"resumed":"ready")}catch(qd){console.warn("[useAgents] Failed to find existing runtime:",qd)}finally{$d||gd(!0)}})(),()=>{$d=!0}},[Ad,Uu,Iu,Xu,bd,lo,Bu,Ku]),reactExports.useEffect(()=>{(Hu==="disconnected"||Hu==="idle")&&(Sd.current=!1)},[Hu]),reactExports.useEffect(()=>{Ad&&Iu&&pd&&!Uu&&!ad.current&&Xu==="idle"&&(ad.current=!0,ld())},[Ad,Iu,pd,Uu,Xu,ld]),reactExports.useEffect(()=>{Vu&&Ad&&Xu!=="error"&&(nd(Vu),ed("error"))},[Vu,Ad,Xu]);const vd=runsInBrowser(ju),Ed=vd?"ready":Ad?Xu:Hu,Cd=vd?null:Ad&&td||Vu,Rd=vd?!0:Ad?(Xu==="ready"||Xu==="resumed")&&!!Uu?.isReady:Hu==="ready"&&!!Uu?.isReady,jd=Uu?.endpoint||null,Td=Uu?.serviceManager||null;return{runtime:Uu,status:Ed,isLaunching:Gu,launchRuntime:ld,connectToRuntime:Ku,disconnect:Yu,endpoint:jd,serviceManager:Td,createAgent:ud,teardown:hd,isCreating:od,isReady:Rd,error:Cd,variant:ju,runtimeCreationTarget:legacyTargetOf(ju),runtimeCreationBaseUrl:dd}}function useAgentRuntimesQuery(Au,lo){const{configuration:$u}=useCoreStore(),{requestDatalayer:Ru}=useDatalayer({notifyOnError:!1}),{user:Iu}=useIAMStore(),Pu=useQueryClient();return useQuery({queryKey:[...agentQueryKeys.agentRuntimes.lists(),"","","",""],queryFn:async()=>{const Mu=new URLSearchParams().toString(),Du=await Ru({url:`${runtimesUrl($u.runtimesUrl)}${Mu?`?${Mu}`:""}`,method:"GET"});if(Du.success&&Du.runtimes){const Lu=Du.runtimes.filter(Bu=>Bu.environment?.name==="ai-agents-env").map(toAgentRuntimeData).filter(Bu=>!isStaleDeletedRuntime(Bu));return Lu.forEach(Bu=>{Pu.setQueryData(agentQueryKeys.agentRuntimes.detail(Bu.runtime_name),Bu)}),Lu}return[]},...AGENT_QUERY_OPTIONS,refetchInterval:lo?.refetchInterval??1e4,refetchOnMount:!0,refetchOnWindowFocus:!0,enabled:(lo?.enabled??!0)&&!!Iu})}function useCreateAgentRuntime(){const{configuration:Au}=useCoreStore(),{requestDatalayer:lo}=useDatalayer({notifyOnError:!1}),$u=useQueryClient();return useMutation({mutationFn:async Ru=>{const Iu=(Ru.contentAttachmentUids??[]).map(Pu=>String(Pu||"").trim()).filter(Boolean);return lo({url:runtimesUrl(Au.runtimesUrl),method:"POST",body:{environment:{name:Ru.environmentName||"ai-agents-env"},given_name:Ru.givenName||"Agent",credits_limit:Ru.creditsLimit||10,type:Ru.type||"notebook",editor_variant:Ru.editorVariant||"none",enable_codemode:Ru.enableCodemode??!1,agent_spec_id:Ru.agentSpecId||void 0,agent_spec:Ru.agentSpec||void 0,user_account_handle:Ru.userAccountHandle||void 0,billing_entity_uid:Ru.billingEntityUid||void 0,billing_entity_type:Ru.billingEntityType||void 0,billing_entity_handle:Ru.billingEntityHandle||void 0,billing_source_organization_uid:Ru.billingSourceOrganizationUid||void 0,billing_source_organization_handle:Ru.billingSourceOrganizationHandle||void 0,runtime_name:Ru.runtimeName||void 0,content_attachment_uids:Iu.length?Iu:void 0}})},onSuccess:Ru=>{if(Ru.success&&Ru.runtime){const Iu=toAgentRuntimeData(Ru.runtime);clearRuntimeDeleted(Iu.runtime_name),$u.setQueryData(agentQueryKeys.agentRuntimes.detail(Iu.runtime_name),Iu),$u.invalidateQueries({queryKey:agentQueryKeys.agentRuntimes.all()})}}})}function useDeleteAgentRuntime(){const{configuration:Au}=useCoreStore(),{requestDatalayer:lo}=useDatalayer({notifyOnError:!1}),$u=useQueryClient(),Ru=Pu=>{if(!Pu||typeof Pu!="object")return;const Ou=Pu.response;return typeof Ou?.status=="number"?Ou.status:void 0},Iu=Pu=>{if(!Pu||typeof Pu!="object")return"";const Ou=Pu.response?.data;return String(Ou?.detail||Ou?.message||Pu.message||"").toLowerCase()};return useMutation({mutationFn:async Pu=>{try{return await lo({url:runtimeUrl(Au.runtimesUrl,Pu),method:"DELETE"})}catch(Ou){const Mu=Ru(Ou),Du=Iu(Ou);if(!(Mu===404||Du.includes("no reservation")||Du.includes("unknown reservation")||Du.includes("not found")))throw Ou;try{throw await lo({url:runtimeUrl(Au.runtimesUrl,Pu),method:"GET"}),Ou}catch(Bu){if(Ru(Bu)===404)return{success:!0,recovered:!0};throw Ou}}},onSuccess:(Pu,Ou)=>{markRuntimeDeleted(Ou),runtimesStore.getState().removeRuntime(Ou),$u.setQueriesData({queryKey:agentQueryKeys.agentRuntimes.lists()},Mu=>Array.isArray(Mu)?Mu.filter(Du=>Du.runtime_name!==Ou):Mu),$u.cancelQueries({queryKey:agentQueryKeys.agentRuntimes.detail(Ou)}),$u.removeQueries({queryKey:agentQueryKeys.agentRuntimes.detail(Ou)}),$u.invalidateQueries({queryKey:agentQueryKeys.agentRuntimes.lists()}),$u.refetchQueries({queryKey:agentQueryKeys.agentRuntimes.lists(),type:"active"}),$u.invalidateQueries({queryKey:agentQueryKeys.checkpoints.all()})}})}function useRefreshAgentRuntimes(){const Au=useQueryClient();return reactExports.useCallback(()=>{Au.invalidateQueries({queryKey:agentQueryKeys.agentRuntimes.all()})},[Au])}const DEFAULT_LIFECYCLE_RECORD={resumePending:!1,pauseLockedForResumed:!1};create$g()(persist((Au,lo)=>({byRuntimeKey:{},markResumePending:$u=>{$u&&Au(Ru=>({byRuntimeKey:{...Ru.byRuntimeKey,[$u]:{...DEFAULT_LIFECYCLE_RECORD,...Ru.byRuntimeKey[$u]??{},resumePending:!0}}}))},markResumeFailed:$u=>{$u&&Au(Ru=>({byRuntimeKey:{...Ru.byRuntimeKey,[$u]:{...DEFAULT_LIFECYCLE_RECORD,...Ru.byRuntimeKey[$u]??{},resumePending:!1,pauseLockedForResumed:!1}}}))},markResumeSettled:$u=>{$u&&Au(Ru=>({byRuntimeKey:{...Ru.byRuntimeKey,[$u]:{...DEFAULT_LIFECYCLE_RECORD,...Ru.byRuntimeKey[$u]??{},resumePending:!1,pauseLockedForResumed:!0}}}))},clearRuntimeLifecycle:$u=>{if(!$u)return;const Ru={...lo().byRuntimeKey};delete Ru[$u],Au({byRuntimeKey:Ru})}}),{name:"datalayer-agent-lifecycle",storage:createJSONStorage(()=>localStorage),partialize:Au=>({byRuntimeKey:Au.byRuntimeKey})}));function useAgentsRuntimes(Au,lo){const $u=useAgentRuntimesQuery(Au,lo),Ru=useCreateAgentRuntime(),Iu=useDeleteAgentRuntime(),Pu=useRefreshAgentRuntimes(),Ou=reactExports.useCallback(async(Mu,Du)=>{const Lu=String(Mu||"").trim();if(Lu)return Du?.beforeStop&&await Du.beforeStop(),Iu.mutateAsync(Lu)},[Iu]);return reactExports.useMemo(()=>({runtimes:$u.data??EMPTY_RUNTIMES,isRuntimesLoading:$u.isLoading,isRuntimesError:$u.isError,runtimesError:$u.error,refetchRuntimes:()=>$u.refetch(),refreshRuntimes:Pu,stopRuntimeByName:Ou,createRuntime:async Mu=>Ru.mutateAsync(Mu)}),[$u.data,$u.isLoading,$u.isError,$u.error,$u.refetch,Pu,Ou,Ru,Iu])}const DEFAULT_WS_PATH="/api/v1/tool-approvals/ws",DEFAULT_RECONNECT_DELAY_MS=3e3;function useAgentRuntimeWebSocket(Au){const{enabled:lo=!0,baseUrl:$u,authToken:Ru,agentId:Iu,autoReconnect:Pu=!0,reconnectDelayMs:Ou=DEFAULT_RECONNECT_DELAY_MS,maxReconnectAttempts:Mu}=Au,Du=reactExports.useRef(Au.onMessage);Du.current=Au.onMessage,reactExports.useEffect(()=>{if(!lo||!$u){agentRuntimeStore.getState().setWsState("closed");return}let Lu=!1,Bu=0,ju=null;function Fu(){const Uu=`${$u}${DEFAULT_WS_PATH}`,Hu=new URL(Uu.replace(/^http/,"ws"));return Ru&&Hu.searchParams.set("token",Ru),Iu&&Hu.searchParams.set("agent_id",Iu),Hu.toString()}function zu(){if(Lu)return;const Uu=Fu();agentRuntimeStore.getState().setWsState("connecting");const Hu=new WebSocket(Uu);agentRuntimeStore.getState().setWs(Hu,Iu),Hu.onopen=()=>{Bu=0,agentRuntimeStore.getState().setWsState("connected")},Hu.onmessage=Vu=>{let Gu;try{Gu=JSON.parse(String(Vu.data))}catch{return}const Wu=parseAgentStreamMessage(Gu);if(Du.current?.({type:Wu?.type,payload:Wu?.payload,raw:Gu}),!Wu)return;const Ku=agentRuntimeStore.getState();if(Wu.type==="agent.snapshot"){Ku.applySnapshot(Wu.payload);return}if(Wu.type==="agent.subagent"){Ku.appendSubagentEvent(Wu.payload);return}if(Wu.type==="agent.compaction"){Ku.setCompaction(Wu.payload);return}},Hu.onclose=()=>{if(agentRuntimeStore.getState().setWs(null,Iu),agentRuntimeStore.getState().setWsState("closed"),Lu||!Pu||(Bu+=1,typeof Mu=="number"&&Bu>Mu))return;const Vu=typeof Ou=="function"?Ou(Bu):Ou;ju=setTimeout(zu,Math.max(0,Vu))},Hu.onerror=()=>{(Hu.readyState===WebSocket.CONNECTING||Hu.readyState===WebSocket.OPEN)&&Hu.close()}}return zu(),()=>{Lu=!0,ju&&clearTimeout(ju),agentRuntimeStore.getState().setWs(null,Iu),agentRuntimeStore.getState().resetWs()}},[lo,$u,Ru,Iu,Pu,Ou,Mu])}const ALPHAVANTAGE_MCP_SERVER_0_0_1={id:"alphavantage",version:"0.0.1",name:"Alpha Vantage",description:"Financial market data and stock information",icon:"@primer/octicons-react:graph",emoji:"💹",url:"",command:"uvx",args:["av-mcp==0.2.1","${ALPHAVANTAGE_API_KEY}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["ALPHAVANTAGE_API_KEY:0.0.1"]},CHART_MCP_SERVER_0_0_1={id:"chart",version:"0.0.1",name:"Chart Generator",description:"Generate charts and visualizations",icon:"@datalayer/icons-react:chart-bar",emoji:"📊",url:"",command:"npx",args:["-y","@antv/mcp-server-chart"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},DATALAYER_MCP_SERVER_0_0_1={id:"datalayer",version:"0.0.1",name:"Datalayer",description:"Read, edit and run Jupyter notebooks on Datalayer, with sandboxes and data",icon:"@datalayer/icons-react:datalayer",emoji:"🚀",url:"",command:"npx",args:["-y","mcp-remote","https://mcp.datalayer.run/mcp","--header","Authorization: Bearer ${DATALAYER_API_KEY}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["DATALAYER_API_KEY:0.0.1"]},EARTHDATA_MCP_SERVER_0_0_1={id:"earthdata",version:"0.0.1",name:"Earthdata MCP",description:"Access NASA Earthdata search and metadata capabilities",icon:"@datalayer/icons-react:globe-americas",emoji:"🌍",url:"",command:"npx",args:["-y","mcp-remote","https://mcp.datalayer.run/mcp?only=earthdata","--header","Authorization: Bearer ${DATALAYER_API_KEY}"],transport:"stdio",enabled:!0,isAvailable:!1,tools:[],requiredEnvVars:["DATALAYER_API_KEY:0.0.1"]},EURUS_MCP_SERVER_0_0_1={id:"eurus",version:"0.0.1",name:"Eurus Climate MCP",description:"Climate and reanalysis analysis tools for spatial workflows",icon:"@primer/octicons-react:cloud",emoji:"🌦️",url:"",command:"eurus-mcp",args:[],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},FILESYSTEM_MCP_SERVER_0_0_1={id:"filesystem",version:"0.0.1",name:"Filesystem",description:"Local filesystem read/write operations",icon:"@primer/octicons-react:file-directory",emoji:"📁",url:"",command:"npx",args:["-y","@modelcontextprotocol/server-filesystem","${TMPDIR}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},GITHUB_MCP_SERVER_0_0_1={id:"github",version:"0.0.1",name:"GitHub",description:"GitHub repository operations (issues, PRs, code search)",icon:"@datalayer/icons-react:github-mark",emoji:"🐙",url:"",command:"docker",args:["run","-i","--rm","-e","GITHUB_PERSONAL_ACCESS_TOKEN","ghcr.io/github/github-mcp-server"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["GITHUB_TOKEN:0.0.1"]},GOOGLE_WORKSPACE_MCP_SERVER_0_0_1={id:"google-workspace",version:"0.0.1",name:"Google Workspace",description:"Gmail of the person an application acts for, read or read and send, with a token Datalayer mints per call",icon:"@datalayer/icons-react:google",emoji:"📧",url:"http://127.0.0.1:9711/mcp",command:"uvx",args:["workspace-mcp","--transport","streamable-http","--permissions","gmail:send"],transport:"streamable-http",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},HUGGINGFACE_MCP_SERVER_0_0_1={id:"huggingface",version:"0.0.1",name:"Hugging Face",description:"Hugging Face models, datasets, spaces, and papers access",icon:"@primer/octicons-react:hubot",emoji:"🤗",url:"",command:"npx",args:["-y","mcp-remote","https://huggingface.co/mcp","--header","Authorization: Bearer ${HF_TOKEN}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["HF_TOKEN:0.0.1"]},KAGGLE_MCP_SERVER_0_0_1={id:"kaggle",version:"0.0.1",name:"Kaggle",description:"Kaggle datasets, models, competitions, and notebooks access",icon:"@datalayer/icons-react:kaggle",emoji:"🏆",url:"",command:"npx",args:["-y","mcp-remote","https://www.kaggle.com/mcp","--header","Authorization: Bearer ${KAGGLE_API_TOKEN}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["KAGGLE_API_TOKEN:0.0.1"]},ODOO_ACCOUNTING_MCP_SERVER_0_0_1={id:"odoo-accounting",version:"0.0.1",name:"Odoo Accounting",description:"An accountant's day in Odoo — invoices, bills, journal entries, reconciliations, bank lines and tax returns — through the Datalayer MCP server",icon:"@datalayer/icons-react:odoo",emoji:"🧮",url:"",command:"npx",args:["-y","mcp-remote","https://mcp.datalayer.run/mcp?only=odoo-accounting","--header","Authorization: Bearer ${DATALAYER_API_KEY}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["DATALAYER_API_KEY:0.0.1"]},ODOO_MCP_SERVER_0_0_1={id:"odoo",version:"0.0.1",name:"Odoo",description:"Odoo ERP operations (search, invoices, journals, reconciliations)",icon:"@datalayer/icons-react:odoo",emoji:"🧾",url:"",command:"uvx",args:["mcp-server-odoo"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},SALESFORCE_MCP_SERVER_0_0_1={id:"salesforce",version:"0.0.1",name:"Salesforce",description:"Salesforce CRM operations (queries, reports, objects, SOQL)",icon:"@primer/octicons-react:briefcase",emoji:"☁️",url:"",command:"npx",args:["-y","@anthropic/salesforce-mcp-server"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["SALESFORCE_ACCESS_TOKEN:0.0.1","SALESFORCE_INSTANCE_URL:0.0.1"]},SLACK_MCP_SERVER_0_0_1={id:"slack",version:"0.0.1",name:"Slack",description:"Slack messaging and channel operations",icon:"@datalayer/icons-react:slack",emoji:"💬",url:"",command:"npx",args:["-y","@datalayer/slack-mcp-server"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["SLACK_BOT_TOKEN:0.0.1","SLACK_TEAM_ID:0.0.1","SLACK_CHANNEL_IDS:0.0.1"]},TAVILY_MCP_SERVER_0_0_1={id:"tavily",version:"0.0.1",name:"Tavily Search",description:"Web search and research capabilities via Tavily API",icon:"@primer/octicons-react:search",emoji:"🔍",url:"",command:"npx",args:["-y","tavily-mcp"],transport:"stdio",enabled:!0,isAvailable:!1,tools:[],requiredEnvVars:["TAVILY_API_KEY:0.0.1"]},MCP_SERVER_LIBRARY={alphavantage:ALPHAVANTAGE_MCP_SERVER_0_0_1,chart:CHART_MCP_SERVER_0_0_1,datalayer:DATALAYER_MCP_SERVER_0_0_1,earthdata:EARTHDATA_MCP_SERVER_0_0_1,eurus:EURUS_MCP_SERVER_0_0_1,filesystem:FILESYSTEM_MCP_SERVER_0_0_1,github:GITHUB_MCP_SERVER_0_0_1,"google-workspace":GOOGLE_WORKSPACE_MCP_SERVER_0_0_1,huggingface:HUGGINGFACE_MCP_SERVER_0_0_1,kaggle:KAGGLE_MCP_SERVER_0_0_1,"odoo-accounting":ODOO_ACCOUNTING_MCP_SERVER_0_0_1,odoo:ODOO_MCP_SERVER_0_0_1,salesforce:SALESFORCE_MCP_SERVER_0_0_1,slack:SLACK_MCP_SERVER_0_0_1,tavily:TAVILY_MCP_SERVER_0_0_1},ACCOUNTING_SKILL_SPEC_0_0_1={id:"accounting",version:"0.0.1",name:"Accounting Skill",description:"Accounting analysis workflows for reconciliation, close, variance, and audit-ready summaries",module:"agent_skills.skills.accounting",package:void 0,method:void 0,path:void 0,requiredEnvVars:[],optionalEnvVars:[],dependencies:["pandas>=2.0.0"],tags:["accounting","finance","reconciliation","close"],icon:"@primer/octicons-react:book",emoji:"🧮",enabled:!1},CRAWL_SKILL_SPEC_0_0_1={id:"crawl",version:"0.0.1",name:"Web Crawl Skill",description:"Web crawling and content extraction capabilities",module:"agent_skills.skills.crawl",package:void 0,method:void 0,path:void 0,requiredEnvVars:["TAVILY_API_KEY:0.0.1"],optionalEnvVars:[],dependencies:["requests>=2.31.0","beautifulsoup4>=4.12.0"],tags:["web","crawl","scraping"],icon:"@primer/octicons-react:globe",emoji:"🌐",enabled:!0},EVENTS_SKILL_SPEC_0_0_1={id:"events",version:"0.0.1",name:"Events Skill",description:"Event generation, enrichment, and lifecycle orchestration",module:"agent_skills.skills.events",package:void 0,method:void 0,path:void 0,requiredEnvVars:[],optionalEnvVars:[],dependencies:["httpx>=0.27.0"],tags:["events","orchestration","automation"],icon:"@primer/octicons-react:calendar",emoji:"📅",enabled:!1},GITHUB_SKILL_SPEC_0_0_1={id:"github",version:"0.0.1",name:"GitHub Skill",description:"GitHub repository management and code operations",module:"agent_skills.skills.github",package:void 0,method:void 0,path:void 0,requiredEnvVars:["GITHUB_TOKEN:0.0.1"],optionalEnvVars:[],dependencies:["PyGithub>=2.1.0"],tags:["github","git","code"],icon:"@datalayer/icons-react:github-mark",emoji:"🐙",enabled:!1},JOKES_SKILL_SPEC_0_0_1={id:"jokes",version:"0.0.1",name:"Jokes Skill",description:"Return random jokes from a local path-based skill.",module:void 0,package:void 0,method:void 0,path:"jokes",requiredEnvVars:[],optionalEnvVars:[],dependencies:[],tags:["fun","humor","demo"],icon:"@primer/octicons-react:smiley",emoji:"😄",enabled:!1},PDF_SKILL_SPEC_0_0_1={id:"pdf",version:"0.0.1",name:"PDF Processing Skill",description:"PDF document reading, parsing, and extraction",module:"agent_skills.skills.pdf",package:void 0,method:void 0,path:void 0,requiredEnvVars:[],optionalEnvVars:[],dependencies:["PyPDF2>=3.0.0","pdfplumber>=0.10.0"],tags:["pdf","documents","extraction"],icon:"@primer/octicons-react:file",emoji:"📄",enabled:!1},TEXT_SUMMARIZER_SKILL_SPEC_0_0_1={id:"text-summarizer",version:"0.0.1",name:"Text Summarizer Skill",description:"Summarize text content using extractive and abstractive techniques. Use when the user asks for summaries, key points, or condensed versions of documents.",module:void 0,package:"agent_skills.skills.text_summarizer",method:"summarize_text",path:void 0,requiredEnvVars:[],optionalEnvVars:[],dependencies:["agent-skills>=0.0.1"],tags:["nlp","summarization","text-processing"],icon:"@primer/octicons-react:note",emoji:"📝",enabled:!1},SKILLS_CATALOG={accounting:ACCOUNTING_SKILL_SPEC_0_0_1,crawl:CRAWL_SKILL_SPEC_0_0_1,events:EVENTS_SKILL_SPEC_0_0_1,github:GITHUB_SKILL_SPEC_0_0_1,jokes:JOKES_SKILL_SPEC_0_0_1,pdf:PDF_SKILL_SPEC_0_0_1,"text-summarizer":TEXT_SUMMARIZER_SKILL_SPEC_0_0_1},CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1={id:"create-plan",version:"0.0.1",name:"Create Plan",description:"Create a plan with multiple steps and emit an AG-UI state snapshot.",tags:["example","ag-ui","state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"create_plan"},icon:"@primer/octicons-react:list-unordered",emoji:"📋"},CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1={id:"current-time",version:"0.0.1",name:"Current Time",description:"Return the current time in ISO format for a given timezone.",tags:["example","ag-ui","time"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"current_time"},icon:"@primer/octicons-react:clock",emoji:"🕒"},DECIDE_BACKEND_TOOL_SPEC_0_0_1={id:"decide",version:"0.0.1",name:"Decide",description:"Ask Jev typed questions about a text — noul (does a statement hold, with its probability), choice (one of named options) or score (a step on a rubric) — and get the typed answers back, through datalayer-ai-inference.",tags:["runtime","decisions","jev"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.tools.decisions",method:"decide"},icon:"@primer/octicons-react:law",emoji:"⚖️"},DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1={id:"display-recipe",version:"0.0.1",name:"Display Recipe",description:"Update the shared recipe state and emit an AG-UI state snapshot.",tags:["example","ag-ui","shared-state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"display_recipe"},icon:"@primer/octicons-react:book",emoji:"🍳"},EXAMPLE_CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1={id:"example-create-plan",version:"0.0.1",name:"Create Plan",description:"Create a plan with multiple steps and emit an AG-UI state snapshot.",tags:["example","ag-ui","state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"create_plan"},icon:"@primer/octicons-react:list-unordered",emoji:"📋"},EXAMPLE_CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1={id:"example-current-time",version:"0.0.1",name:"Current Time",description:"Return the current time in ISO format for a given timezone.",tags:["example","ag-ui","time"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"current_time"},icon:"@primer/octicons-react:clock",emoji:"🕒"},EXAMPLE_DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1={id:"example-display-recipe",version:"0.0.1",name:"Display Recipe",description:"Update the shared recipe state and emit an AG-UI state snapshot.",tags:["example","ag-ui","shared-state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"display_recipe"},icon:"@primer/octicons-react:book",emoji:"🍳"},EXAMPLE_GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1={id:"example-generate-haiku",version:"0.0.1",name:"Generate Haiku",description:"Generate a haiku (Japanese + English + gradient) rendered as a card by the frontend.",tags:["example","ag-ui","generative-ui"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"generate_haiku"},icon:"@primer/octicons-react:pencil",emoji:"🖋️"},EXAMPLE_GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1={id:"example-generate-task-steps",version:"0.0.1",name:"Generate Task Steps",description:"Generate task steps for human review and emit an AG-UI state snapshot.",tags:["example","ag-ui","human-in-the-loop"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"generate_task_steps"},icon:"@primer/octicons-react:tasklist",emoji:"🙋"},EXAMPLE_GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1={id:"example-get-weather",version:"0.0.1",name:"Get Weather",description:"Fetch current weather for a location from the Open-Meteo API for frontend rendering.",tags:["example","ag-ui","weather"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"get_weather"},icon:"@primer/octicons-react:sun",emoji:"🌤️"},EXAMPLE_RENDER_A2UI_SURFACE_BACKEND_TOOL_SPEC_0_0_1={id:"example-render-a2ui-surface",version:"0.0.1",name:"Render A2UI Surface",description:"Turn a declarative field spec into a validated A2UI v0.9 surface rendered live by the frontend as an interactive form/card.",tags:["example","ag-ui","a2ui","generative-ui"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.a2ui",method:"render_a2ui_surface"},icon:"@primer/octicons-react:browser",emoji:"🎛️"},EXAMPLE_UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1={id:"example-update-plan-step",version:"0.0.1",name:"Update Plan Step",description:"Update a plan step and emit an AG-UI state delta (JSON Patch RFC 6902).",tags:["example","ag-ui","state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"update_plan_step"},icon:"@primer/octicons-react:checklist",emoji:"✅"},GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1={id:"generate-haiku",version:"0.0.1",name:"Generate Haiku",description:"Generate a haiku (Japanese + English + gradient) rendered as a card by the frontend.",tags:["example","ag-ui","generative-ui"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"generate_haiku"},icon:"@primer/octicons-react:pencil",emoji:"🖋️"},GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1={id:"generate-task-steps",version:"0.0.1",name:"Generate Task Steps",description:"Generate task steps for human review and emit an AG-UI state snapshot.",tags:["example","ag-ui","human-in-the-loop"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"generate_task_steps"},icon:"@primer/octicons-react:tasklist",emoji:"🙋"},GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1={id:"get-weather",version:"0.0.1",name:"Get Weather",description:"Fetch current weather for a location from the Open-Meteo API for frontend rendering.",tags:["example","ag-ui","weather"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"get_weather"},icon:"@primer/octicons-react:sun",emoji:"🌤️"},RUNTIME_ECHO_BACKEND_TOOL_SPEC_0_0_1={id:"runtime-echo",version:"0.0.1",name:"Runtime Echo",description:"Echo text back to the caller for quick runtime verification.",tags:["runtime","utility"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools",method:"runtime_echo"},icon:"@primer/octicons-react:comment",emoji:"💬"},RUNTIME_SEND_MAIL_BACKEND_TOOL_SPEC_0_0_1={id:"runtime-send-mail",version:"0.0.1",name:"Runtime Send Mail (Fake)",description:"Fake mail sender for tool approval demos; returns a simulated send receipt.",tags:["runtime","approval","mail"],enabled:!0,approval:"manual",timeout:void 0,requiresApproval:!0,runtime:{language:"python",package:"agent_runtimes.examples.tools",method:"runtime_send_mail"},icon:"@primer/octicons-react:mail",emoji:"📧"},RUNTIME_SENSITIVE_ECHO_BACKEND_TOOL_SPEC_0_0_1={id:"runtime-sensitive-echo",version:"0.0.1",name:"Runtime Sensitive Echo",description:"Echo text with a manual approval checkpoint before execution.",tags:["runtime","approval"],enabled:!0,approval:"manual",timeout:void 0,requiresApproval:!0,runtime:{language:"python",package:"agent_runtimes.examples.tools",method:"runtime_sensitive_echo"},icon:"@primer/octicons-react:shield",emoji:"🛡️"},UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1={id:"update-plan-step",version:"0.0.1",name:"Update Plan Step",description:"Update a plan step and emit an AG-UI state delta (JSON Patch RFC 6902).",tags:["example","ag-ui","state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"update_plan_step"},icon:"@primer/octicons-react:checklist",emoji:"✅"},BACKEND_TOOL_CATALOG={"create-plan":CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1,"current-time":CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1,decide:DECIDE_BACKEND_TOOL_SPEC_0_0_1,"display-recipe":DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1,"example-create-plan":EXAMPLE_CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1,"example-current-time":EXAMPLE_CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1,"example-display-recipe":EXAMPLE_DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1,"example-generate-haiku":EXAMPLE_GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1,"example-generate-task-steps":EXAMPLE_GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1,"example-get-weather":EXAMPLE_GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1,"example-render-a2ui-surface":EXAMPLE_RENDER_A2UI_SURFACE_BACKEND_TOOL_SPEC_0_0_1,"example-update-plan-step":EXAMPLE_UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1,"generate-haiku":GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1,"generate-task-steps":GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1,"get-weather":GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1,"runtime-echo":RUNTIME_ECHO_BACKEND_TOOL_SPEC_0_0_1,"runtime-send-mail":RUNTIME_SEND_MAIL_BACKEND_TOOL_SPEC_0_0_1,"runtime-sensitive-echo":RUNTIME_SENSITIVE_ECHO_BACKEND_TOOL_SPEC_0_0_1,"update-plan-step":UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1},DECKS_FRONTEND_TOOL_SPEC_0_0_1={id:"decks",version:"0.0.1",name:"Decks",description:"Read, write and drive presentations kept as data — a deck, its slides, and the one on screen.",tags:["frontend","decks","presentations"],enabled:!0,toolset:["decks_list_decks","decks_get_deck","decks_create_deck","decks_update_deck","decks_update_slide","decks_insert_slide","decks_delete_slide","decks_list_slides","decks_get_slide","decks_add_slide","decks_delete_deck","decks_list","decks_open","decks_go_to_slide","decks_next_slide","decks_previous_slide","decks_present","decks_print"],icon:"@primer/octicons-react:project",emoji:"🃏"},JUPYTER_NOTEBOOK_EDIT_FRONTEND_TOOL_SPEC_0_0_1={id:"jupyter-notebook-edit",version:"0.0.1",name:"Jupyter Notebook (edit)",description:"Read and edit a notebook, and run cells — but never delete from it.",tags:["frontend","notebook","edit"],enabled:!0,toolset:["readCell","readAllCells","insertCell","updateCell","runCell","executeCode"],icon:"@datalayer/icons-react:jupyter",emoji:"📓"},JUPYTER_NOTEBOOK_PROPOSE_FRONTEND_TOOL_SPEC_0_0_1={id:"jupyter-notebook-propose",version:"0.0.1",name:"Jupyter Notebook (propose)",description:"Read a notebook and propose changes for a person to accept, never applying them.",tags:["frontend","notebook","propose"],enabled:!0,toolset:["readCell","readAllCells","proposeCellUpdate","runCell"],icon:"@datalayer/icons-react:jupyter",emoji:"📓"},JUPYTER_NOTEBOOK_READ_FRONTEND_TOOL_SPEC_0_0_1={id:"jupyter-notebook-read",version:"0.0.1",name:"Jupyter Notebook (read only)",description:"Read a notebook without changing it — cells, outputs and errors.",tags:["frontend","notebook","read"],enabled:!0,toolset:["readCell","readAllCells"],icon:"@datalayer/icons-react:jupyter",emoji:"📓"},JUPYTER_NOTEBOOK_FRONTEND_TOOL_SPEC_0_0_1={id:"jupyter-notebook",version:"0.0.1",name:"Jupyter Notebook",description:"Frontend tools for interacting with Jupyter notebooks.",tags:["frontend","notebook","jupyter-server"],enabled:!0,toolset:"all",icon:"@datalayer/icons-react:jupyter",emoji:"📓"},LEXICAL_DOCUMENT_FRONTEND_TOOL_SPEC_0_0_1={id:"lexical-document",version:"0.0.1",name:"Lexical Document",description:"Frontend tools for interacting with Lexical documents: reading and writing blocks, running Jupyter cells in the page, and drawing diagrams into the document with Excalidraw.",tags:["frontend","document","lexical","drawing","diagram"],enabled:!0,toolset:"all",icon:"@primer/octicons-react:file",emoji:"📄"},FRONTEND_TOOL_CATALOG={decks:DECKS_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-edit":JUPYTER_NOTEBOOK_EDIT_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-propose":JUPYTER_NOTEBOOK_PROPOSE_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-read":JUPYTER_NOTEBOOK_READ_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook":JUPYTER_NOTEBOOK_FRONTEND_TOOL_SPEC_0_0_1,"lexical-document":LEXICAL_DOCUMENT_FRONTEND_TOOL_SPEC_0_0_1},MCP_SERVER_MAP$1={"alphavantage:0.0.1":ALPHAVANTAGE_MCP_SERVER_0_0_1,"chart:0.0.1":CHART_MCP_SERVER_0_0_1,"earthdata:0.0.1":EARTHDATA_MCP_SERVER_0_0_1,"eurus:0.0.1":EURUS_MCP_SERVER_0_0_1,"filesystem:0.0.1":FILESYSTEM_MCP_SERVER_0_0_1,"github:0.0.1":GITHUB_MCP_SERVER_0_0_1,"google-workspace:0.0.1":GOOGLE_WORKSPACE_MCP_SERVER_0_0_1,"huggingface:0.0.1":HUGGINGFACE_MCP_SERVER_0_0_1,"kaggle:0.0.1":KAGGLE_MCP_SERVER_0_0_1,"odoo:0.0.1":ODOO_MCP_SERVER_0_0_1,"salesforce:0.0.1":SALESFORCE_MCP_SERVER_0_0_1,"slack:0.0.1":SLACK_MCP_SERVER_0_0_1,"tavily:0.0.1":TAVILY_MCP_SERVER_0_0_1},SKILL_MAP$1={"accounting:0.0.1":ACCOUNTING_SKILL_SPEC_0_0_1,"crawl:0.0.1":CRAWL_SKILL_SPEC_0_0_1,"events:0.0.1":EVENTS_SKILL_SPEC_0_0_1,"github:0.0.1":GITHUB_SKILL_SPEC_0_0_1,"jokes:0.0.1":JOKES_SKILL_SPEC_0_0_1,"pdf:0.0.1":PDF_SKILL_SPEC_0_0_1,"text-summarizer:0.0.1":TEXT_SUMMARIZER_SKILL_SPEC_0_0_1};function toAgentSkillSpec$1(Au){return{id:Au.id,name:Au.name,description:Au.description,version:Au.version??"0.0.1",tags:Au.tags,enabled:Au.enabled,requiredEnvVars:Au.requiredEnvVars}}const TOOL_MAP$1={"decide:0.0.1":DECIDE_BACKEND_TOOL_SPEC_0_0_1,"example-create-plan:0.0.1":EXAMPLE_CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1,"example-current-time:0.0.1":EXAMPLE_CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1,"example-display-recipe:0.0.1":EXAMPLE_DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1,"example-generate-haiku:0.0.1":EXAMPLE_GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1,"example-generate-task-steps:0.0.1":EXAMPLE_GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1,"example-get-weather:0.0.1":EXAMPLE_GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1,"example-render-a2ui-surface:0.0.1":EXAMPLE_RENDER_A2UI_SURFACE_BACKEND_TOOL_SPEC_0_0_1,"example-update-plan-step:0.0.1":EXAMPLE_UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1,"runtime-echo:0.0.1":RUNTIME_ECHO_BACKEND_TOOL_SPEC_0_0_1,"runtime-send-mail:0.0.1":RUNTIME_SEND_MAIL_BACKEND_TOOL_SPEC_0_0_1,"runtime-sensitive-echo:0.0.1":RUNTIME_SENSITIVE_ECHO_BACKEND_TOOL_SPEC_0_0_1},FRONTEND_TOOL_MAP$1={"decks:0.0.1":DECKS_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-edit:0.0.1":JUPYTER_NOTEBOOK_EDIT_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-propose:0.0.1":JUPYTER_NOTEBOOK_PROPOSE_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-read:0.0.1":JUPYTER_NOTEBOOK_READ_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook:0.0.1":JUPYTER_NOTEBOOK_FRONTEND_TOOL_SPEC_0_0_1,"lexical-document:0.0.1":LEXICAL_DOCUMENT_FRONTEND_TOOL_SPEC_0_0_1},EXAMPLE_A2A_RESEARCHER_AGENTSPEC_0_0_1={id:"example-a2a-researcher",version:"0.0.1",name:"Example A2A Researcher",description:"A research specialist served over the A2A protocol. Given a topic, gathers the key facts and returns concise, source-aware notes.",tags:["research","a2a"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],frontendTools:[],environmentName:"ai-agents-env",icon:"search",emoji:"🔎",color:"#0EA5E9",suggestions:[{text:"Gather the key facts on a topic, with sources",summary:"Key facts with sources"}],welcomeMessage:"A2A researcher ready.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:void 0,harness:"pydantic-ai",systemPrompt:"You are a meticulous research specialist, reached by other agents over the A2A protocol. Given a topic, gather the key facts and return concise, source-aware notes. Prefer verifiable claims and flag anything uncertain. Answer with the notes themselves: no preamble, no questions back. You have no tools and no web access: work from what you know, and say when something should be checked.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"a2a",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_A2A_WRITER_AGENTSPEC_0_0_1={id:"example-a2a-writer",version:"0.0.1",name:"Example A2A Writer",description:"A writing specialist served over the A2A protocol. Given notes or instructions, produces clear, well-structured prose.",tags:["writing","a2a"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],frontendTools:[],environmentName:"ai-agents-env",icon:"pencil",emoji:"✍️",color:"#F59E0B",suggestions:[{text:"Turn a set of notes into a short, structured write-up",summary:"Notes into a write-up"}],welcomeMessage:"A2A writer ready.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:void 0,harness:"pydantic-ai",systemPrompt:"You are a concise writing specialist, reached by other agents over the A2A protocol. Given notes or findings, produce clear, well-structured prose. Keep it focused and free of filler. Answer with the text itself: no preamble, no questions back. You have no tools: work from the notes and instructions you are given.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"a2a",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_A2A_AGENTSPEC_0_0_1={id:"example-a2a",version:"0.0.1",name:"Example A2A Agent",description:"Demonstrates delegation to separate agents over the A2A protocol. The orchestrator hands research and writing to a researcher and a writer that run as agents of their own — launched beside it on the local server, or on Datalayer runtimes when it runs in the cloud — and talks to them over A2A.",tags:["research","workflow","a2a"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],frontendTools:[],environmentName:"ai-agents-env",icon:"broadcast",emoji:"📡",color:"#7C3AED",suggestions:[{text:"Research three key facts about the A2A protocol through the researcher, then have the writer turn them into one short paragraph.",summary:"Research then write over A2A"},{text:"Have the researcher gather five source-backed notes on Jupyter kernels and report them to me as they are.",summary:"Research via the A2A researcher"},{text:"Have the writer draft a short guide to naming variables from these points: be specific, prefer words to abbreviations, keep units in the name.",summary:"Draft via the A2A writer"}],welcomeMessage:"A2A example agent ready. Ask me to delegate research and writing to the agents I reach over A2A.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:'You are the A2A Orchestrator. You do not research or write yourself: you split a request into specialist tasks and hand each to a separate agent reached over the A2A protocol, then synthesize their answers into one coherent reply.\nYour agents are `researcher` — facts, background, source-backed notes — and `writer` — clear, structured prose from notes or instructions. Reach them with `delegate_task`, naming the agent; a request to "research and write" is two delegations, the researcher\'s notes handed to the writer. Give each a task it can carry out without the rest of this conversation. The first delegation to an agent may take a moment while it is launched.\nAnswer in the conversation, and only with the tools you actually have; never call a tool you were not given.',systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:{includeGeneralPurpose:!1,subagents:[{name:"researcher",description:"A separate research agent, reached over A2A. Gathers facts and source-backed notes on a topic; use for research, fact-finding and background gathering.",ref:"example-a2a-researcher:0.0.1",a2a:{launch:"auto"}},{name:"writer",description:"A separate writing agent, reached over A2A. Turns notes into clear, well-structured prose; use for summaries, drafts and final write-ups.",ref:"example-a2a-writer:0.0.1",a2a:{launch:"auto"}}]}},EXAMPLE_A2UI_AGENT_SPEC_0_0_1={id:"example-a2ui-agent",version:"0.0.1",name:"A2UI Agent",description:"An AG-UI agent that generates interactive A2UI surfaces on demand. Describe a form, intake, configurator, survey or booking flow and the agent renders a validated, themeable A2UI surface you can fill in.",tags:["workflow","automation","analysis"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[TOOL_MAP$1["example-render-a2ui-surface:0.0.1"]],frontendTools:[],frontendRenderTools:[{tool:"render_a2ui_surface",renderer:"a2ui-surface"}],environmentName:"ai-agents-env",icon:"browser",emoji:"🎛️",color:"#6366F1",suggestions:[{text:"Build a support ticket intake form with category, priority and a description.",summary:"Support ticket form"},{text:"Create a trip booking form with destination, dates, travelers and budget.",summary:"Trip booking form"},{text:"Generate a customer feedback survey with a rating slider and comments.",summary:"Feedback survey"},{text:"Make a product configurator for a laptop with CPU, RAM and add-ons.",summary:"Laptop configurator"}],welcomeMessage:`Hi! I turn requests into interactive A2UI surfaces. Ask me to build a form, survey, configurator or booking flow and I'll render it live for you.
|
|
2200
2200
|
`,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:void 0,harness:"pydantic-ai",systemPrompt:"You are an A2UI generative-UI agent. You render real, interactive user\ninterfaces (forms, intakes, configurators, surveys, bookings, checklists)\nfrom the user's request.\n\nHow to respond:\n1. ALWAYS call the `render_a2ui_surface` tool to produce the UI. Never\n describe the form in prose instead of rendering it.\n2. Choose a concise `title` and a one-sentence `intro`.\n3. Design a sensible ordered list of `fields`. Pick the best `type` for each:\n - `text` / `email` for short input, `longtext` for descriptions/notes\n - `choice` (single) or `multichoice` (many) with `options` for pick-lists\n - `checkbox` for yes/no, `slider` (with `min`/`max`) for ranges/ratings\n - `date` / `datetime` for scheduling\n4. When the request implies triage or categorization (e.g. support tickets),\n add `summary_items` such as detected Category or Priority.\n5. Keep forms focused: usually 4-8 fields.\n6. After the tool call, reply with ONE short sentence confirming what you\n built. Do NOT repeat every field in text — the surface is shown directly.\n",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"ag-ui",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_A2UI_JUPYTER_OUTPUT_AGENTSPEC_0_0_1={id:"example-a2ui-jupyter-output",version:"0.0.1",name:"A2UI Jupyter Output Agent",description:"Drives the A2UI Jupyter Output example by selecting a kernel-output demonstration and asking the frontend to execute it in the connected sandbox.",tags:["a2ui","jupyter","output"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],frontendTools:[],environmentName:"ai-agents-env",icon:"notebook",emoji:"📓",color:"#0969DA",suggestions:[{text:"Run something in the code sandbox that prints as it goes.",summary:"Streaming output",emoji:"📜"},{text:"Plot a chart in the code sandbox and show me the image.",summary:"Plot a chart",emoji:"📈"},{text:"Build a small DataFrame in the code sandbox and show it as a table.",summary:"DataFrame as a table",emoji:"🧮"},{text:"Run something in the code sandbox that fails, so I can see the traceback.",summary:"Show a traceback",emoji:"🐛"},{text:"Show me an interactive slider from the code sandbox.",summary:"Interactive slider",emoji:"🎛️"},{text:"Give me a surface with buttons I can press.",summary:"Buttons to press",emoji:"🖲️"}],welcomeMessage:"Choose a suggestion to execute a Jupyter output demonstration and compare the kernel output with its A2UI surface.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You operate the A2UI Jupyter Output example. It exists to show one code\nsandbox execution twice over: what the kernel itself returned, and the A2UI\nsurface the server converter made of the same outputs.\n\nShowing that comparison is done with one tool and nothing else:\n`run_jupyter_output_demo`, whose `kind` is one of `stream`, `figure`,\n`table`, `error`, `ipywidgets`, or `interactive`.\n\nSo: whenever somebody asks you to run something in the code sandbox, or to\nshow what some kind of output looks like, call `run_jupyter_output_demo`\nexactly once with the kind that matches what they asked for. They will ask\nin ordinary words rather than by naming the tool or the kind, and reading\nthe request is your job:\n\n- printing, stdout, output arriving as it goes, a returned value -> `stream`\n- a plot, a chart, a figure, an image -> `figure`\n- a DataFrame, a table, tabular data -> `table`\n- a failure, an exception, a traceback, something that breaks -> `error`\n- a slider, a widget, an interactive control -> `ipywidgets`\n- a surface with buttons, something to press or click -> `interactive`\n\nNever write or execute Python of your own instead. The six demonstrations\nare fixed on purpose: the two panels are only worth comparing when both are\nshowing the same execution, and substituted code breaks the comparison the\nexample exists to make.\n\nAfter the tool returns, say in a sentence what was run and that it is now\nvisible in both the A2UI Surface and the Jupyter Output panels, with a word\non what differs between them where it is interesting. An `error`\ndemonstration is deliberate and has succeeded when its traceback is on\nscreen — do not apologise for it or offer to fix the code.\n",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"vercel-ai",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_A2UI_VIEWER_AGENTSPEC_0_0_1={id:"example-a2ui-viewer",version:"0.0.1",name:"A2UI Viewer Agent",description:"Answers beside the A2UI Viewer, whose scenes — a recipe card, a booking form, a sales snapshot and a shipping status — it renders on request as live A2UI surfaces, and runs code in the sandbox to show its outputs.",tags:["a2ui","viewer","loop"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[TOOL_MAP$1["example-render-a2ui-surface:0.0.1"]],frontendTools:[],frontendRenderTools:[{tool:"render_a2ui_surface",renderer:"a2ui-surface"}],environmentName:"ai-agents-env",icon:"browser",emoji:"🔍",color:"#6366F1",suggestions:[{text:"Show a recipe card for a Mediterranean quinoa bowl, with a photo, its rating and review count, prep and cook time, and how many it serves.",summary:"Recipe Card",emoji:"🍲"},{text:"Build a table booking form with party size, date and time, dietary requirements and a Submit Reservation button.",summary:"Booking Form",emoji:"📅"},{text:"Show a Q2 sales snapshot by category — Apparel, Electronics, Home Goods and Health & Beauty — as KPI tiles under one headline.",summary:"Sales Snapshot",emoji:"📈"},{text:"Show a package status card with the tracking number, the steps from placed to shipped to out for delivery, and the ETA.",summary:"Shipping Status",emoji:"📦"},{text:"Plot a chart in the code sandbox and show me the image.",summary:"Plot a chart",emoji:"📈"},{text:"Build a small DataFrame in the code sandbox and show it as a table.",summary:"DataFrame as a table",emoji:"🧮"},{text:"Run something in the code sandbox that fails, so I can see the traceback.",summary:"Show a traceback",emoji:"🐛"},{text:"Show me an interactive slider from the code sandbox.",summary:"Interactive slider",emoji:"🎛️"}],welcomeMessage:"This is the A2UI Viewer. Pick a scene above to see a surface drawn from A2UI messages, ask me to render one of them here, or run something in the code sandbox and see its output.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"browser",harness:"vercel-ai",systemPrompt:"You answer beside the A2UI Viewer, an example that renders A2UI surfaces\nfrom pasted protocol messages: a recipe card, a table booking form, a sales\nsnapshot of KPI tiles, and a shipping status timeline.\n\nWhen asked for a surface — one of those, or anything like them:\n1. ALWAYS call the `render_a2ui_surface` tool to produce it. Never describe\n the surface in prose instead of rendering it.\n2. Choose a concise `title` and a one-sentence `intro`.\n3. Design a sensible ordered list of `fields`, picking the best `type` for\n each: `text` / `email` for short input, `longtext` for notes, `choice`\n or `multichoice` with `options` for pick-lists, `checkbox` for yes/no,\n `slider` with `min`/`max` for ranges and ratings, `date` / `datetime`\n for scheduling. A card that shows values rather than asking for them\n still renders as a surface: put each value in a field with its label.\n4. After the tool call, reply with ONE short sentence saying what you\n rendered. Do not repeat the fields in text — the surface is shown.\n\nWhen asked to run code, use `execute_code` in the sandbox and let the\noutputs speak: a figure, a table, a traceback, a widget. Do not look for\nhelpers or skills in the sandbox; write the Python yourself.\n",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"vercel-ai",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_AGENT_CRITIC_LOOP_FOR_ANALYSIS_AGENTSPEC_0_0_1={id:"example-agent-critic-loop-for-analysis",version:"0.0.1",name:"Agent Critic Loop for Analysis",description:"Use a planner, executor, and critic agent loop to iteratively improve analysis quality and reduce logical errors in outputs.",tags:["analysis","data-quality","analytics"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],frontendTools:[FRONTEND_TOOL_MAP$1["jupyter-notebook:0.0.1"],FRONTEND_TOOL_MAP$1["lexical-document:0.0.1"]],environmentName:"ai-agents-env",icon:"sync",emoji:"📊",color:"#1F883D",suggestions:[{text:"Use /home/datalayer/datasets/datalayer-nfs/finance/transactions_q1.csv and run a critic loop: first produce a reconciliation analysis, then critique it for gaps and publish a corrected final report.",summary:"Critic loop on transactions"}],welcomeMessage:"Hi! I can help with agent critic loop for analysis. Share data, files, or context and I will run the workflow end-to-end, explain what matters, and suggest practical next steps.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are a specialized assistant for this gallery workflow: Agent Critic Loop for Analysis. Objective: Use a planner, executor, and critic agent loop to iteratively improve analysis quality and reduce logical errors in outputs. Use the runtime tools and notebook execution environment when needed. Keep outputs concise, structured, and decision-oriented. Provide clear reasoning and recommended next actions.",systemPromptCodemodeAddons:"Compose focused execution steps, validate intermediate results, and summarize outcomes after each run. Prefer efficient, reproducible code paths.",goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:{enabled:!0,token_reduction:"~80%",speedup:"~1.5x"},output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_AGENTIC_CHAT_AGENTSPEC_0_0_1={id:"example-agentic-chat",version:"0.0.1",name:"Agentic Chat",description:"A basic conversational AG-UI agent that can chat and use a tool to get the current time in any timezone.",tags:["workflow","automation","analysis"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[TOOL_MAP$1["example-current-time:0.0.1"]],frontendTools:[],environmentName:"ai-agents-env",icon:"clock",emoji:"🕒",color:"#6366F1",suggestions:[{text:"What is the current time?",summary:"Current time"},{text:"What's the current date?",summary:"Current date"}],welcomeMessage:`Hi! Ask me for the current time in any timezone.
|
|
2201
2201
|
`,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:void 0,harness:"pydantic-ai",systemPrompt:`You are a helpful assistant that can provide the current time in any timezone. Use the current_time tool when asked about the time. Keep your responses concise and helpful.
|
|
2202
2202
|
`,systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"ag-ui",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_AGENTIC_GENERATIVE_UI_AGENTSPEC_0_0_1={id:"example-agentic-generative-ui",version:"0.0.1",name:"Agentic Generative UI",description:"An AG-UI agent that creates plans with steps and updates individual steps as progress is made using JSON Patch (RFC 6902) state deltas.",tags:["workflow","automation","analysis"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[TOOL_MAP$1["example-create-plan:0.0.1"],TOOL_MAP$1["example-update-plan-step:0.0.1"]],frontendTools:[],environmentName:"ai-agents-env",icon:"list-unordered",emoji:"📋",color:"#6366F1",suggestions:[{text:"Create a project plan for building a mobile app.",summary:"Mobile app plan"},{text:"Generate a marketing strategy for a new product launch.",summary:"Marketing strategy"}],welcomeMessage:`Hi! Give me a goal and I'll create a plan, then work through the steps.
|
|
@@ -3629,7 +3629,7 @@ ${lo}</tr>
|
|
|
3629
3629
|
`}tablecell(lo){let $u=this.parser.parseInline(lo.tokens),Ru=lo.header?"th":"td";return(lo.align?`<${Ru} align="${lo.align}">`:`<${Ru}>`)+$u+`</${Ru}>
|
|
3630
3630
|
`}strong({tokens:lo}){return`<strong>${this.parser.parseInline(lo)}</strong>`}em({tokens:lo}){return`<em>${this.parser.parseInline(lo)}</em>`}codespan({text:lo}){return`<code>${w$2(lo,!0)}</code>`}br(lo){return"<br>"}del({tokens:lo}){return`<del>${this.parser.parseInline(lo)}</del>`}link({href:lo,title:$u,tokens:Ru}){let Iu=this.parser.parseInline(Ru),Pu=J$2(lo);if(Pu===null)return Iu;lo=Pu;let Ou='<a href="'+lo+'"';return $u&&(Ou+=' title="'+w$2($u)+'"'),Ou+=">"+Iu+"</a>",Ou}image({href:lo,title:$u,text:Ru,tokens:Iu}){Iu&&(Ru=this.parser.parseInline(Iu,this.parser.textRenderer));let Pu=J$2(lo);if(Pu===null)return w$2(Ru);lo=Pu;let Ou=`<img src="${lo}" alt="${Ru}"`;return $u&&(Ou+=` title="${w$2($u)}"`),Ou+=">",Ou}text(lo){return"tokens"in lo&&lo.tokens?this.parser.parseInline(lo.tokens):"escaped"in lo&&lo.escaped?lo.text:w$2(lo.text)}},$$1=class{strong({text:lo}){return lo}em({text:lo}){return lo}codespan({text:lo}){return lo}del({text:lo}){return lo}html({text:lo}){return lo}text({text:lo}){return lo}link({text:lo}){return""+lo}image({text:lo}){return""+lo}br(){return""}},b$5=class P_{options;renderer;textRenderer;constructor(lo){this.options=lo||T$1,this.options.renderer=this.options.renderer||new P$3,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new $$1}static parse(lo,$u){return new P_($u).parse(lo)}static parseInline(lo,$u){return new P_($u).parseInline(lo)}parse(lo,$u=!0){let Ru="";for(let Iu=0;Iu<lo.length;Iu++){let Pu=lo[Iu];if(this.options.extensions?.renderers?.[Pu.type]){let Mu=Pu,Du=this.options.extensions.renderers[Mu.type].call({parser:this},Mu);if(Du!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(Mu.type)){Ru+=Du||"";continue}}let Ou=Pu;switch(Ou.type){case"space":{Ru+=this.renderer.space(Ou);continue}case"hr":{Ru+=this.renderer.hr(Ou);continue}case"heading":{Ru+=this.renderer.heading(Ou);continue}case"code":{Ru+=this.renderer.code(Ou);continue}case"table":{Ru+=this.renderer.table(Ou);continue}case"blockquote":{Ru+=this.renderer.blockquote(Ou);continue}case"list":{Ru+=this.renderer.list(Ou);continue}case"html":{Ru+=this.renderer.html(Ou);continue}case"def":{Ru+=this.renderer.def(Ou);continue}case"paragraph":{Ru+=this.renderer.paragraph(Ou);continue}case"text":{let Mu=Ou,Du=this.renderer.text(Mu);for(;Iu+1<lo.length&&lo[Iu+1].type==="text";)Mu=lo[++Iu],Du+=`
|
|
3631
3631
|
`+this.renderer.text(Mu);$u?Ru+=this.renderer.paragraph({type:"paragraph",raw:Du,text:Du,tokens:[{type:"text",raw:Du,text:Du,escaped:!0}]}):Ru+=Du;continue}default:{let Mu='Token with "'+Ou.type+'" type was not found.';if(this.options.silent)return console.error(Mu),"";throw new Error(Mu)}}}return Ru}parseInline(lo,$u=this.renderer){let Ru="";for(let Iu=0;Iu<lo.length;Iu++){let Pu=lo[Iu];if(this.options.extensions?.renderers?.[Pu.type]){let Mu=this.options.extensions.renderers[Pu.type].call({parser:this},Pu);if(Mu!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(Pu.type)){Ru+=Mu||"";continue}}let Ou=Pu;switch(Ou.type){case"escape":{Ru+=$u.text(Ou);break}case"html":{Ru+=$u.html(Ou);break}case"link":{Ru+=$u.link(Ou);break}case"image":{Ru+=$u.image(Ou);break}case"strong":{Ru+=$u.strong(Ou);break}case"em":{Ru+=$u.em(Ou);break}case"codespan":{Ru+=$u.codespan(Ou);break}case"br":{Ru+=$u.br(Ou);break}case"del":{Ru+=$u.del(Ou);break}case"text":{Ru+=$u.text(Ou);break}default:{let Mu='Token with "'+Ou.type+'" type was not found.';if(this.options.silent)return console.error(Mu),"";throw new Error(Mu)}}}return Ru}},S$2=class{options;block;constructor(lo){this.options=lo||T$1}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(lo){return lo}postprocess(lo){return lo}processAllTokens(lo){return lo}emStrongMask(lo){return lo}provideLexer(){return this.block?x$7.lex:x$7.lexInline}provideParser(){return this.block?b$5.parse:b$5.parseInline}},B$2=class{defaults=L$2();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=b$5;Renderer=P$3;TextRenderer=$$1;Lexer=x$7;Tokenizer=y$4;Hooks=S$2;constructor(...lo){this.use(...lo)}walkTokens(lo,$u){let Ru=[];for(let Iu of lo)switch(Ru=Ru.concat($u.call(this,Iu)),Iu.type){case"table":{let Pu=Iu;for(let Ou of Pu.header)Ru=Ru.concat(this.walkTokens(Ou.tokens,$u));for(let Ou of Pu.rows)for(let Mu of Ou)Ru=Ru.concat(this.walkTokens(Mu.tokens,$u));break}case"list":{let Pu=Iu;Ru=Ru.concat(this.walkTokens(Pu.items,$u));break}default:{let Pu=Iu;this.defaults.extensions?.childTokens?.[Pu.type]?this.defaults.extensions.childTokens[Pu.type].forEach(Ou=>{let Mu=Pu[Ou].flat(1/0);Ru=Ru.concat(this.walkTokens(Mu,$u))}):Pu.tokens&&(Ru=Ru.concat(this.walkTokens(Pu.tokens,$u)))}}return Ru}use(...lo){let $u=this.defaults.extensions||{renderers:{},childTokens:{}};return lo.forEach(Ru=>{let Iu={...Ru};if(Iu.async=this.defaults.async||Iu.async||!1,Ru.extensions&&(Ru.extensions.forEach(Pu=>{if(!Pu.name)throw new Error("extension name required");if("renderer"in Pu){let Ou=$u.renderers[Pu.name];Ou?$u.renderers[Pu.name]=function(...Mu){let Du=Pu.renderer.apply(this,Mu);return Du===!1&&(Du=Ou.apply(this,Mu)),Du}:$u.renderers[Pu.name]=Pu.renderer}if("tokenizer"in Pu){if(!Pu.level||Pu.level!=="block"&&Pu.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let Ou=$u[Pu.level];Ou?Ou.unshift(Pu.tokenizer):$u[Pu.level]=[Pu.tokenizer],Pu.start&&(Pu.level==="block"?$u.startBlock?$u.startBlock.push(Pu.start):$u.startBlock=[Pu.start]:Pu.level==="inline"&&($u.startInline?$u.startInline.push(Pu.start):$u.startInline=[Pu.start]))}"childTokens"in Pu&&Pu.childTokens&&($u.childTokens[Pu.name]=Pu.childTokens)}),Iu.extensions=$u),Ru.renderer){let Pu=this.defaults.renderer||new P$3(this.defaults);for(let Ou in Ru.renderer){if(!(Ou in Pu))throw new Error(`renderer '${Ou}' does not exist`);if(["options","parser"].includes(Ou))continue;let Mu=Ou,Du=Ru.renderer[Mu],Lu=Pu[Mu];Pu[Mu]=(...Bu)=>{let ju=Du.apply(Pu,Bu);return ju===!1&&(ju=Lu.apply(Pu,Bu)),ju||""}}Iu.renderer=Pu}if(Ru.tokenizer){let Pu=this.defaults.tokenizer||new y$4(this.defaults);for(let Ou in Ru.tokenizer){if(!(Ou in Pu))throw new Error(`tokenizer '${Ou}' does not exist`);if(["options","rules","lexer"].includes(Ou))continue;let Mu=Ou,Du=Ru.tokenizer[Mu],Lu=Pu[Mu];Pu[Mu]=(...Bu)=>{let ju=Du.apply(Pu,Bu);return ju===!1&&(ju=Lu.apply(Pu,Bu)),ju}}Iu.tokenizer=Pu}if(Ru.hooks){let Pu=this.defaults.hooks||new S$2;for(let Ou in Ru.hooks){if(!(Ou in Pu))throw new Error(`hook '${Ou}' does not exist`);if(["options","block"].includes(Ou))continue;let Mu=Ou,Du=Ru.hooks[Mu],Lu=Pu[Mu];S$2.passThroughHooks.has(Ou)?Pu[Mu]=Bu=>{if(this.defaults.async&&S$2.passThroughHooksRespectAsync.has(Ou))return(async()=>{let Fu=await Du.call(Pu,Bu);return Lu.call(Pu,Fu)})();let ju=Du.call(Pu,Bu);return Lu.call(Pu,ju)}:Pu[Mu]=(...Bu)=>{if(this.defaults.async)return(async()=>{let Fu=await Du.apply(Pu,Bu);return Fu===!1&&(Fu=await Lu.apply(Pu,Bu)),Fu})();let ju=Du.apply(Pu,Bu);return ju===!1&&(ju=Lu.apply(Pu,Bu)),ju}}Iu.hooks=Pu}if(Ru.walkTokens){let Pu=this.defaults.walkTokens,Ou=Ru.walkTokens;Iu.walkTokens=function(Mu){let Du=[];return Du.push(Ou.call(this,Mu)),Pu&&(Du=Du.concat(Pu.call(this,Mu))),Du}}this.defaults={...this.defaults,...Iu}}),this}setOptions(lo){return this.defaults={...this.defaults,...lo},this}lexer(lo,$u){return x$7.lex(lo,$u??this.defaults)}parser(lo,$u){return b$5.parse(lo,$u??this.defaults)}parseMarkdown(lo){return($u,Ru)=>{let Iu={...Ru},Pu={...this.defaults,...Iu},Ou=this.onError(!!Pu.silent,!!Pu.async);if(this.defaults.async===!0&&Iu.async===!1)return Ou(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof $u>"u"||$u===null)return Ou(new Error("marked(): input parameter is undefined or null"));if(typeof $u!="string")return Ou(new Error("marked(): input parameter is of type "+Object.prototype.toString.call($u)+", string expected"));if(Pu.hooks&&(Pu.hooks.options=Pu,Pu.hooks.block=lo),Pu.async)return(async()=>{let Mu=Pu.hooks?await Pu.hooks.preprocess($u):$u,Du=await(Pu.hooks?await Pu.hooks.provideLexer():lo?x$7.lex:x$7.lexInline)(Mu,Pu),Lu=Pu.hooks?await Pu.hooks.processAllTokens(Du):Du;Pu.walkTokens&&await Promise.all(this.walkTokens(Lu,Pu.walkTokens));let Bu=await(Pu.hooks?await Pu.hooks.provideParser():lo?b$5.parse:b$5.parseInline)(Lu,Pu);return Pu.hooks?await Pu.hooks.postprocess(Bu):Bu})().catch(Ou);try{Pu.hooks&&($u=Pu.hooks.preprocess($u));let Mu=(Pu.hooks?Pu.hooks.provideLexer():lo?x$7.lex:x$7.lexInline)($u,Pu);Pu.hooks&&(Mu=Pu.hooks.processAllTokens(Mu)),Pu.walkTokens&&this.walkTokens(Mu,Pu.walkTokens);let Du=(Pu.hooks?Pu.hooks.provideParser():lo?b$5.parse:b$5.parseInline)(Mu,Pu);return Pu.hooks&&(Du=Pu.hooks.postprocess(Du)),Du}catch(Mu){return Ou(Mu)}}}onError(lo,$u){return Ru=>{if(Ru.message+=`
|
|
3632
|
-
Please report this to https://github.com/markedjs/marked.`,lo){let Iu="<p>An error occurred:</p><pre>"+w$2(Ru.message+"",!0)+"</pre>";return $u?Promise.resolve(Iu):Iu}if($u)return Promise.reject(Ru);throw Ru}}},_$4=new B$2;function k$2(Au,lo){return _$4.parse(Au,lo)}k$2.options=k$2.setOptions=function(Au){return _$4.setOptions(Au),k$2.defaults=_$4.defaults,G$1(k$2.defaults),k$2};k$2.getDefaults=L$2;k$2.defaults=T$1;k$2.use=function(...Au){return _$4.use(...Au),k$2.defaults=_$4.defaults,G$1(k$2.defaults),k$2};k$2.walkTokens=function(Au,lo){return _$4.walkTokens(Au,lo)};k$2.parseInline=_$4.parseInline;k$2.Parser=b$5;k$2.parser=b$5.parse;k$2.Renderer=P$3;k$2.TextRenderer=$$1;k$2.Lexer=x$7;k$2.lexer=x$7.lex;k$2.Tokenizer=y$4;k$2.Hooks=S$2;k$2.parse=k$2;k$2.options;k$2.setOptions;k$2.use;k$2.walkTokens;k$2.parseInline;b$5.parse;x$7.lex;var u$2=(...Au)=>twMerge(clsx(Au)),R$2=(Au,lo,$u)=>{let Ru=typeof lo=="string"?new Blob([lo],{type:$u}):lo,Iu=URL.createObjectURL(Ru),Pu=document.createElement("a");Pu.href=Iu,Pu.download=Au,document.body.appendChild(Pu),Pu.click(),document.body.removeChild(Pu),URL.revokeObjectURL(Iu)},Dt$4=reactExports.createContext({code:""}),U$2=()=>reactExports.useContext(Dt$4),ie$4=({onCopy:Au,onError:lo,timeout:$u=2e3,children:Ru,className:Iu,code:Pu,...Ou})=>{let[Mu,Du]=reactExports.useState(!1),Lu=reactExports.useRef(0),{code:Bu}=U$2(),{isAnimating:ju}=reactExports.useContext(C$1),Fu=Pu??Bu,zu=async()=>{var Hu;if(typeof window>"u"||!((Hu=navigator?.clipboard)!=null&&Hu.writeText)){lo?.(new Error("Clipboard API not available"));return}try{Mu||(await navigator.clipboard.writeText(Fu),Du(!0),Au?.(),Lu.current=window.setTimeout(()=>Du(!1),$u))}catch(Vu){lo?.(Vu)}};reactExports.useEffect(()=>()=>{window.clearTimeout(Lu.current)},[]);let Uu=Mu?Check:Copy;return jsxRuntimeExports.jsx("button",{className:u$2("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",Iu),"data-streamdown":"code-block-copy-button",disabled:ju,onClick:zu,title:"Copy Code",type:"button",...Ou,children:Ru??jsxRuntimeExports.jsx(Uu,{size:14})})},xe$2={"1c":"1c","1c-query":"1cq",abap:"abap","actionscript-3":"as",ada:"ada",adoc:"adoc","angular-html":"html","angular-ts":"ts",apache:"conf",apex:"cls",apl:"apl",applescript:"applescript",ara:"ara",asciidoc:"adoc",asm:"asm",astro:"astro",awk:"awk",ballerina:"bal",bash:"sh",bat:"bat",batch:"bat",be:"be",beancount:"beancount",berry:"berry",bibtex:"bib",bicep:"bicep",blade:"blade.php",bsl:"bsl",c:"c","c#":"cs","c++":"cpp",cadence:"cdc",cairo:"cairo",cdc:"cdc",clarity:"clar",clj:"clj",clojure:"clj","closure-templates":"soy",cmake:"cmake",cmd:"cmd",cobol:"cob",codeowners:"CODEOWNERS",codeql:"ql",coffee:"coffee",coffeescript:"coffee","common-lisp":"lisp",console:"sh",coq:"v",cpp:"cpp",cql:"cql",crystal:"cr",cs:"cs",csharp:"cs",css:"css",csv:"csv",cue:"cue",cypher:"cql",d:"d",dart:"dart",dax:"dax",desktop:"desktop",diff:"diff",docker:"dockerfile",dockerfile:"dockerfile",dotenv:"env","dream-maker":"dm",edge:"edge",elisp:"el",elixir:"ex",elm:"elm","emacs-lisp":"el",erb:"erb",erl:"erl",erlang:"erl",f:"f","f#":"fs",f03:"f03",f08:"f08",f18:"f18",f77:"f77",f90:"f90",f95:"f95",fennel:"fnl",fish:"fish",fluent:"ftl",for:"for","fortran-fixed-form":"f","fortran-free-form":"f90",fs:"fs",fsharp:"fs",fsl:"fsl",ftl:"ftl",gdresource:"tres",gdscript:"gd",gdshader:"gdshader",genie:"gs",gherkin:"feature","git-commit":"gitcommit","git-rebase":"gitrebase",gjs:"js",gleam:"gleam","glimmer-js":"js","glimmer-ts":"ts",glsl:"glsl",gnuplot:"plt",go:"go",gql:"gql",graphql:"graphql",groovy:"groovy",gts:"gts",hack:"hack",haml:"haml",handlebars:"hbs",haskell:"hs",haxe:"hx",hbs:"hbs",hcl:"hcl",hjson:"hjson",hlsl:"hlsl",hs:"hs",html:"html","html-derivative":"html",http:"http",hxml:"hxml",hy:"hy",imba:"imba",ini:"ini",jade:"jade",java:"java",javascript:"js",jinja:"jinja",jison:"jison",jl:"jl",js:"js",json:"json",json5:"json5",jsonc:"jsonc",jsonl:"jsonl",jsonnet:"jsonnet",jssm:"jssm",jsx:"jsx",julia:"jl",kotlin:"kt",kql:"kql",kt:"kt",kts:"kts",kusto:"kql",latex:"tex",lean:"lean",lean4:"lean",less:"less",liquid:"liquid",lisp:"lisp",lit:"lit",llvm:"ll",log:"log",logo:"logo",lua:"lua",luau:"luau",make:"mak",makefile:"mak",markdown:"md",marko:"marko",matlab:"m",md:"md",mdc:"mdc",mdx:"mdx",mediawiki:"wiki",mermaid:"mmd",mips:"s",mipsasm:"s",mmd:"mmd",mojo:"mojo",move:"move",nar:"nar",narrat:"narrat",nextflow:"nf",nf:"nf",nginx:"conf",nim:"nim",nix:"nix",nu:"nu",nushell:"nu",objc:"m","objective-c":"m","objective-cpp":"mm",ocaml:"ml",pascal:"pas",perl:"pl",perl6:"p6",php:"php",plsql:"pls",po:"po",polar:"polar",postcss:"pcss",pot:"pot",potx:"potx",powerquery:"pq",powershell:"ps1",prisma:"prisma",prolog:"pl",properties:"properties",proto:"proto",protobuf:"proto",ps:"ps",ps1:"ps1",pug:"pug",puppet:"pp",purescript:"purs",py:"py",python:"py",ql:"ql",qml:"qml",qmldir:"qmldir",qss:"qss",r:"r",racket:"rkt",raku:"raku",razor:"cshtml",rb:"rb",reg:"reg",regex:"regex",regexp:"regexp",rel:"rel",riscv:"s",rs:"rs",rst:"rst",ruby:"rb",rust:"rs",sas:"sas",sass:"sass",scala:"scala",scheme:"scm",scss:"scss",sdbl:"sdbl",sh:"sh",shader:"shader",shaderlab:"shader",shell:"sh",shellscript:"sh",shellsession:"sh",smalltalk:"st",solidity:"sol",soy:"soy",sparql:"rq",spl:"spl",splunk:"spl",sql:"sql","ssh-config":"config",stata:"do",styl:"styl",stylus:"styl",svelte:"svelte",swift:"swift","system-verilog":"sv",systemd:"service",talon:"talon",talonscript:"talon",tasl:"tasl",tcl:"tcl",templ:"templ",terraform:"tf",tex:"tex",tf:"tf",tfvars:"tfvars",toml:"toml",ts:"ts","ts-tags":"ts",tsp:"tsp",tsv:"tsv",tsx:"tsx",turtle:"ttl",twig:"twig",typ:"typ",typescript:"ts",typespec:"tsp",typst:"typ",v:"v",vala:"vala",vb:"vb",verilog:"v",vhdl:"vhdl",vim:"vim",viml:"vim",vimscript:"vim",vue:"vue","vue-html":"html","vue-vine":"vine",vy:"vy",vyper:"vy",wasm:"wasm",wenyan:"wy",wgsl:"wgsl",wiki:"wiki",wikitext:"wiki",wit:"wit",wl:"wl",wolfram:"wl",xml:"xml",xsl:"xsl",yaml:"yaml",yml:"yml",zenscript:"zs",zig:"zig",zsh:"zsh",文言:"wy"},Me$3=({onDownload:Au,onError:lo,language:$u,children:Ru,className:Iu,code:Pu,...Ou})=>{let{code:Mu}=U$2(),{isAnimating:Du}=reactExports.useContext(C$1),Lu=Pu??Mu,Bu=`file.${$u&&$u in xe$2?xe$2[$u]:"txt"}`,ju="text/plain",Fu=()=>{try{R$2(Bu,Lu,ju),Au?.()}catch(zu){lo?.(zu)}};return jsxRuntimeExports.jsx("button",{className:u$2("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",Iu),"data-streamdown":"code-block-download-button",disabled:Du,onClick:Fu,title:"Download file",type:"button",...Ou,children:Ru??jsxRuntimeExports.jsx(Download$1,{size:14})})},de$3=()=>jsxRuntimeExports.jsxs("div",{className:"w-full divide-y divide-border overflow-hidden rounded-xl border border-border",children:[jsxRuntimeExports.jsx("div",{className:"h-[46px] w-full bg-muted/80"}),jsxRuntimeExports.jsx("div",{className:"flex w-full items-center justify-center p-4",children:jsxRuntimeExports.jsx(LoaderCircle,{className:"size-4 animate-spin"})})]}),Jt$3=/\.[^/.]+$/,Pe$3=({node:Au,className:lo,src:$u,alt:Ru,...Iu})=>{let Pu=async()=>{if($u)try{let Ou=await(await fetch($u)).blob(),Mu=new URL($u,window.location.origin).pathname.split("/").pop()||"",Du=Mu.split(".").pop(),Lu=Mu.includes(".")&&Du!==void 0&&Du.length<=4,Bu="";if(Lu)Bu=Mu;else{let ju=Ou.type,Fu="png";ju.includes("jpeg")||ju.includes("jpg")?Fu="jpg":ju.includes("png")?Fu="png":ju.includes("svg")?Fu="svg":ju.includes("gif")?Fu="gif":ju.includes("webp")&&(Fu="webp"),Bu=`${(Ru||Mu||"image").replace(Jt$3,"")}.${Fu}`}R$2(Bu,Ou,Ou.type)}catch(Ou){console.error("Failed to download image:",Ou)}};return $u?jsxRuntimeExports.jsxs("div",{className:"group relative my-4 inline-block","data-streamdown":"image-wrapper",children:[jsxRuntimeExports.jsx("img",{alt:Ru,className:u$2("max-w-full rounded-lg",lo),"data-streamdown":"image",src:$u,...Iu}),jsxRuntimeExports.jsx("div",{className:"pointer-events-none absolute inset-0 hidden rounded-lg bg-black/10 group-hover:block"}),jsxRuntimeExports.jsx("button",{className:u$2("absolute right-2 bottom-2 flex h-8 w-8 cursor-pointer items-center justify-center rounded-md border border-border bg-background/90 shadow-sm backdrop-blur-sm transition-all duration-200 hover:bg-background","opacity-0 group-hover:opacity-100"),onClick:Pu,title:"Download image",type:"button",children:jsxRuntimeExports.jsx(Download$1,{size:14})})]}):null},_$3=async Au=>{let lo={startOnLoad:!1,theme:"default",securityLevel:"strict",fontFamily:"monospace",suppressErrorRendering:!0,...Au},$u=(await __vitePreload(async()=>{const{default:Ru}=await import("./chunks/mermaid.core-D0955PCw.js").then(Iu=>Iu.an);return{default:Ru}},[],import.meta.url)).default;return $u.initialize(lo),$u},Te$3=(Au,lo)=>{var $u;let Ru=($u=void 0)!=null?$u:5;return new Promise((Iu,Pu)=>{let Ou="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(Au))),Mu=new Image;Mu.crossOrigin="anonymous",Mu.onload=()=>{let Du=document.createElement("canvas"),Lu=Mu.width*Ru,Bu=Mu.height*Ru;Du.width=Lu,Du.height=Bu;let ju=Du.getContext("2d");if(!ju){Pu(new Error("Failed to create 2D canvas context for PNG export"));return}ju.drawImage(Mu,0,0,Lu,Bu),Du.toBlob(Fu=>{if(!Fu){Pu(new Error("Failed to create PNG blob"));return}Iu(Fu)},"image/png")},Mu.onerror=()=>Pu(new Error("Failed to load SVG image")),Mu.src=Ou})},Se$2=({chart:Au,children:lo,className:$u,onDownload:Ru,config:Iu,onError:Pu})=>{let[Ou,Mu]=reactExports.useState(!1),Du=reactExports.useRef(null),{isAnimating:Lu}=reactExports.useContext(C$1),Bu=async ju=>{try{if(ju==="mmd"){R$2("diagram.mmd",Au,"text/plain"),Mu(!1),Ru?.(ju);return}let Fu=await _$3(Iu),zu=Au.split("").reduce((Vu,Gu)=>(Vu<<5)-Vu+Gu.charCodeAt(0)|0,0),Uu=`mermaid-${Math.abs(zu)}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,{svg:Hu}=await Fu.render(Uu,Au);if(!Hu){Pu?.(new Error("SVG not found. Please wait for the diagram to render."));return}if(ju==="svg"){R$2("diagram.svg",Hu,"image/svg+xml"),Mu(!1),Ru?.(ju);return}if(ju==="png"){let Vu=await Te$3(Hu);R$2("diagram.png",Vu,"image/png"),Ru?.(ju),Mu(!1);return}}catch(Fu){Pu?.(Fu)}};return reactExports.useEffect(()=>{let ju=Fu=>{Du.current&&!Du.current.contains(Fu.target)&&Mu(!1)};return document.addEventListener("mousedown",ju),()=>{document.removeEventListener("mousedown",ju)}},[]),jsxRuntimeExports.jsxs("div",{className:"relative",ref:Du,children:[jsxRuntimeExports.jsx("button",{className:u$2("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",$u),disabled:Lu,onClick:()=>Mu(!Ou),title:"Download diagram",type:"button",children:lo??jsxRuntimeExports.jsx(Download$1,{size:14})}),Ou&&jsxRuntimeExports.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[120px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[jsxRuntimeExports.jsx("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>Bu("svg"),title:"Download diagram as SVG",type:"button",children:"SVG"}),jsxRuntimeExports.jsx("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>Bu("png"),title:"Download diagram as PNG",type:"button",children:"PNG"}),jsxRuntimeExports.jsx("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>Bu("mmd"),title:"Download diagram as MMD",type:"button",children:"MMD"})]})]})},J$1=0,to$1=()=>{J$1+=1,J$1===1&&(document.body.style.overflow="hidden")},oo$1=()=>{J$1=Math.max(0,J$1-1),J$1===0&&(document.body.style.overflow="")},De$2=({chart:Au,config:lo,onFullscreen:$u,onExit:Ru,className:Iu,...Pu})=>{let[Ou,Mu]=reactExports.useState(!1),{isAnimating:Du,controls:Lu}=reactExports.useContext(C$1),Bu=(()=>{if(typeof Lu=="boolean")return Lu;let Fu=Lu.mermaid;return Fu===!1?!1:Fu===!0||Fu===void 0?!0:Fu.panZoom!==!1})(),ju=()=>{Mu(!Ou)};return reactExports.useEffect(()=>{if(Ou){to$1();let Fu=zu=>{zu.key==="Escape"&&Mu(!1)};return document.addEventListener("keydown",Fu),()=>{document.removeEventListener("keydown",Fu),oo$1()}}},[Ou]),reactExports.useEffect(()=>{Ou?$u?.():Ru&&Ru()},[Ou,$u,Ru]),jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("button",{className:u$2("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",Iu),disabled:Du,onClick:ju,title:"View fullscreen",type:"button",...Pu,children:jsxRuntimeExports.jsx(Maximize2,{size:14})}),Ou&&jsxRuntimeExports.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/95 backdrop-blur-sm",onClick:ju,onKeyDown:Fu=>{Fu.key==="Escape"&&ju()},role:"button",tabIndex:0,children:[jsxRuntimeExports.jsx("button",{className:"absolute top-4 right-4 z-10 rounded-md p-2 text-muted-foreground transition-all hover:bg-muted hover:text-foreground",onClick:ju,title:"Exit fullscreen",type:"button",children:jsxRuntimeExports.jsx(X$3,{size:20})}),jsxRuntimeExports.jsx("div",{className:"flex h-full w-full items-center justify-center p-4",onClick:Fu=>Fu.stopPropagation(),onKeyDown:Fu=>Fu.stopPropagation(),role:"presentation",children:jsxRuntimeExports.jsx(Ee$2,{chart:Au,className:"h-full w-full [&>div]:h-full [&>div]:overflow-hidden [&_svg]:h-auto [&_svg]:w-auto",config:lo,fullscreen:!0,showControls:Bu})})]})]})},Y$1=Au=>{var lo,$u;let Ru=[],Iu=[],Pu=Au.querySelectorAll("thead th");for(let Mu of Pu)Ru.push(((lo=Mu.textContent)==null?void 0:lo.trim())||"");let Ou=Au.querySelectorAll("tbody tr");for(let Mu of Ou){let Du=[],Lu=Mu.querySelectorAll("td");for(let Bu of Lu)Du.push((($u=Bu.textContent)==null?void 0:$u.trim())||"");Iu.push(Du)}return{headers:Ru,rows:Iu}},Q$1=Au=>{let{headers:lo,rows:$u}=Au,Ru=Mu=>{let Du=!1,Lu=!1;for(let Bu=0;Bu<Mu.length;Bu+=1){let ju=Mu[Bu];if(ju==='"'){Du=!0,Lu=!0;break}(ju===","||ju===`
|
|
3632
|
+
Please report this to https://github.com/markedjs/marked.`,lo){let Iu="<p>An error occurred:</p><pre>"+w$2(Ru.message+"",!0)+"</pre>";return $u?Promise.resolve(Iu):Iu}if($u)return Promise.reject(Ru);throw Ru}}},_$4=new B$2;function k$2(Au,lo){return _$4.parse(Au,lo)}k$2.options=k$2.setOptions=function(Au){return _$4.setOptions(Au),k$2.defaults=_$4.defaults,G$1(k$2.defaults),k$2};k$2.getDefaults=L$2;k$2.defaults=T$1;k$2.use=function(...Au){return _$4.use(...Au),k$2.defaults=_$4.defaults,G$1(k$2.defaults),k$2};k$2.walkTokens=function(Au,lo){return _$4.walkTokens(Au,lo)};k$2.parseInline=_$4.parseInline;k$2.Parser=b$5;k$2.parser=b$5.parse;k$2.Renderer=P$3;k$2.TextRenderer=$$1;k$2.Lexer=x$7;k$2.lexer=x$7.lex;k$2.Tokenizer=y$4;k$2.Hooks=S$2;k$2.parse=k$2;k$2.options;k$2.setOptions;k$2.use;k$2.walkTokens;k$2.parseInline;b$5.parse;x$7.lex;var u$2=(...Au)=>twMerge(clsx(Au)),R$2=(Au,lo,$u)=>{let Ru=typeof lo=="string"?new Blob([lo],{type:$u}):lo,Iu=URL.createObjectURL(Ru),Pu=document.createElement("a");Pu.href=Iu,Pu.download=Au,document.body.appendChild(Pu),Pu.click(),document.body.removeChild(Pu),URL.revokeObjectURL(Iu)},Dt$4=reactExports.createContext({code:""}),U$2=()=>reactExports.useContext(Dt$4),ie$4=({onCopy:Au,onError:lo,timeout:$u=2e3,children:Ru,className:Iu,code:Pu,...Ou})=>{let[Mu,Du]=reactExports.useState(!1),Lu=reactExports.useRef(0),{code:Bu}=U$2(),{isAnimating:ju}=reactExports.useContext(C$1),Fu=Pu??Bu,zu=async()=>{var Hu;if(typeof window>"u"||!((Hu=navigator?.clipboard)!=null&&Hu.writeText)){lo?.(new Error("Clipboard API not available"));return}try{Mu||(await navigator.clipboard.writeText(Fu),Du(!0),Au?.(),Lu.current=window.setTimeout(()=>Du(!1),$u))}catch(Vu){lo?.(Vu)}};reactExports.useEffect(()=>()=>{window.clearTimeout(Lu.current)},[]);let Uu=Mu?Check:Copy;return jsxRuntimeExports.jsx("button",{className:u$2("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",Iu),"data-streamdown":"code-block-copy-button",disabled:ju,onClick:zu,title:"Copy Code",type:"button",...Ou,children:Ru??jsxRuntimeExports.jsx(Uu,{size:14})})},xe$2={"1c":"1c","1c-query":"1cq",abap:"abap","actionscript-3":"as",ada:"ada",adoc:"adoc","angular-html":"html","angular-ts":"ts",apache:"conf",apex:"cls",apl:"apl",applescript:"applescript",ara:"ara",asciidoc:"adoc",asm:"asm",astro:"astro",awk:"awk",ballerina:"bal",bash:"sh",bat:"bat",batch:"bat",be:"be",beancount:"beancount",berry:"berry",bibtex:"bib",bicep:"bicep",blade:"blade.php",bsl:"bsl",c:"c","c#":"cs","c++":"cpp",cadence:"cdc",cairo:"cairo",cdc:"cdc",clarity:"clar",clj:"clj",clojure:"clj","closure-templates":"soy",cmake:"cmake",cmd:"cmd",cobol:"cob",codeowners:"CODEOWNERS",codeql:"ql",coffee:"coffee",coffeescript:"coffee","common-lisp":"lisp",console:"sh",coq:"v",cpp:"cpp",cql:"cql",crystal:"cr",cs:"cs",csharp:"cs",css:"css",csv:"csv",cue:"cue",cypher:"cql",d:"d",dart:"dart",dax:"dax",desktop:"desktop",diff:"diff",docker:"dockerfile",dockerfile:"dockerfile",dotenv:"env","dream-maker":"dm",edge:"edge",elisp:"el",elixir:"ex",elm:"elm","emacs-lisp":"el",erb:"erb",erl:"erl",erlang:"erl",f:"f","f#":"fs",f03:"f03",f08:"f08",f18:"f18",f77:"f77",f90:"f90",f95:"f95",fennel:"fnl",fish:"fish",fluent:"ftl",for:"for","fortran-fixed-form":"f","fortran-free-form":"f90",fs:"fs",fsharp:"fs",fsl:"fsl",ftl:"ftl",gdresource:"tres",gdscript:"gd",gdshader:"gdshader",genie:"gs",gherkin:"feature","git-commit":"gitcommit","git-rebase":"gitrebase",gjs:"js",gleam:"gleam","glimmer-js":"js","glimmer-ts":"ts",glsl:"glsl",gnuplot:"plt",go:"go",gql:"gql",graphql:"graphql",groovy:"groovy",gts:"gts",hack:"hack",haml:"haml",handlebars:"hbs",haskell:"hs",haxe:"hx",hbs:"hbs",hcl:"hcl",hjson:"hjson",hlsl:"hlsl",hs:"hs",html:"html","html-derivative":"html",http:"http",hxml:"hxml",hy:"hy",imba:"imba",ini:"ini",jade:"jade",java:"java",javascript:"js",jinja:"jinja",jison:"jison",jl:"jl",js:"js",json:"json",json5:"json5",jsonc:"jsonc",jsonl:"jsonl",jsonnet:"jsonnet",jssm:"jssm",jsx:"jsx",julia:"jl",kotlin:"kt",kql:"kql",kt:"kt",kts:"kts",kusto:"kql",latex:"tex",lean:"lean",lean4:"lean",less:"less",liquid:"liquid",lisp:"lisp",lit:"lit",llvm:"ll",log:"log",logo:"logo",lua:"lua",luau:"luau",make:"mak",makefile:"mak",markdown:"md",marko:"marko",matlab:"m",md:"md",mdc:"mdc",mdx:"mdx",mediawiki:"wiki",mermaid:"mmd",mips:"s",mipsasm:"s",mmd:"mmd",mojo:"mojo",move:"move",nar:"nar",narrat:"narrat",nextflow:"nf",nf:"nf",nginx:"conf",nim:"nim",nix:"nix",nu:"nu",nushell:"nu",objc:"m","objective-c":"m","objective-cpp":"mm",ocaml:"ml",pascal:"pas",perl:"pl",perl6:"p6",php:"php",plsql:"pls",po:"po",polar:"polar",postcss:"pcss",pot:"pot",potx:"potx",powerquery:"pq",powershell:"ps1",prisma:"prisma",prolog:"pl",properties:"properties",proto:"proto",protobuf:"proto",ps:"ps",ps1:"ps1",pug:"pug",puppet:"pp",purescript:"purs",py:"py",python:"py",ql:"ql",qml:"qml",qmldir:"qmldir",qss:"qss",r:"r",racket:"rkt",raku:"raku",razor:"cshtml",rb:"rb",reg:"reg",regex:"regex",regexp:"regexp",rel:"rel",riscv:"s",rs:"rs",rst:"rst",ruby:"rb",rust:"rs",sas:"sas",sass:"sass",scala:"scala",scheme:"scm",scss:"scss",sdbl:"sdbl",sh:"sh",shader:"shader",shaderlab:"shader",shell:"sh",shellscript:"sh",shellsession:"sh",smalltalk:"st",solidity:"sol",soy:"soy",sparql:"rq",spl:"spl",splunk:"spl",sql:"sql","ssh-config":"config",stata:"do",styl:"styl",stylus:"styl",svelte:"svelte",swift:"swift","system-verilog":"sv",systemd:"service",talon:"talon",talonscript:"talon",tasl:"tasl",tcl:"tcl",templ:"templ",terraform:"tf",tex:"tex",tf:"tf",tfvars:"tfvars",toml:"toml",ts:"ts","ts-tags":"ts",tsp:"tsp",tsv:"tsv",tsx:"tsx",turtle:"ttl",twig:"twig",typ:"typ",typescript:"ts",typespec:"tsp",typst:"typ",v:"v",vala:"vala",vb:"vb",verilog:"v",vhdl:"vhdl",vim:"vim",viml:"vim",vimscript:"vim",vue:"vue","vue-html":"html","vue-vine":"vine",vy:"vy",vyper:"vy",wasm:"wasm",wenyan:"wy",wgsl:"wgsl",wiki:"wiki",wikitext:"wiki",wit:"wit",wl:"wl",wolfram:"wl",xml:"xml",xsl:"xsl",yaml:"yaml",yml:"yml",zenscript:"zs",zig:"zig",zsh:"zsh",文言:"wy"},Me$3=({onDownload:Au,onError:lo,language:$u,children:Ru,className:Iu,code:Pu,...Ou})=>{let{code:Mu}=U$2(),{isAnimating:Du}=reactExports.useContext(C$1),Lu=Pu??Mu,Bu=`file.${$u&&$u in xe$2?xe$2[$u]:"txt"}`,ju="text/plain",Fu=()=>{try{R$2(Bu,Lu,ju),Au?.()}catch(zu){lo?.(zu)}};return jsxRuntimeExports.jsx("button",{className:u$2("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",Iu),"data-streamdown":"code-block-download-button",disabled:Du,onClick:Fu,title:"Download file",type:"button",...Ou,children:Ru??jsxRuntimeExports.jsx(Download$1,{size:14})})},de$3=()=>jsxRuntimeExports.jsxs("div",{className:"w-full divide-y divide-border overflow-hidden rounded-xl border border-border",children:[jsxRuntimeExports.jsx("div",{className:"h-[46px] w-full bg-muted/80"}),jsxRuntimeExports.jsx("div",{className:"flex w-full items-center justify-center p-4",children:jsxRuntimeExports.jsx(LoaderCircle,{className:"size-4 animate-spin"})})]}),Jt$3=/\.[^/.]+$/,Pe$3=({node:Au,className:lo,src:$u,alt:Ru,...Iu})=>{let Pu=async()=>{if($u)try{let Ou=await(await fetch($u)).blob(),Mu=new URL($u,window.location.origin).pathname.split("/").pop()||"",Du=Mu.split(".").pop(),Lu=Mu.includes(".")&&Du!==void 0&&Du.length<=4,Bu="";if(Lu)Bu=Mu;else{let ju=Ou.type,Fu="png";ju.includes("jpeg")||ju.includes("jpg")?Fu="jpg":ju.includes("png")?Fu="png":ju.includes("svg")?Fu="svg":ju.includes("gif")?Fu="gif":ju.includes("webp")&&(Fu="webp"),Bu=`${(Ru||Mu||"image").replace(Jt$3,"")}.${Fu}`}R$2(Bu,Ou,Ou.type)}catch(Ou){console.error("Failed to download image:",Ou)}};return $u?jsxRuntimeExports.jsxs("div",{className:"group relative my-4 inline-block","data-streamdown":"image-wrapper",children:[jsxRuntimeExports.jsx("img",{alt:Ru,className:u$2("max-w-full rounded-lg",lo),"data-streamdown":"image",src:$u,...Iu}),jsxRuntimeExports.jsx("div",{className:"pointer-events-none absolute inset-0 hidden rounded-lg bg-black/10 group-hover:block"}),jsxRuntimeExports.jsx("button",{className:u$2("absolute right-2 bottom-2 flex h-8 w-8 cursor-pointer items-center justify-center rounded-md border border-border bg-background/90 shadow-sm backdrop-blur-sm transition-all duration-200 hover:bg-background","opacity-0 group-hover:opacity-100"),onClick:Pu,title:"Download image",type:"button",children:jsxRuntimeExports.jsx(Download$1,{size:14})})]}):null},_$3=async Au=>{let lo={startOnLoad:!1,theme:"default",securityLevel:"strict",fontFamily:"monospace",suppressErrorRendering:!0,...Au},$u=(await __vitePreload(async()=>{const{default:Ru}=await import("./chunks/mermaid.core-CN-kUGXQ.js").then(Iu=>Iu.an);return{default:Ru}},[],import.meta.url)).default;return $u.initialize(lo),$u},Te$3=(Au,lo)=>{var $u;let Ru=($u=void 0)!=null?$u:5;return new Promise((Iu,Pu)=>{let Ou="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(Au))),Mu=new Image;Mu.crossOrigin="anonymous",Mu.onload=()=>{let Du=document.createElement("canvas"),Lu=Mu.width*Ru,Bu=Mu.height*Ru;Du.width=Lu,Du.height=Bu;let ju=Du.getContext("2d");if(!ju){Pu(new Error("Failed to create 2D canvas context for PNG export"));return}ju.drawImage(Mu,0,0,Lu,Bu),Du.toBlob(Fu=>{if(!Fu){Pu(new Error("Failed to create PNG blob"));return}Iu(Fu)},"image/png")},Mu.onerror=()=>Pu(new Error("Failed to load SVG image")),Mu.src=Ou})},Se$2=({chart:Au,children:lo,className:$u,onDownload:Ru,config:Iu,onError:Pu})=>{let[Ou,Mu]=reactExports.useState(!1),Du=reactExports.useRef(null),{isAnimating:Lu}=reactExports.useContext(C$1),Bu=async ju=>{try{if(ju==="mmd"){R$2("diagram.mmd",Au,"text/plain"),Mu(!1),Ru?.(ju);return}let Fu=await _$3(Iu),zu=Au.split("").reduce((Vu,Gu)=>(Vu<<5)-Vu+Gu.charCodeAt(0)|0,0),Uu=`mermaid-${Math.abs(zu)}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,{svg:Hu}=await Fu.render(Uu,Au);if(!Hu){Pu?.(new Error("SVG not found. Please wait for the diagram to render."));return}if(ju==="svg"){R$2("diagram.svg",Hu,"image/svg+xml"),Mu(!1),Ru?.(ju);return}if(ju==="png"){let Vu=await Te$3(Hu);R$2("diagram.png",Vu,"image/png"),Ru?.(ju),Mu(!1);return}}catch(Fu){Pu?.(Fu)}};return reactExports.useEffect(()=>{let ju=Fu=>{Du.current&&!Du.current.contains(Fu.target)&&Mu(!1)};return document.addEventListener("mousedown",ju),()=>{document.removeEventListener("mousedown",ju)}},[]),jsxRuntimeExports.jsxs("div",{className:"relative",ref:Du,children:[jsxRuntimeExports.jsx("button",{className:u$2("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",$u),disabled:Lu,onClick:()=>Mu(!Ou),title:"Download diagram",type:"button",children:lo??jsxRuntimeExports.jsx(Download$1,{size:14})}),Ou&&jsxRuntimeExports.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[120px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[jsxRuntimeExports.jsx("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>Bu("svg"),title:"Download diagram as SVG",type:"button",children:"SVG"}),jsxRuntimeExports.jsx("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>Bu("png"),title:"Download diagram as PNG",type:"button",children:"PNG"}),jsxRuntimeExports.jsx("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>Bu("mmd"),title:"Download diagram as MMD",type:"button",children:"MMD"})]})]})},J$1=0,to$1=()=>{J$1+=1,J$1===1&&(document.body.style.overflow="hidden")},oo$1=()=>{J$1=Math.max(0,J$1-1),J$1===0&&(document.body.style.overflow="")},De$2=({chart:Au,config:lo,onFullscreen:$u,onExit:Ru,className:Iu,...Pu})=>{let[Ou,Mu]=reactExports.useState(!1),{isAnimating:Du,controls:Lu}=reactExports.useContext(C$1),Bu=(()=>{if(typeof Lu=="boolean")return Lu;let Fu=Lu.mermaid;return Fu===!1?!1:Fu===!0||Fu===void 0?!0:Fu.panZoom!==!1})(),ju=()=>{Mu(!Ou)};return reactExports.useEffect(()=>{if(Ou){to$1();let Fu=zu=>{zu.key==="Escape"&&Mu(!1)};return document.addEventListener("keydown",Fu),()=>{document.removeEventListener("keydown",Fu),oo$1()}}},[Ou]),reactExports.useEffect(()=>{Ou?$u?.():Ru&&Ru()},[Ou,$u,Ru]),jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("button",{className:u$2("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",Iu),disabled:Du,onClick:ju,title:"View fullscreen",type:"button",...Pu,children:jsxRuntimeExports.jsx(Maximize2,{size:14})}),Ou&&jsxRuntimeExports.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/95 backdrop-blur-sm",onClick:ju,onKeyDown:Fu=>{Fu.key==="Escape"&&ju()},role:"button",tabIndex:0,children:[jsxRuntimeExports.jsx("button",{className:"absolute top-4 right-4 z-10 rounded-md p-2 text-muted-foreground transition-all hover:bg-muted hover:text-foreground",onClick:ju,title:"Exit fullscreen",type:"button",children:jsxRuntimeExports.jsx(X$3,{size:20})}),jsxRuntimeExports.jsx("div",{className:"flex h-full w-full items-center justify-center p-4",onClick:Fu=>Fu.stopPropagation(),onKeyDown:Fu=>Fu.stopPropagation(),role:"presentation",children:jsxRuntimeExports.jsx(Ee$2,{chart:Au,className:"h-full w-full [&>div]:h-full [&>div]:overflow-hidden [&_svg]:h-auto [&_svg]:w-auto",config:lo,fullscreen:!0,showControls:Bu})})]})]})},Y$1=Au=>{var lo,$u;let Ru=[],Iu=[],Pu=Au.querySelectorAll("thead th");for(let Mu of Pu)Ru.push(((lo=Mu.textContent)==null?void 0:lo.trim())||"");let Ou=Au.querySelectorAll("tbody tr");for(let Mu of Ou){let Du=[],Lu=Mu.querySelectorAll("td");for(let Bu of Lu)Du.push((($u=Bu.textContent)==null?void 0:$u.trim())||"");Iu.push(Du)}return{headers:Ru,rows:Iu}},Q$1=Au=>{let{headers:lo,rows:$u}=Au,Ru=Mu=>{let Du=!1,Lu=!1;for(let Bu=0;Bu<Mu.length;Bu+=1){let ju=Mu[Bu];if(ju==='"'){Du=!0,Lu=!0;break}(ju===","||ju===`
|
|
3633
3633
|
`)&&(Du=!0)}return Du?Lu?`"${Mu.replace(/"/g,'""')}"`:`"${Mu}"`:Mu},Iu=lo.length>0?$u.length+1:$u.length,Pu=new Array(Iu),Ou=0;lo.length>0&&(Pu[Ou]=lo.map(Ru).join(","),Ou+=1);for(let Mu of $u)Pu[Ou]=Mu.map(Ru).join(","),Ou+=1;return Pu.join(`
|
|
3634
3634
|
`)},Le$3=Au=>{let{headers:lo,rows:$u}=Au,Ru=Mu=>{let Du=!1;for(let Bu=0;Bu<Mu.length;Bu+=1){let ju=Mu[Bu];if(ju===" "||ju===`
|
|
3635
3635
|
`||ju==="\r"){Du=!0;break}}if(!Du)return Mu;let Lu=[];for(let Bu=0;Bu<Mu.length;Bu+=1){let ju=Mu[Bu];ju===" "?Lu.push("\\t"):ju===`
|
|
@@ -3688,7 +3688,7 @@ ${Pu}\`\`\``}),lo}function ChatMarkdown({text:Au,density:lo="comfortable"}){retu
|
|
|
3688
3688
|
}`;function squeezed(Au){return Au.replace(/\s+/g," ").trim()}function saidMessageId(Au,lo){const $u=squeezed(lo??"");if($u)for(let Ru=Au.length-1;Ru>=0;Ru-=1){const Iu=answerText(Au[Ru]);if(Iu!==void 0&&squeezed(plainWords(Iu)).includes($u)){const Pu=Au[Ru].id;return typeof Pu=="string"?Pu:void 0}}}function sentenceRange(Au,lo){const $u=squeezed(lo);if(!$u||!Au.ownerDocument)return;const Ru=Au.ownerDocument,Iu=Ru.createTreeWalker(Au,4);let Pu="";const Ou=[];let Mu=!0;for(let Fu=Iu.nextNode();Fu;Fu=Iu.nextNode()){const zu=Fu.nodeValue??"";for(let Uu=0;Uu<zu.length;Uu+=1){const Hu=zu[Uu];if(/\s/.test(Hu)){if(Mu)continue;Mu=!0,Pu+=" "}else Mu=!1,Pu+=Hu;Ou.push({node:Fu,offset:Uu})}}const Du=Pu.indexOf($u);if(Du<0)return;const Lu=Ou[Du],Bu=Ou[Du+$u.length-1],ju=Ru.createRange();return ju.setStart(Lu.node,Lu.offset),ju.setEnd(Bu.node,Bu.offset+1),ju}function registry(){return globalThis.CSS?.highlights}function highlightOf(Au){const lo=globalThis.Highlight;return lo?new lo(Au):void 0}let styled=!1;function ensureStyle(Au){if(styled||Au.getElementById("datalayer-voice-said")){styled=!0;return}const lo=Au.createElement("style");lo.id="datalayer-voice-said",lo.textContent=SAID_STYLE,Au.head.appendChild(lo),styled=!0}function useSaidSentence(Au,lo,$u){reactExports.useEffect(()=>{const Ru=registry(),Iu=Au.current?.querySelector("[data-voice-saying]");if(!Ru||!Iu||!lo)return;const Pu=()=>{const Mu=sentenceRange(Iu,lo),Du=Mu?highlightOf(Mu):void 0;return Du?(ensureStyle(Iu.ownerDocument),Ru.set(SAID_HIGHLIGHT,Du),!0):!1};let Ou;return!Pu()&&typeof MutationObserver<"u"&&(Ou=new MutationObserver(()=>{Pu()&&Ou?.disconnect()}),Ou.observe(Iu,{childList:!0,subtree:!0,characterData:!0})),()=>{Ou?.disconnect(),Ru.delete(SAID_HIGHLIGHT)}},[Au,lo,$u])}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(`
|
|
3689
3689
|
|
|
3690
3690
|
`)){const Ru=$u.split(`
|
|
3691
|
-
`).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-DNziilOG.js"),[],import.meta.url).then(Au=>({default:Au.EphemeralDocument}))),loadAgentDetails=()=>__vitePreload(()=>import("./chunks/AgentDetails-BriiIXid.js"),[],import.meta.url).then(Au=>({default:Au.AgentDetails})),loadEphemeralNotebook=()=>__vitePreload(()=>import("./chunks/EphemeralNotebook-COnqhW7Q.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)}
|
|
3691
|
+
`).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-BcxH847U.js"),[],import.meta.url).then(Au=>({default:Au.EphemeralDocument}))),loadAgentDetails=()=>__vitePreload(()=>import("./chunks/AgentDetails-BriiIXid.js"),[],import.meta.url).then(Au=>({default:Au.AgentDetails})),loadEphemeralNotebook=()=>__vitePreload(()=>import("./chunks/EphemeralNotebook-COnqhW7Q.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)}
|
|
3692
3692
|
...`: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:Sd,loadingState:_d,headerActions:yd,kernelIndicatorState:wd,kernelIndicatorPlacement:Ad="left",kernel:md,kernelEnvironmentName:dd,kernelCpu:bd,kernelMemory:ld,kernelGpu:ud,themeVariant:hd,colorMode:vd,chatViewMode:Ed,onChatViewModeChange:Cd,disabledViewModes:Rd,useStore:jd=!0,protocol:Td,onSendMessage:$d,onSendReady:Id,onLoadingChange:qd,onSpeakingChange:Md,onContextSnapshot:Wd,enableStreaming:rh=!1,brandIcon:Yd,avatarConfig:mh,headerButtons:oh,showPoweredBy:yh=!1,poweredByProps:gh,emptyState:Xd,renderHeader:eh,showTurnFooter:ah=!0,renderMessageFooter:Oh,notebookToolSurfacesId:Gd,footerContent:zd,welcome:Pd,trailingContent:Od,voice:Vd,voiceSpeaking:Ld=!1,voiceSentence:Kd,onStopSpeaking:Qd,voiceLevel:fh,onReadAloud:_h,showInformation:Ch=!1,onInformationClick:Zh,headerContent:Nd,children:xd,borderRadius:Hd,backgroundColor:Zd,border:hh,boxShadow:wh,compact:Eh=!1,placeholder:Ah,description:$h="Start a conversation with the AI agent.",onStateUpdate:Sh,onNewChat:Mh,onClear:Kh,onMessagesChange:Ph,onItemsChange:rp,onDisplayItemsChange:ip,autoFocus:up=!1,suggestions:bp,submitOnSuggestionClick:Qh=!0,hideMessagesAfterToolUI:_p=!1,focusTrigger:np,frontendTools:ap,enableEphemeralNotebook:qh=!1,initialEphemeralNotebookOpen:Uh=!0,onEphemeralNotebookOpenChange:Jh,enableEphemeralDocument:wf=!1,initialEphemeralSurfaceMode:Op,onEphemeralSurfaceModeChange:Rh,collapsed:jh=!1,onExpandFromCollapsed:Qp,ephemeralNotebookToolbar:Fp,ephemeralNotebookToolbarExtraItems:ef,ephemeralDocumentToolbarExtraItems:tf,ephemeralNotebookCollaborationProvider:tp,ephemeralNotebookCollaborationDocumentId:Gp,ephemeralDocumentCollaboration:Tf,ephemeralRuntimeOverride:om,onToolCallStart:Af,onToolCallComplete:jf,onToolCallUpdate:Wf,inspector:vp,onAuthorizationRequired:zp,connectedIdentities:xp,runtimeId:Cp,thread:ff,historyEndpoint:Zp,historyAuthToken:uf,pendingPrompt:fp,contextSnapshot:Cm,mcpStatusData:mf,sandboxStatusData:Tm,showToolApprovalBanner:Pf=!0,pendingApprovals:Ff,onApproveApproval:df,onRejectApproval:vm}){const im=useChatWords();reactExports.useEffect(()=>{setupPrimerPortals()},[]);const Of=useChatAvailability(),Dh=Ku??Of.disabled,Ud=Ju??Of.disableReason,{theme:lh}=useThemeStore(),Lh=getColorPalette(lh,"dark").textLight,Nh=useAgentRuntimeStore(Dd=>Dd.approvals),hp=useAgentRuntimeStore(Dd=>Dd.historyVersion),lp=useAgentRuntimeStore(Dd=>Dd.mcpStatus),Sp=mf??lp,Np=typeof Td=="object"?Td:void 0,yf=useCoreStore(Dd=>Dd.configuration?.aiAgentsUrl),Fh=Np?.agentId||Cp,cp=Cp||Fh,Up=Np?.authToken,hm=reactExports.useRef(`ephemeral-notebook-${Math.random().toString(36).slice(2,10)}`),kf=Cp||Np?.agentId||Fh,Yp=Gp||(kf?`ephemeral-notebook-${kf}`:hm.current),Pm=useAgentRuntimeStore(Dd=>Dd.getEphemeralNotebookModel(Yp)),Om=useAgentRuntimeStore(Dd=>Dd.setEphemeralNotebookModel),og=reactExports.useCallback(Dd=>{Om(Yp,Dd)},[Yp,Om]),Kf=Tf?.roomId||(kf?`ephemeral-document-${kf}`:`ephemeral-document-${hm.current}`),zf=useAgentRuntimeStore(Dd=>Dd.getEphemeralDocumentModel(Kf)),Zf=useAgentRuntimeStore(Dd=>Dd.setEphemeralDocumentModel),Uf=reactExports.useCallback(Dd=>{Zf(Kf,Dd)},[Kf,Zf]),Ef=Op??(qh&&Uh?"notebook":"none"),[Hf,Ep]=reactExports.useState(Ef),qf=reactExports.useCallback(Dd=>{Ep(Dd),Rh?.(Dd),Jh?.(Dd==="notebook")},[Rh,Jh]),gf=qh&&Hf==="notebook",Vh=wf&&Hf==="document",$p=gf||Vh,Hp=$p&&jh,vf=Hp?{key:"ephemeral-surface",type:"custom",order:900,render:()=>jsxRuntimeExports.jsx(EphemeralSurfaceControl,{mode:Hf,onChange:qf,enableNotebook:qh,enableDocument:wf,enableChatOnly:!1})}:null,Mf=vf?[...ef??[],vf]:ef,bm=vf?[...tf??[],vf]:tf,[Yf,Ap]=reactExports.useState(null);reactExports.useEffect(()=>{if(!gf){Ap(null);return}const Dd=()=>notebookStore.getState().selectNotebook(Yp)?.adapter?.kernel??null,Fd=()=>{const nh=Dd();Ap(bh=>bh?.id===nh?.id?bh:nh)};Fd();const sh=window.setInterval(Fd,750),vh=notebookStore.subscribe(Fd);return()=>{window.clearInterval(sh),vh()}},[gf,Yp]);const[Jf,Am]=reactExports.useState(null),hf=reactExports.useCallback(Dd=>{Am(Fd=>Fd?.id===Dd?.id?Fd:Dd)},[]);reactExports.useEffect(()=>{Vh||Am(null)},[Vh]);const Yh=$p&&isFloatingChatViewMode(Ed),Lp=Ed==="floating-small"||Ed==="floating-draggable",pm=useNotebookTools(Yp),[rf,$f]=reactExports.useState([]),u0=reactExports.useCallback(Dd=>{$f(Dd)},[]),Mm=reactExports.useMemo(()=>gf?[...ap||[],...pm]:Vh?[...ap||[],...rf]:ap,[gf,Vh,ap,pm,rf]),Hg=reactExports.useMemo(()=>normalizeAiAgentsBaseUrl(yf||DEFAULT_SERVICE_URLS.AI_AGENTS),[yf]),Xf=reactExports.useRef(null),d0=reactExports.useRef(new Map),Tg=reactExports.useCallback((Dd,Fd,sh)=>{const vh=Xf.current;if(!vh||vh.readyState!==WebSocket.OPEN)return logApprovalTrace("send_decision_skipped_ws_not_ready",{approvalId:Dd,approved:Fd,wsReadyState:vh?.readyState}),!1;try{return logApprovalTrace("send_decision",{approvalId:Dd,approved:Fd,hasNote:!!sh}),vh.send(JSON.stringify({type:"tool_approval_decision",approvalId:Dd,approved:Fd,...sh?{note:sh}:{}})),!0}catch{return logApprovalTrace("send_decision_failed",{approvalId:Dd,approved:Fd}),!1}},[]),qg=reactExports.useCallback(()=>{const Dd=Xf.current;if(!Dd||Dd.readyState!==WebSocket.OPEN)return!1;try{return Dd.send(JSON.stringify({type:"tool-approvals-history"})),logApprovalTrace("request_history",{}),!0}catch{return!1}},[]),D0=reactExports.useCallback(Dd=>{Dd&&(d0.current.set(Dd,Date.now()+RESOLVED_TOOL_CALL_SUPPRESSION_MS),logApprovalTrace("suppress_pending_for_tool_call",{toolCallId:Dd,windowMs:RESOLVED_TOOL_CALL_SUPPRESSION_MS}))},[]),g1=reactExports.useCallback(Dd=>{if(!Dd)return!1;const Fd=d0.current.get(Dd);return Fd?Fd<Date.now()?(d0.current.delete(Dd),!1):!0:!1},[]),N0=reactExports.useCallback((Dd,Fd,sh)=>{window.setTimeout(()=>{if(!agentRuntimeStore.getState().approvals.some(bh=>bh.id===Dd&&bh.status==="pending"))return;const nh=Tg(Dd,Fd,sh);logApprovalTrace("retry_send_decision",{approvalId:Dd,approved:Fd,sent:nh}),nh&&qg()},500)},[qg,Tg]),L0=reactExports.useMemo(()=>Ff||Nh.filter(Dd=>Dd.status==="pending"&&isApprovalForAgent(Dd,Fh)).map(Dd=>({id:Dd.id,toolName:Dd.tool_name,toolDescription:Dd.note??void 0,args:Dd.tool_args??{},agentId:Dd.agent_id??"",requestedAt:Dd.created_at??new Date().toISOString()})),[Ff,Nh,Fh]),G1=reactExports.useCallback((Dd,Fd)=>{const sh=agentRuntimeStore.getState().approvals.find(Wh=>Wh.id===Dd),vh=sh?.tool_name;if(!vh)return;const bh=(()=>{if(vh.startsWith("skill:")){const pp=vh.slice(6);return pp?normalizeSkillApprovalId(pp):null}if(!new Set(["run_skill_script","load_skill","read_skill_resource"]).has(vh))return null;const gp=sh?.tool_args??{},Gh=gp.skill_name??gp.skill??gp.name;return typeof Gh!="string"||!Gh?null:normalizeSkillApprovalId(Gh)})();if(bh){f0(gp=>{const Gh=new Map(gp);return Gh.set(bh,Fd),Gh}),agentRuntimeStore.getState().sendRawMessage({type:Fd?"skill_approve":"skill_unapprove",skillId:bh},Fh)||console.warn("[ChatBase] skill_approve persistence dropped: websocket not ready");return}const zh=vh.indexOf("__");if(zh!==-1){const Wh=vh.slice(0,zh),gp=vh.slice(zh+2);agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tool_approve",serverId:Wh,toolName:gp,approved:Fd},Fh)||console.warn("[ChatBase] mcp_server_tool_approve persistence dropped: websocket not ready")}},[Fh]),h0=reactExports.useCallback(async(Dd,Fd,sh)=>{const nh=agentRuntimeStore.getState().approvals.find(Wh=>Wh.id===Dd)?.tool_call_id??sh;if(D0(nh),Ff){await df?.(Dd,Fd);return}const bh=Tg(Dd,!0,Fd);bh||console.warn("[ChatBase] ai-agents tool_approval_decision not sent: websocket not ready");const zh=agentRuntimeStore.getState().sendDecision(Dd,!0,Fd,nh,Fh);zh?G1(Dd,!0):console.warn("[ChatBase] tool_approval_decision dropped: websocket not ready"),(bh||zh)&&agentRuntimeStore.getState().removeApproval(Dd),qg(),N0(Dd,!0,Fd),await df?.(Dd,Fd)},[Fh,D0,df,Ff,G1,N0,qg,Tg]),Vg=reactExports.useCallback(async(Dd,Fd,sh)=>{const nh=agentRuntimeStore.getState().approvals.find(Wh=>Wh.id===Dd)?.tool_call_id??sh;if(D0(nh),Ff){await vm?.(Dd,Fd);return}const bh=Tg(Dd,!1,Fd);bh||console.warn("[ChatBase] ai-agents tool_approval_decision not sent: websocket not ready");const zh=agentRuntimeStore.getState().sendDecision(Dd,!1,Fd,nh,Fh);zh||console.warn("[ChatBase] tool_approval_decision dropped: websocket not ready"),(bh||zh)&&agentRuntimeStore.getState().removeApproval(Dd),qg(),N0(Dd,!1,Fd),await vm?.(Dd,Fd)},[Fh,D0,vm,Ff,N0,qg,Tg]),B0=reactExports.useRef(null),km=reactExports.useCallback(Dd=>{const Fd=agentRuntimeStore.getState(),sh=new Set([Dd.id]),nh=!!Dd.tool_name?approvalSignature(Dd.tool_name,Dd.tool_args??{}):null;for(const bh of Fd.approvals){if(bh.status!=="pending"||!isApprovalForAgent(bh,Fh))continue;if(bh.id===Dd.id){sh.add(bh.id);continue}if(Dd.tool_call_id&&bh.tool_call_id&&bh.tool_call_id===Dd.tool_call_id){sh.add(bh.id);continue}if(!nh||!bh.tool_name)continue;approvalSignature(bh.tool_name,bh.tool_args??{})===nh&&sh.add(bh.id)}for(const bh of sh)Fd.removeApproval(bh)},[Fh]);reactExports.useEffect(()=>{if(!Pf||Ff||!Up)return;const Dd=toWsUrl(Hg,`${AI_AGENTS_API_PREFIX}/ws`,Up);if(!Dd)return;let Fd=!1;const sh=new WebSocket(Dd);return Xf.current=sh,sh.onopen=()=>{logApprovalTrace("ws_open_request_history",{activeAgentId:Fh}),sh.send(JSON.stringify({type:"tool-approvals-history"}))},sh.onmessage=vh=>{try{const nh=JSON.parse(String(vh.data)),bh=[],zh=typeof nh.type=="string"?nh.type:void 0,Wh=typeof nh.event=="string"?nh.event:void 0;if(zh==="tool-approvals-history"){const pp=(nh.data&&typeof nh.data=="object"?nh.data:{}).approvals;if(Array.isArray(pp))for(const Hh of pp)Hh&&typeof Hh=="object"&&bh.push(Hh)}else if(Wh?.startsWith("tool_approval_")){const Gh=nh.data&&typeof nh.data=="object"?nh.data:nh.payload&&typeof nh.payload=="object"?nh.payload:null;if(Gh){const pp=statusFromApprovalEvent(Wh);logApprovalTrace("recv_tool_approval_event",{event:Wh,approvalId:typeof Gh.id=="string"?Gh.id:typeof Gh.approval_id=="string"?Gh.approval_id:void 0,status:typeof Gh.status=="string"?Gh.status:pp}),bh.push(pp&&typeof Gh.status!="string"?{...Gh,status:pp}:Gh)}}if(bh.length===0)return;const gp=agentRuntimeStore.getState();for(const Gh of bh){let pp=normalizeApprovalPayload(Gh);if(!pp){const Rp=typeof Gh.id=="string"&&Gh.id||typeof Gh.approval_id=="string"&&Gh.approval_id||typeof Gh.approvalId=="string"&&Gh.approvalId||"",Bp=typeof Gh.status=="string"&&Gh.status||"";if(Rp&&Bp&&Bp!=="pending"){const xf=gp.approvals.find(Lf=>Lf.id===Rp);xf&&(pp={...xf,status:Bp})}}if(!pp)continue;const Hh=pp.agent_id||!Fh?pp:{...pp,agent_id:Fh};if(isApprovalForAgent(Hh,Fh)){if(Hh.status==="pending"&&g1(Hh.tool_call_id)){logApprovalTrace("drop_transient_pending",{approvalId:Hh.id,toolCallId:Hh.tool_call_id,status:Hh.status});continue}logApprovalTrace("apply_tool_approval_update",{approvalId:Hh.id,status:Hh.status,agentId:Hh.agent_id,activeAgentId:Fh}),Hh.status==="pending"?gp.upsertApproval(Hh):(km(Hh),B0.current?.(Hh,Hh.status==="approved",Hh.note??void 0))}}}catch{}},sh.onclose=()=>{Fd||(Xf.current=null)},sh.onerror=()=>{Xf.current=null},()=>{Fd=!0,Xf.current=null,sh.close()}},[Pf,Ff,Hg,Up,Fh,g1,km]);const Xh=typeof Td=="object"?Td:void 0,Pv=Xh?JSON.stringify(Xh):"",b1="agent-runtimes",j0=useChatStore(Dd=>Dd.clearMessages),fm=Xh?.type==="a2a",[F0,z0]=reactExports.useState(()=>emptyConversation(BROWSER_LIMITS)),Qf=reactExports.useRef(F0),Gg=reactExports.useRef(!1),Rf=reactExports.useCallback(Dd=>{const Fd=Dd(Qf.current);Fd!==Qf.current&&(Qf.current=Fd,Gg.current=!0,z0(Fd))},[]),[p0,W1]=reactExports.useState(emptyChatLayer),Ag=reactExports.useRef(p0),sm=reactExports.useCallback(Dd=>{const Fd=Dd(Ag.current);Fd!==Ag.current&&(Ag.current=Fd,W1(Fd))},[]),ig=reactExports.useCallback(()=>{Rf(()=>emptyConversation(BROWSER_LIMITS)),sm(()=>emptyChatLayer())},[Rf,sm]),em=reactExports.useCallback(Dd=>{let Fd;try{Fd=reduceConversation(emptyConversation(BROWSER_LIMITS),snapshotOfMessages(Dd))}catch(vh){console.error("[ChatBase] Conversation not read again:",vh),Df(vh instanceof Error?vh:new Error(String(vh)));return}const sh=new Map;for(const vh of Dd){const{id:nh,role:bh,content:zh,toolCalls:Wh,...gp}=vh;sh.set(nh,gp)}sm(()=>({...emptyChatLayer(),extras:sh})),Rf(()=>Fd)},[Rf,sm]),ym=reactExports.useCallback(Dd=>Rf(Fd=>reduceConversation(Fd,Dd)),[Rf]),hg=reactExports.useCallback(Dd=>{const Fd=Qf.current.items.find(sh=>sh.kind==="tool"&&sh.id===Dd);return Fd&&Fd.kind==="tool"?toolCallOf(Fd):void 0},[]),Vf=reactExports.useCallback(()=>Qf.current.items.flatMap(Dd=>Dd.kind==="tool"?[toolCallOf(Dd)]:[]),[]),Dm=reactExports.useRef(im);Dm.current=im;const pg=reactExports.useMemo(()=>conversationDrawer(Dd=>Dm.current.error(Dd)),[]),Wp=reactExports.useMemo(()=>pg(F0,p0),[pg,F0,p0]),kg=reactExports.useRef(Wp);kg.current=Wp;const[fg,Wg]=reactExports.useState(null),[y1,Bh]=reactExports.useState(!1),[yp,bf]=reactExports.useState(!1),[$m,Jp]=reactExports.useState(),[mg,_m]=reactExports.useState(!1),[xm,Df]=reactExports.useState(null),[Kg,gg]=reactExports.useState("");reactExports.useEffect(()=>{if(!md){Jp(void 0);return}Jp(md.status);const Dd=(Fd,sh)=>{Jp(sh)};return md.statusChanged.connect(Dd),()=>{md.statusChanged.disconnect(Dd)}},[md]);const[am,Sm]=reactExports.useState(!cp),[K1,Z1]=reactExports.useState(0),$g=reactExports.useRef(new Map),Y1=reactExports.useRef(emptyUiModel()),_1=reactExports.useRef(new Set),[J1,U0]=reactExports.useState(!1),x1=reactExports.useRef(null),Nm=fp&&[Cp||Zp||Xh?.endpoint||Xh?.agentId,fp].filter(Boolean).join("::"),[sg,Ov]=reactExports.useState(""),[Rg,vg]=reactExports.useState(new Map),[Mv,X1]=reactExports.useState(new Map),[H0,fb]=reactExports.useState([]),Zg=useAgentRuntimeWsState(),S1=!!Xh?.enableConfigQuery&&td,jp=useConfig(S1,Xh?.configEndpoint,Xh?.authToken,Xh?.agentId),Ig=useSkills(S1&&Bu,Xh?.configEndpoint,Xh?.authToken),{enableSkill:q0,disableSkill:w1,approveSkill:Dv,unapproveSkill:Q1}=useSkillActions(Fh),[Hm,f0]=reactExports.useState(new Map);reactExports.useEffect(()=>{f0(new Map)},[Fh]);const mm=reactExports.useMemo(()=>{const Dd=new Set;for(const Fd of Ig.data?.skills??[])(Fd.status==="enabled"||Fd.status==="loaded")&&Dd.add(Fd.id);return Dd},[Ig.data]);reactExports.useEffect(()=>{if(!Fh||T1.current.has(Fh))return;const Dd=Ig.data?.skills??[];if(Dd.length===0)return;if(Dd.some(nh=>nh.status==="enabled"||nh.status==="loaded")){T1.current.add(Fh);return}const sh=Dd.filter(nh=>nh.status==="available").map(nh=>nh.id).filter(Boolean);if(sh.length===0){T1.current.add(Fh);return}sh.every(nh=>q0(nh))&&T1.current.add(Fh)},[Fh,Ig.data,q0]);const Yg=reactExports.useMemo(()=>{const Dd=new Set;for(const Fd of Ig.data?.skills??[])Fd.approved===!0&&Dd.add(Fd.id);return Hm.forEach((Fd,sh)=>{Fd?Dd.add(sh):Dd.delete(sh)}),Dd},[Hm,Ig.data]),ev=reactExports.useMemo(()=>{const Dd=jp.data?.builtinTools??[],Fd=Xh?.options?.frontendTools??[],sh=new Set(Dd.map(nh=>nh.name)),vh=[...Mm??[],...Fd].filter(nh=>sh.has(nh.name)?!1:(sh.add(nh.name),!0)).map(nh=>({id:nh.name,name:nh.name}));return{runtime:Dd,frontend:vh}},[jp.data?.builtinTools,Mm,Xh?.options]),Jg=reactExports.useMemo(()=>Vu??(Fh?[{id:Fh,name:Au||Fh,description:lo||$h}]:[]),[Vu,Fh,Au,lo,$h]),m0=typeof Xh?.options?.model=="string"?(Xh?.options).model:void 0,Pg=reactExports.useMemo(()=>{const Dd=ad||jp.data?.models||(jp.isError?[]:void 0);return offeredModels(Dd,()=>{const Fd=Object.values(AI_MODEL_CATALOGUE).filter(sh=>sh.available&&isChatModel(sh)).map(sh=>({id:sh.id,name:sh.name,provider:sh.provider}));return Fd.length>0?Fd:m0?[{id:m0,name:m0,provider:"inference"}]:[]})},[ad,jp.data?.models,jp.isError,m0]),g0=reactExports.useMemo(()=>zu??Jg.map(Dd=>({name:Dd.name,description:Dd.description,icon:Dd.icon,disabled:Dd.id===(Gu??Jg[0]?.id),disabledReason:`You are already talking to ${Dd.name}`})),[zu,Jg,Gu]),mb=useContextSnapshot(S1&&Ru,Xh?.configEndpoint,Xh?.agentId,Xh?.authToken),tv=reactExports.useMemo(()=>Xh?.enableConfigQuery?void 0:{totalTokens:fg?.totalTokens??0,contextWindow:2e5,sumResponseInputTokens:fg?.sessionInput??0,sumResponseOutputTokens:fg?.sessionOutput??0,systemPromptTokens:0,userMessageTokens:0,assistantMessageTokens:0,toolTokens:0,toolCallTokens:0,toolReturnTokens:0,historyToolCallTokens:0,historyToolReturnTokens:0,currentToolCallTokens:0,currentToolReturnTokens:0,turnUsage:{inputTokens:fg?.turnInput??0,outputTokens:fg?.turnOutput??0,requests:0,toolCalls:0,toolNames:[],durationSeconds:0},sessionUsage:{inputTokens:fg?.sessionInput??0,outputTokens:fg?.sessionOutput??0,requests:0,toolCalls:0,turns:0,durationSeconds:0}},[fg,Xh?.enableConfigQuery]),v0=reactExports.useRef(Fh),gb=reactExports.useRef(null),lm=mb.data,rv=reactExports.useRef(lm);rv.current=lm,reactExports.useEffect(()=>{v0.current!==Fh&&(v0.current=Fh,Wg(null),gb.current=rv.current??null)},[Fh]);const Og=lm&&lm!==gb.current?lm:void 0,E1=Cm??Og??tv;reactExports.useEffect(()=>{Wd?.(E1)},[E1,Wd]);const C1=useSandbox(S1&&$u&&!Xh?.ownRoutesOnly,Xh?.configEndpoint,Xh?.authToken,Xh?.agentId),Gf=reactExports.useRef(null),nv=reactExports.useRef(null),Lm=reactExports.useRef(0),ov=reactExports.useRef(new Set),T1=reactExports.useRef(new Set),Bm=reactExports.useRef(new Set),qm=reactExports.useRef(!1),Xg=reactExports.useRef(_p);Xg.current=_p;const bg=reactExports.useRef(ff?.id||generateMessageId()),V0=reactExports.useRef(ff),jm=reactExports.useRef(ff?.messages.length?ff.id:null),Fm=reactExports.useCallback(()=>{const Dd=bg.current;jm.current!==Dd&&(jm.current=Dd,V0.current?.onStarted?.(Dd))},[]),Vm=reactExports.useRef(null),Rm=reactExports.useRef([]),Gm=reactExports.useRef(new Set),ag=Xh?.uiSocket,iv=reactExports.useRef(Xh?.authToken);iv.current=Xh?.authToken;const A1=Xh?.uiFiles,k1=reactExports.useCallback(Dd=>A1?uploadFile(Dd,{url:A1,scope:bg.current,token:iv.current}):Promise.reject(new Error("This conversation takes no file.")),[A1]),b0=reactExports.useCallback(()=>{const Dd=Ag.current;return Qf.current.items.flatMap(Fd=>Fd.kind==="message"||Fd.kind==="error"?[{id:Fd.id,displays:Dd.displays.get(Fd.id),speaker:Dd.speakers.get(Fd.id)}]:[])},[]),If=reactExports.useCallback(Dd=>{const Fd=b0();let sh;try{sh=withUiOp(Fd,Dd)}catch(bh){console.error("[ChatBase] reactor.ui op not applied:",bh);return}const vh=new Set(sh.map(bh=>bh.id)),nh=Fd.filter(bh=>!vh.has(bh.id)).map(bh=>bh.id);sm(bh=>{const zh=new Map(bh.displays),Wh=new Map(bh.speakers);for(const gp of sh)gp.displays&&zh.set(gp.id,gp.displays),gp.speaker&&Wh.set(gp.id,gp.speaker);for(const gp of nh)zh.delete(gp),Wh.delete(gp);return{...bh,displays:zh,speakers:Wh}}),nh.length>0&&Rf(bh=>withoutItems(bh,nh))},[b0,sm,Rf]),sf=reactExports.useCallback((Dd,Fd)=>{if(Fd){if(Dd.op==="window")return;if((Dd.op==="show"||Dd.op==="ask")&&isStepDisplay(Dd.body)){Gm.current.add(Dd.body.id);return}if((Dd.op==="patch"||Dd.op==="append")&&Gm.current.has(Dd.id))return}let sh;try{sh=routeUiOp(Dd,Y1.current,_1.current)}catch(nh){console.error("[ChatBase] reactor.ui op not applied:",nh);return}Y1.current=sh.steps;const vh=sh.routed;if(vh.to==="window")tellLoopWindow(vh.data);else if(vh.to==="step"){const nh=vh.step;sm(bh=>{const zh=new Map(bh.steps.map(Gh=>[Gh.item.id,Gh.after])),Wh=Qf.current.items.at(-1)?.id??null,gp=withLoopStep(bh.steps.map(Gh=>Gh.item),nh);return{...bh,steps:gp.map(Gh=>({item:Gh,after:zh.has(Gh.id)?zh.get(Gh.id)??null:Wh}))}})}else if(vh.to==="element")_1.current.add(vh.change.id),applyLoopElement(vh.change);else if(placeable(b0(),vh.op))If(vh.op);else{const nh=vh.op.op==="show"||vh.op.op==="ask"?vh.op.body.data?.message_id:void 0;Fd&&typeof nh=="string"?(ym({type:"MESSAGE_SAID",messageId:nh,role:"assistant",text:"",streaming:!1}),If(vh.op)):Rm.current.push(vh.op)}},[If,b0,sm,ym]),kp=reactExports.useRef(sf);kp.current=sf,reactExports.useEffect(()=>{if(Rm.current.length===0)return;const Dd=Rm.current.splice(0);for(const Fd of Dd){if(!placeable(b0(),Fd)){Rm.current.push(Fd);continue}If(Fd)}},[F0,If,b0]);const Mg=reactExports.useCallback(()=>{if(!ag)return null;const Dd=bg.current,Fd=Vm.current;if(Fd&&Fd.scope===Dd)return Fd.socket;Fd?.socket.close(),Y1.current=emptyUiModel(),_1.current=new Set,Rm.current=[],Gm.current=new Set;const sh=new UiSocket({url:ag,scope:Dd,token:()=>iv.current??"",onOp:(vh,nh,bh)=>kp.current(vh,bh),onStatus:(vh,nh)=>{(vh==="refused"||vh==="gone")&&console.error(`[ChatBase] ui socket ${vh}: ${nh??""}`)}});return Vm.current={socket:sh,scope:Dd},sh.connect(),sh},[ag]),Im=reactExports.useRef(Mg);Im.current=Mg,reactExports.useEffect(()=>(ff?.messages.length&&Im.current(),()=>{Vm.current?.socket.close(),Vm.current=null}),[]);const $1=reactExports.useRef(null),Dg=reactExports.useRef(null),Ng=reactExports.useRef(null),R1=reactExports.useRef(null),lg=reactExports.useRef(!1),Qg=reactExports.useRef(xp);Qg.current=xp;const I1=reactExports.useRef(Mm);I1.current=Mm;const G0=reactExports.useRef(Af);G0.current=Af;const sv=reactExports.useRef(jf);sv.current=jf;const Lg=reactExports.useRef(Wf);Lg.current=Wf;const Bg=useAgentInspectorTracer(),Wm=vp??Bg,yg=reactExports.useRef("Agent");yg.current=typeof Au=="string"&&Au||Fh||"Agent";const Km=reactExports.useRef(null);Wm&&Km.current?.tracer!==Wm?Km.current={tracer:Wm,recorder:chatSpanRecorder(Wm,()=>yg.current,{frontendTools:()=>(I1.current??[]).map(Dd=>Dd.name)})}:Wm||(Km.current=null);const W0=reactExports.useRef(""),y0=reactExports.useRef(void 0),K0=reactExports.useRef(null);reactExports.useEffect(()=>{let Dd=agentRuntimeStore.getState().toolDecisionRequest?.seq??0;return agentRuntimeStore.subscribe(Fd=>Fd.toolDecisionRequest,Fd=>{if(!Fd||Fd.seq===Dd)return;Dd=Fd.seq;const sh=K0.current;if(!sh)return;const vh=zh=>(zh??"").toLowerCase().replace(/[-_]/g,""),nh=Vf(),bh=nh.find(zh=>zh.result?.approvalId===Fd.approvalId)??nh.find(zh=>vh(zh.toolName)===vh(Fd.toolName)&&(zh.status==="executing"||zh.status==="inProgress"));bh&&sh(bh.toolCallId,{type:"tool-approval-decision",approved:Fd.approved,approvalId:Fd.approvalId,toolName:bh.toolName})})},[]);const jg=reactExports.useCallback((Dd,Fd,sh)=>{if(!Dd?.id||ov.current.has(Dd.id))return!1;let vh=Dd.tool_call_id;if(!vh)for(const bh of Vf()){if(bh.status!=="inProgress"&&bh.status!=="executing")continue;const zh=approvalSignature(bh.toolName,bh.args??{}),Wh=approvalSignature(Dd.tool_name,Dd.tool_args??{});if(zh===Wh){vh=bh.toolCallId;break}}if(!vh)return!1;const nh=hg(vh);return!nh||nh.status!=="inProgress"&&nh.status!=="executing"?!1:(ov.current.add(Dd.id),K0.current?.(vh,{type:"tool-approval-decision",approved:Fd,approvalId:Dd.id,toolName:Dd.tool_name||nh.toolName,_fromServerEcho:!0,_alreadyDispatched:!0,...sh?{message:sh}:{}}),!0)},[Fh]);B0.current=jg;const cm=!!(Xh?.endpoint&&/\/api\/runtimes\/v1\/agent-nodes\/[^/]+\/ag-ui\/?$/.test(Xh.endpoint)),P1=Xh?.configEndpoint?Xh.configEndpoint.replace(/\/api\/v1\/(config|configure)\/?$/,""):Xh?.endpoint?.replace(/\/api\/v1\/.*$/,"")??"";useAgentRuntimeWebSocket({enabled:!!Xh&&!!P1&&!cm&&!Xh.ownRoutesOnly,baseUrl:P1,authToken:Xh?.authToken,agentId:Xh?.agentId,onMessage:Dd=>{if(Dd.type!=="tool_approval_created"&&Dd.type!=="tool_approval_approved"&&Dd.type!=="tool_approval_rejected")return;const Fd=Dd.payload;if(Fd){if(Dd.type==="tool_approval_created"){isApprovalForAgent(Fd,Fh)&&agentRuntimeStore.getState().upsertApproval(Fd);return}km(Fd),jg(Fd,Dd.type==="tool_approval_approved",Fd.note??void 0)}}});const _0=reactExports.useCallback(Dd=>{if(!pd)return!0;const Fd=Dd.isConfig===!1?"catalog":"config";return pd.some(sh=>sh.id===Dd.id&&sh.origin===Fd)},[pd]);reactExports.useEffect(()=>{if(up&&Ng.current){const Dd=setTimeout(()=>Ng.current?.focus(),100);return()=>clearTimeout(Dd)}},[up]),reactExports.useEffect(()=>{if(np!==void 0&&np>0&&Ng.current){const Dd=setTimeout(()=>Ng.current?.focus(),150);return()=>clearTimeout(Dd)}},[np]);const vb=reactExports.useRef(!1);reactExports.useEffect(()=>{if(vb.current&&!yp&&Ng.current){const Dd=setTimeout(()=>Ng.current?.focus(),50);return()=>clearTimeout(Dd)}vb.current=yp},[yp]);const av=reactExports.useCallback(()=>{const Dd=Ng.current;if(Dd){Dd.style.height="auto";const Fd=120,vh=Math.min(Math.max(Dd.scrollHeight,40),Fd);Dd.style.height=`${vh}px`,Dd.style.overflowY=Dd.scrollHeight>Fd?"auto":"hidden"}},[]);reactExports.useEffect(()=>{av()},[Kg,av]),reactExports.useEffect(()=>{const Dd=setTimeout(av,0);return()=>clearTimeout(Dd)},[av]),reactExports.useEffect(()=>{if(Pg.length===0||isOffered(Pg,sg))return;const Dd=initialModelId(Pg,sd||jp.data?.defaultModel||DEFAULT_MODEL);Dd&&Dd!==sg&&Ov(Dd)},[Pg,sg,sd,jp.data?.defaultModel]);const bb=reactExports.useRef(!1);reactExports.useEffect(()=>{if(Pg.length>0&&!bb.current){bb.current=!0;const Dd=jp.data?.builtinTools?.map(Fd=>Fd.id)||[];if(fb(Dd),jp.data?.mcpServers){const Fd=new Map;for(const sh of jp.data.mcpServers)if(sh.isAvailable&&sh.enabled&&_0(sh)){const nh=new Set(sh.tools.map(bh=>bh.name).filter(bh=>!!bh));Fd.set(sh.id,nh)}vg(Fd)}}},[jp.data,Pg,sg,sd,ad,pd,_0]),reactExports.useEffect(()=>{!jp.data?.mcpServers||!pd||vg(Dd=>{const Fd=new Map;for(const sh of jp.data?.mcpServers??[])if(_0(sh)&&Dd.has(sh.id)){const vh=Dd.get(sh.id);vh&&Fd.set(sh.id,vh)}else if(_0(sh)&&sh.isAvailable&&sh.enabled){const vh=new Set(sh.tools.map(nh=>nh.name).filter(nh=>!!nh));Fd.set(sh.id,vh)}return Fd})},[pd,jp.data?.mcpServers,_0]);const af=reactExports.useRef(pd);af.current=pd,reactExports.useEffect(()=>{const Dd=parseEnabledMcpToolsByServer(Sp);if(!Dd)return;const Fd=Fh||"__global__",sh=!Bm.current.has(Fd)&&Zg==="connected";vg(vh=>{const nh=new Map(vh);if(Dd.forEach((bh,zh)=>{(!af.current||af.current.some(gp=>gp.id===zh))&&bh.size!==0&&nh.set(zh,new Set(bh))}),sh){const bh=[];for(const Wh of jp.data?.mcpServers??[]){if(!(!af.current||af.current.some(Hh=>Hh.id===Wh.id))||!Wh.isAvailable||!Wh.enabled)continue;const Gh=Wh.tools.map(Hh=>Hh.name).filter(Hh=>!!Hh);if(Gh.length===0)continue;const pp=nh.get(Wh.id);(!pp||pp.size===0)&&(nh.set(Wh.id,new Set(Gh)),bh.push({serverId:Wh.id,enabledToolNames:Gh}))}let zh=!0;for(const Wh of bh)agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tools_set",serverId:Wh.serverId,enabledToolNames:Wh.enabledToolNames},Fh)||(zh=!1,console.warn("[ChatBase] initial mcp_server_tools_set dropped: websocket not ready"));zh&&Bm.current.add(Fd)}return nh})},[Sp,Fh,jp.data?.mcpServers,Zg]),reactExports.useEffect(()=>{const Dd=parseApprovedMcpToolsByServer(Sp);Dd&&X1(()=>{const Fd=new Map;return Dd.forEach((sh,vh)=>{(!af.current||af.current.some(bh=>bh.id===vh))&&Fd.set(vh,new Set(sh))}),Fd})},[Sp]);const lv=reactExports.useRef("");reactExports.useEffect(()=>{const Dd=Sp?.servers;if(!Dd||Dd.length===0)return;const Fd=Dd.filter(bh=>bh.status==="started").map(bh=>bh.id).sort();if(Fd.length===0)return;const sh=jp.data?.mcpServers||[],vh=Fd.some(bh=>{const zh=sh.find(Wh=>Wh.id===bh);return!zh||zh.tools.length===0}),nh=Fd.join(",");vh&&nh!==lv.current&&jp.refetch&&(lv.current=nh,jp.refetch())},[Sp,jp]);const O1=reactExports.useCallback((Dd,Fd)=>{vg(sh=>{const vh=new Map(sh),nh=new Set(sh.get(Dd)||[]);return nh.has(Fd)?nh.delete(Fd):nh.add(Fd),vh.set(Dd,nh),agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tools_set",serverId:Dd,enabledToolNames:Array.from(nh)},Fh)||console.warn("[ChatBase] mcp_server_tools_set dropped: websocket not ready"),vh})},[Fh]),M1=reactExports.useCallback((Dd,Fd,sh)=>{vg(vh=>{const nh=new Map(vh),bh=sh?new Set(Fd):new Set;return nh.set(Dd,bh),agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tools_set",serverId:Dd,enabledToolNames:Array.from(bh)},Fh)||console.warn("[ChatBase] mcp_server_tools_set dropped: websocket not ready"),nh})},[Fh]),Nv=reactExports.useCallback(Dd=>{mm.has(Dd)?w1(Dd):q0(Dd)},[mm,q0,w1]),Z0=reactExports.useCallback((Dd,Fd)=>{for(const sh of Dd)Fd?q0(sh):w1(sh)},[q0,w1]),Y0=reactExports.useCallback((Dd,Fd)=>{X1(sh=>{const vh=new Map(sh),nh=new Set(sh.get(Dd)??[]),bh=nh.has(Fd);return bh?nh.delete(Fd):nh.add(Fd),vh.set(Dd,nh),agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tool_approve",serverId:Dd,toolName:Fd,approved:!bh},Fh)||console.warn("[ChatBase] mcp_server_tool_approve dropped: websocket not ready"),vh})},[Fh]),hy=reactExports.useCallback(Dd=>{Yg.has(Dd)?(f0(Fd=>{const sh=new Map(Fd);return sh.set(Dd,!1),sh}),Q1(Dd)):(f0(Fd=>{const sh=new Map(Fd);return sh.set(Dd,!0),sh}),Dv(Dd))},[Yg,Dv,Q1]),cv=reactExports.useCallback(()=>{const Dd=[];return Rg.forEach((Fd,sh)=>{(!pd||pd.some(vh=>vh.id===sh))&&Fd.forEach(vh=>Dd.push(vh))}),Dd},[Rg,pd]),yb=reactExports.useCallback(()=>Array.from(mm),[mm]);reactExports.useEffect(()=>{if(jd&&!Cp){const Dd=useChatStore.getState().messages;Dd.length>0&&em(Dd)}},[jd,Cp,em]);const Lv=reactExports.useRef(void 0),e0=reactExports.useRef(0),D1=reactExports.useRef(!1),N1=reactExports.useRef(null);reactExports.useEffect(()=>{if(cp!==Lv.current&&(cp&&$g.current.set(cp,0),Lv.current=cp,ig(),!cp)||!cp)return;const Dd=V0.current;if(Dd){N1.current!==Dd.id&&(N1.current=Dd.id,useConversationStore.getState().setMessages(cp,Dd.messages),em(Dd.messages),useConversationStore.getState().markFetched(cp),Sm(!0));return}hp!==e0.current&&(e0.current=hp,hp>0&&(useConversationStore.getState().clearMessages(cp),ig(),$g.current.set(cp,0),D1.current=!0));const Fd=useConversationStore.getState(),sh=Fd.isFetching(cp),vh=Fd.getMessages(cp);if(vh.length>0&&(Qf.current.items.length===0&&em(vh),Sm(!0)),sh)return;if(Zg!=="connected"){vh.length===0&&Sm(!1);return}Fd.setFetching(cp,!0);const nh=()=>extractChatMessagesFromFullContext(agentRuntimeStore.getState().fullContext),bh=Bp=>{Fd.setMessages(cp,Bp),em(Bp),$g.current.set(cp,0),Fd.markFetched(cp),Sm(!0)},zh=D1.current?[]:nh();if(D1.current=!1,zh.length>0){bh(zh);return}const Wh=()=>{const Bp=[Fh,Np?.agentId,Cp,cp,"default",void 0],xf=new Set;for(const Lf of Bp){const a0=typeof Lf=="string"?Lf.trim():void 0,vv=a0||"__global__";if(xf.has(vv))continue;if(xf.add(vv),agentRuntimeStore.getState().requestRefresh(a0))return!0}return!1};if(!Wh()){Fd.setFetching(cp,!1),vh.length===0&&Sm(!1);return}let Gh=!1;const pp=window.setTimeout(()=>{Gh||Wh()},500),Hh=agentRuntimeStore.subscribe(Bp=>Bp.fullContext,Bp=>{if(Gh||!Bp)return;const xf=extractChatMessagesFromFullContext(Bp);Gh=!0,Hh(),bh(xf)}),Rp=window.setTimeout(()=>{if(Gh)return;Gh=!0,Hh(),Fd.setFetching(cp,!1),Sm(vh.length>0);const Bp=$g.current.get(cp)??0;Zg==="connected"&&Bp<3?($g.current.set(cp,Bp+1),Wh(),Z1(Lf=>Lf+1)):Sm(!0)},2e3);return()=>{window.clearTimeout(pp),window.clearTimeout(Rp),Hh()}},[cp,Zp,Xh?.agentId,Zg,Fh,K1,hp,ig,em]),reactExports.useEffect(()=>{if(cp&&Wp.length>0){const Dd=Wp.filter(Fd=>!isToolCallMessage(Fd));Dd.length>0&&useConversationStore.getState().setMessages(cp,Dd)}},[cp,Wp]),reactExports.useEffect(()=>{!jd||!Gg.current||useChatStore.getState().setMessages(Wp.filter(Dd=>!isToolCallMessage(Dd)))},[jd,Wp]);const L1=Wp.filter(Dd=>!isToolCallMessage(Dd)),x0=reactExports.useRef(0);reactExports.useEffect(()=>{const Dd=L1.length;Dd!==x0.current&&(x0.current=Dd,Ph?.(L1))},[Wp,L1,Ph]),reactExports.useEffect(()=>{rp?.(Wp.filter(Dd=>!isToolCallMessage(Dd)))},[Wp,rp]),reactExports.useEffect(()=>{ip?.(Wp)},[Wp,ip]);const J0=Eh?2:3,uv=reactExports.useMemo(()=>{if(Xh?.configEndpoint)return{apiBaseUrl:getApiBaseFromConfig(Xh.configEndpoint),authToken:Xh.authToken}},[Xh?.configEndpoint,Xh?.authToken]),dv={userAvatar:jsxRuntimeExports.jsx(PersonIcon,{size:16}),assistantAvatar:jsxRuntimeExports.jsx(ForwardRef$2,{size:16,color:Lh}),showAvatars:!0,avatarSize:32,userAvatarBg:"neutral.muted",assistantAvatarBg:"accent.emphasis",...mh};reactExports.useEffect(()=>{if(!Xh||!td||Dh)return;const Dd=createProtocolAdapter(Xh);if(Dd)return Gf.current=Dd,U0(!0),nv.current=Dd.subscribe(Fd=>{if(Im.current(),lg.current&&Fd.type!=="state-update"&&Fd.type!=="error"&&Fd.type!=="done")return;const sh=()=>{try{const nh=conversationEventsOf(Fd,Qf.current);Rf(bh=>nh.reduce((zh,Wh)=>reduceConversation(zh,Wh),bh))}catch(nh){console.error("[ChatBase] Protocol event not read:",nh),Df(nh instanceof Error?nh:new Error(String(nh)))}},vh=()=>{const nh=Qf.current.items;if(nh.some(Wh=>Wh.kind==="message"&&Wh.role==="assistant"&&Wh.text.trim().length>0))return;const zh=[...nh].reverse().find(Wh=>Wh.kind==="tool"&&Wh.status==="complete"&&Wh.value!==void 0);!zh||zh.kind!=="tool"||ym({type:"MESSAGE_SAID",messageId:generateMessageId(),role:"assistant",text:formatToolResultFallback(zh.value),streaming:!1})};switch(Fd.type){case"message":if(Fd.usage){const nh=Fd.timestamp instanceof Date?Fd.timestamp.getTime():Date.now(),bh=Math.max(0,Fd.usage.promptTokens??0),zh=Math.max(0,Fd.usage.completionTokens??0),Wh=Math.max(bh+zh,Fd.usage.totalTokens??0),gp=agentRuntimeStore.getState();gp.appendLocalTokenTurn({serviceName:b1,agentId:Xh?.agentId,timestampMs:nh,promptTokens:bh,completionTokens:zh,totalTokens:Wh});const Gh=gp.costUsage?.cumulativeCostUsd;typeof Gh=="number"&&Number.isFinite(Gh)&&gp.upsertLocalCostPoint({serviceName:b1,agentId:Xh?.agentId,timestampMs:nh,cumulativeUsd:Math.max(0,Gh)})}if(qm.current)break;if(Fd.message){const nh=Fd.message.content;typeof nh=="string"&&nh&&(W0.current=sanitizeAssistantContent(nh)),sh()}break;case"tool-call":if(Fd.toolCall&&!lg.current){const nh=Fd.toolCall.toolCallId,bh=Fd.toolCall.toolName,zh=Fd.toolCall.args||{},Wh=Fd.toolCall.argsComplete,gp=hg(nh);sh();const Gh=hg(nh);if(!Gh)break;const pp=I1.current?.find(Rp=>Rp.name===bh),Hh=pp?.handler;gp?Hh&&gp.status==="executing"&&(Wh??Object.keys(zh).length>0)&&(Lm.current++,Bv(Hh,Gh,nh)):(G0.current?.({toolName:bh,toolCallId:nh,args:zh}),Km.current?.recorder.toolStarted({id:nh,name:bh,args:zh}),Hh&&(Wh??(Object.keys(zh).length>0||!frontendToolExpectsArgs(pp)))&&(Lm.current++,Bv(Hh,Gh,nh)))}break;case"tool-result":if(Fd.toolResult){const nh=Fd.toolResult.toolCallId??"",bh=hg(nh);sh();const zh=hg(nh);bh&&zh&&(Km.current?.recorder.toolEnded(nh,{result:Fd.toolResult.result,error:Fd.toolResult.error??(zh.status==="error"?zh.executionError??"failed":void 0)}),sv.current?.({toolName:bh.toolName,toolCallId:nh,args:bh.args,result:Fd.toolResult.result,status:zh.status,error:Fd.toolResult.error}))}break;case"state-update":Sh?.(Fd.data),sh();break;case"activity":if(Fd.activity&&y0.current?.(Fd.activity),sh(),Fd.activity?.type===HARNESS_TOOL_CALL&&Lg.current){const nh=Fd.activity.data,bh=nh&&typeof nh=="object"&&"id"in nh?String(nh.id??""):"",zh=Qf.current.items.find(Wh=>Wh.kind==="tool"&&Wh.id===bh);zh&&zh.kind==="tool"&&zh.display&&Lg.current({toolName:zh.name,toolCallId:bh,args:zh.input??{},display:zh.display})}break;case"done":{Km.current?.recorder.turnEnded({text:W0.current||void 0,usage:Fd.usage}),W0.current="";const nh=Fd.usage?.promptTokens??0,bh=Fd.usage?.completionTokens??0,zh=Fd.usage?.totalTokens??nh+bh;zh>0&&Wg(Wh=>({turnInput:nh,turnOutput:bh,sessionInput:(Wh?.sessionInput??0)+nh,sessionOutput:(Wh?.sessionOutput??0)+bh,totalTokens:zh}))}qm.current&&Xg.current&&vh(),lg.current||sh(),qm.current=!1,Lm.current=0,bf(!1),_m(!1),agentRuntimeStore.getState().requestRefresh(Fh);break;case"error":console.error("[ChatBase] Protocol error:",Fd.error),Km.current?.recorder.turnEnded({error:Fd.error?.message??"error"}),Fd.error?.message&&/exceeded maximum retries/i.test(Fd.error.message)&&Xg.current&&vh(),sh(),qm.current=!1,Df(Fd.error||new Error("Unknown error")),Lm.current=0,bf(!1),_m(!1),agentRuntimeStore.getState().requestRefresh(Fh);break;default:sh();break}}),Dd.connect().catch(console.error),()=>{nv.current?.(),Gf.current?.disconnect()}},[Pv,Sh,jd,td]);function Bv(Dd,Fd,sh){(async()=>{if(lg.current){Lm.current--,Lm.current<0&&(Lm.current=0);return}try{const vh=await Dd(Fd.args);Gf.current&&await Gf.current.sendToolResult(sh,{toolCallId:sh,success:!0,result:vh}),Km.current?.recorder.toolEnded(sh,{result:vh}),ym({type:"TOOL_CALL_DONE",toolCallId:sh,success:!0,result:vh})}catch(vh){console.error("[ChatBase] Frontend tool execution error:",vh),Km.current?.recorder.toolEnded(sh,{error:vh.message}),ym({type:"TOOL_CALL_DONE",toolCallId:sh,success:!1,error:vh.message})}finally{Lm.current--,Lm.current<0&&(Lm.current=0)}})()}reactExports.useEffect(()=>{const Dd=$1.current;if(Dd){Dd.scrollTo({top:Dd.scrollHeight,behavior:"smooth"});return}Dg.current?.scrollIntoView({behavior:"smooth"})},[Wp]);const hv=reactExports.useRef(void 0),[t0]=useVoiceSettings(),Zm=reactExports.useMemo(()=>Vd?settledVoice(Vd,t0):void 0,[Vd,t0]),[xb,Sb]=reactExports.useState(!1),_g=!!(_h||Qd),um=useVoiceSpeaker(Zm,!_g);useSpokenAnswers(Wp,yp,!_g&&Zm?.output==="always",um.speaker);const X0=Ld||um.state.speaking,Q0=_g?Kd:um.state.sentence,B1=reactExports.useRef(null);useSaidSentence(B1,Q0,Wp);const[jv,r0]=reactExports.useState("");y0.current=Dd=>{if(isVoiceInterrupted(Dd)){Qd?Qd():um.speaker&&um.stop();return}const Fd=lineToSay(Dd);Fd&&(r0(Fd),Zm?.output==="always"&&(_h?_h(Fd):um.speaker?.say(Fd)))},reactExports.useEffect(()=>{yp||r0("")},[yp]);const[Fv,n0]=reactExports.useState(()=>new Set),pv=reactExports.useRef([]),j1=reactExports.useCallback(()=>{const Dd=answerSpokenOver(pv.current.filter(Fd=>!isToolCallMessage(Fd)));Dd&&n0(Fd=>new Set([...Fd,Dd]))},[]),xg=Qd??(um.speaker?um.stop:void 0),Sg=_g?fh:um.level,o0=_h??(um.speaker?um.read:void 0),Ym=reactExports.useCallback(async(Dd,Fd,sh)=>{const vh=(Dd??Kg).trim();if(!vh||yp||!Gf.current&&!$d)return;if(Fd&&namesFiles(Fd))try{Fd=await withUploadedFiles(Fd,k1)}catch(Hh){Df(Hh instanceof Error?Hh:new Error(String(Hh)));return}const nh=displayPressOf(Fd);if(nh&&Fd){const Hh=Vm.current?.socket;if(!Hh){Df(new Error("This conversation’s ui channel is not open."));return}try{const Rp=await Hh.act(nh);if(!Rp.ok){Df(new Error(Rp.detail||`The press was refused (${Rp.status}).`));return}Fd=withPress(Fd,Rp.value)}catch(Rp){Df(Rp instanceof Error?Rp:new Error(String(Rp)));return}}lg.current=!1,W0.current="",Km.current?.recorder.turnStarted(vh,sg||void 0),qm.current=isToolCallOnlyPrompt(vh);const bh=sh??spokenOf(Fd?.voice)??(Dd===void 0?hv.current:void 0);hv.current=void 0;const zh=bh?{...Fd??{},voice:bh}:Fd;let Wh;if(bh){const{sound:Hh,...Rp}=bh;Wh=Rp}const gp=createUserMessage(vh,Wh?{...Wh}:void 0),pp=[...Wp.filter(Hh=>!isToolCallMessage(Hh)),gp];{const{id:Hh,role:Rp,content:Bp,...xf}=gp;sm(Lf=>({...Lf,extras:new Map(Lf.extras).set(Hh,xf)}))}Rf(Hh=>reduceConversation(withPrompt(Hh,gp.id,vh),{type:"RUN_STARTED"})),gg(""),bf(!0),_m(!0),Df(null);try{if($d)if(rh){const Hh=generateMessageId(),Rp=(Bp,xf)=>ym({type:"MESSAGE_SAID",messageId:Hh,role:"assistant",text:Bp,streaming:xf});Rp("",!0),jd&&useChatStore.getState().startStreaming(Hh),R1.current=new AbortController,await $d(vh,pp,{onChunk:Bp=>{ym({type:"TEXT_MESSAGE_CONTENT",messageId:Hh,delta:Bp})},onComplete:Bp=>{Rp(Bp,!1),jd&&useChatStore.getState().stopStreaming()},onError:Bp=>{Rp(im.error(Bp.message),!1),jd&&useChatStore.getState().stopStreaming(),Df(Bp)},signal:R1.current.signal})}else{const Hh=await $d(vh,pp);Hh&&ym({type:"MESSAGE_SAID",messageId:generateMessageId(),role:"assistant",text:Hh,streaming:!1})}else if(Gf.current){const Hh=(Mm||[]).map(xf=>({name:xf.name,description:xf.description,parameters:xf.parameters||{type:"object",properties:{}}}));console.warn("[ChatBase] frontendTools count:",Mm?.length??0,"toolsForRequest:",Hh.map(xf=>xf.name));const Rp=cv(),Bp=yb();Fm(),await Gf.current.sendMessage(gp,{threadId:bg.current,messages:pp,...sg&&{model:sg},tools:Hh,builtinTools:Rp,skills:Bp,identities:Qg.current,...zh?{forwardedProps:zh}:{}})}}catch(Hh){Hh.name!=="AbortError"&&(console.error("[ChatBase] Send error:",Hh),Rf(Rp=>withError(Rp,Hh.message)),Df(Hh))}finally{Gf.current||(Qf.current.running&&ym({type:"RUN_FINISHED"}),bf(!1),_m(!1),agentRuntimeStore.getState().requestRefresh(Fh)),qm.current=!1,R1.current=null}},[Kg,yp,Wp,sg,Mm,jd,$d,Fh,rh,cv,yb,Fm,im,k1,Rf,sm,ym]);reactExports.useEffect(()=>{if(!fp||Nm&&x1.current===Nm)return;if(Nm&&sentPendingPromptKeys.has(Nm)){x1.current=Nm;return}!am&&!(!cp||Zg!=="connected")||!J1&&!$d||(x1.current=Nm??null,Nm&&sentPendingPromptKeys.add(Nm),queueMicrotask(()=>Ym(fp)))},[fp,Nm,am,cp,Zg,J1,Ym,$d,jg]);const e1=reactExports.useCallback(Dd=>{lg.current=!0,R1.current?.abort();const Fd=Gf.current;Fd&&(typeof Fd.stopGeneration=="function"&&Fd.stopGeneration(),Dd&&typeof Fd.interruptSession=="function"?Fd.interruptSession().catch(()=>{}):typeof Fd.terminateSession=="function"?Fd.terminateSession().catch(()=>{}):typeof Fd.terminateAgent=="function"?Fd.terminateAgent().catch(()=>{}):typeof Fd.terminateTask=="function"?Fd.terminateTask().catch(()=>{}):typeof Fd.terminateRequest=="function"&&Fd.terminateRequest().catch(()=>{})),Rf(sh=>withTurnEnded(sh,"stopped")),jd&&useChatStore.getState().stopStreaming(),Lm.current=0,bf(!1),_m(!1),agentRuntimeStore.getState().requestRefresh(Fh),agentRuntimeStore.getState().stopSubagentActivity(),qm.current=!1,C1.interrupt(),md&&md.interrupt().catch(()=>{})},[md,jd,Fh,Xh?.configEndpoint,Xh?.authToken,Xh?.agentId]),S0=reactExports.useCallback(()=>e1(!1),[e1]),w0=reactExports.useCallback(()=>e1(!0),[e1]),wb=reactExports.useCallback(Dd=>async Fd=>{const sh=Dd.actions?.find(bh=>bh.name===Fd.action);if(!sh)throw new Error(`“${Fd.action}” was not offered here.`);const vh=Fd.payload?.value,nh=Fd.action===ANSWER_ACTION?typeof vh=="string"?vh:isFileRef(vh)?vh.name:"Answered.":Fd.action;await Ym(nh,{loop:{action:{name:Fd.action,display_id:Dd.id,token:sh.token,payload:Fd.payload??{}}}})},[Ym]),fv=reactExports.useCallback(()=>{ig(),Lm.current=0,gg(""),bg.current=generateMessageId(),jd&&j0(),cp&&useConversationStore.getState().clearMessages(cp),Mh?.(),oh?.onNewChat?.()},[j0,Mh,oh,jd,Cp,ig]);reactExports.useEffect(()=>{if(Id){if(!J1&&!$d){Id(null);return}return Id({send:(Dd,Fd)=>{Ym(Dd,Fd)},stop:S0,newChat:fv,thread:()=>bg.current,stopSpeaking:xg,voiceLevel:Sg,markInterrupted:j1,interrupt:w0}),()=>{Id(null)}}},[Id,J1,$d,Ym,S0,w0,fv,xg,Sg,j1]),reactExports.useEffect(()=>{qd?.(yp)},[qd,yp]),reactExports.useEffect(()=>{Md?.(X0)},[Md,X0]);const t1=reactExports.useCallback(()=>{window.confirm("Clear all messages?")&&(ig(),jd&&j0(),cp&&useConversationStore.getState().clearMessages(cp),Kh?.(),oh?.onClear?.())},[j0,Kh,oh,jd,Cp,ig]),mv=reactExports.useCallback(Dd=>{const Fd=new Set(Dd),sh=kg.current.filter(vh=>Fd.has(vh.id)).map(rowIdOf);Rf(vh=>withoutItems(vh,sh)),sm(vh=>vh.steps.some(nh=>Fd.has(nh.item.id))?{...vh,steps:vh.steps.filter(nh=>!Fd.has(nh.item.id))}:vh)},[Rf,sm]),zv=reactExports.useCallback(async(Dd,Fd)=>{const sh=hg(Dd);if(sh&&(sh.status==="executing"||sh.status==="inProgress")){if(!!Fd&&typeof Fd=="object"&&Fd.type==="tool-approval-decision"&&typeof Fd.approved=="boolean"&&Gf.current){const nh=Fd,bh=!!nh.approved,zh=nh._fromServerEcho===!0,Wh=nh._alreadyDispatched===!0,gp=sh.status==="inProgress",Gh=typeof nh.toolName=="string"?nh.toolName:sh.toolName,pp=Gh.includes("__");if(bh){const Hh=Gh.indexOf("__");if(Hh!==-1){const Rp=Gh.slice(0,Hh),Bp=Gh.slice(Hh+2);X1(xf=>{const Lf=new Map(xf),a0=new Set(xf.get(Rp)??[]);return a0.add(Bp),Lf.set(Rp,a0),Lf})}}try{const Hh=typeof Fd=="object"&&Fd!==null&&typeof Fd.approvalId=="string"?Fd.approvalId:void 0;if(!zh&&!gp){Hh&&(bh?await h0?.(Hh,void 0,Dd):await Vg?.(Hh,void 0,Dd));return}if(Hh&&!Wh&&(bh?await h0?.(Hh,void 0,Dd):await Vg?.(Hh,void 0,Dd)),pp&&!gp)return;Rf(Rp=>reduceConversation(reduceConversation(Rp,{type:"TOOL_CALL_DONE",toolCallId:Dd,success:bh,result:Fd,answered:!0,...bh?{}:{error:"Tool approval rejected by user"}}),{type:"RUN_STARTED"})),bf(!0),_m(!0),await Gf.current.sendToolResult(Dd,{toolCallId:Dd,success:bh,result:bh?{approved:!0,message:"Tool call approved by user.",...Hh?{approvalId:Hh}:{}}:{approved:!1,message:"Tool call rejected by user.",...Hh?{approvalId:Hh}:{}},...bh?{}:{error:"Tool approval rejected by user"}})}catch(Hh){console.error("[ChatBase] Approval continuation error:",Hh),Df(Hh)}return}if(ym({type:"TOOL_CALL_DONE",toolCallId:Dd,success:!0,result:Fd,answered:!0}),Gf.current){let nh;if(typeof Fd=="string")nh=Fd;else if(Fd&&typeof Fd=="object"&&"accepted"in Fd){const zh=Fd;if(zh.accepted){const Wh=zh.steps?.map(gp=>gp.description).join(", ")||"";nh=Wh?`I confirm and approve the following steps: ${Wh}`:"I confirm and approve the plan."}else nh="I reject this plan. Please suggest something else."}else nh=JSON.stringify(Fd,null,2);const bh={id:generateMessageId(),role:"user",content:nh,createdAt:new Date};bf(!0),_m(!0),ym({type:"RUN_STARTED"});try{const zh=Wp.filter(Wh=>!isToolCallMessage(Wh));await Gf.current.sendMessage(bh,{threadId:bg.current,messages:[...zh,bh]})}catch(zh){console.error("[ChatBase] HITL respond error:",zh)}}}},[Wp,h0,Vg,hg,Rf,ym]);K0.current=zv;const Uv=reactExports.useCallback(Dd=>{Ym(Dd.message)},[Ym]),Hv=reactExports.useCallback(Dd=>{gg(Dd),setTimeout(()=>Ng.current?.focus(),0)},[]),zm=reactExports.useCallback(async(Dd,Fd)=>{await h0?.(Dd,Fd)},[h0]),Jm=reactExports.useCallback(async(Dd,Fd)=>{await Vg?.(Dd,Fd)},[Vg]),wg=(jp.data?.mcpServers||[]).filter(Dd=>!pd||_0(Dd)),gv=reactExports.useMemo(()=>{const Dd=wg.map(sh=>{const vh=Sp?.servers?.find(nh=>nh.id===sh.id);if(vh&&vh.status==="started"){const nh={};if(sh.isAvailable||(nh.isAvailable=!0),vh.tools&&vh.tools.length>0&&(nh.tools=vh.tools.map(bh=>({name:bh.name,description:bh.description||"",enabled:bh.enabled??!0}))),Object.keys(nh).length>0)return{...sh,...nh}}return sh}),Fd=new Set(wg.map(sh=>sh.id));for(const sh of Sp?.servers??[])sh.status==="started"&&!Fd.has(sh.id)&&sh.tools&&sh.tools.length>0&&(!pd||pd.some(nh=>nh.id===sh.id))&&Dd.push({id:sh.id,name:sh.id,description:"",url:"",enabled:!0,tools:sh.tools.map(nh=>({name:nh.name,description:nh.description||"",enabled:nh.enabled??!0})),args:[],requiredEnvVars:[],isAvailable:!0,transport:"stdio",isConfig:!1,isRunning:!0});return Dd},[wg,Sp,pd]),Eb=Xh?.configEndpoint?Xh.configEndpoint.replace(/\/api\/v1\/(config|configure)\/?$/,""):void 0,i0=!Xh||!Xh.enableConfigQuery||!!jp.data||!!Ig.data,Um=$h||jp.data?.welcomeMessage||"",_f=jp.data?.suggestions,F1=bp&&bp.length>0?bp:Array.isArray(_f)&&_f.length>0?_f.map(Dd=>{if(typeof Dd=="string"){const vh=Dd.trim();return{title:vh,message:vh}}const Fd=(Dd?.text??"").trim();return{title:(Dd?.summary??"").trim()||Fd,message:Fd}}).filter(Dd=>Dd.message):void 0,Xm=Pd?[{id:"__welcome__",role:"assistant",content:Pd,createdAt:WELCOME_AT},...Wp]:Wp;pv.current=Xm;const wp=saidMessageId(Xm,Q0),Xp=yp||mg?[...Xm].reverse().find(Dd=>!isToolCallMessage(Dd)&&Dd.role==="assistant")?.id:void 0,Nf=o0||Fv.size||Oh?(Dd,Fd)=>{const sh=getMessageText(Dd),vh=Oh?.(Dd,Fd)??null,nh=Fv.has(Dd.id),bh=!!(o0&&readsAloud(Dd,sh,Xp));return!vh&&!nh&&!bh?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[nh?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",fontStyle:"italic"},"data-interrupted":"",children:"interrupted"}):null,bh&&o0?jsxRuntimeExports.jsx(ReadAloud,{onRead:()=>o0(sh)}):null,vh]})}:void 0,z1=xd||jsxRuntimeExports.jsxs(Box,{ref:B1,display:"flex",flexDirection:"column",minHeight:0,width:"100%",maxWidth:920,mx:"auto",bg:"canvas.default",children:[jsxRuntimeExports.jsx(ChatMessageList,{displayItems:Xm,actOn:Xh?.uiSocket?wb:void 0,upload:Xh?.uiFiles?k1:void 0,isLoading:yp,isStreaming:mg,showLoadingIndicator:Pu,hideMessagesAfterToolUI:_p,avatarConfig:dv,padding:J0,notebookToolSurfacesId:Gd,approvalConfig:uv,messagesEndRef:Dg,onRespond:zv,showTurnFooters:ah,renderMessageFooter:Nf,saidMessageId:wp,agentUsage:E1,onRemoveItems:mv,mcpServers:gv,emptyContent:Xu?null:jsxRuntimeExports.jsx(ChatEmptyState,{emptyState:Xd,brandIcon:Yd,description:Um,suggestions:F1,submitOnSuggestionClick:Qh,onSuggestionSubmit:Uv,onSuggestionFill:Hv})}),Od]}),E0=Zm&&Zm.input!=="off"?jsxRuntimeExports.jsx(ComposerVoice,{voice:Zm,input:Kg,setInput:gg,disabled:Dh||Xu,speaking:X0,onStopSpeaking:xg,playbackLevel:Sg,running:yp,onStopRun:w0,onInterrupted:j1,onInterimChange:Sb,answers:!!(Vd?.output&&Vd.output!=="off"&&Vd.speechUrl),onSpoken:Dd=>{hv.current=Dd},send:(Dd,Fd)=>{Ym(Dd,void 0,Fd)}}):void 0,s0=!_g&&um.state.refused?jsxRuntimeExports.jsx(Text$3,{role:"alert",sx:{fontSize:0,color:"danger.fg",maxWidth:260},"data-voice-refused":"",children:um.state.refused}):null,U1=jv?jsxRuntimeExports.jsxs(Text$3,{"aria-live":"polite",sx:{fontSize:0,fontStyle:"italic",color:"fg.muted",maxWidth:260,display:"inline-flex",alignItems:"center",gap:1},"data-voice-say":"",children:[jsxRuntimeExports.jsx(UnmuteIcon,{size:12,"aria-label":"Said aloud"}),jv]}):null,r1=Mu?jsxRuntimeExports.jsx(InputPrompt,{footerExtras:s0||U1?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[U1,s0,E0]}):E0,interim:xb,input:Kg,setInput:gg,isLoading:yp,kernelStatus:$m,connectionConfirmed:i0,placeholder:Ah,typingSuggestions:F1?.map(Dd=>Dd.message||Dd.title),autoFocus:up,focusTrigger:np,padding:J0,onSend:()=>Ym(),onStop:S0,disableInputPrompt:ju||Dh||!!Yu||Xu,promptVariant:Fu,mentionableAgents:g0,promptCommands:Uu,promptHistory:jp.data?.promptHistory?.map(askedOf),showTokenUsage:Ru,showContextRing:Iu,agentUsage:E1,showModelSelector:Du,showToolsMenu:Lu,showSkillsMenu:Bu,codemodeEnabled:nd,onToggleCodemode:od,isA2AProtocol:fm,showAgentsMenu:Hu,agents:Jg,selectedAgentId:Gu??Jg[0]?.id,onSelectAgent:Wu,hasConfigData:!!jp.data,hasSkillsData:!!Ig.data,configLoading:jp.isLoading,models:Pg,decisions:jp.data?{models:jp.data.decisionModels,note:jp.data.decisionsNote}:void 0,selectedModel:sg,onModelSelect:Ov,availableTools:ev.runtime,availableFrontendTools:ev.frontend,mcpServers:gv,enabledMcpTools:Rg,enabledMcpToolCount:cv().length,onToggleMcpTool:O1,onToggleAllMcpServerTools:M1,approvedMcpTools:Mv,onToggleMcpToolApproval:Y0,skills:Ig.data?.skills||[],skillsLoading:!1,enabledSkills:mm,onToggleSkill:Nv,onToggleAllSkills:Z0,approvedSkills:Yg,onToggleSkillApproval:hy,apiBase:Eb,authToken:Xh?.authToken,mcpStatusData:Sp}):null,C0={title:Au,subtitle:lo,disableReason:Dh?Ud:void 0,brandIcon:Yd,headerContent:Nd,headerActions:yd,showInformation:Ch,onInformationClick:Zh??(()=>Bh(!0)),padding:J0,kernelIndicatorState:wd,kernelIndicatorPlacement:Ad,runtimeStatus:Tm??C1.data,kernel:gf?Yf??md:Vh?Jf??md:md,kernelEnvironmentName:dd,kernelCpu:bd,kernelMemory:ld,kernelGpu:ud,headerButtons:oh,messageCount:L1.length,onNewChat:fv,onClear:t1,chatViewMode:Ed,onChatViewModeChange:Cd,disabledViewModes:Rd,showEphemeralSurfaceControl:qh||wf,enableEphemeralNotebookOption:qh,enableEphemeralDocumentOption:wf,ephemeralSurfaceMode:Hf,onEphemeralSurfaceModeChange:qf},Cb=$u?eh?eh(C0):jsxRuntimeExports.jsx(ChatBaseHeader,{...C0}):null;return jsxRuntimeExports.jsxs(Box,{className:Sd,position:"relative",display:"flex",flexDirection:"column",height:"100%",maxHeight:"100%",minHeight:0,flex:"1 1 auto",width:"100%",minWidth:0,bg:Zd||"canvas.default",borderRadius:Hd,border:hh,boxShadow:wh,overflow:"hidden",children:[!$p&&Cb,y1&&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:Yd,protocol:Xh?.type??"unknown",url:Xh?.endpoint||"",messageCount:Wp.length,agentId:Fh,apiBase:Xh?.configEndpoint,onBack:()=>Bh(!1)}})}),Pf&&L0&&L0.length>0&&jsxRuntimeExports.jsx(ToolApprovalBannerSection,{pendingApprovals:L0,onApprove:zm,onReject:Jm}),Ou&&xm&&jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,p:J0,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:xm.message})]}),$p?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:Yh||Hp?null:{borderRight:"1px solid",borderColor:"border.default"},children:Xu||Yu?jsxRuntimeExports.jsx(CompanionSurfaceSkeleton,{mode:gf?"notebook":"document"}):gf?jsxRuntimeExports.jsx(ReactorLazy,{load:loadEphemeralNotebook,errorFallback:ephemeralNotebookRefused,fallback:jsxRuntimeExports.jsx(CompanionSurfaceSkeleton,{mode:"notebook"}),props:{notebookId:Yp,runtimeName:Cp||Fh,runtimeOverride:om,themeVariant:hd,colorMode:vd,nbformat:Pm??void 0,onNbformatChange:og,toolbarComponent:Fp,toolbarExtraItems:Mf,collaborationProvider:tp}}):jsxRuntimeExports.jsx(vM.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(EphemeralDocument,{documentId:Kf,runtimeName:Cp||Fh,runtimeOverride:om,themeVariant:hd,colorMode:vd,content:zf??void 0,onContentChange:Uf,onToolsReady:u0,onKernelChange:hf,collaboration:Tf,toolbarExtraItems:bm})})}),!Hp&&jsxRuntimeExports.jsxs(Box,{sx:Yh?{position:"absolute",right:16,width:Lp?360:440,maxWidth:"calc(100% - 32px)",...Lp?{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:[Cb,jsxRuntimeExports.jsx(Box,{ref:$1,flex:1,minHeight:0,overflow:"auto",bg:"canvas.default",children:z1}),zd,r1]}),Hp&&Qp&&(Ed==="sidebar"?jsxRuntimeExports.jsx(Box,{position:"absolute",top:8,right:8,zIndex:6,children:jsxRuntimeExports.jsx(IconButton,{icon:SidebarExpandIcon,"aria-label":"Open chat",onClick:Qp,variant:"default",size:"small"})}):jsxRuntimeExports.jsx(FloatingBrandButton,{isOpen:!1,onToggle:Qp,position:"bottom-right",tooltip:"Open chat"}))]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Box,{ref:$1,"data-chat-history":"",flex:1,flexGrow:1,minHeight:0,overflow:"auto",bg:"canvas.default",children:z1}),zd,r1]}),yh&&jsxRuntimeExports.jsx(PoweredByTag,{...gh}),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(`
|
|
3693
3693
|
`),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(Sd){ed(`Nothing was decided: ${Sd instanceof Error?Sd.message:String(Sd)}`)}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
|
|
3694
3694
|
Tech
|
|
@@ -3853,12 +3853,12 @@ ${lo}`;let Iu=MODULES.get(Ru);return Iu||(Iu=(async()=>{const Pu=await $u(Au,{cr
|
|
|
3853
3853
|
${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(`
|
|
3854
3854
|
|
|
3855
3855
|
`)){const Ru=$u.split(`
|
|
3856
|
-
`).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(yd=>yd.value.id))].sort(),Du=Mu.join(","),Lu=useOwnComponents(),Bu=reactExports.useMemo(()=>{const yd=blocksMissing(componentsOnPage(Pu),Mu);if(yd)return{problem:yd};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(yd=>yd.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(yd=>{td.current=yd,!ed.current&&(ed.current=!0,(async()=>{for(;td.current&&od.current;){const wd=td.current;td.current=null;const Ad=Ju.current;if(!Ad){Fu(Yu.current);continue}try{Xu.current??=openPageSession(Ad);const md=await runPageIn(Ad,await Xu.current,wd);if(!od.current)break;"refused"in md?Fu(md.refused):(Fu(null),Hu(md.outputs))}catch(md){Xu.current=null,od.current&&Fu(md instanceof Error?md.message:String(md))}}ed.current=!1})())},[]),ad=reactExports.useRef(null);reactExports.useEffect(()=>(od.current=!0,()=>{od.current=!1,ad.current?.()}),[]);const pd=reactExports.useCallback(yd=>{if(!zu?.live)return;ad.current?.();let wd;const Ad=dd=>{const bd=pageInputsOf(Au,dd),ld=JSON.stringify(bd);ld!==nd.current&&(clearTimeout(wd),wd=setTimeout(()=>{nd.current=ld,sd(bd)},PAGE_RUN_DELAY_MS))},md=yd.dataModel.subscribe("/inputs",Ad);Ad(md.value),ad.current=()=>{clearTimeout(wd),md.unsubscribe()}},[Au,zu?.live,sd]),gd=reactExports.useRef(lo);gd.current=lo;const Sd=reactExports.useRef(""),_d=reactExports.useCallback((yd,wd)=>{const Ad=appPageAction(Au,{name:yd.name,context:yd.context??{}},dd=>wd?.dataModel.get(dd),Sd.current),md=gd.current.viewControls;if("refused"in Ad){Fu(Ad.refused);return}if(Fu(null),"runPage"in Ad)sd(Ad.runPage);else if("stop"in Ad)md.stop?.();else if("newChat"in Ad)md.newChat?.();else{if(md.send){const dd=md.send(Ad.send,{loop:Ad.loop});if(dd){Fu(dd);return}}else if(Ad.loop.files){Fu("The conversation is not ready for a file yet: try again.");return}else gd.current.prompts.submit(Ad.send);Sd.current=Ad.inputs;for(const dd of Ad.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:_d,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(void 0),Ju=reactExports.useCallback(ld=>{Ku(ud=>ud===ld?ud:ld)},[]),[Yu,Xu]=reactExports.useState(Pu??""),[ed,td]=reactExports.useState(Iu),[nd]=reactExports.useState(createPromptChannel),[od,sd]=reactExports.useState({}),ad=reactExports.useCallback(ld=>{sd(ld??{})},[]),pd=useContributions(LoopViewType),gd=useContributions(LoopCommand),Sd=useSlotComponents(LoopSlots.sidebar),_d=reactExports.useRef(gd),yd=reactExports.useRef(null),wd=Mu==="panel",Ad=reactExports.useCallback(async ld=>{const ud=parseCommand(ld);if(!ud)return Ou?.(ld,yd.current),nd.submit(ld)||Ou?{handled:!0}:{handled:!1,reason:"Nothing is listening for prompts in this view yet."};const hd=_d.current.find(Ed=>Ed.value.name===ud.name||(Ed.value.aliases??[]).includes(ud.name));if(!hd)return{handled:!1,command:ud.name,reason:`Unknown command: /${ud.name}. Type /help to see what there is.`};const vd=await hd.value.run({workspace:yd.current,argv:ud.argv});return vd?.prompt&&(Ou?.(vd.prompt,yd.current),nd.submit(vd.prompt)),{handled:!0,command:ud.name,result:vd??void 0}},[Ou,nd]),md=reactExports.useMemo(()=>({serverUrl:Au,agentId:Hu,surfaceId:Gu.current,setAgentId:Vu,conversationId:$u,thread:Wu,setThread:Ju,model:Ru,sandbox:ed,setSandbox:td,activeViewType:Yu,setActiveViewType:Xu,prompts:nd,submit:Ad,viewControls:od,setViewControls:ad,chatHeaderActions:Bu,chatViewModes:ju}),[Au,Hu,$u,Wu,Ru,ed,Yu,nd,Ad,od,ad,Bu,ju]);yd.current=md,_d.current=gd;const dd=reactExports.useMemo(()=>Yu||(pd.find(ud=>canOpenView(ud.value,md))?.value.viewType??""),[Yu,pd,md]);useReactorEvent(dd?onView(dd):void 0);const bd=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Fu,jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.header,props:{workspace:md}}),Du?jsxRuntimeExports.jsx(ViewSwitcher,{views:pd,workspace:md,compact:wd}):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:bd}),zu):null,Lu&&zu===void 0?jsxRuntimeExports.jsx(Box,{as:"header",display:"flex",alignItems:"center",justifyContent:wd?"flex-start":"space-between",flexWrap:"wrap",gap:2,px:wd?2:3,py:2,borderBottom:"1px solid",borderColor:"border.default",flex:"0 0 auto",children:bd}):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:dd,props:{viewType:dd,workspace:md},fallback:jsxRuntimeExports.jsx(Centered,{children:"Loading…"}),empty:jsxRuntimeExports.jsx(Centered,{children:"No view is available yet."}),errorFallback:ld=>jsxRuntimeExports.jsxs(Centered,{children:["This view failed to load: ",ld.message]})})}),Sd.length>0&&Uu&&!wd?jsxRuntimeExports.jsx(SidebarRail,{components:Sd,props:{workspace:md},width:SIDEBAR_WIDTH}):Sd.length>0?jsxRuntimeExports.jsx(Box,{as:"aside",flex:"0 0 auto",width:wd?"100%":`${SIDEBAR_WIDTH}px`,minWidth:0,borderLeft:wd?"none":"1px solid",borderTop:wd?"1px solid":"none",borderColor:"border.default",bg:"canvas.subtle",overflowY:"auto",px:3,py:3,children:jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.sidebar,props:{workspace:md}})}):null]}),jsxRuntimeExports.jsxs(Box,{flex:"0 0 auto",children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.footer,props:{workspace:md}}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.status,props:{workspace:md}})]}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.root,props:{workspace:md}})]})}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]}const sessionFileName=Au=>`${Au.uid}.session.jsonl`,SESSION_ACTION_WORDS={switchAgent:"Switch agent…",switchTitle:Au=>`Switch ${Au} to`,noPicker:"Switching the agent needs a picker this page has not: use `loop sessions swap`.",noAgents:"No other agent of the catalogue runs on a harness.",cloneFromHere:"Clone from here",cloned:(Au,lo)=>`Cloned from turn ${Au} as ${lo}: opened here, the source untouched.`,export:"Export",exported:(Au,lo,$u)=>`Exported ${Au} turn${Au===1?"":"s"}, ${lo} redaction${lo===1?"":"s"} → ${$u}.`,import:"Import…",noFilePicker:"Importing a session needs a file picker this page has not: use `loop sessions import`.",imported:(Au,lo,$u)=>`Imported as ${Au} (${lo} turn${lo===1?"":"s"}, ${$u} redaction${$u===1?"":"s"}): opened here.`,resume:"Resume",resumed:Au=>`Resumed ${Au}.`};function agentChoices(Au){const lo=listAgentspecs();return listHarnesses().filter($u=>$u.id!=="custom"&&$u.enabled).flatMap($u=>{const Ru=lo.find(Iu=>Iu.harness===$u.id);return!Ru||Ru.id===Au.agent?[]:[{id:Ru.id,label:`${Ru.name} (${$u.name})`,description:$u.description}]})}const spokenAs=(Au,lo)=>(lo?listHarnesses().find(Ru=>Ru.id===lo):void 0)?.name??(lo||Au);function swapSentence(Au,lo){const $u=spokenAs(Au.agent,Au.harness),Ru=lo.label.replace(/\s*\(.*\)$/,"");return`This conversation was with ${$u} until turn ${Au.turns}; from here it is with ${Ru}. What was said stays.`}const idle=Au=>Au.state==="open"&&Au.turn==="idle";function redactionsOf(Au){const lo=Au.split(`
|
|
3857
|
-
`)[0]??"";try{return Number(JSON.parse(lo).redactions??0)||0}catch{return 0}}const SWITCH_AGENT={id:"switch-agent",label:SESSION_ACTION_WORDS.switchAgent,order:10,when:idle,run:async(Au,lo)=>{if(!lo.choose){lo.say(SESSION_ACTION_WORDS.noPicker);return}const $u=agentChoices(Au);if($u.length===0){lo.say(SESSION_ACTION_WORDS.noAgents);return}const Ru=await lo.choose({title:SESSION_ACTION_WORDS.switchTitle(Au.agent),options:$u,says:async Pu=>{const Ou=$u.find(Mu=>Mu.id===Pu);return Ou?swapSentence(Au,Ou):""}});if(!Ru)return;const Iu=await lo.client.swap(Au.uid,Ru);lo.say(String(Iu.said??`Swapped to ${Ru}.`))}},CLONE_FROM_HERE={id:"clone-from-here",label:SESSION_ACTION_WORDS.cloneFromHere,order:20,placement:"both",when:Au=>Au.turns>0,run:async(Au,lo)=>{const $u=lo.atTurn??Au.turns,Ru=await lo.client.clone(Au.uid,{upToTurn:$u}),Iu=String(Ru.uid??"");if(!Iu)throw new Error(`The runtime cloned session ${Au.uid} and named no new session.`);lo.say(SESSION_ACTION_WORDS.cloned($u,Iu)),lo.openThread?.(Iu)}},EXPORT={id:"export",label:SESSION_ACTION_WORDS.export,order:30,when:Au=>Au.turns>0,run:async(Au,lo)=>{const $u=await lo.client.exportFile(Au.uid),Ru=sessionFileName(Au);lo.download?.(Ru,$u,"application/x-ndjson"),lo.say(SESSION_ACTION_WORDS.exported(Au.turns,redactionsOf($u),Ru))}},IMPORT={id:"import",label:SESSION_ACTION_WORDS.import,order:35,when:()=>!0,run:async(Au,lo)=>{if(!lo.pickFile){lo.say(SESSION_ACTION_WORDS.noFilePicker);return}const $u=await lo.pickFile(".jsonl,application/x-ndjson");if(!$u)return;const Ru=await lo.client.importFile($u),Iu=String(Ru.uid??"");if(!Iu)throw new Error("The runtime imported the file and named no session.");lo.say(SESSION_ACTION_WORDS.imported(Iu,Number(Ru.turns??0)||0,Number(Ru.redactions??0)||0)),lo.openThread?.(Iu)}},RESUME={id:"resume",label:SESSION_ACTION_WORDS.resume,order:40,divider:!0,when:Au=>Au.state==="paused",run:async(Au,lo)=>{await lo.client.resume(Au.uid,Au.agent,{onEvent:()=>{}}),lo.say(SESSION_ACTION_WORDS.resumed(Au.uid)),lo.openThread?.(Au.uid)}},CHAT_SESSION_ACTIONS=[SWITCH_AGENT,CLONE_FROM_HERE,EXPORT,IMPORT,RESUME];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:[...CHAT_SESSION_ACTIONS.map(Au=>contribution(LoopSessionAction,Au,{id:Au.id,order:Au.order})),contribution(LoopViewType,{viewType:"chat",title:"Chat",icon:CommentDiscussionIcon,order:0,load:()=>__vitePreload(()=>import("./chunks/ChatView-LzqHHAEe.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-B-gxvk_X.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-BNuZDTPn.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"]);function isCreatingAgent(Au){return!Au.isReady&&!Au.agentId&&CREATING_STATUSES.has((Au.status||"").toLowerCase())}const 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 Ju=Ou.current?.getBoundingClientRect();Pu(!!(Ju&&Ju.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 Ju=Au.baseUrl.replace(/\/$/,"");return Ju.endsWith("/api/v1")?Ju:`${Ju}/api/v1`})():void 0,Fu=ju?`${ju}/runtime/status`:void 0,zu=toSandboxStatusUrl(Au?.sandboxBaseUrl);if(!Au)return null;const Uu=isCreatingAgent(Au),Hu=!!Au.error,Vu=!!Au.agentId||Uu,Gu=strip(Au.agentName,MAX_AGENT_NAME_LENGTH),Wu=`${Au.agentName} · ${Au.location}`,Ku=`${Gu} · ${Au.location}`;return jsxRuntimeExports.jsxs(Box,{ref:Ou,position:"relative",onMouseEnter:Lu,onMouseLeave:Bu,children:[jsxRuntimeExports.jsxs(Box,{as:"button",type:"button",title:Wu,px:2,py:"6px",maxWidth:280,minWidth:0,border:"1px solid",borderColor:Hu?"danger.emphasis":"border.default",borderRadius:2,bg:Hu?"danger.subtle":"canvas.default",color:Hu?"danger.fg":"fg.default",fontSize:0,cursor:"default",display:"flex",alignItems:"center",gap:1,children:[Uu&&jsxRuntimeExports.jsx(StyledSpinner,{size:"small",sx:{width:12,height:12}}),Hu&&jsxRuntimeExports.jsx("span",{"aria-hidden":!0,children:"⚠"}),jsxRuntimeExports.jsx(Box,{as:"span",display:"block",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",children:Ku})]}),$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: ",Uu?"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:Uu?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:"," ",Vu&&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"]}),Hu&&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-BOGJMsUN.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-DDWPvnOk.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} {
|
|
3856
|
+
`).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(yd=>yd.value.id))].sort(),Du=Mu.join(","),Lu=useOwnComponents(),Bu=reactExports.useMemo(()=>{const yd=blocksMissing(componentsOnPage(Pu),Mu);if(yd)return{problem:yd};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(yd=>yd.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(yd=>{td.current=yd,!ed.current&&(ed.current=!0,(async()=>{for(;td.current&&od.current;){const wd=td.current;td.current=null;const Ad=Ju.current;if(!Ad){Fu(Yu.current);continue}try{Xu.current??=openPageSession(Ad);const md=await runPageIn(Ad,await Xu.current,wd);if(!od.current)break;"refused"in md?Fu(md.refused):(Fu(null),Hu(md.outputs))}catch(md){Xu.current=null,od.current&&Fu(md instanceof Error?md.message:String(md))}}ed.current=!1})())},[]),ad=reactExports.useRef(null);reactExports.useEffect(()=>(od.current=!0,()=>{od.current=!1,ad.current?.()}),[]);const pd=reactExports.useCallback(yd=>{if(!zu?.live)return;ad.current?.();let wd;const Ad=dd=>{const bd=pageInputsOf(Au,dd),ld=JSON.stringify(bd);ld!==nd.current&&(clearTimeout(wd),wd=setTimeout(()=>{nd.current=ld,sd(bd)},PAGE_RUN_DELAY_MS))},md=yd.dataModel.subscribe("/inputs",Ad);Ad(md.value),ad.current=()=>{clearTimeout(wd),md.unsubscribe()}},[Au,zu?.live,sd]),gd=reactExports.useRef(lo);gd.current=lo;const Sd=reactExports.useRef(""),_d=reactExports.useCallback((yd,wd)=>{const Ad=appPageAction(Au,{name:yd.name,context:yd.context??{}},dd=>wd?.dataModel.get(dd),Sd.current),md=gd.current.viewControls;if("refused"in Ad){Fu(Ad.refused);return}if(Fu(null),"runPage"in Ad)sd(Ad.runPage);else if("stop"in Ad)md.stop?.();else if("newChat"in Ad)md.newChat?.();else{if(md.send){const dd=md.send(Ad.send,{loop:Ad.loop});if(dd){Fu(dd);return}}else if(Ad.loop.files){Fu("The conversation is not ready for a file yet: try again.");return}else gd.current.prompts.submit(Ad.send);Sd.current=Ad.inputs;for(const dd of Ad.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:_d,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(void 0),Ju=reactExports.useCallback(ld=>{Ku(ud=>ud===ld?ud:ld)},[]),[Yu,Xu]=reactExports.useState(Pu??""),[ed,td]=reactExports.useState(Iu),[nd]=reactExports.useState(createPromptChannel),[od,sd]=reactExports.useState({}),ad=reactExports.useCallback(ld=>{sd(ld??{})},[]),pd=useContributions(LoopViewType),gd=useContributions(LoopCommand),Sd=useSlotComponents(LoopSlots.sidebar),_d=reactExports.useRef(gd),yd=reactExports.useRef(null),wd=Mu==="panel",Ad=reactExports.useCallback(async ld=>{const ud=parseCommand(ld);if(!ud)return Ou?.(ld,yd.current),nd.submit(ld)||Ou?{handled:!0}:{handled:!1,reason:"Nothing is listening for prompts in this view yet."};const hd=_d.current.find(Ed=>Ed.value.name===ud.name||(Ed.value.aliases??[]).includes(ud.name));if(!hd)return{handled:!1,command:ud.name,reason:`Unknown command: /${ud.name}. Type /help to see what there is.`};const vd=await hd.value.run({workspace:yd.current,argv:ud.argv});return vd?.prompt&&(Ou?.(vd.prompt,yd.current),nd.submit(vd.prompt)),{handled:!0,command:ud.name,result:vd??void 0}},[Ou,nd]),md=reactExports.useMemo(()=>({serverUrl:Au,agentId:Hu,surfaceId:Gu.current,setAgentId:Vu,conversationId:$u,thread:Wu,setThread:Ju,model:Ru,sandbox:ed,setSandbox:td,activeViewType:Yu,setActiveViewType:Xu,prompts:nd,submit:Ad,viewControls:od,setViewControls:ad,chatHeaderActions:Bu,chatViewModes:ju}),[Au,Hu,$u,Wu,Ru,ed,Yu,nd,Ad,od,ad,Bu,ju]);yd.current=md,_d.current=gd;const dd=reactExports.useMemo(()=>Yu||(pd.find(ud=>canOpenView(ud.value,md))?.value.viewType??""),[Yu,pd,md]);useReactorEvent(dd?onView(dd):void 0);const bd=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Fu,jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.header,props:{workspace:md}}),Du?jsxRuntimeExports.jsx(ViewSwitcher,{views:pd,workspace:md,compact:wd}):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:bd}),zu):null,Lu&&zu===void 0?jsxRuntimeExports.jsx(Box,{as:"header",display:"flex",alignItems:"center",justifyContent:wd?"flex-start":"space-between",flexWrap:"wrap",gap:2,px:wd?2:3,py:2,borderBottom:"1px solid",borderColor:"border.default",flex:"0 0 auto",children:bd}):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:dd,props:{viewType:dd,workspace:md},fallback:jsxRuntimeExports.jsx(Centered,{children:"Loading…"}),empty:jsxRuntimeExports.jsx(Centered,{children:"No view is available yet."}),errorFallback:ld=>jsxRuntimeExports.jsxs(Centered,{children:["This view failed to load: ",ld.message]})})}),Sd.length>0&&Uu&&!wd?jsxRuntimeExports.jsx(SidebarRail,{components:Sd,props:{workspace:md},width:SIDEBAR_WIDTH}):Sd.length>0?jsxRuntimeExports.jsx(Box,{as:"aside",flex:"0 0 auto",width:wd?"100%":`${SIDEBAR_WIDTH}px`,minWidth:0,borderLeft:wd?"none":"1px solid",borderTop:wd?"1px solid":"none",borderColor:"border.default",bg:"canvas.subtle",overflowY:"auto",px:3,py:3,children:jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.sidebar,props:{workspace:md}})}):null]}),jsxRuntimeExports.jsxs(Box,{flex:"0 0 auto",children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.footer,props:{workspace:md}}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.status,props:{workspace:md}})]}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.root,props:{workspace:md}})]})}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]}const SESSION_RULE_DECISIONS=["allow","ask","deny"],SESSION_RULE_CLASSES=["read","write","send","buy","delete","execute"],SESSION_RULES_WORDS={title:"This session",none:"No rule of your own on this session yet.",noSession:"Start a conversation to add a rule to its session.",add:"Add",remove:"Remove",namePlaceholder:"A name, quoted in every sentence it decides",decisions:{allow:"do it",ask:"ask me first",deny:"leave it to me"},classes:{read:"reading",write:"writing",send:"sending",buy:"buying",delete:"deleting",execute:"running a command"},scopes:{organization:"your organization",team:"this application",session:"this session"},goneWithSession:"In force at once, for this session only; gone when it ends.",unavailable:Au=>`Nothing is decided right now: ${Au}`},WHERE_WORDS={inside:"inside the workspace",outside:"outside the workspace"};function sessionRuleInWords(Au){const lo=(Au.classes??[]).map(Ru=>SESSION_RULES_WORDS.classes[Ru]??Ru);let $u=lo.length>0?lo.join(", "):"everything";return(Au.where==="inside"||Au.where==="outside")&&($u=`${$u} ${WHERE_WORDS[Au.where]}`),Au.paths&&Au.paths.length>0&&($u=`${$u} (${Au.paths.join(", ")})`),Au.commands&&Au.commands.length>0&&($u=`${$u} matching ${Au.commands.map(Ru=>`\`${Ru}\``).join(" or ")}`),`${$u}: ${SESSION_RULES_WORDS.decisions[Au.decision]}`}const FILE_AND_SHELL_RULES=[{name:"Edit inside the workspace",decision:"allow",classes:["write"],where:"inside"},{name:"Ask before deleting a file",decision:"ask",classes:["delete"]},{name:"Ask before running a command",decision:"ask",classes:["execute"]},{name:"Leave files outside the workspace to me",decision:"deny",classes:["read","write","delete"],where:"outside"},{name:"Ask before git push",decision:"ask",classes:["execute"],commands:["^git\\s+push\\b"]},{name:"Ask before installing a package",decision:"ask",classes:["execute"],commands:["\\b(pip|npm|uv|yarn|apt(-get)?)\\s+(install|add)\\b"]},{name:"Leave sudo to me",decision:"deny",classes:["execute"],commands:["^sudo\\b"]}];function sessionRuleOf(Au){const lo=Au.name.trim();if(!lo)return"A rule needs a name: it is quoted in every sentence it decides.";if(!SESSION_RULE_DECISIONS.includes(Au.decision))return`A rule says ${SESSION_RULE_DECISIONS.join(", ")}, not “${Au.decision}”.`;const $u=Au.classes.filter(Ru=>SESSION_RULE_CLASSES.includes(Ru));return{name:lo,decision:Au.decision,classes:$u}}const sessionRulesUrl=(Au,lo)=>`${Au}/api/v1/apps/sessions/${encodeURIComponent(lo)}/rules`;function parsed(Au){try{return Au?JSON.parse(Au):null}catch{return null}}async function answered(Au,lo){const $u=parsed(await Au.text());if(!Au.ok){const Ru=$u&&typeof $u=="object"&&"detail"in $u?String($u.detail):`${lo} (${Au.status})`;throw new Error(Ru)}return $u}async function readSessionRules(Au,lo,$u,Ru=fetch){const Iu=await Ru(sessionRulesUrl(Au,$u),{headers:{Authorization:`Bearer ${lo}`}});return answered(Iu,"The rules of the session could not be read")}async function addSessionRule(Au,lo,$u,Ru,Iu=fetch){const Pu=await Iu(sessionRulesUrl(Au,$u),{method:"POST",headers:{Authorization:`Bearer ${lo}`,"Content-Type":"application/json"},body:JSON.stringify(Ru)});return answered(Pu,"The rule could not be added")}async function removeSessionRule(Au,lo,$u,Ru,Iu=fetch){const Pu=await Iu(`${sessionRulesUrl(Au,$u)}/${encodeURIComponent(Ru)}`,{method:"DELETE",headers:{Authorization:`Bearer ${lo}`}});return answered(Pu,"The rule could not be removed")}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 SessionRules({agentServerUrl:Au,sessionUid:lo,token:$u}){const[Ru,Iu]=reactExports.useState(null),[Pu,Ou]=reactExports.useState(""),[Mu,Du]=reactExports.useState(""),[Lu,Bu]=reactExports.useState("ask"),[ju,Fu]=reactExports.useState("send"),[zu,Uu]=reactExports.useState(!1),Hu=reactExports.useCallback(()=>{let Wu=!1;return readSessionRules(Au,$u,lo).then(Ku=>!Wu&&Iu(Ku),Ku=>!Wu&&Ou(Ku instanceof Error?Ku.message:String(Ku))),()=>{Wu=!0}},[Au,$u,lo]);reactExports.useEffect(Hu,[Hu]);const Vu=async Wu=>{Uu(!0),Ou("");try{Iu(await Wu())}catch(Ku){Ou(Ku instanceof Error?Ku.message:String(Ku))}finally{Uu(!1)}},Gu=()=>{const Wu=sessionRuleOf({name:Mu,decision:Lu,classes:[ju]});if(typeof Wu=="string"){Ou(Wu);return}Vu(()=>addSessionRule(Au,$u,lo,Wu)).then(()=>Du(""))};return jsxRuntimeExports.jsxs(Box,{"data-testid":"session-rules",mt:3,children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:1,mb:1},children:SESSION_RULES_WORDS.title}),Ru?.unavailable?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"alert",sx:{fontSize:0,m:0,mb:1},children:SESSION_RULES_WORDS.unavailable(Ru.unavailable)}):null,Ru&&Ru.session_rules.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:SESSION_RULES_WORDS.none}):jsxRuntimeExports.jsx(Box,{as:"ul",listStyle:"none",p:0,m:0,children:(Ru?.session_rules??[]).map(Wu=>jsxRuntimeExports.jsxs(Box,{as:"li",py:1,fontSize:1,display:"flex",gap:2,alignItems:"center",children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold"},children:Wu.name}),jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0},children:sessionRuleInWords(Wu)}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",disabled:zu,onClick:()=>{Vu(()=>removeSessionRule(Au,$u,lo,Wu.name))},children:SESSION_RULES_WORDS.remove})]},Wu.name))}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:1,mt:1,flexWrap:"wrap",alignItems:"center",children:[jsxRuntimeExports.jsx(TextInput$1,{size:"small",value:Mu,placeholder:SESSION_RULES_WORDS.namePlaceholder,"aria-label":"The rule's name",onChange:Wu=>Du(Wu.target.value)}),jsxRuntimeExports.jsx(Select$1,{size:"small",value:ju,"aria-label":"What it covers",onChange:Wu=>Fu(Wu.target.value),children:SESSION_RULE_CLASSES.map(Wu=>jsxRuntimeExports.jsx(Select$1.Option,{value:Wu,children:SESSION_RULES_WORDS.classes[Wu]},Wu))}),jsxRuntimeExports.jsx(Select$1,{size:"small",value:Lu,"aria-label":"What it says",onChange:Wu=>Bu(Wu.target.value),children:SESSION_RULE_DECISIONS.map(Wu=>jsxRuntimeExports.jsx(Select$1.Option,{value:Wu,children:SESSION_RULES_WORDS.decisions[Wu]},Wu))}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:zu,onClick:Gu,children:SESSION_RULES_WORDS.add})]}),jsxRuntimeExports.jsx(Box,{display:"flex",gap:1,mt:1,flexWrap:"wrap","data-testid":"session-rules-file-and-shell",children:FILE_AND_SHELL_RULES.map(Wu=>jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",disabled:zu,title:sessionRuleInWords(Wu),onClick:()=>{Vu(()=>addSessionRule(Au,$u,lo,Wu))},children:Wu.name},Wu.name))}),Pu?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"alert",sx:{fontSize:0,m:0,mt:1},children:Pu}):null,jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",mt:1,mb:0},children:SESSION_RULES_WORDS.goneWithSession})]})}function sessionUidOf(Au){return Au?.conversationId||Au?.thread||void 0}function AppRulesCard({app:Au,workspace:lo}){const $u=useIAMStore(Ou=>Ou.token)??"",Ru=!!$u,Iu=lo?agentServerOf(lo.sandbox,lo.serverUrl):void 0,Pu=sessionUidOf(lo);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((Ou,Mu)=>jsxRuntimeExports.jsxs(Box,{as:"li",py:1,fontSize:1,children:[jsxRuntimeExports.jsx(Text$3,{children:Ou.action})," ",jsxRuntimeExports.jsx(Label,{title:Ou.means,children:Ou.says}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:Ou.covers})]},Mu))}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",mt:1,mb:0},children:APP_RULES_WORDS.byDefault}),Ru?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}),Ru&&Iu?Pu?jsxRuntimeExports.jsx(SessionRules,{agentServerUrl:Iu,sessionUid:Pu,token:$u}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",mt:3,mb:0},children:SESSION_RULES_WORDS.noSession}):null]})}const SESSION_RULES_ACTION_WORDS={label:"Rules for this session…",title:"Rules for this session",noPanel:"Showing the session’s rules needs a panel this page has not: use the Rules card of the application’s page.",signedOut:"Sign in to see and add the rules of this session."},SESSION_RULES={id:"session-rules",label:SESSION_RULES_ACTION_WORDS.label,order:25,when:Au=>Au.state==="open",run:(Au,lo)=>{if(!lo.show){lo.say(SESSION_RULES_ACTION_WORDS.noPanel);return}const $u=lo.client.accessToken()??"";if(!$u){lo.say(SESSION_RULES_ACTION_WORDS.signedOut);return}lo.show({title:SESSION_RULES_ACTION_WORDS.title,render:()=>jsxRuntimeExports.jsx(SessionRules,{agentServerUrl:lo.client.serverUrl,token:$u,sessionUid:Au.uid})})}},sessionFileName=Au=>`${Au.uid}.session.jsonl`,SESSION_ACTION_WORDS={switchAgent:"Switch agent…",switchTitle:Au=>`Switch ${Au} to`,noPicker:"Switching the agent needs a picker this page has not: use `loop sessions swap`.",noAgents:"No other agent of the catalogue runs on a harness.",cloneFromHere:"Clone from here",cloned:(Au,lo)=>`Cloned from turn ${Au} as ${lo}: opened here, the source untouched.`,export:"Export",exported:(Au,lo,$u)=>`Exported ${Au} turn${Au===1?"":"s"}, ${lo} redaction${lo===1?"":"s"} → ${$u}.`,import:"Import…",noFilePicker:"Importing a session needs a file picker this page has not: use `loop sessions import`.",imported:(Au,lo,$u)=>`Imported as ${Au} (${lo} turn${lo===1?"":"s"}, ${$u} redaction${$u===1?"":"s"}): opened here.`,resume:"Resume",resumed:Au=>`Resumed ${Au}.`};function agentChoices(Au){const lo=listAgentspecs();return listHarnesses().filter($u=>$u.id!=="custom"&&$u.enabled).flatMap($u=>{const Ru=lo.find(Iu=>Iu.harness===$u.id);return!Ru||Ru.id===Au.agent?[]:[{id:Ru.id,label:`${Ru.name} (${$u.name})`,description:$u.description}]})}const spokenAs=(Au,lo)=>(lo?listHarnesses().find(Ru=>Ru.id===lo):void 0)?.name??(lo||Au);function swapSentence(Au,lo){const $u=spokenAs(Au.agent,Au.harness),Ru=lo.label.replace(/\s*\(.*\)$/,"");return`This conversation was with ${$u} until turn ${Au.turns}; from here it is with ${Ru}. What was said stays.`}const idle=Au=>Au.state==="open"&&Au.turn==="idle";function redactionsOf(Au){const lo=Au.split(`
|
|
3857
|
+
`)[0]??"";try{return Number(JSON.parse(lo).redactions??0)||0}catch{return 0}}const SWITCH_AGENT={id:"switch-agent",label:SESSION_ACTION_WORDS.switchAgent,order:10,when:idle,run:async(Au,lo)=>{if(!lo.choose){lo.say(SESSION_ACTION_WORDS.noPicker);return}const $u=agentChoices(Au);if($u.length===0){lo.say(SESSION_ACTION_WORDS.noAgents);return}const Ru=await lo.choose({title:SESSION_ACTION_WORDS.switchTitle(Au.agent),options:$u,says:async Pu=>{const Ou=$u.find(Mu=>Mu.id===Pu);return Ou?swapSentence(Au,Ou):""}});if(!Ru)return;const Iu=await lo.client.swap(Au.uid,Ru);lo.say(String(Iu.said??`Swapped to ${Ru}.`))}},CLONE_FROM_HERE={id:"clone-from-here",label:SESSION_ACTION_WORDS.cloneFromHere,order:20,placement:"both",when:Au=>Au.turns>0,run:async(Au,lo)=>{const $u=lo.atTurn??Au.turns,Ru=await lo.client.clone(Au.uid,{upToTurn:$u}),Iu=String(Ru.uid??"");if(!Iu)throw new Error(`The runtime cloned session ${Au.uid} and named no new session.`);lo.say(SESSION_ACTION_WORDS.cloned($u,Iu)),lo.openThread?.(Iu)}},EXPORT={id:"export",label:SESSION_ACTION_WORDS.export,order:30,when:Au=>Au.turns>0,run:async(Au,lo)=>{const $u=await lo.client.exportFile(Au.uid),Ru=sessionFileName(Au);lo.download?.(Ru,$u,"application/x-ndjson"),lo.say(SESSION_ACTION_WORDS.exported(Au.turns,redactionsOf($u),Ru))}},IMPORT={id:"import",label:SESSION_ACTION_WORDS.import,order:35,when:()=>!0,run:async(Au,lo)=>{if(!lo.pickFile){lo.say(SESSION_ACTION_WORDS.noFilePicker);return}const $u=await lo.pickFile(".jsonl,application/x-ndjson");if(!$u)return;const Ru=await lo.client.importFile($u),Iu=String(Ru.uid??"");if(!Iu)throw new Error("The runtime imported the file and named no session.");lo.say(SESSION_ACTION_WORDS.imported(Iu,Number(Ru.turns??0)||0,Number(Ru.redactions??0)||0)),lo.openThread?.(Iu)}},RESUME={id:"resume",label:SESSION_ACTION_WORDS.resume,order:40,divider:!0,when:Au=>Au.state==="paused",run:async(Au,lo)=>{await lo.client.resume(Au.uid,Au.agent,{onEvent:()=>{}}),lo.say(SESSION_ACTION_WORDS.resumed(Au.uid)),lo.openThread?.(Au.uid)}},CHAT_SESSION_ACTIONS=[SWITCH_AGENT,CLONE_FROM_HERE,SESSION_RULES,EXPORT,IMPORT,RESUME];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:[...CHAT_SESSION_ACTIONS.map(Au=>contribution(LoopSessionAction,Au,{id:Au.id,order:Au.order})),contribution(LoopViewType,{viewType:"chat",title:"Chat",icon:CommentDiscussionIcon,order:0,load:()=>__vitePreload(()=>import("./chunks/ChatView-uYgfl4KN.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-B-gxvk_X.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-BNuZDTPn.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"]);function isCreatingAgent(Au){return!Au.isReady&&!Au.agentId&&CREATING_STATUSES.has((Au.status||"").toLowerCase())}const 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 Ju=Ou.current?.getBoundingClientRect();Pu(!!(Ju&&Ju.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 Ju=Au.baseUrl.replace(/\/$/,"");return Ju.endsWith("/api/v1")?Ju:`${Ju}/api/v1`})():void 0,Fu=ju?`${ju}/runtime/status`:void 0,zu=toSandboxStatusUrl(Au?.sandboxBaseUrl);if(!Au)return null;const Uu=isCreatingAgent(Au),Hu=!!Au.error,Vu=!!Au.agentId||Uu,Gu=strip(Au.agentName,MAX_AGENT_NAME_LENGTH),Wu=`${Au.agentName} · ${Au.location}`,Ku=`${Gu} · ${Au.location}`;return jsxRuntimeExports.jsxs(Box,{ref:Ou,position:"relative",onMouseEnter:Lu,onMouseLeave:Bu,children:[jsxRuntimeExports.jsxs(Box,{as:"button",type:"button",title:Wu,px:2,py:"6px",maxWidth:280,minWidth:0,border:"1px solid",borderColor:Hu?"danger.emphasis":"border.default",borderRadius:2,bg:Hu?"danger.subtle":"canvas.default",color:Hu?"danger.fg":"fg.default",fontSize:0,cursor:"default",display:"flex",alignItems:"center",gap:1,children:[Uu&&jsxRuntimeExports.jsx(StyledSpinner,{size:"small",sx:{width:12,height:12}}),Hu&&jsxRuntimeExports.jsx("span",{"aria-hidden":!0,children:"⚠"}),jsxRuntimeExports.jsx(Box,{as:"span",display:"block",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",children:Ku})]}),$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: ",Uu?"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:Uu?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:"," ",Vu&&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"]}),Hu&&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-BOGJMsUN.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-DDWPvnOk.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} {
|
|
3858
3858
|
0%, 100% { opacity: 0.25; }
|
|
3859
3859
|
50% { opacity: 1; }
|
|
3860
3860
|
}`;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-CsiMsnAN.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-BOGJMsUN.js").then(Au=>Au.r),[],import.meta.url).then(Au=>(jupyterReact=Au,Au))}const PREVIEW_LENGTH=56;function stripped(Au){const $u=(Au.split(`
|
|
3861
|
-
`).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-sPywsCAF.js").then(Mu=>Mu.a),[],import.meta.url).then(()=>__vitePreload(()=>import("./chunks/index-CLdL3h_Z.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-D8h-aEea.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 Sd=0;Sd<2;Sd+=1)if(Ou[od][gd-Sd]==null){let _d=!1;ad<ed.length&&(_d=(ed[ad]>>>sd&1)==1),pd(od,gd-Sd)&&(_d=!_d),Ou[od][gd-Sd]=_d,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 yd=0;yd<td.length;yd+=1){const wd=td[yd].dataCount,Ad=td[yd].totalCount-wd;od=Math.max(od,wd),sd=Math.max(sd,Ad),ad[yd]=new Array(wd);for(let ld=0;ld<ad[yd].length;ld+=1)ad[yd][ld]=255&ed.getBuffer()[ld+nd];nd+=wd;const md=QRUtil.getErrorCorrectPolynomial(Ad),bd=qrPolynomial(ad[yd],md.getLength()-1).mod(md);pd[yd]=new Array(md.getLength()-1);for(let ld=0;ld<pd[yd].length;ld+=1){const ud=ld+bd.getLength()-pd[yd].length;pd[yd][ld]=ud>=0?bd.getAt(ud):0}}let gd=0;for(let yd=0;yd<td.length;yd+=1)gd+=td[yd].totalCount;const Sd=new Array(gd);let _d=0;for(let yd=0;yd<od;yd+=1)for(let wd=0;wd<td.length;wd+=1)yd<ad[wd].length&&(Sd[_d]=ad[wd][yd],_d+=1);for(let yd=0;yd<sd;yd+=1)for(let wd=0;wd<td.length;wd+=1)yd<pd[wd].length&&(Sd[_d]=pd[wd][yd],_d+=1);return Sd},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,Sd,_d,yd="",wd;for(wd="l"+ed+",0 0,"+ed+" -"+ed+",0 0,-"+ed+"z ",yd+='<svg version="1.1" xmlns="http://www.w3.org/2000/svg"',yd+=sd.scalable?"":' width="'+ad+'px" height="'+ad+'px"',yd+=' viewBox="0 0 '+ad+" "+ad+'" ',yd+=' preserveAspectRatio="xMinYMin meet"',yd+=od.text||nd.text?' role="img" aria-labelledby="'+Yu([od.id,nd.id].join(" ").trim())+'"':"",yd+=">",yd+=od.text?'<title id="'+Yu(od.id)+'">'+Yu(od.text)+"</title>":"",yd+=nd.text?'<description id="'+Yu(nd.id)+'">'+Yu(nd.text)+"</description>":"",yd+='<rect width="100%" height="100%" fill="white" cx="0" cy="0"/>',yd+='<path d="',Sd=0;Sd<Bu.getModuleCount();Sd+=1)for(_d=Sd*ed+td,pd=0;pd<Bu.getModuleCount();pd+=1)Bu.isDark(Sd,pd)&&(gd=pd*ed+td,yd+="M"+gd+","+_d+wd);return yd+='" stroke="transparent" fill="black"/>',yd+="</svg>",yd},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),Sd=Math.floor((pd-od)/ed);return Bu.isDark(Sd,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+="<";break;case">":td+=">";break;case"&":td+="&";break;case'"':td+=""";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,Sd,_d;const yd={"██":"█","█ ":"▀"," █":"▄"," ":" "},wd={"██":"▀","█ ":"▀"," █":" "," ":" "};let Ad="";for(ad=0;ad<nd;ad+=2){for(gd=Math.floor((ad-od)/1),Sd=Math.floor((ad+1-od)/1),pd=0;pd<nd;pd+=1)_d="█",od<=pd&&pd<sd&&od<=ad&&ad<sd&&Bu.isDark(gd,Math.floor((pd-od)/1))&&(_d=" "),od<=pd&&pd<sd&&od<=ad+1&&ad+1<sd&&Bu.isDark(Sd,Math.floor((pd-od)/1))?_d+=" ":_d+="█",Ad+=ed<1&&ad+1>=sd?wd[_d]:yd[_d];Ad+=`
|
|
3861
|
+
`).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-sPywsCAF.js").then(Mu=>Mu.a),[],import.meta.url).then(()=>__vitePreload(()=>import("./chunks/index-BCGvaYVt.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-D8h-aEea.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 Sd=0;Sd<2;Sd+=1)if(Ou[od][gd-Sd]==null){let _d=!1;ad<ed.length&&(_d=(ed[ad]>>>sd&1)==1),pd(od,gd-Sd)&&(_d=!_d),Ou[od][gd-Sd]=_d,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 yd=0;yd<td.length;yd+=1){const wd=td[yd].dataCount,Ad=td[yd].totalCount-wd;od=Math.max(od,wd),sd=Math.max(sd,Ad),ad[yd]=new Array(wd);for(let ld=0;ld<ad[yd].length;ld+=1)ad[yd][ld]=255&ed.getBuffer()[ld+nd];nd+=wd;const md=QRUtil.getErrorCorrectPolynomial(Ad),bd=qrPolynomial(ad[yd],md.getLength()-1).mod(md);pd[yd]=new Array(md.getLength()-1);for(let ld=0;ld<pd[yd].length;ld+=1){const ud=ld+bd.getLength()-pd[yd].length;pd[yd][ld]=ud>=0?bd.getAt(ud):0}}let gd=0;for(let yd=0;yd<td.length;yd+=1)gd+=td[yd].totalCount;const Sd=new Array(gd);let _d=0;for(let yd=0;yd<od;yd+=1)for(let wd=0;wd<td.length;wd+=1)yd<ad[wd].length&&(Sd[_d]=ad[wd][yd],_d+=1);for(let yd=0;yd<sd;yd+=1)for(let wd=0;wd<td.length;wd+=1)yd<pd[wd].length&&(Sd[_d]=pd[wd][yd],_d+=1);return Sd},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,Sd,_d,yd="",wd;for(wd="l"+ed+",0 0,"+ed+" -"+ed+",0 0,-"+ed+"z ",yd+='<svg version="1.1" xmlns="http://www.w3.org/2000/svg"',yd+=sd.scalable?"":' width="'+ad+'px" height="'+ad+'px"',yd+=' viewBox="0 0 '+ad+" "+ad+'" ',yd+=' preserveAspectRatio="xMinYMin meet"',yd+=od.text||nd.text?' role="img" aria-labelledby="'+Yu([od.id,nd.id].join(" ").trim())+'"':"",yd+=">",yd+=od.text?'<title id="'+Yu(od.id)+'">'+Yu(od.text)+"</title>":"",yd+=nd.text?'<description id="'+Yu(nd.id)+'">'+Yu(nd.text)+"</description>":"",yd+='<rect width="100%" height="100%" fill="white" cx="0" cy="0"/>',yd+='<path d="',Sd=0;Sd<Bu.getModuleCount();Sd+=1)for(_d=Sd*ed+td,pd=0;pd<Bu.getModuleCount();pd+=1)Bu.isDark(Sd,pd)&&(gd=pd*ed+td,yd+="M"+gd+","+_d+wd);return yd+='" stroke="transparent" fill="black"/>',yd+="</svg>",yd},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),Sd=Math.floor((pd-od)/ed);return Bu.isDark(Sd,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+="<";break;case">":td+=">";break;case"&":td+="&";break;case'"':td+=""";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,Sd,_d;const yd={"██":"█","█ ":"▀"," █":"▄"," ":" "},wd={"██":"▀","█ ":"▀"," █":" "," ":" "};let Ad="";for(ad=0;ad<nd;ad+=2){for(gd=Math.floor((ad-od)/1),Sd=Math.floor((ad+1-od)/1),pd=0;pd<nd;pd+=1)_d="█",od<=pd&&pd<sd&&od<=ad&&ad<sd&&Bu.isDark(gd,Math.floor((pd-od)/1))&&(_d=" "),od<=pd&&pd<sd&&od<=ad+1&&ad+1<sd&&Bu.isDark(Sd,Math.floor((pd-od)/1))?_d+=" ":_d+="█",Ad+=ed<1&&ad+1>=sd?wd[_d]:yd[_d];Ad+=`
|
|
3862
3862
|
`}return nd%2&&ed>0?Ad.substring(0,Ad.length-nd-1)+Array(nd+1).join("▀"):Ad.substring(0,Ad.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,Sd;const _d=Array(ed+1).join("██"),yd=Array(ed+1).join(" ");let wd="",Ad="";for(ad=0;ad<nd;ad+=1){for(gd=Math.floor((ad-od)/ed),Ad="",pd=0;pd<nd;pd+=1)Sd=1,od<=pd&&pd<sd&&od<=ad&&ad<sd&&Bu.isDark(gd,Math.floor((pd-od)/ed))&&(Sd=0),Ad+=Sd?_d:yd;for(gd=0;gd<ed;gd+=1)wd+=Ad+`
|
|
3863
3863
|
`}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;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 Uu=new BroadcastChannel(PAP_SIGN_IN_CHANNEL);return Uu.onmessage=Hu=>{const Vu=signInReturnOf(Hu.data,Lu);Vu&&(Mu(Vu),Uu.close())},()=>Uu.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.organization,zu=Du.mode==="mediated"?Fu?PAP_SIGN_IN_WORDS.mediatedTitleFor(Fu.name,Fu.domain,Du.host):PAP_SIGN_IN_WORDS.mediatedTitle(Du.host):Fu&&Du.mode==="device"?PAP_SIGN_IN_WORDS.titleFor(Fu.name,Fu.domain,Du.host):PAP_SIGN_IN_WORDS.title(ju);return jsxRuntimeExports.jsxs(Box,{as:"section","aria-label":zu,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:zu}),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(),isRecord=Au=>!!Au&&typeof Au=="object"&&!Array.isArray(Au),records=Au=>Array.isArray(Au)?Au.filter(isRecord):[],said=Au=>typeof Au=="string"?Au:Au==null?"":String(Au),SESSION_STATES=["open","paused","ended"],SESSION_TURNS=["idle","running","waiting"],runsOnOf=Au=>{if(!isRecord(Au))return null;if(Au.kind==="runtime")return{kind:"runtime",uid:said(Au.uid)};if(Au.kind==="team_run")return{kind:"team_run",executionId:said(Au.execution_id),seat:said(Au.seat)};throw new Error(`A session runs on a runtime or a team run, not on ${JSON.stringify(Au.kind)}.`)},lineageOf=Au=>{const lo=isRecord(Au)?Au:{},$u=isRecord(lo.forked_from)?lo.forked_from:null,Ru=isRecord(lo.imported_from)?lo.imported_from:null;return{forkedFrom:$u?{uid:said($u.uid),atTurn:Number($u.at_turn)||0}:null,importedFrom:Ru?{digest:said(Ru.digest),exportedAt:said(Ru.exported_at),exportedBy:said(Ru.exported_by)}:null}};function sessionRowOf(Au){const lo=said(Au.uid);if(!lo)throw new Error("A session row names its uid; this one does not.");const $u=said(Au.state);if(!SESSION_STATES.includes($u))throw new Error(`There is no session state ${JSON.stringify($u)} (session ${lo}): one of ${SESSION_STATES.join(", ")}.`);const Ru=said(Au.turn);if(Ru&&!SESSION_TURNS.includes(Ru))throw new Error(`There is no turn phase ${JSON.stringify(Ru)} (session ${lo}): one of ${SESSION_TURNS.join(", ")}.`);return{uid:lo,appUid:said(Au.app_uid),deploymentUid:said(Au.deployment_uid),version:Number(Au.version)||0,purpose:said(Au.purpose),launchUid:said(Au.launch_uid),ownerUid:said(Au.owner_uid),openedBy:said(Au.opened_by),wokenBy:said(Au.woken_by),state:$u,turn:Ru,held:typeof Au.held=="boolean"?Au.held:null,agent:said(Au.agent),harness:said(Au.harness),title:said(Au.title),archived:Au.archived===!0,runsOn:runsOnOf(Au.runs_on),lineage:lineageOf(Au.lineage),turns:Number(Au.turns)||0,startedAt:said(Au.started_at),keptUntil:said(Au.kept_until)}}function sessionPageOf(Au){return{sessions:records(Au.sessions).map(sessionRowOf),hasMore:Au.has_more===!0}}const SESSION_STATE_WORDS={open:"Open",paused:"Paused",ended:"Ended"},SESSION_TURN_WORDS={idle:"",running:"answering",waiting:"waiting for you"};function sessionStateSaid(Au){const lo=Au.state==="open"&&Au.turn?SESSION_TURN_WORDS[Au.turn]:"";return lo?`${SESSION_STATE_WORDS[Au.state]} · ${lo}`:SESSION_STATE_WORDS[Au.state]}const SESSION_LINEAGE_WORDS={cloned:(Au,lo)=>`Cloned from ${Au} at turn ${lo}`,imported:Au=>Au?`Imported from a file exported ${Au}`:"Imported from a file"};function sessionLineageSaid(Au){const{forkedFrom:lo,importedFrom:$u}=Au.lineage;return lo?SESSION_LINEAGE_WORDS.cloned(lo.uid,lo.atTurn):$u?SESSION_LINEAGE_WORDS.imported($u.exportedAt):""}function sessionAgentSaid(Au){return Au.agent?Au.harness&&Au.harness!==Au.agent?`${Au.agent} (${Au.harness})`:Au.agent:""}const COLOURS={context:{bg:"transparent",fg:"fg.muted",sign:" "},add:{bg:"success.subtle",fg:"success.fg",sign:"+"},remove:{bg:"danger.subtle",fg:"danger.fg",sign:"-"}};function DiffCard({display:Au}){const lo=unifiedDiffLines(Au.oldText,Au.newText);return jsxRuntimeExports.jsxs(Box,{"data-shield-display":"diff","data-language":Au.language,sx:{width:"100%",border:"1px solid",borderColor:"border.default",borderRadius:2,overflow:"hidden",fontSize:0},children:[jsxRuntimeExports.jsxs(Box,{sx:{px:2,py:1,bg:"canvas.subtle",borderBottom:"1px solid",borderColor:"border.default",display:"flex",justifyContent:"space-between"},children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontFamily:"mono",fontWeight:"bold"},children:Au.path}),jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted"},children:displayLine(Au)})]}),jsxRuntimeExports.jsx(Box,{as:"pre",className:`language-${Au.language}`,sx:{m:0,overflowX:"auto",fontFamily:"mono"},children:lo.map(($u,Ru)=>jsxRuntimeExports.jsxs(Box,{as:"span","data-diff-line":$u.kind,sx:{display:"block",px:2,bg:COLOURS[$u.kind].bg,color:COLOURS[$u.kind].fg,whiteSpace:"pre"},children:[COLOURS[$u.kind].sign,$u.text]},Ru))})]})}function TerminalCard({display:Au}){const lo=Au.exitCode!==null&&Au.exitCode!==0;return jsxRuntimeExports.jsxs(Box,{"data-shield-display":"terminal","data-exit-code":Au.exitCode===null?"running":Au.exitCode,sx:{width:"100%",border:"1px solid",borderColor:lo?"danger.muted":"border.default",borderRadius:2,overflow:"hidden",fontSize:0},children:[jsxRuntimeExports.jsxs(Box,{sx:{px:2,py:1,bg:"canvas.subtle",borderBottom:"1px solid",borderColor:"border.default",display:"flex",justifyContent:"space-between"},children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontFamily:"mono",fontWeight:"bold"},children:Au.command?`$ ${Au.command}`:Au.terminalId}),jsxRuntimeExports.jsx(Text$3,{sx:{color:lo?"danger.fg":"fg.muted"},children:displayLine(Au)})]}),jsxRuntimeExports.jsx(Box,{as:"pre",sx:{m:0,px:2,py:1,overflowX:"auto",fontFamily:"mono",whiteSpace:"pre-wrap",bg:"canvas.default"},children:Au.output||(Au.exitCode===null?"…":"(no output)")})]})}const SHIELD_DISPLAYS_PLUGIN_NAME="@datalayer/loop-plugin-shield-displays";function Diff({display:Au,context:lo}){const $u=protocolDisplayOf(Au);return!$u||$u.kind!=="diff"?reactExports.createElement("span",null,lo?.defaultUI??Au.text):reactExports.createElement(DiffCard,{key:Au.id,display:$u})}function Terminal$1({display:Au,context:lo}){const $u=protocolDisplayOf(Au);return!$u||$u.kind!=="terminal"?reactExports.createElement("span",null,lo?.defaultUI??Au.text):reactExports.createElement(TerminalCard,{key:Au.id,display:$u})}function createShieldDisplaysPlugin(){return{name:SHIELD_DISPLAYS_PLUGIN_NAME,displayName:"Diffs and terminals",description:"What a coding agent changed, as a unified diff, and what it ran, with its output.",octicon:"diff",emoji:"🛡",contributes:[contribution(Renderers,defineRenderer({type:SHIELD_DIFF_TYPE,component:Diff}),{id:"shield-diff"}),contribution(Renderers,defineRenderer({type:SHIELD_TERMINAL_TYPE,component:Terminal$1}),{id:"shield-terminal"})]}}const ShieldDisplaysPlugin=createShieldDisplaysPlugin();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=`
|
|
3864
3864
|
/*
|
|
@@ -4017,12 +4017,12 @@ ${Mu}`:ju,inputs:Mu,clear:Ou?[]:[DRAFT.path],loop:Lu()}:{refused:"Nothing to sen
|
|
|
4017
4017
|
opacity: 0.6;
|
|
4018
4018
|
border-top: 1px solid var(--cmdk-border);
|
|
4019
4019
|
}
|
|
4020
|
-
`;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-ssQ835Wa.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-DbTGOMyq.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-CB5BxGYz.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-BDChKuA9.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-ThwcTbLM.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(`
|
|
4020
|
+
`;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-DTZjQfu5.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-DbTGOMyq.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-CB5BxGYz.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-BDChKuA9.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-ThwcTbLM.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(`
|
|
4021
4021
|
|
|
4022
4022
|
`);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:Sd,colorMode:_d,presence:yd,showTokenUsage:wd,voice:Ad,thread:md,floatingPrompt:dd=!1,editorSelector:bd=!1,editors:ld=!0,conversation:ud=!0,commandPalette:hd=!1,pluginsPanel:vd=!1,windowFrame:Ed=!1,firstPromptHook:Cd}=Au,Rd=Ru??(ld?"notebook":"none");return ud?[configurePlugin(ChatPlugin,{defaultSurface:Rd,showSurfaceSelector:ld&&Iu&&!bd,hideHeader:Pu,headerButtons:{newChat:Ou,clear:Ou},promptPlacement:dd?"floating":Mu,autoFocusPrompt:Du,suggestionLabels:Lu,fullScreenTopOffset:Bu,themeVariant:gd,themeOverrides:Sd,colorMode:_d,presence:yd,showTokenUsage:wd,...Ad?{voice:Ad}:{},...md?{thread:md}:{}}),configurePlugin(InputPromptPlugin,{firstPromptHook:Cd}),ChatHeaderPlugin,A2uiSurfacePlugin,PapSignInPlugin,ShieldDisplaysPlugin,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:Rd,showSelector:ld&&bd}),...dd?[PromptPlugin]:[],...Hu?[configurePlugin(LoopPageLayoutPlugin,{arrangement:Vu,turnPanel:Gu,turnPanelFooter:Yu,prompt:Wu,promptAnchor:Ku,pageSize:Ju})]:[],...hd?[LoopCommandsPlugin]:[],...vd?[PluginsPanelPlugin]:[],...Ed?[WindowFramePlugin]:[]]:[ThemePlugin,configurePlugin(ShellPlugin,{defaultEditor:"none",showSelector:!1}),...hd?[LoopCommandsPlugin]:[],...vd?[PluginsPanelPlugin]:[],...Ed?[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 sessionPageOf(Iu)}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.uid),`${lo.uid}:${Au.token}`,$u),Pu=[sessionStateSaid(lo),sessionAgentSaid(lo),sessionLineageSaid(lo)].filter(Boolean);return jsxRuntimeExports.jsxs(Box,{as:"details",onToggle:Ou=>Ru(Ou.currentTarget.open),borderTop:"1px solid",borderColor:"border.muted",py:2,children:[jsxRuntimeExports.jsxs(Box,{as:"summary",cursor:"pointer",fontSize:1,children:[lo.startedAt?jsxRuntimeExports.jsx(RelativeTime,{datetime:lo.startedAt}):"A session",lo.title?` · ${lo.title}`:"",lo.version?` · version ${lo.version}`:"",Pu.length?` · ${Pu.join(" · ")}`:"",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(Ou=>jsxRuntimeExports.jsxs(Box,{as:"li",mb:1,children:[jsxRuntimeExports.jsx(Label,{sx:{mr:2},children:RECORD_KIND_WORDS[Ou.kind]??Ou.kind}),entrySaid(Ou)]},Ou.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?.sessions??[]).length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.none}):(Bu.value?.sessions??[]).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-C6wDxDrg.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(`
|
|
4023
4023
|
`):"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)}
|
|
4024
4024
|
… (${($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(`
|
|
4025
|
-
`)})]},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 SESSION_RULE_DECISIONS=["allow","ask","deny"],SESSION_RULE_CLASSES=["read","write","send","buy","delete","execute"],SESSION_RULES_WORDS={title:"This session",none:"No rule of your own on this session yet.",noSession:"Start a conversation to add a rule to its session.",add:"Add",remove:"Remove",namePlaceholder:"A name, quoted in every sentence it decides",decisions:{allow:"do it",ask:"ask me first",deny:"leave it to me"},classes:{read:"reading",write:"writing",send:"sending",buy:"buying",delete:"deleting",execute:"running a command"},scopes:{organization:"your organization",team:"this application",session:"this session"},goneWithSession:"In force at once, for this session only; gone when it ends.",unavailable:Au=>`Nothing is decided right now: ${Au}`},WHERE_WORDS={inside:"inside the workspace",outside:"outside the workspace"};function sessionRuleInWords(Au){const lo=(Au.classes??[]).map(Ru=>SESSION_RULES_WORDS.classes[Ru]??Ru);let $u=lo.length>0?lo.join(", "):"everything";return(Au.where==="inside"||Au.where==="outside")&&($u=`${$u} ${WHERE_WORDS[Au.where]}`),Au.paths&&Au.paths.length>0&&($u=`${$u} (${Au.paths.join(", ")})`),Au.commands&&Au.commands.length>0&&($u=`${$u} matching ${Au.commands.map(Ru=>`\`${Ru}\``).join(" or ")}`),`${$u}: ${SESSION_RULES_WORDS.decisions[Au.decision]}`}const FILE_AND_SHELL_RULES=[{name:"Edit inside the workspace",decision:"allow",classes:["write"],where:"inside"},{name:"Ask before deleting a file",decision:"ask",classes:["delete"]},{name:"Ask before running a command",decision:"ask",classes:["execute"]},{name:"Leave files outside the workspace to me",decision:"deny",classes:["read","write","delete"],where:"outside"},{name:"Ask before git push",decision:"ask",classes:["execute"],commands:["^git\\s+push\\b"]},{name:"Ask before installing a package",decision:"ask",classes:["execute"],commands:["\\b(pip|npm|uv|yarn|apt(-get)?)\\s+(install|add)\\b"]},{name:"Leave sudo to me",decision:"deny",classes:["execute"],commands:["^sudo\\b"]}];function sessionRuleOf(Au){const lo=Au.name.trim();if(!lo)return"A rule needs a name: it is quoted in every sentence it decides.";if(!SESSION_RULE_DECISIONS.includes(Au.decision))return`A rule says ${SESSION_RULE_DECISIONS.join(", ")}, not “${Au.decision}”.`;const $u=Au.classes.filter(Ru=>SESSION_RULE_CLASSES.includes(Ru));return{name:lo,decision:Au.decision,classes:$u}}const sessionRulesUrl=(Au,lo)=>`${Au}/api/v1/apps/sessions/${encodeURIComponent(lo)}/rules`;function parsed(Au){try{return Au?JSON.parse(Au):null}catch{return null}}async function answered(Au,lo){const $u=parsed(await Au.text());if(!Au.ok){const Ru=$u&&typeof $u=="object"&&"detail"in $u?String($u.detail):`${lo} (${Au.status})`;throw new Error(Ru)}return $u}async function readSessionRules(Au,lo,$u,Ru=fetch){const Iu=await Ru(sessionRulesUrl(Au,$u),{headers:{Authorization:`Bearer ${lo}`}});return answered(Iu,"The rules of the session could not be read")}async function addSessionRule(Au,lo,$u,Ru,Iu=fetch){const Pu=await Iu(sessionRulesUrl(Au,$u),{method:"POST",headers:{Authorization:`Bearer ${lo}`,"Content-Type":"application/json"},body:JSON.stringify(Ru)});return answered(Pu,"The rule could not be added")}async function removeSessionRule(Au,lo,$u,Ru,Iu=fetch){const Pu=await Iu(`${sessionRulesUrl(Au,$u)}/${encodeURIComponent(Ru)}`,{method:"DELETE",headers:{Authorization:`Bearer ${lo}`}});return answered(Pu,"The rule could not be removed")}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 SessionRules({agentServerUrl:Au,sessionUid:lo,token:$u}){const[Ru,Iu]=reactExports.useState(null),[Pu,Ou]=reactExports.useState(""),[Mu,Du]=reactExports.useState(""),[Lu,Bu]=reactExports.useState("ask"),[ju,Fu]=reactExports.useState("send"),[zu,Uu]=reactExports.useState(!1),Hu=reactExports.useCallback(()=>{let Wu=!1;return readSessionRules(Au,$u,lo).then(Ku=>!Wu&&Iu(Ku),Ku=>!Wu&&Ou(Ku instanceof Error?Ku.message:String(Ku))),()=>{Wu=!0}},[Au,$u,lo]);reactExports.useEffect(Hu,[Hu]);const Vu=async Wu=>{Uu(!0),Ou("");try{Iu(await Wu())}catch(Ku){Ou(Ku instanceof Error?Ku.message:String(Ku))}finally{Uu(!1)}},Gu=()=>{const Wu=sessionRuleOf({name:Mu,decision:Lu,classes:[ju]});if(typeof Wu=="string"){Ou(Wu);return}Vu(()=>addSessionRule(Au,$u,lo,Wu)).then(()=>Du(""))};return jsxRuntimeExports.jsxs(Box,{"data-testid":"session-rules",mt:3,children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:1,mb:1},children:SESSION_RULES_WORDS.title}),Ru?.unavailable?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"alert",sx:{fontSize:0,m:0,mb:1},children:SESSION_RULES_WORDS.unavailable(Ru.unavailable)}):null,Ru&&Ru.session_rules.length===0?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:SESSION_RULES_WORDS.none}):jsxRuntimeExports.jsx(Box,{as:"ul",listStyle:"none",p:0,m:0,children:(Ru?.session_rules??[]).map(Wu=>jsxRuntimeExports.jsxs(Box,{as:"li",py:1,fontSize:1,display:"flex",gap:2,alignItems:"center",children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold"},children:Wu.name}),jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0},children:sessionRuleInWords(Wu)}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",disabled:zu,onClick:()=>{Vu(()=>removeSessionRule(Au,$u,lo,Wu.name))},children:SESSION_RULES_WORDS.remove})]},Wu.name))}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:1,mt:1,flexWrap:"wrap",alignItems:"center",children:[jsxRuntimeExports.jsx(TextInput$1,{size:"small",value:Mu,placeholder:SESSION_RULES_WORDS.namePlaceholder,"aria-label":"The rule's name",onChange:Wu=>Du(Wu.target.value)}),jsxRuntimeExports.jsx(Select$1,{size:"small",value:ju,"aria-label":"What it covers",onChange:Wu=>Fu(Wu.target.value),children:SESSION_RULE_CLASSES.map(Wu=>jsxRuntimeExports.jsx(Select$1.Option,{value:Wu,children:SESSION_RULES_WORDS.classes[Wu]},Wu))}),jsxRuntimeExports.jsx(Select$1,{size:"small",value:Lu,"aria-label":"What it says",onChange:Wu=>Bu(Wu.target.value),children:SESSION_RULE_DECISIONS.map(Wu=>jsxRuntimeExports.jsx(Select$1.Option,{value:Wu,children:SESSION_RULES_WORDS.decisions[Wu]},Wu))}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:zu,onClick:Gu,children:SESSION_RULES_WORDS.add})]}),jsxRuntimeExports.jsx(Box,{display:"flex",gap:1,mt:1,flexWrap:"wrap","data-testid":"session-rules-file-and-shell",children:FILE_AND_SHELL_RULES.map(Wu=>jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",disabled:zu,title:sessionRuleInWords(Wu),onClick:()=>{Vu(()=>addSessionRule(Au,$u,lo,Wu))},children:Wu.name},Wu.name))}),Pu?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"alert",sx:{fontSize:0,m:0,mt:1},children:Pu}):null,jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",mt:1,mb:0},children:SESSION_RULES_WORDS.goneWithSession})]})}function sessionUidOf(Au){return Au?.conversationId||Au?.thread||void 0}function AppRulesCard({app:Au,workspace:lo}){const $u=useIAMStore(Ou=>Ou.token)??"",Ru=!!$u,Iu=lo?agentServerOf(lo.sandbox,lo.serverUrl):void 0,Pu=sessionUidOf(lo);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((Ou,Mu)=>jsxRuntimeExports.jsxs(Box,{as:"li",py:1,fontSize:1,children:[jsxRuntimeExports.jsx(Text$3,{children:Ou.action})," ",jsxRuntimeExports.jsx(Label,{title:Ou.means,children:Ou.says}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:Ou.covers})]},Mu))}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",mt:1,mb:0},children:APP_RULES_WORDS.byDefault}),Ru?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}),Ru&&Iu?Pu?jsxRuntimeExports.jsx(SessionRules,{agentServerUrl:Iu,sessionUid:Pu,token:$u}):jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",mt:3,mb:0},children:SESSION_RULES_WORDS.noSession}):null]})}const APP_RULES_PLUGIN_NAME="@datalayer/loop-plugin-app-rules";function defineAppRulesPlugin(Au){function lo(Ru){return jsxRuntimeExports.jsx(AppRulesCard,{app:Au,workspace:Ru.workspace})}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}
|
|
4025
|
+
`)})]},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 APP_RULES_PLUGIN_NAME="@datalayer/loop-plugin-app-rules";function defineAppRulesPlugin(Au){function lo(Ru){return jsxRuntimeExports.jsx(AppRulesCard,{app:Au,workspace:Ru.workspace})}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}
|
|
4026
4026
|
|
|
4027
4027
|
${$u}`:Au.prompt}function modeDefaults(Au){return Object.fromEntries((Au.interface.modes??[]).filter(lo=>lo.options.length>0).map(lo=>[lo.id,lo.default||lo.options[0].id]))}function modeChoice(Au,lo={}){const $u=Au.interface.modes??[];for(const[Ru,Iu]of Object.entries(lo)){const Pu=$u.find(Ou=>Ou.id===Ru);if(!Pu)throw new Error(`${Au.name} has no mode “${Ru}”.`);if(!Pu.options.some(Ou=>Ou.id===Iu))throw new Error(`The mode ${Pu.label} has no option “${Iu}”.`)}return{...modeDefaults(Au),...lo}}function profileChoice(Au,lo){const $u=Au.interface.profiles??[];if(lo){const Ru=$u.find(Iu=>Iu.id===lo);if(!Ru)throw new Error($u.length===0?`${Au.name} has no profiles: “${lo}” cannot be chosen.`:`${Au.name} has no profile “${lo}”.`);return Ru}return $u[0]}function startersFor(Au,lo){const $u=profileChoice(Au,lo);return $u&&$u.starters.length>0?$u.starters:Au.interface.starters}function modeEffect(Au,lo={},$u){const Ru=modeChoice(Au,lo),Iu=profileChoice(Au,$u),Pu=(Au.interface.modes??[]).flatMap(Du=>Du.options.filter(Lu=>Lu.id===Ru[Du.id])),Ou=[Iu?.instructions??"",...Pu.map(Du=>Du.instructions??"")].map(Du=>Du.trim()).filter(Boolean).join(`
|
|
4028
4028
|
|
|
@@ -4069,4 +4069,4 @@ iframe.datalayer-app-frame {
|
|
|
4069
4069
|
`;return Au?`${lo}
|
|
4070
4070
|
${scopeThemeCss(Au,[`[${THEME_SCOPE_ATTRIBUTE}]`])}`:lo}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.avatar})}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 (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&®isterPortalRoot(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=JSON.stringify(Au.interface.avatar??null),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://r1.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(`
|
|
4071
4071
|
`),$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(`
|
|
4072
|
-
`).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)}:embedTokenDeployment(Ru)?{kind:"spec",app:Du}:{kind:"said",text:EMBED_TOKEN_NAMES_NO_DEPLOYMENT}}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.agents(),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}agents(){return(this.getAttribute("api")||coreStore.getState().configuration?.aiAgentsUrl||DEFAULT_API).replace(/\/+$/,"")}api(){return(this.getAttribute("api")||coreStore.getState().configuration?.spacerUrl||"https://prod1.datalayer.run").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{useSandboxService as $,CopyIcon as A,Box as B,CROSSFADE_SECONDS as C,Dialog$1 as D,createAllAgentRuntimesTools as E,vM as F,GOODBYE_WAVE_SECONDS as G,Heading$2 as H,IconButton as I,renderOcticon as J,useNotebookStore$1 as K,Label as L,SquareFillIcon as M,NO_WEBGL_SENTENCE as N,OUT_OF_FRAME as O,PlayIcon as P,QueryClient as Q,REST_POSE as R,SANDBOX_KIND_LABELS as S,Text$3 as T,TrashIcon as U,PlusIcon as V,CodeIcon as W,notebookStore as X,decode$4 as Y,formatTokenCount as Z,__vitePreload as _,walkClipName as a,setIfUndefined as a$,useSignalValue$1 as a0,MessageProcessor as a1,datalayerCatalog as a2,A2uiSurfaceComposed as a3,ChatBaseHeader as a4,useContributions as a5,LoopPromptPanel as a6,InputPrompt as a7,Signal as a8,o$1 as a9,PanelLayout as aA,ITranslator as aB,createToolbarFactory as aC,nullTranslator as aD,ObservableList as aE,Toolbar$1 as aF,ReactWidget as aG,some$1 as aH,useAgentsRuntimes as aI,xu as aJ,useThemeStore as aK,useSystemColorMode as aL,getThemeConfig as aM,JupyterReactTheme$1 as aN,l$1 as aO,v$1 as aP,a$1 as aQ,Kernel as aR,registerSandboxServiceManager as aS,DatalayerThemeProvider as aT,de$1 as aU,on$1 as aV,nl as aW,es as aX,H as aY,disposeServiceManager as aZ,create$g as a_,LoopOpeningNotebook as aa,LoopNotebookToolbarItem as ab,LoopNotebookToolbar as ac,LRLanguage as ad,LanguageSupport as ae,indentNodeProp as af,continuedIndent as ag,foldNodeProp as ah,styleTags as ai,tags as aj,ExternalTokenizer as ak,ifNotIn as al,completeFromList as am,LRParser as an,syntaxTree as ao,delimitedIndent as ap,foldInside as aq,getDefaultExportFromCjs as ar,MimeModel as as,standardRendererFactories as at,purify$1 as au,Token$2 as av,Menu as aw,DisposableDelegate as ax,ArrayExt as ay,Widget as az,talkAmount as b,Prec as b$,create$6 as b0,fromBase64 as b1,onChange as b2,varStorage as b3,toBase64 as b4,createUint8ArrayFromArrayBuffer as b5,offChange as b6,map$3 as b7,ContextTracker as b8,NodeWeakMap as b9,SubItem as bA,Box$1 as bB,themeConfigs as bC,LoopDocumentToolbarItem as bD,LoopDocumentToolbar as bE,LoopOpeningDocument as bF,IDLE_SANDBOX_SNAPSHOT_SIGNAL as bG,definePlugin as bH,DOCUMENT_TOOLBAR_PLUGIN_NAME as bI,contribution as bJ,KernelIndicator as bK,NOTEBOOK_TOOLBAR_PLUGIN_NAME as bL,LocalTokenGroup as bM,flatIndent as bN,parseMixed as bO,bracketMatchingHandle as bP,EditorView as bQ,EditorSelection as bR,sublanguageProp as bS,defineLanguageFacet as bT,Parser$2 as bU,NodeType as bV,NodeProp as bW,Tag as bX,NodeSet as bY,Tree as bZ,countColumn as b_,IterMode as ba,snippetCompletion as bb,Panel as bc,PromiseDelegate as bd,DEFAULT_SERVICE_URLS as be,requestDatalayerAPI as bf,API_BASE_PATHS as bg,useReactorPlatform as bh,AGENTS_PLUGIN_NAME as bi,DEFAULT_DATALAYER_AGENTSPEC as bj,useOptionalSandboxService as bk,IDLE_SANDBOX_TARGET_SIGNAL as bl,ensureVisitorAgent as bm,AGENTSPECS$1 as bn,useAgentRuntimes as bo,ActionList as bp,distExports as bq,ActionListContainerContext as br,BoxWithFallback as bs,merge$5 as bt,defaultSxProp as bu,useId as bv,reactDomExports as bw,useIsomorphicLayoutEffect$2 as bx,ChevronDownIcon as by,classes$t as bz,cameraDistance as c,cutIcon as c$,keymap as c0,Language as c1,indentUnit as c2,foldService as c3,CompletionContext as c4,EditorState as c5,languageDataProp as c6,LanguageDescription as c7,ParseContext as c8,Eu as c9,Dialog as cA,showDialog$1 as cB,SearchDocumentModel as cC,SearchDocumentView as cD,isResponsiveValue as cE,clsx as cF,commonjsRequire as cG,TextInput$1 as cH,SearchIcon as cI,SyncIcon as cJ,ToggleSwitch as cK,Flash as cL,ChevronRightIcon as cM,StyledSpinner as cN,ToolbarButton as cO,fileUploadIcon as cP,libExports$2 as cQ,WidgetTracker as cR,folderIcon as cS,linkIcon as cT,Clipboard as cU,downloadIcon as cV,copyIcon as cW,setToolbar as cX,Notification as cY,CommandRegistry as cZ,closeIcon as c_,Ke$2 as ca,_c as cb,is as cc,Ys as cd,PencilIcon as ce,SingletonLayout as cf,FocusTracker as cg,libExports$5 as ch,VDomModel as ci,TableOfContents as cj,JSONExt as ck,VDomRenderer as cl,LabIcon as cm,classes as cn,map$5 as co,showErrorMessage as cp,AttachedProperty as cq,addIcon as cr,launcherIcon as cs,MainAreaWidget as ct,find$3 as cu,TranslatorConnector as cv,Gettext as cw,DEFAULT_LANGUAGE_CODE as cx,normalizeDomain as cy,ITranslatorConnector as cz,dampedPose as d,COMPLETER_ACTIVE_CLASS as d$,pasteIcon as d0,newFolderIcon as d1,textEditorIcon as d2,markdownIcon as d3,refreshIcon as d4,editIcon as d5,fileIcon as d6,stopIcon as d7,filterIcon as d8,DisposableSet as d9,deleteLine as dA,toggleBlockComment as dB,toggleComment as dC,toggleTabFocusMode as dD,selectNextOccurrence as dE,foldable as dF,foldCode as dG,unfoldCode as dH,foldState as dI,foldEffect as dJ,unfoldEffect as dK,foldAll as dL,unfoldAll as dM,IEditorServices as dN,EditorLanguageRegistry as dO,parseMathIPython as dP,StreamLanguage as dQ,pythonBuiltin as dR,EditorThemeRegistry as dS,EditorExtensionRegistry as dT,ybinding as dU,IPositionModel as dV,historyIcon as dW,CommandToolbarButton as dX,caretLeftIcon as dY,caretRightIcon as dZ,checkIcon as d_,clearNumbering as da,getHeadingId as db,addPrefix as dc,parseHeadings as dd,filterHeadings as de,StackedLayout as df,ABCWidgetFactory as dg,DocumentWidget as dh,ITableOfContentsRegistry as di,markdownRendererFactory as dj,SkeletonBox as dk,getBrightPalette as dl,useColorPalette as dm,SkeletonText as dn,Tooltip as dp,ActionMenu as dq,buildIcon as dr,jupyterIcon as ds,SettingRegistry as dt,moveUpIcon as du,moveDownIcon as dv,Button$1 as dw,deleteIcon as dx,DOMUtils as dy,lineFormIcon as dz,proceduralPose as e,NoteIcon as e$,Debouncer as e0,SessionContextDialogs as e1,saveIcon as e2,addCommandToolbarButtonClass as e3,UseSignal as e4,CommandToolbarButtonComponent as e5,createStore$1 as e6,useStore$1 as e7,runtimesStore as e8,DATALAYER_IAM_TOKEN_KEY as e9,Platform as eA,caretDownEmptyThinIcon as eB,StringExt as eC,SegmentedControl as eD,ListUnorderedIcon as eE,GraphIcon as eF,ClockIcon as eG,DatabaseIcon as eH,FileIcon as eI,ToolsIcon as eJ,CommentDiscussionIcon as eK,AiModelIcon as eL,InfoIcon as eM,KeyIcon as eN,devtools as eO,subscribeWithSelector as eP,persist as eQ,CheckCircleFillIcon as eR,AlertIcon as eS,useAgentRuntimeMcpStatus as eT,useAgentRuntimeCodemodeStatus as eU,useAgentRuntimeContextSnapshot as eV,useAgentRuntimeFullContext as eW,useAgentRuntimeWsState as eX,useMutation as eY,useQuery as eZ,ForwardRef$2 as e_,DATALAYER_IAM_USER_KEY as ea,coreStore as eb,iamStore as ec,layoutStore as ed,useCoreStore as ee,useIAMStore as ef,useLayoutStore as eg,useRuntimesStore as eh,OutputPrompt as ei,Stdin as ej,CodeCell as ek,useJupyterLabCssLoaded as el,TelescopeIcon as em,XIcon as en,CounterLabel as eo,PauseIcon as ep,DownloadIcon as eq,SPAN_SOURCE_LABELS as er,sourceOfSpan as es,AGENT_SPAN_ATTRIBUTES as et,describeAgentSpan as eu,SpecMark as ev,parse$4 as ew,UUID as ex,EN_US as ey,errorIcon as ez,accentPose as f,messagesOfThread as f$,ServerIcon as f0,CheckCircleIcon as f1,XCircleIcon as f2,BriefcaseIcon as f3,MenuBar as f4,runIcon as f5,fastForwardIcon as f6,require_MapCache as f7,require_Symbol as f8,require_Uint8Array as f9,CodeMirrorEditor as fA,getPrefix as fB,isMarkdown as fC,findNext as fD,gotoLine as fE,consoleIcon as fF,undoIcon as fG,redoIcon as fH,selectAll as fI,Sanitizer as fJ,COMPLETER_ENABLED_CLASS as fK,MessageLoop as fL,COMPLETER_LINE_BEGINNING_CLASS as fM,Message as fN,ElementExt as fO,renderText as fP,Printing as fQ,clientExports as fR,RenderedJavaScript as fS,AgentTools as fT,useToast as fU,isInsideJupyterLab as fV,FormControl$1 as fW,MailIcon as fX,Textarea as fY,$e$5 as fZ,PRESENCE_LINES as f_,requireEq as fa,require_getAllKeys as fb,require_Stack as fc,require_getTag as fd,requireIsArray as fe,requireIsBuffer as ff,requireIsTypedArray as fg,requireIsObjectLike as fh,getAnchoredPosition as fi,reactIsExports as fj,useTheme as fk,useOnEscapePress as fl,useOnOutsideClick as fm,useResizeObserver as fn,VisuallyHidden as fo,TriangleDownIcon as fp,qe$4 as fq,sx as fr,requireSerialize as fs,requireMessages as ft,mockSocketExports as fu,ObservableMap as fv,CodeEditorWrapper as fw,CodeEditor as fx,IEditorMimeTypeService as fy,EditorSearchProvider as fz,smoothed as g,generateMessageId as g$,sessionRowOf as g0,agUiRefusal as g1,refusalBody as g2,readRunStream as g3,useAnonymousInferenceSession as g4,browserModelRequiresSignIn as g5,getAgentspecs as g6,useOptionalReactorPlatform as g7,LoopSessionAction as g8,sessionActionsFor as g9,givenFilesSentence as gA,sendInstead as gB,onSurfaceRequest as gC,setEditorOptions as gD,seedEditorChoice as gE,canOpenView as gF,useWorkspaceFullScreen as gG,targetRunsAgentInPage as gH,useOptionalTeamSelection as gI,LoopAgentBlueprint as gJ,resolveAgentspec as gK,LoopChatSuggestion as gL,agentIcon as gM,LoopFrontendTool as gN,BROWSER_CODE_TOOL as gO,agentServerOf as gP,LoopCommand as gQ,subagentsFor as gR,useChatAvailability as gS,noRuntimeSaid as gT,useVoiceSettings as gU,settledVoice as gV,useSlotComponents as gW,LoopSlots as gX,onPromptFocusRequest as gY,useVisitorToken as gZ,voiceAskedAs as g_,sessionLineageSaid as ga,sessionStateSaid as gb,Select$1 as gc,FluentEmoji as gd,useChatWords as ge,CHAT_PLUGIN_NAME as gf,INPUT_PROMPT_PLUGIN_NAME as gg,LoopChatSurface as gh,LoopChatComposer as gi,LoopChatHeader as gj,LoopChatLayout as gk,LoopChatTurn as gl,turnWritersOf as gm,LoopChatExtras as gn,computed$1 as go,useGate as gp,presenceState as gq,presenceToolOf as gr,newestIsAnswer as gs,latestSaying as gt,messageText as gu,LoopRunProps as gv,runForwardedProps as gw,dataUrlBase64 as gx,sandboxFileName as gy,writeFilesCode as gz,QueryClientProvider as h,ref$1 as h$,openThread as h0,THREAD_WORDS as h1,agentInstructions as h2,useConfig as h3,useSkills as h4,useSkillActions as h5,runtimeModelsUrl as h6,readServerCatalogue as h7,readServerDecisions as h8,offeredModels as h9,Throttler as hA,Selector$1 as hB,jupyterFaviconIcon as hC,caretDownEmptyIcon as hD,addToolbarButtonClass as hE,NotebookActions as hF,offlineBoltIcon as hG,circleIcon as hH,ObservableJSON as hI,ConflatableMessage as hJ,jumpBackIcon as hK,jumpForwardIcon as hL,MarkdownCell as hM,Cell as hN,trustedIcon as hO,notTrustedIcon as hP,runCell as hQ,InputPrompt$1 as hR,NotebookPanel as hS,setCellExecutor as hT,StaticNotebook as hU,notebookIcon as hV,NotebookSearchProvider as hW,duplicateIcon as hX,addAboveIcon as hY,addBelowIcon as hZ,children$1 as h_,AI_MODEL_CATALOGUE as ha,isChatModel as hb,ReactorSlot as hc,ComposerVoice as hd,ReactorLazy as he,ChatBase as hf,ScreenNormalIcon as hg,ScreenFullIcon as hh,SUGGESTION_CHIP_WIDTH as hi,Truncate as hj,useAnonymousSessionStore as hk,inPageAgentRefusal as hl,signal$2 as hm,LoopAgentGate as hn,agentRuntimeStore as ho,loopShapeVars as hp,NONE_EDITOR as hq,filterListIcon as hr,CommandPalette$1 as hs,h$7 as ht,LabIconStyle as hu,copyrightIcon as hv,ToolbarButtonComponent as hw,bellIcon as hx,Button$3 as hy,paletteIcon as hz,idleClipName as i,ellipsesIcon as i$,html$6 as i0,startSlotTemplate as i1,endSlotTemplate as i2,slotted as i3,elements as i4,FoundationElement as i5,isHTMLElement as i6,__decorate$1 as i7,attr as i8,observable as i9,typeRampBaseFontSize$1 as iA,typeRampBaseLineHeight$1 as iB,density$1 as iC,typeRampPlus1FontSize$1 as iD,disabledOpacity$1 as iE,disabledCursor as iF,baseHeightMultiplier$1 as iG,neutralFillRest$1 as iH,neutralFillHover$1 as iI,neutralFillActive$1 as iJ,accentForegroundRest$1 as iK,display as iL,css as iM,forcedColorsStylesheetBehavior as iN,SystemColors as iO,cssPartial as iP,DesignToken as iQ,neutralFillStealthRecipe$1 as iR,neutralFillRecipe$1 as iS,useEventListener as iT,useProperties as iU,provideJupyterDesignSystem$1 as iV,ITableOfContentsTracker as iW,tocIcon as iX,numberingIcon as iY,expandAllIcon as iZ,collapseAllIcon as i_,applyMixins as ia,StartEnd as ib,keyEnter as ic,keyArrowUp as id,keyArrowDown as ie,keyArrowRight as ig,keyArrowLeft as ih,keyEnd as ii,keyHome as ij,DOM as ik,getDisplayedNodes as il,direction$1 as im,neutralForegroundRest$1 as io,neutralFillStealthRest$1 as ip,bodyFont$1 as iq,focusVisible as ir,accentFillFocus$1 as is,focusStrokeWidth$1 as it,strokeWidth$1 as iu,controlCornerRadius$1 as iv,heightNumber$1 as iw,neutralFillStealthHover$1 as ix,neutralFillStealthActive$1 as iy,designUnit$1 as iz,jsxRuntimeExports as j,CheckboxOrRadioGroupCaption as j$,caretDownIcon as j0,circleEmptyIcon as j1,searchIcon as j2,SplitPanel as j3,TabBar as j4,jsonIcon as j5,spreadsheetIcon as j6,terminalIcon as j7,kernelIcon as j8,NotificationManager as j9,StateEffect as jA,Decoration as jB,WidgetType as jC,DEFAULT_VARIANT as jD,MarimoReactive as jE,NotebookCommandIds as jF,OutputAreaModel as jG,useJupyterReactStore as jH,newUuid as jI,NotebookPanelProvider as jJ,addNotebookCommands as jK,YArray as jL,YText as jM,newUlid as jN,k$2 as jO,loopColors as jP,sunColors as jQ,ivoryColors as jR,sandColors as jS,earthColors as jT,matrixColors as jU,lovelyColors as jV,spatialColors as jW,datalayerColors as jX,getColorPalette as jY,CheckboxOrRadioGroupValidation as jZ,CheckboxOrRadioGroupLabel as j_,SessionContext as ja,Spinner as jb,Styling as jc,SystemClipboard as jd,VisuallyHidden$1 as je,StopIcon as jf,ViewPlugin as jg,createRelativePositionFromTypeIndex as jh,createRelativePositionFromJSON as ji,tooltips as jj,Facet as jk,Annotation as jl,layer as jm,StateField as jn,showTooltip as jo,createAbsolutePositionFromRelativePosition as jp,RectangleMarker as jq,YDocument as jr,createCellModelFromSharedType as js,createCell as jt,YMap as ju,RawCellModel as jv,MarkdownCellModel as jw,CodeCellModel as jx,MINOR_VERSION as jy,MAJOR_VERSION as jz,libExports$3 as k,stringify as k$,useRenderForcingRef as k0,CheckboxOrRadioGroup$1 as k1,CheckboxGroupContext as k2,Checkbox as k3,RadioGroup$1 as k4,Radio as k5,SelectPanel as k6,TextInputWithTokens as k7,object as k8,preprocess$1 as k9,history as kA,foldGutter as kB,drawSelection as kC,dropCursor as kD,indentOnInput as kE,syntaxHighlighting as kF,bracketMatching as kG,closeBrackets as kH,autocompletion as kI,rectangularSelection as kJ,crosshairCursor as kK,highlightActiveLine as kL,highlightSelectionMatches as kM,closeBracketsKeymap as kN,defaultKeymap as kO,searchKeymap as kP,historyKeymap as kQ,foldKeymap as kR,completionKeymap as kS,defaultHighlightStyle as kT,ArrowRightIcon as kU,useOutputsStore as kV,Compartment as kW,whitespace as kX,svg$2 as kY,find as kZ,stringify$1 as k_,record$2 as ka,string$2 as kb,unknown$1 as kc,zodToToolParameters as kd,array as ke,_enum as kf,number$2 as kg,boolean$1 as kh,validateWithZod as ki,useJupyterReactStoreFromProps as kj,OutputArea as kk,createStandaloneCell as kl,BoxPanel as km,cellsStore as kn,RawCell as ko,useCellsStore as kp,getPanel as kq,activateHover as kr,showPanel as ks,combineConfig as kt,RangeSetBuilder as ku,crelt as kv,hoverTooltip as kw,lineNumbers as kx,highlightActiveLineGutter as ky,highlightSpecialChars as kz,leavingPose as l,useProvidedRefOrCreate as l$,ccount as l0,zwitch as l1,html$4 as l2,htmlVoidElements as l3,C$1 as l4,Dt$4 as l5,u$2 as l6,dt$2 as l7,Go as l8,ns as l9,_n as lA,hn$2 as lB,qc as lC,Ie$2 as lD,cs as lE,dr as lF,Jl as lG,fn$2 as lH,hn$1 as lI,pn$1 as lJ,Wo as lK,xt$2 as lL,Zs as lM,gc as lN,On as lO,na as lP,ea as lQ,ia as lR,sa as lS,decodeNamedCharacterReference as lT,requireReact as lU,StyleModule as lV,jupyterHighlightStyle as lW,useFocusZone as lX,FocusKeys as lY,useSafeTimeout as lZ,useSlots as l_,mn$1 as la,qi as lb,Pi as lc,isStream as ld,isExecuteResult as le,isDisplayData as lf,isError$1 as lg,Xo as lh,Ki as li,Yi as lj,er as lk,T as ll,v$2 as lm,S$1 as ln,C as lo,m$2 as lp,x$5 as lq,y$3 as lr,p$4 as ls,ol as lt,He$2 as lu,pn$2 as lv,Kr as lw,ur as lx,ls as ly,cn$1 as lz,modelNotLoadedSentence as m,folderFavoriteIcon as m$,useResponsiveValue as m0,ScrollableRegion as m1,viewportRanges as m2,JupyterLiteServer as m3,Router as m4,ContextMenu as m5,TabPanel as m6,DockPanel as m7,hpass as m8,AccordionPanel as m9,writeVarUint as mA,encodeStateVector as mB,writeVarUint8Array as mC,encodeStateAsUpdate as mD,readVarUint as mE,applyUpdate as mF,readVarUint8Array as mG,readVarString as mH,ObservableV2 as mI,Awareness as mJ,toUint8Array$1 as mK,length as mL,encodeAwarenessUpdate as mM,removeAwarenessStates as mN,isNode as mO,getUnixTime as mP,createEncoder as mQ,min as mR,pow as mS,createDecoder as mT,applyAwarenessUpdate as mU,UndoManager as mV,Doc$1 as mW,isCodeCellModel as mX,Drag as mY,MimeData as mZ,useConsoleStore as m_,AccordionLayout as ma,FormAssociated as mb,nullableNumberConverter as mc,ARIAGlobalStatesAndProperties as md,neutralFillInputRest$1 as me,neutralFillStrongRest$1 as mf,errorFillRest$1 as mg,neutralFillInputHover$1 as mh,neutralFillStrongHover$1 as mi,errorFillHover$1 as mj,neutralFillStrongActive$1 as mk,errorFillActive$1 as ml,errorFillFocus$1 as mm,neutralStrokeRest$1 as mn,__decorate as mo,BoxLayout as mp,VirtualDOM as mq,TextModelFactory as mr,pdfIcon as ms,pythonIcon as mt,juliaIcon as mu,rKernelIcon as mv,yamlIcon as mw,imageIcon as mx,audioIcon as my,videoIcon as mz,sandboxIsLive as n,kernelsStore as n$,filter$3 as n0,caretUpIcon as n1,Poll as n2,each as n3,Application as n4,StackedPanel as n5,tabIcon as n6,Base64ModelFactory as n7,useTerminalStore as n8,requestAPI$1 as n9,SettingManagerLess as nA,TerminalManagerLess as nB,UserManagerLess as nC,WorkspaceManagerLess as nD,cellSourceAsString as nE,consoleStore as nF,createLiteServer as nG,createServerSettings as nH,deleteCellsOperation as nI,deleteCellsTool as nJ,disableKernelReconnect as nK,disposeKernelConnections as nL,ensureJupyterAuth as nM,ensureJupyterConfig as nN,executeCodeOperation as nO,executeCodeTool as nP,formatResponse as nQ,getCookie as nR,getJupyterServerToken as nS,getJupyterServerUrl as nT,getKernelIndicatorMeta as nU,insertCellOperation as nV,insertCellTool as nW,isAnyCellRunning as nX,isReactiveVariant as nY,isServedByJupyterLab as nZ,jupyterLabTheme as n_,loadJupyterConfig as na,createLiteServiceManager as nb,jupyterReactStore as nc,ANSWER_MARKER as nd,BuilderManagerLess as ne,ContentsManagerLess as nf,DEFAULT_API_KERNEL_PREFIX_URL as ng,DEFAULT_JUPYTER_SERVER_TOKEN as nh,DEFAULT_JUPYTER_SERVER_URL as ni,DEFAULT_KERNEL_NAME as nj,DefaultExecutor as nk,EventsManagerLess as nl,ExecutionPhase as nm,HELPER_NAME as nn,JupyterLabCss as no,KERNEL_HELPER_SOURCE as np,KERNEL_STATES as nq,KERNEL_STATE_LABELS as nr,KERNEL_STATE_VISUALS as ns,KernelExecutor as nt,KernelManagerLess as nu,KernelspecManagerLess as nv,NbConvertManagerLess as nw,OperationRunner as nx,ServiceManagerLess as ny,SessionManagerLess as nz,sandboxExecuteOverHttp as o,La as o$,loadJupyterLabCss as o0,notebookToolDefinitions as o1,notebookToolOperations as o2,notebookTools as o3,outputsAsString as o4,outputsStore as o5,readAllCellsOperation as o6,readAllCellsTool as o7,readCellOperation as o8,readCellTool as o9,sn$1 as oA,vc as oB,tr as oC,Sn as oD,Zo as oE,Cu as oF,Bs as oG,Me as oH,yn as oI,Se as oJ,Cn as oK,fn as oL,qr as oM,Ia as oN,zs as oO,gn$2 as oP,or as oQ,Jr as oR,sn$2 as oS,ln$1 as oT,rn$1 as oU,nn$2 as oV,Vr as oW,nu as oX,du as oY,Va as oZ,au as o_,refreshJupyterLabPortalTheme as oa,renderKernelStateGlyph as ob,resetJupyterConfig as oc,runCellOperation as od,runCellTool as oe,setJupyterServerToken as of,setJupyterServerUrl as og,sleep as oh,syncJupyterLabPortalTheme as oi,terminalStore as oj,toKernelState as ok,updateCellOperation as ol,updateCellTool as om,useJupyterReactColormode as on,useKernelsStore as oo,ThemeProvider as op,Overlay$1 as oq,Fi as or,Zl as os,bu as ot,Nu as ou,Wl as ov,Fr as ow,Li as ox,Vc as oy,Fo as oz,prefersReducedMotion as p,qe$2 as p$,Is as p0,Dl as p1,h$1 as p2,Sn$1 as p3,Nn$1 as p4,ce$1 as p5,Tu as p6,vu as p7,ae$1 as p8,xt$3 as p9,yn$1 as pA,It$1 as pB,Tt as pC,l$2 as pD,a$2 as pE,d$2 as pF,s$2 as pG,Ue$2 as pH,dn$2 as pI,$e$2 as pJ,un$1 as pK,Bi as pL,It as pM,en$2 as pN,_$1 as pO,te$2 as pP,le$2 as pQ,on$2 as pR,$t$3 as pS,mn$2 as pT,Xe$2 as pU,gr as pV,Ge$2 as pW,_r as pX,Ve$2 as pY,je$1 as pZ,Ye$1 as p_,St$3 as pa,Pc as pb,Lc as pc,Ic as pd,mt$3 as pe,rs as pf,an$1 as pg,Je$2 as ph,Ft$1 as pi,Os as pj,Mt$1 as pk,gt as pl,Co as pm,Tn as pn,Dt as po,So as pp,vn as pq,kn$1 as pr,xl as ps,oa as pt,Cn$1 as pu,et as pv,xn as pw,St as px,Rt as py,xt as pz,displayUrl as q,x$4 as q$,Yt as q0,Ya as q1,Pe$2 as q2,Ja as q3,tu as q4,zl as q5,Fl as q6,Ma as q7,ja as q8,Hl as q9,Re as qA,Kc as qB,Wt$1 as qC,z$2 as qD,ac as qE,On$1 as qF,Ht$1 as qG,Le$2 as qH,zr as qI,Bt$1 as qJ,Ll as qK,ui as qL,ec as qM,nc as qN,zt$1 as qO,Ir as qP,i$1 as qQ,uu as qR,Aa as qS,Wa as qT,Ul as qU,ql as qV,dc as qW,be as qX,ke as qY,ft as qZ,pi as q_,Ba as qa,Bl as qb,Pr as qc,Pe as qd,uo as qe,mu as qf,iu as qg,ku as qh,Mo as qi,Rl as qj,wu as qk,Fn as ql,lc as qm,$s as qn,he as qo,Fe as qp,Ut$1 as qq,We as qr,Fs as qs,Al as qt,No as qu,bo as qv,as as qw,_t as qx,eu as qy,fc as qz,reactExports as r,BookIcon as r$,z as r0,O$1 as r1,r$2 as r2,t$2 as r3,Es as r4,_s as r5,vt$2 as r6,n$2 as r7,b$1 as r8,nn$1 as r9,Pt$1 as rA,s$1 as rB,f$3 as rC,P$1 as rD,fe$1 as rE,PaperAirplaneIcon as rF,bn$2 as rG,TableIcon as rH,q as rI,ChecklistIcon as rJ,fn$1 as rK,GrabberIcon as rL,vo as rM,yo as rN,wo as rO,mo as rP,j$1 as rQ,r$3 as rR,$2AODx$react as rS,jt$1 as rT,oe$1 as rU,ie$2 as rV,RowsIcon as rW,x$2 as rX,AlertFillIcon as rY,BeakerIcon as rZ,BellIcon as r_,r$1 as ra,g$1 as rb,Tt$2 as rc,ys as rd,e$1 as re,vl as rf,u$1 as rg,b$3 as rh,z$1 as ri,zi as rj,Ji as rk,ko as rl,To as rm,Ze$2 as rn,Qe$2 as ro,Mn$1 as rp,wn$1 as rq,En$1 as rr,xo as rs,vi as rt,Ql as ru,ut$2 as rv,Gl as rw,ReactDOM as rx,M$2 as ry,PersonIcon as rz,stateMotion as s,require_isIterateeCall as s$,BroadcastIcon as s0,BrowserIcon as s1,BugIcon as s2,CircleSlashIcon as s3,CodeReviewIcon as s4,CpuIcon as s5,CreditCardIcon as s6,DependabotIcon as s7,DeviceDesktopIcon as s8,DeviceMobileIcon as s9,SunIcon as sA,TagIcon as sB,TasklistIcon as sC,ThumbsdownIcon as sD,ThumbsupIcon as sE,UnmuteIcon as sF,UploadIcon as sG,XCircleFillIcon as sH,ZapIcon as sI,requireFastDeepEqual as sJ,getAugmentedNamespace as sK,requireParseSrcset as sL,requirePostcss as sM,requireIsPlainObject as sN,requireEscapeStringRegexp as sO,requireIsArguments as sP,require_arrayPush as sQ,require_baseGetTag as sR,requireIsObject as sS,requireKeys as sT,require_isIndex as sU,requireIsLength as sV,requireIdentity as sW,require_baseFor as sX,requireIsArrayLike as sY,require_baseUnary as sZ,require_baseRest as s_,FoldIcon as sa,GearIcon as sb,GitBranchIcon as sc,GlobeIcon as sd,HeartIcon as se,IssueOpenedIcon as sf,LightBulbIcon as sg,LinkExternalIcon as sh,MegaphoneIcon as si,MortarBoardIcon as sj,MuteIcon as sk,OrganizationIcon as sl,PackageIcon as sm,PaperclipIcon as sn,PeopleIcon as so,PulseIcon as sp,RocketIcon as sq,RssIcon as sr,ShareAndroidIcon as ss,ShieldCheckIcon as st,ShieldIcon as su,SidebarExpandIcon as sv,SkipIcon as sw,SlidersIcon as sx,SparkleFillIcon as sy,SquareCircleIcon as sz,talkingMorphIndices as t,__spreadArray as t$,require_Set as t0,requireKeysIn as t1,requireIsArrayLikeObject as t2,requireIsPlainObject$1 as t3,require_baseMerge as t4,require_createAssigner as t5,require_apply as t6,require_copyArray as t7,require_arrayEach as t8,requireCloneDeep as t9,JWT_REFRESH_TOKEN_COOKIE_NAME as tA,LIBRARY_VIEW as tB,NAVIGATION_VIEW_HOMES as tC,RESERVATION_WARNING_TIME_MS as tD,SESSION_COOKIES as tE,SESSION_LOCAL_STORAGE_KEYS as tF,SESSION_OWNER_KEY as tG,SETTINGS_VIEW as tH,TUTOR_VIEW as tI,claimSessionState as tJ,forgetSessionState as tK,getOtelConsumeUrl as tL,getStoredToken as tM,getStoredUser as tN,isRememberableRoute as tO,isShellNeutralRoute as tP,loadRefreshTokenFromCookie as tQ,navigationStore as tR,pageConfiguration as tS,profileStore as tT,registerSessionState as tU,storeToken as tV,storeUser as tW,useNavigationStore as tX,useProfile as tY,useProfileStore as tZ,viewForRoute as t_,requireFastUri as ta,ForwardRef$1 as tb,ForwardRef as tc,memoize as td,isPropValid as te,tabbable as tf,focusable as tg,isTabbable as th,getTabIndex as ti,isFocusable as tj,index_esm as tk,requirePropTypes as tl,s$5 as tm,__assign as tn,requireReactDom as to,__extends as tp,__awaiter as tq,__rest as tr,__generator as ts,require$$0 as tt,requireObjectAssign as tu,ulid$1 as tv,AGENTS_VIEW as tw,CONTENTS_VIEW as tx,DATALAYER_VIEW as ty,JWT_DATALAYER_ISSUER as tz,timeLeft as u,katex$1 as u0,Lexical_prod as u1,LexicalUtils_prod as u2,ButtonComponent as v,webglAvailable as w,NO_SANDBOX_YET as x,Link$1 as y,CheckIcon as z};
|
|
4072
|
+
`).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)}:embedTokenDeployment(Ru)?{kind:"spec",app:Du}:{kind:"said",text:EMBED_TOKEN_NAMES_NO_DEPLOYMENT}}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.agents(),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}agents(){return(this.getAttribute("api")||coreStore.getState().configuration?.aiAgentsUrl||DEFAULT_API).replace(/\/+$/,"")}api(){return(this.getAttribute("api")||coreStore.getState().configuration?.spacerUrl||"https://prod1.datalayer.run").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{useSandboxService as $,CopyIcon as A,Box as B,CROSSFADE_SECONDS as C,Dialog$1 as D,createAllAgentRuntimesTools as E,vM as F,GOODBYE_WAVE_SECONDS as G,Heading$2 as H,IconButton as I,renderOcticon as J,useNotebookStore$1 as K,Label as L,SquareFillIcon as M,NO_WEBGL_SENTENCE as N,OUT_OF_FRAME as O,PlayIcon as P,QueryClient as Q,REST_POSE as R,SANDBOX_KIND_LABELS as S,Text$3 as T,TrashIcon as U,PlusIcon as V,CodeIcon as W,notebookStore as X,decode$4 as Y,formatTokenCount as Z,__vitePreload as _,walkClipName as a,setIfUndefined as a$,useSignalValue$1 as a0,MessageProcessor as a1,datalayerCatalog as a2,A2uiSurfaceComposed as a3,ChatBaseHeader as a4,useContributions as a5,LoopPromptPanel as a6,InputPrompt as a7,Signal as a8,o$1 as a9,PanelLayout as aA,ITranslator as aB,createToolbarFactory as aC,nullTranslator as aD,ObservableList as aE,Toolbar$1 as aF,ReactWidget as aG,some$1 as aH,useAgentsRuntimes as aI,xu as aJ,useThemeStore as aK,useSystemColorMode as aL,getThemeConfig as aM,JupyterReactTheme$1 as aN,l$1 as aO,v$1 as aP,a$1 as aQ,Kernel as aR,registerSandboxServiceManager as aS,DatalayerThemeProvider as aT,de$1 as aU,on$1 as aV,nl as aW,es as aX,H as aY,disposeServiceManager as aZ,create$g as a_,LoopOpeningNotebook as aa,LoopNotebookToolbarItem as ab,LoopNotebookToolbar as ac,LRLanguage as ad,LanguageSupport as ae,indentNodeProp as af,continuedIndent as ag,foldNodeProp as ah,styleTags as ai,tags as aj,ExternalTokenizer as ak,ifNotIn as al,completeFromList as am,LRParser as an,syntaxTree as ao,delimitedIndent as ap,foldInside as aq,getDefaultExportFromCjs as ar,MimeModel as as,standardRendererFactories as at,purify$1 as au,Token$2 as av,Menu as aw,DisposableDelegate as ax,ArrayExt as ay,Widget as az,talkAmount as b,Prec as b$,create$6 as b0,fromBase64 as b1,onChange as b2,varStorage as b3,toBase64 as b4,createUint8ArrayFromArrayBuffer as b5,offChange as b6,map$3 as b7,ContextTracker as b8,NodeWeakMap as b9,SubItem as bA,Box$1 as bB,themeConfigs as bC,LoopDocumentToolbarItem as bD,LoopDocumentToolbar as bE,LoopOpeningDocument as bF,IDLE_SANDBOX_SNAPSHOT_SIGNAL as bG,definePlugin as bH,DOCUMENT_TOOLBAR_PLUGIN_NAME as bI,contribution as bJ,KernelIndicator as bK,NOTEBOOK_TOOLBAR_PLUGIN_NAME as bL,LocalTokenGroup as bM,flatIndent as bN,parseMixed as bO,bracketMatchingHandle as bP,EditorView as bQ,EditorSelection as bR,sublanguageProp as bS,defineLanguageFacet as bT,Parser$2 as bU,NodeType as bV,NodeProp as bW,Tag as bX,NodeSet as bY,Tree as bZ,countColumn as b_,IterMode as ba,snippetCompletion as bb,Panel as bc,PromiseDelegate as bd,DEFAULT_SERVICE_URLS as be,requestDatalayerAPI as bf,API_BASE_PATHS as bg,useReactorPlatform as bh,AGENTS_PLUGIN_NAME as bi,DEFAULT_DATALAYER_AGENTSPEC as bj,useOptionalSandboxService as bk,IDLE_SANDBOX_TARGET_SIGNAL as bl,ensureVisitorAgent as bm,AGENTSPECS$1 as bn,useAgentRuntimes as bo,ActionList as bp,distExports as bq,ActionListContainerContext as br,BoxWithFallback as bs,merge$5 as bt,defaultSxProp as bu,useId as bv,reactDomExports as bw,useIsomorphicLayoutEffect$2 as bx,ChevronDownIcon as by,classes$t as bz,cameraDistance as c,cutIcon as c$,keymap as c0,Language as c1,indentUnit as c2,foldService as c3,CompletionContext as c4,EditorState as c5,languageDataProp as c6,LanguageDescription as c7,ParseContext as c8,Eu as c9,Dialog as cA,showDialog$1 as cB,SearchDocumentModel as cC,SearchDocumentView as cD,isResponsiveValue as cE,clsx as cF,commonjsRequire as cG,TextInput$1 as cH,SearchIcon as cI,SyncIcon as cJ,ToggleSwitch as cK,Flash as cL,ChevronRightIcon as cM,StyledSpinner as cN,ToolbarButton as cO,fileUploadIcon as cP,libExports$2 as cQ,WidgetTracker as cR,folderIcon as cS,linkIcon as cT,Clipboard as cU,downloadIcon as cV,copyIcon as cW,setToolbar as cX,Notification as cY,CommandRegistry as cZ,closeIcon as c_,Ke$2 as ca,_c as cb,is as cc,Ys as cd,PencilIcon as ce,SingletonLayout as cf,FocusTracker as cg,libExports$5 as ch,VDomModel as ci,TableOfContents as cj,JSONExt as ck,VDomRenderer as cl,LabIcon as cm,classes as cn,map$5 as co,showErrorMessage as cp,AttachedProperty as cq,addIcon as cr,launcherIcon as cs,MainAreaWidget as ct,find$3 as cu,TranslatorConnector as cv,Gettext as cw,DEFAULT_LANGUAGE_CODE as cx,normalizeDomain as cy,ITranslatorConnector as cz,dampedPose as d,COMPLETER_ACTIVE_CLASS as d$,pasteIcon as d0,newFolderIcon as d1,textEditorIcon as d2,markdownIcon as d3,refreshIcon as d4,editIcon as d5,fileIcon as d6,stopIcon as d7,filterIcon as d8,DisposableSet as d9,deleteLine as dA,toggleBlockComment as dB,toggleComment as dC,toggleTabFocusMode as dD,selectNextOccurrence as dE,foldable as dF,foldCode as dG,unfoldCode as dH,foldState as dI,foldEffect as dJ,unfoldEffect as dK,foldAll as dL,unfoldAll as dM,IEditorServices as dN,EditorLanguageRegistry as dO,parseMathIPython as dP,StreamLanguage as dQ,pythonBuiltin as dR,EditorThemeRegistry as dS,EditorExtensionRegistry as dT,ybinding as dU,IPositionModel as dV,historyIcon as dW,CommandToolbarButton as dX,caretLeftIcon as dY,caretRightIcon as dZ,checkIcon as d_,clearNumbering as da,getHeadingId as db,addPrefix as dc,parseHeadings as dd,filterHeadings as de,StackedLayout as df,ABCWidgetFactory as dg,DocumentWidget as dh,ITableOfContentsRegistry as di,markdownRendererFactory as dj,SkeletonBox as dk,getBrightPalette as dl,useColorPalette as dm,SkeletonText as dn,Tooltip as dp,ActionMenu as dq,buildIcon as dr,jupyterIcon as ds,SettingRegistry as dt,moveUpIcon as du,moveDownIcon as dv,Button$1 as dw,deleteIcon as dx,DOMUtils as dy,lineFormIcon as dz,proceduralPose as e,NoteIcon as e$,Debouncer as e0,SessionContextDialogs as e1,saveIcon as e2,addCommandToolbarButtonClass as e3,UseSignal as e4,CommandToolbarButtonComponent as e5,createStore$1 as e6,useStore$1 as e7,runtimesStore as e8,DATALAYER_IAM_TOKEN_KEY as e9,Platform as eA,caretDownEmptyThinIcon as eB,StringExt as eC,SegmentedControl as eD,ListUnorderedIcon as eE,GraphIcon as eF,ClockIcon as eG,DatabaseIcon as eH,FileIcon as eI,ToolsIcon as eJ,CommentDiscussionIcon as eK,AiModelIcon as eL,InfoIcon as eM,KeyIcon as eN,devtools as eO,subscribeWithSelector as eP,persist as eQ,CheckCircleFillIcon as eR,AlertIcon as eS,useAgentRuntimeMcpStatus as eT,useAgentRuntimeCodemodeStatus as eU,useAgentRuntimeContextSnapshot as eV,useAgentRuntimeFullContext as eW,useAgentRuntimeWsState as eX,useMutation as eY,useQuery as eZ,ForwardRef$2 as e_,DATALAYER_IAM_USER_KEY as ea,coreStore as eb,iamStore as ec,layoutStore as ed,useCoreStore as ee,useIAMStore as ef,useLayoutStore as eg,useRuntimesStore as eh,OutputPrompt as ei,Stdin as ej,CodeCell as ek,useJupyterLabCssLoaded as el,TelescopeIcon as em,XIcon as en,CounterLabel as eo,PauseIcon as ep,DownloadIcon as eq,SPAN_SOURCE_LABELS as er,sourceOfSpan as es,AGENT_SPAN_ATTRIBUTES as et,describeAgentSpan as eu,SpecMark as ev,parse$4 as ew,UUID as ex,EN_US as ey,errorIcon as ez,accentPose as f,messagesOfThread as f$,ServerIcon as f0,CheckCircleIcon as f1,XCircleIcon as f2,BriefcaseIcon as f3,MenuBar as f4,runIcon as f5,fastForwardIcon as f6,require_MapCache as f7,require_Symbol as f8,require_Uint8Array as f9,CodeMirrorEditor as fA,getPrefix as fB,isMarkdown as fC,findNext as fD,gotoLine as fE,consoleIcon as fF,undoIcon as fG,redoIcon as fH,selectAll as fI,Sanitizer as fJ,COMPLETER_ENABLED_CLASS as fK,MessageLoop as fL,COMPLETER_LINE_BEGINNING_CLASS as fM,Message as fN,ElementExt as fO,renderText as fP,Printing as fQ,clientExports as fR,RenderedJavaScript as fS,AgentTools as fT,useToast as fU,isInsideJupyterLab as fV,FormControl$1 as fW,MailIcon as fX,Textarea as fY,$e$5 as fZ,PRESENCE_LINES as f_,requireEq as fa,require_getAllKeys as fb,require_Stack as fc,require_getTag as fd,requireIsArray as fe,requireIsBuffer as ff,requireIsTypedArray as fg,requireIsObjectLike as fh,getAnchoredPosition as fi,reactIsExports as fj,useTheme as fk,useOnEscapePress as fl,useOnOutsideClick as fm,useResizeObserver as fn,VisuallyHidden as fo,TriangleDownIcon as fp,qe$4 as fq,sx as fr,requireSerialize as fs,requireMessages as ft,mockSocketExports as fu,ObservableMap as fv,CodeEditorWrapper as fw,CodeEditor as fx,IEditorMimeTypeService as fy,EditorSearchProvider as fz,smoothed as g,generateMessageId as g$,sessionRowOf as g0,agUiRefusal as g1,refusalBody as g2,readRunStream as g3,useAnonymousInferenceSession as g4,browserModelRequiresSignIn as g5,getAgentspecs as g6,useOptionalReactorPlatform as g7,LoopSessionAction as g8,sessionActionsFor as g9,givenFilesSentence as gA,sendInstead as gB,onSurfaceRequest as gC,setEditorOptions as gD,seedEditorChoice as gE,canOpenView as gF,useWorkspaceFullScreen as gG,targetRunsAgentInPage as gH,useOptionalTeamSelection as gI,LoopAgentBlueprint as gJ,resolveAgentspec as gK,LoopChatSuggestion as gL,agentIcon as gM,LoopFrontendTool as gN,BROWSER_CODE_TOOL as gO,agentServerOf as gP,LoopCommand as gQ,subagentsFor as gR,useChatAvailability as gS,noRuntimeSaid as gT,useVoiceSettings as gU,settledVoice as gV,useSlotComponents as gW,LoopSlots as gX,onPromptFocusRequest as gY,useVisitorToken as gZ,voiceAskedAs as g_,sessionLineageSaid as ga,sessionStateSaid as gb,Select$1 as gc,FluentEmoji as gd,useChatWords as ge,CHAT_PLUGIN_NAME as gf,INPUT_PROMPT_PLUGIN_NAME as gg,LoopChatSurface as gh,LoopChatComposer as gi,LoopChatHeader as gj,LoopChatLayout as gk,LoopChatTurn as gl,turnWritersOf as gm,LoopChatExtras as gn,computed$1 as go,useGate as gp,presenceState as gq,presenceToolOf as gr,newestIsAnswer as gs,latestSaying as gt,messageText as gu,LoopRunProps as gv,runForwardedProps as gw,dataUrlBase64 as gx,sandboxFileName as gy,writeFilesCode as gz,QueryClientProvider as h,ref$1 as h$,openThread as h0,THREAD_WORDS as h1,agentInstructions as h2,useConfig as h3,useSkills as h4,useSkillActions as h5,runtimeModelsUrl as h6,readServerCatalogue as h7,readServerDecisions as h8,offeredModels as h9,Throttler as hA,Selector$1 as hB,jupyterFaviconIcon as hC,caretDownEmptyIcon as hD,addToolbarButtonClass as hE,NotebookActions as hF,offlineBoltIcon as hG,circleIcon as hH,ObservableJSON as hI,ConflatableMessage as hJ,jumpBackIcon as hK,jumpForwardIcon as hL,MarkdownCell as hM,Cell as hN,trustedIcon as hO,notTrustedIcon as hP,runCell as hQ,InputPrompt$1 as hR,NotebookPanel as hS,setCellExecutor as hT,StaticNotebook as hU,notebookIcon as hV,NotebookSearchProvider as hW,duplicateIcon as hX,addAboveIcon as hY,addBelowIcon as hZ,children$1 as h_,AI_MODEL_CATALOGUE as ha,isChatModel as hb,ReactorSlot as hc,ComposerVoice as hd,ReactorLazy as he,ChatBase as hf,ScreenNormalIcon as hg,ScreenFullIcon as hh,SUGGESTION_CHIP_WIDTH as hi,Truncate as hj,useAnonymousSessionStore as hk,inPageAgentRefusal as hl,signal$2 as hm,LoopAgentGate as hn,agentRuntimeStore as ho,loopShapeVars as hp,NONE_EDITOR as hq,filterListIcon as hr,CommandPalette$1 as hs,h$7 as ht,LabIconStyle as hu,copyrightIcon as hv,ToolbarButtonComponent as hw,bellIcon as hx,Button$3 as hy,paletteIcon as hz,idleClipName as i,ellipsesIcon as i$,html$6 as i0,startSlotTemplate as i1,endSlotTemplate as i2,slotted as i3,elements as i4,FoundationElement as i5,isHTMLElement as i6,__decorate$1 as i7,attr as i8,observable as i9,typeRampBaseFontSize$1 as iA,typeRampBaseLineHeight$1 as iB,density$1 as iC,typeRampPlus1FontSize$1 as iD,disabledOpacity$1 as iE,disabledCursor as iF,baseHeightMultiplier$1 as iG,neutralFillRest$1 as iH,neutralFillHover$1 as iI,neutralFillActive$1 as iJ,accentForegroundRest$1 as iK,display as iL,css as iM,forcedColorsStylesheetBehavior as iN,SystemColors as iO,cssPartial as iP,DesignToken as iQ,neutralFillStealthRecipe$1 as iR,neutralFillRecipe$1 as iS,useEventListener as iT,useProperties as iU,provideJupyterDesignSystem$1 as iV,ITableOfContentsTracker as iW,tocIcon as iX,numberingIcon as iY,expandAllIcon as iZ,collapseAllIcon as i_,applyMixins as ia,StartEnd as ib,keyEnter as ic,keyArrowUp as id,keyArrowDown as ie,keyArrowRight as ig,keyArrowLeft as ih,keyEnd as ii,keyHome as ij,DOM as ik,getDisplayedNodes as il,direction$1 as im,neutralForegroundRest$1 as io,neutralFillStealthRest$1 as ip,bodyFont$1 as iq,focusVisible as ir,accentFillFocus$1 as is,focusStrokeWidth$1 as it,strokeWidth$1 as iu,controlCornerRadius$1 as iv,heightNumber$1 as iw,neutralFillStealthHover$1 as ix,neutralFillStealthActive$1 as iy,designUnit$1 as iz,jsxRuntimeExports as j,CheckboxOrRadioGroupCaption as j$,caretDownIcon as j0,circleEmptyIcon as j1,searchIcon as j2,SplitPanel as j3,TabBar as j4,jsonIcon as j5,spreadsheetIcon as j6,terminalIcon as j7,kernelIcon as j8,NotificationManager as j9,StateEffect as jA,Decoration as jB,WidgetType as jC,DEFAULT_VARIANT as jD,MarimoReactive as jE,NotebookCommandIds as jF,OutputAreaModel as jG,useJupyterReactStore as jH,newUuid as jI,NotebookPanelProvider as jJ,addNotebookCommands as jK,YArray as jL,YText as jM,newUlid as jN,k$2 as jO,loopColors as jP,sunColors as jQ,ivoryColors as jR,sandColors as jS,earthColors as jT,matrixColors as jU,lovelyColors as jV,spatialColors as jW,datalayerColors as jX,getColorPalette as jY,CheckboxOrRadioGroupValidation as jZ,CheckboxOrRadioGroupLabel as j_,SessionContext as ja,Spinner as jb,Styling as jc,SystemClipboard as jd,VisuallyHidden$1 as je,StopIcon as jf,ViewPlugin as jg,createRelativePositionFromTypeIndex as jh,createRelativePositionFromJSON as ji,tooltips as jj,Facet as jk,Annotation as jl,layer as jm,StateField as jn,showTooltip as jo,createAbsolutePositionFromRelativePosition as jp,RectangleMarker as jq,YDocument as jr,createCellModelFromSharedType as js,createCell as jt,YMap as ju,RawCellModel as jv,MarkdownCellModel as jw,CodeCellModel as jx,MINOR_VERSION as jy,MAJOR_VERSION as jz,libExports$3 as k,stringify as k$,useRenderForcingRef as k0,CheckboxOrRadioGroup$1 as k1,CheckboxGroupContext as k2,Checkbox as k3,RadioGroup$1 as k4,Radio as k5,SelectPanel as k6,TextInputWithTokens as k7,object as k8,preprocess$1 as k9,history as kA,foldGutter as kB,drawSelection as kC,dropCursor as kD,indentOnInput as kE,syntaxHighlighting as kF,bracketMatching as kG,closeBrackets as kH,autocompletion as kI,rectangularSelection as kJ,crosshairCursor as kK,highlightActiveLine as kL,highlightSelectionMatches as kM,closeBracketsKeymap as kN,defaultKeymap as kO,searchKeymap as kP,historyKeymap as kQ,foldKeymap as kR,completionKeymap as kS,defaultHighlightStyle as kT,ArrowRightIcon as kU,useOutputsStore as kV,Compartment as kW,whitespace as kX,svg$2 as kY,find as kZ,stringify$1 as k_,record$2 as ka,string$2 as kb,unknown$1 as kc,zodToToolParameters as kd,array as ke,_enum as kf,number$2 as kg,boolean$1 as kh,validateWithZod as ki,useJupyterReactStoreFromProps as kj,OutputArea as kk,createStandaloneCell as kl,BoxPanel as km,cellsStore as kn,RawCell as ko,useCellsStore as kp,getPanel as kq,activateHover as kr,showPanel as ks,combineConfig as kt,RangeSetBuilder as ku,crelt as kv,hoverTooltip as kw,lineNumbers as kx,highlightActiveLineGutter as ky,highlightSpecialChars as kz,leavingPose as l,useProvidedRefOrCreate as l$,ccount as l0,zwitch as l1,html$4 as l2,htmlVoidElements as l3,C$1 as l4,Dt$4 as l5,u$2 as l6,dt$2 as l7,Go as l8,ns as l9,_n as lA,hn$2 as lB,qc as lC,Ie$2 as lD,cs as lE,dr as lF,Jl as lG,fn$2 as lH,hn$1 as lI,pn$1 as lJ,Wo as lK,xt$2 as lL,Zs as lM,gc as lN,On as lO,na as lP,ea as lQ,ia as lR,sa as lS,decodeNamedCharacterReference as lT,requireReact as lU,StyleModule as lV,jupyterHighlightStyle as lW,useFocusZone as lX,FocusKeys as lY,useSafeTimeout as lZ,useSlots as l_,mn$1 as la,qi as lb,Pi as lc,isStream as ld,isExecuteResult as le,isDisplayData as lf,isError$1 as lg,Xo as lh,Ki as li,Yi as lj,er as lk,T as ll,v$2 as lm,S$1 as ln,C as lo,m$2 as lp,x$5 as lq,y$3 as lr,p$4 as ls,ol as lt,He$2 as lu,pn$2 as lv,Kr as lw,ur as lx,ls as ly,cn$1 as lz,modelNotLoadedSentence as m,folderFavoriteIcon as m$,useResponsiveValue as m0,ScrollableRegion as m1,viewportRanges as m2,JupyterLiteServer as m3,Router as m4,ContextMenu as m5,TabPanel as m6,DockPanel as m7,hpass as m8,AccordionPanel as m9,writeVarUint as mA,encodeStateVector as mB,writeVarUint8Array as mC,encodeStateAsUpdate as mD,readVarUint as mE,applyUpdate as mF,readVarUint8Array as mG,readVarString as mH,ObservableV2 as mI,Awareness as mJ,toUint8Array$1 as mK,length as mL,encodeAwarenessUpdate as mM,removeAwarenessStates as mN,isNode as mO,getUnixTime as mP,createEncoder as mQ,min as mR,pow as mS,createDecoder as mT,applyAwarenessUpdate as mU,UndoManager as mV,Doc$1 as mW,isCodeCellModel as mX,Drag as mY,MimeData as mZ,useConsoleStore as m_,AccordionLayout as ma,FormAssociated as mb,nullableNumberConverter as mc,ARIAGlobalStatesAndProperties as md,neutralFillInputRest$1 as me,neutralFillStrongRest$1 as mf,errorFillRest$1 as mg,neutralFillInputHover$1 as mh,neutralFillStrongHover$1 as mi,errorFillHover$1 as mj,neutralFillStrongActive$1 as mk,errorFillActive$1 as ml,errorFillFocus$1 as mm,neutralStrokeRest$1 as mn,__decorate as mo,BoxLayout as mp,VirtualDOM as mq,TextModelFactory as mr,pdfIcon as ms,pythonIcon as mt,juliaIcon as mu,rKernelIcon as mv,yamlIcon as mw,imageIcon as mx,audioIcon as my,videoIcon as mz,sandboxIsLive as n,kernelsStore as n$,filter$3 as n0,caretUpIcon as n1,Poll as n2,each as n3,Application as n4,StackedPanel as n5,tabIcon as n6,Base64ModelFactory as n7,useTerminalStore as n8,requestAPI$1 as n9,SettingManagerLess as nA,TerminalManagerLess as nB,UserManagerLess as nC,WorkspaceManagerLess as nD,cellSourceAsString as nE,consoleStore as nF,createLiteServer as nG,createServerSettings as nH,deleteCellsOperation as nI,deleteCellsTool as nJ,disableKernelReconnect as nK,disposeKernelConnections as nL,ensureJupyterAuth as nM,ensureJupyterConfig as nN,executeCodeOperation as nO,executeCodeTool as nP,formatResponse as nQ,getCookie as nR,getJupyterServerToken as nS,getJupyterServerUrl as nT,getKernelIndicatorMeta as nU,insertCellOperation as nV,insertCellTool as nW,isAnyCellRunning as nX,isReactiveVariant as nY,isServedByJupyterLab as nZ,jupyterLabTheme as n_,loadJupyterConfig as na,createLiteServiceManager as nb,jupyterReactStore as nc,ANSWER_MARKER as nd,BuilderManagerLess as ne,ContentsManagerLess as nf,DEFAULT_API_KERNEL_PREFIX_URL as ng,DEFAULT_JUPYTER_SERVER_TOKEN as nh,DEFAULT_JUPYTER_SERVER_URL as ni,DEFAULT_KERNEL_NAME as nj,DefaultExecutor as nk,EventsManagerLess as nl,ExecutionPhase as nm,HELPER_NAME as nn,JupyterLabCss as no,KERNEL_HELPER_SOURCE as np,KERNEL_STATES as nq,KERNEL_STATE_LABELS as nr,KERNEL_STATE_VISUALS as ns,KernelExecutor as nt,KernelManagerLess as nu,KernelspecManagerLess as nv,NbConvertManagerLess as nw,OperationRunner as nx,ServiceManagerLess as ny,SessionManagerLess as nz,sandboxExecuteOverHttp as o,La as o$,loadJupyterLabCss as o0,notebookToolDefinitions as o1,notebookToolOperations as o2,notebookTools as o3,outputsAsString as o4,outputsStore as o5,readAllCellsOperation as o6,readAllCellsTool as o7,readCellOperation as o8,readCellTool as o9,sn$1 as oA,vc as oB,tr as oC,Sn as oD,Zo as oE,Cu as oF,Bs as oG,Me as oH,yn as oI,Se as oJ,Cn as oK,fn as oL,qr as oM,Ia as oN,zs as oO,gn$2 as oP,or as oQ,Jr as oR,sn$2 as oS,ln$1 as oT,rn$1 as oU,nn$2 as oV,Vr as oW,nu as oX,du as oY,Va as oZ,au as o_,refreshJupyterLabPortalTheme as oa,renderKernelStateGlyph as ob,resetJupyterConfig as oc,runCellOperation as od,runCellTool as oe,setJupyterServerToken as of,setJupyterServerUrl as og,sleep as oh,syncJupyterLabPortalTheme as oi,terminalStore as oj,toKernelState as ok,updateCellOperation as ol,updateCellTool as om,useJupyterReactColormode as on,useKernelsStore as oo,ThemeProvider as op,Overlay$1 as oq,Fi as or,Zl as os,bu as ot,Nu as ou,Wl as ov,Fr as ow,Li as ox,Vc as oy,Fo as oz,prefersReducedMotion as p,qe$2 as p$,Is as p0,Dl as p1,h$1 as p2,Sn$1 as p3,Nn$1 as p4,ce$1 as p5,Tu as p6,vu as p7,ae$1 as p8,xt$3 as p9,yn$1 as pA,It$1 as pB,Tt as pC,l$2 as pD,a$2 as pE,d$2 as pF,s$2 as pG,Ue$2 as pH,dn$2 as pI,$e$2 as pJ,un$1 as pK,Bi as pL,It as pM,en$2 as pN,_$1 as pO,te$2 as pP,le$2 as pQ,on$2 as pR,$t$3 as pS,mn$2 as pT,Xe$2 as pU,gr as pV,Ge$2 as pW,_r as pX,Ve$2 as pY,je$1 as pZ,Ye$1 as p_,St$3 as pa,Pc as pb,Lc as pc,Ic as pd,mt$3 as pe,rs as pf,an$1 as pg,Je$2 as ph,Ft$1 as pi,Os as pj,Mt$1 as pk,gt as pl,Co as pm,Tn as pn,Dt as po,So as pp,vn as pq,kn$1 as pr,xl as ps,oa as pt,Cn$1 as pu,et as pv,xn as pw,St as px,Rt as py,xt as pz,displayUrl as q,x$4 as q$,Yt as q0,Ya as q1,Pe$2 as q2,Ja as q3,tu as q4,zl as q5,Fl as q6,Ma as q7,ja as q8,Hl as q9,Re as qA,Kc as qB,Wt$1 as qC,z$2 as qD,ac as qE,On$1 as qF,Ht$1 as qG,Le$2 as qH,zr as qI,Bt$1 as qJ,Ll as qK,ui as qL,ec as qM,nc as qN,zt$1 as qO,Ir as qP,i$1 as qQ,uu as qR,Aa as qS,Wa as qT,Ul as qU,ql as qV,dc as qW,be as qX,ke as qY,ft as qZ,pi as q_,Ba as qa,Bl as qb,Pr as qc,Pe as qd,uo as qe,mu as qf,iu as qg,ku as qh,Mo as qi,Rl as qj,wu as qk,Fn as ql,lc as qm,$s as qn,he as qo,Fe as qp,Ut$1 as qq,We as qr,Fs as qs,Al as qt,No as qu,bo as qv,as as qw,_t as qx,eu as qy,fc as qz,reactExports as r,BookIcon as r$,z as r0,O$1 as r1,r$2 as r2,t$2 as r3,Es as r4,_s as r5,vt$2 as r6,n$2 as r7,b$1 as r8,nn$1 as r9,Pt$1 as rA,s$1 as rB,f$3 as rC,P$1 as rD,fe$1 as rE,PaperAirplaneIcon as rF,bn$2 as rG,TableIcon as rH,q as rI,ChecklistIcon as rJ,fn$1 as rK,GrabberIcon as rL,vo as rM,yo as rN,wo as rO,mo as rP,j$1 as rQ,r$3 as rR,$2AODx$react as rS,jt$1 as rT,oe$1 as rU,ie$2 as rV,RowsIcon as rW,x$2 as rX,AlertFillIcon as rY,BeakerIcon as rZ,BellIcon as r_,r$1 as ra,g$1 as rb,Tt$2 as rc,ys as rd,e$1 as re,vl as rf,u$1 as rg,b$3 as rh,z$1 as ri,zi as rj,Ji as rk,ko as rl,To as rm,Ze$2 as rn,Qe$2 as ro,Mn$1 as rp,wn$1 as rq,En$1 as rr,xo as rs,vi as rt,Ql as ru,ut$2 as rv,Gl as rw,ReactDOM as rx,M$2 as ry,PersonIcon as rz,stateMotion as s,require_isIterateeCall as s$,BroadcastIcon as s0,BrowserIcon as s1,BugIcon as s2,CircleSlashIcon as s3,CodeReviewIcon as s4,CpuIcon as s5,CreditCardIcon as s6,DependabotIcon as s7,DeviceDesktopIcon as s8,DeviceMobileIcon as s9,SunIcon as sA,TagIcon as sB,TasklistIcon as sC,ThumbsdownIcon as sD,ThumbsupIcon as sE,UnmuteIcon as sF,UploadIcon as sG,XCircleFillIcon as sH,ZapIcon as sI,requireFastDeepEqual as sJ,getAugmentedNamespace as sK,requireParseSrcset as sL,requirePostcss as sM,requireIsPlainObject as sN,requireEscapeStringRegexp as sO,requireIsArguments as sP,require_arrayPush as sQ,require_baseGetTag as sR,requireIsObject as sS,requireKeys as sT,require_isIndex as sU,requireIsLength as sV,requireIdentity as sW,require_baseFor as sX,requireIsArrayLike as sY,require_baseUnary as sZ,require_baseRest as s_,FoldIcon as sa,GearIcon as sb,GitBranchIcon as sc,GlobeIcon as sd,HeartIcon as se,IssueOpenedIcon as sf,LightBulbIcon as sg,LinkExternalIcon as sh,MegaphoneIcon as si,MortarBoardIcon as sj,MuteIcon as sk,OrganizationIcon as sl,PackageIcon as sm,PaperclipIcon as sn,PeopleIcon as so,PulseIcon as sp,RocketIcon as sq,RssIcon as sr,ShareAndroidIcon as ss,ShieldCheckIcon as st,ShieldIcon as su,SidebarExpandIcon as sv,SkipIcon as sw,SlidersIcon as sx,SparkleFillIcon as sy,SquareCircleIcon as sz,talkingMorphIndices as t,viewForRoute as t$,require_Set as t0,requireKeysIn as t1,requireIsArrayLikeObject as t2,requireIsPlainObject$1 as t3,require_baseMerge as t4,require_createAssigner as t5,require_apply as t6,require_copyArray as t7,require_arrayEach as t8,requireCloneDeep as t9,JWT_REFRESH_TOKEN_COOKIE_NAME as tA,LIBRARY_VIEW as tB,NAVIGATION_VIEW_HOMES as tC,RESERVATION_WARNING_TIME_MS as tD,SESSION_COOKIES as tE,SESSION_LOCAL_STORAGE_KEYS as tF,SESSION_OWNER_KEY as tG,SETTINGS_VIEW as tH,TUTOR_VIEW as tI,claimSessionState as tJ,forgetSessionState as tK,getOtelConsumeUrl as tL,getStoredToken as tM,getStoredUser as tN,isHostedAppRoute as tO,isRememberableRoute as tP,isShellNeutralRoute as tQ,loadRefreshTokenFromCookie as tR,navigationStore as tS,pageConfiguration as tT,profileStore as tU,registerSessionState as tV,storeToken as tW,storeUser as tX,useNavigationStore as tY,useProfile as tZ,useProfileStore as t_,requireFastUri as ta,ForwardRef$1 as tb,ForwardRef as tc,memoize as td,isPropValid as te,tabbable as tf,focusable as tg,isTabbable as th,getTabIndex as ti,isFocusable as tj,index_esm as tk,requirePropTypes as tl,s$5 as tm,__assign as tn,requireReactDom as to,__extends as tp,__awaiter as tq,__rest as tr,__generator as ts,require$$0 as tt,requireObjectAssign as tu,ulid$1 as tv,AGENTS_VIEW as tw,CONTENTS_VIEW as tx,DATALAYER_VIEW as ty,JWT_DATALAYER_ISSUER as tz,timeLeft as u,__spreadArray as u0,katex$1 as u1,Lexical_prod as u2,LexicalUtils_prod as u3,ButtonComponent as v,webglAvailable as w,NO_SANDBOX_YET as x,Link$1 as y,CheckIcon as z};
|