@datalayer/agent-runtimes 1.5.86 → 1.5.87

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist-embed/chunks/{DeckComponent-D4X-rpbh.js → DeckComponent-etBrFG87.js} +1 -1
  2. package/dist-embed/chunks/{DocumentView-Aird-zRf.js → DocumentView-LE7AJ2BO.js} +1 -1
  3. package/dist-embed/chunks/{EphemeralDocument-qnhIdhNh.js → EphemeralDocument-YiGgJGkL.js} +1 -1
  4. package/dist-embed/chunks/{ExcalidrawComponent-C33gsDzG.js → ExcalidrawComponent-C5J8Uqqj.js} +1 -1
  5. package/dist-embed/chunks/{ExcalidrawModal-DHCo94OE.js → ExcalidrawModal-D3cbhMgF.js} +1 -1
  6. package/dist-embed/chunks/{JupyterLexicalExtension-Cb2zt9Ki.js → JupyterLexicalExtension-BipHQ8U3.js} +7 -7
  7. package/dist-embed/chunks/{YouTubePlugin-C0a_9VKl.js → YouTubePlugin-BewlFg9c.js} +1 -1
  8. package/dist-embed/chunks/{ar-SA-G6X2FPQ2-DS3Xmdel.js → ar-SA-G6X2FPQ2-BgdfqrVp.js} +1 -1
  9. package/dist-embed/chunks/{az-AZ-76LH7QW2-DIApsK5M.js → az-AZ-76LH7QW2-xUMz4Jqu.js} +1 -1
  10. package/dist-embed/chunks/{bg-BG-XCXSNQG7-X-aS4Onm.js → bg-BG-XCXSNQG7-UR5Ld32v.js} +1 -1
  11. package/dist-embed/chunks/{bn-BD-2XOGV67Q-1YCe_Jnl.js → bn-BD-2XOGV67Q-CCNH7olK.js} +1 -1
  12. package/dist-embed/chunks/{ca-ES-6MX7JW3Y-D26sHSba.js → ca-ES-6MX7JW3Y-DaZb-gMN.js} +1 -1
  13. package/dist-embed/chunks/{cs-CZ-2BRQDIVT-B5pRYPPF.js → cs-CZ-2BRQDIVT-OaROtN46.js} +1 -1
  14. package/dist-embed/chunks/{da-DK-5WZEPLOC-BfajxBtH.js → da-DK-5WZEPLOC-DrcoMVce.js} +1 -1
  15. package/dist-embed/chunks/{de-DE-XR44H4JA-BovBXD5H.js → de-DE-XR44H4JA-b2_lYxS1.js} +1 -1
  16. package/dist-embed/chunks/{el-GR-BZB4AONW-rLXnfS2l.js → el-GR-BZB4AONW-BOT3RaFd.js} +1 -1
  17. package/dist-embed/chunks/{es-ES-U4NZUMDT-Do4MvuPW.js → es-ES-U4NZUMDT-BVlxd_yM.js} +1 -1
  18. package/dist-embed/chunks/{eu-ES-A7QVB2H4-CldbgpdZ.js → eu-ES-A7QVB2H4-BScAWOoO.js} +1 -1
  19. package/dist-embed/chunks/{fa-IR-HGAKTJCU-C988cp8F.js → fa-IR-HGAKTJCU-Kxnh8bHZ.js} +1 -1
  20. package/dist-embed/chunks/{fi-FI-Z5N7JZ37-BYmFVIh7.js → fi-FI-Z5N7JZ37-BOmDZi5v.js} +1 -1
  21. package/dist-embed/chunks/{fr-FR-RHASNOE6-D2Tarz3u.js → fr-FR-RHASNOE6-GOPhqKT4.js} +1 -1
  22. package/dist-embed/chunks/{gl-ES-HMX3MZ6V-BLuuMSHB.js → gl-ES-HMX3MZ6V-BRZS4fho.js} +1 -1
  23. package/dist-embed/chunks/{he-IL-6SHJWFNN-CyDIOeVd.js → he-IL-6SHJWFNN-MQEVUj2T.js} +1 -1
  24. package/dist-embed/chunks/{hi-IN-IWLTKZ5I-DKCduSTz.js → hi-IN-IWLTKZ5I-D_puNbt2.js} +1 -1
  25. package/dist-embed/chunks/{hu-HU-A5ZG7DT2-CFEUsNFV.js → hu-HU-A5ZG7DT2-VTn7BLHk.js} +1 -1
  26. package/dist-embed/chunks/{id-ID-SAP4L64H-DJgKxRp8.js → id-ID-SAP4L64H-DDpkcMxl.js} +1 -1
  27. package/dist-embed/chunks/{index-CaAB7eph.js → index-BnyTIBRs.js} +1 -1
  28. package/dist-embed/chunks/{index-BvYhxJ42.js → index-D4E_ai6G.js} +1 -1
  29. package/dist-embed/chunks/{it-IT-JPQ66NNP-CB1iVsAn.js → it-IT-JPQ66NNP-Dmm1oVBi.js} +1 -1
  30. package/dist-embed/chunks/{ja-JP-DBVTYXUO-BMEokiIe.js → ja-JP-DBVTYXUO-c8yMMjUO.js} +1 -1
  31. package/dist-embed/chunks/{kaa-6HZHGXH3-NDSx8vED.js → kaa-6HZHGXH3-Cr7KlyI3.js} +1 -1
  32. package/dist-embed/chunks/{kab-KAB-ZGHBKWFO-CDD0AUe8.js → kab-KAB-ZGHBKWFO-C5lvSze2.js} +1 -1
  33. package/dist-embed/chunks/{kk-KZ-P5N5QNE5-DiW940Xv.js → kk-KZ-P5N5QNE5-BWzl0srY.js} +1 -1
  34. package/dist-embed/chunks/{km-KH-HSX4SM5Z-D1yNJSuC.js → km-KH-HSX4SM5Z-D0hsReza.js} +1 -1
  35. package/dist-embed/chunks/{ko-KR-MTYHY66A-gxN7WKqI.js → ko-KR-MTYHY66A-BG6oRC2d.js} +1 -1
  36. package/dist-embed/chunks/{ku-TR-6OUDTVRD-AGx6lASh.js → ku-TR-6OUDTVRD-BcZeKYN4.js} +1 -1
  37. package/dist-embed/chunks/{lt-LT-XHIRWOB4-7aG3WRZ7.js → lt-LT-XHIRWOB4-CDMAwSRa.js} +1 -1
  38. package/dist-embed/chunks/{lv-LV-5QDEKY6T-kYU1Z9N2.js → lv-LV-5QDEKY6T-D2MZFbM-.js} +1 -1
  39. package/dist-embed/chunks/{mr-IN-CRQNXWMA-E1I_f_B2.js → mr-IN-CRQNXWMA-C4tnFlhM.js} +1 -1
  40. package/dist-embed/chunks/{my-MM-5M5IBNSE-BLvme-se.js → my-MM-5M5IBNSE-BeA-YSi-.js} +1 -1
  41. package/dist-embed/chunks/{nb-NO-T6EIAALU-CQe3vLx-.js → nb-NO-T6EIAALU-PoKJfg4d.js} +1 -1
  42. package/dist-embed/chunks/{nl-NL-IS3SIHDZ-DQ5lObK-.js → nl-NL-IS3SIHDZ-Cf4_wadm.js} +1 -1
  43. package/dist-embed/chunks/{nn-NO-6E72VCQL-JwOO_c6b.js → nn-NO-6E72VCQL-xgmyjeCA.js} +1 -1
  44. package/dist-embed/chunks/{oc-FR-POXYY2M6-OYZJk3Hj.js → oc-FR-POXYY2M6-CdWNnVCw.js} +1 -1
  45. package/dist-embed/chunks/{pa-IN-N4M65BXN-B7p6nOzS.js → pa-IN-N4M65BXN-QYWCqzud.js} +1 -1
  46. package/dist-embed/chunks/{percentages-BXMCSKIN-Cz9igCrb.js → percentages-BXMCSKIN-azlLrVPY.js} +3 -3
  47. package/dist-embed/chunks/{pl-PL-T2D74RX3-DiIfEp3O.js → pl-PL-T2D74RX3-CR9S6Ibc.js} +1 -1
  48. package/dist-embed/chunks/{pt-BR-5N22H2LF-7rqxomNz.js → pt-BR-5N22H2LF-BdXbK3ya.js} +1 -1
  49. package/dist-embed/chunks/{pt-PT-UZXXM6DQ-DE-uZxHk.js → pt-PT-UZXXM6DQ-2XA1j-L3.js} +1 -1
  50. package/dist-embed/chunks/{ro-RO-JPDTUUEW-BlMk-egr.js → ro-RO-JPDTUUEW-BtXn8ZEx.js} +1 -1
  51. package/dist-embed/chunks/{ru-RU-B4JR7IUQ-caVTslk_.js → ru-RU-B4JR7IUQ-CQX4iIyB.js} +1 -1
  52. package/dist-embed/chunks/{si-LK-N5RQ5JYF-DT4Sk0wC.js → si-LK-N5RQ5JYF-HKjZkrpb.js} +1 -1
  53. package/dist-embed/chunks/{sk-SK-C5VTKIMK-DS8_VUwQ.js → sk-SK-C5VTKIMK-D0qjylR3.js} +1 -1
  54. package/dist-embed/chunks/{sl-SI-NN7IZMDC-Dm37QL2T.js → sl-SI-NN7IZMDC-vxztaOUj.js} +1 -1
  55. package/dist-embed/chunks/{subset-shared.chunk-ByorZVMF.js → subset-shared.chunk-DEWjD_XG.js} +1 -1
  56. package/dist-embed/chunks/{subset-worker.chunk-CDbohCL0.js → subset-worker.chunk-DWTibNnY.js} +1 -1
  57. package/dist-embed/chunks/{sv-SE-XGPEYMSR-Ds2_OJfr.js → sv-SE-XGPEYMSR-N-SacX3h.js} +1 -1
  58. package/dist-embed/chunks/{ta-IN-2NMHFXQM-DalALtL3.js → ta-IN-2NMHFXQM-9GMEN3M3.js} +1 -1
  59. package/dist-embed/chunks/{th-TH-HPSO5L25-Db3wq-Mt.js → th-TH-HPSO5L25-CeESdLid.js} +1 -1
  60. package/dist-embed/chunks/{tr-TR-DEFEU3FU-BwZ2BWFh.js → tr-TR-DEFEU3FU-BjBigRhJ.js} +1 -1
  61. package/dist-embed/chunks/transformers.web-Br6X7w0a.js +42 -0
  62. package/dist-embed/chunks/{uk-UA-QMV73CPH-CvvKxEh4.js → uk-UA-QMV73CPH-v4nMobEN.js} +1 -1
  63. package/dist-embed/chunks/{vi-VN-M7AON7JQ-CWecJG5X.js → vi-VN-M7AON7JQ-D5thvMrO.js} +1 -1
  64. package/dist-embed/chunks/{zh-CN-LNUGB5OW-Bt8FQMA4.js → zh-CN-LNUGB5OW-Cn3ae1JT.js} +1 -1
  65. package/dist-embed/chunks/{zh-HK-E62DVLB3-D-aO7Cxy.js → zh-HK-E62DVLB3-OlNuka00.js} +1 -1
  66. package/dist-embed/chunks/{zh-TW-RAJ6MFWO-DhGr0I8R.js → zh-TW-RAJ6MFWO-DAwaB-Vu.js} +1 -1
  67. package/dist-embed/datalayer-app-main.js +6 -6
  68. package/lib/components/cards/ToolApprovalCard.js +5 -2
  69. package/lib/runtimes/variants.d.ts +10 -8
  70. package/lib/runtimes/variants.js +14 -9
  71. package/lib/specs/harnesses.js +11 -3
  72. package/lib/types/agentspecs.d.ts +2 -0
  73. package/package.json +1 -1
  74. package/scripts/codegen/generate_harnesses.py +2 -0
  75. package/dist-embed/chunks/transformers.web-CLaqP_Vm.js +0 -42
@@ -2324,7 +2324,7 @@ Execution failed: ${Du}`,diff:Pu}}}catch(Pu){const Ou=Pu instanceof Error?Pu.mes
2324
2324
  `)}function decode$4(Au,lo){return decodeFromLines(Au.split(`
2325
2325
  `))}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$4(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.
2326
2326
 
2327
- 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 Zu;return zu?Zu=Hu:Uu?Zu=Vu:ju.route.Component?Zu=reactExports.createElement(ju.route.Component,null):ju.route.element?Zu=ju.route.element:Zu=Bu,reactExports.createElement(RenderedRoute,{match:ju,routeContext:{outlet:Bu,matches:Gu,isDataRoute:Ru!=null},children:Zu})};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 Zu=Pu.routes[Wu.route.id];!Zu||!Zu.hasLoader||(!Bu.some(Ju=>Ju.route.id===Wu.route.id)&&Wu.route.id in Du&&Ou[Wu.route.id]?.shouldRevalidate||Zu.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),Zu=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),vd=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":!Zu&&$u==="render"?"true":void 0});return td&&!Zu?reactExports.createElement(reactExports.Fragment,null,vd,reactExports.createElement(PrefetchPageLinks,{page:Yu})):vd});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,Zu=zu&&zu.navigation&&zu.navigation.location?zu.navigation.location.pathname:null;$u||(Wu=Wu.toLowerCase(),Zu=Zu?Zu.toLowerCase():null,Gu=Gu.toLowerCase()),Zu&&Hu&&(Zu=stripBasename(Zu,Hu)||Zu);const Ju=Gu!=="/"&&Gu.endsWith("/")?Gu.length-1:Gu.length;let Yu=Wu===Gu||!Iu&&Wu.startsWith(Gu)&&Wu.charAt(Ju)==="/",Xu=Zu!=null&&(Zu===Gu||!Iu&&Zu.startsWith(Gu)&&Zu.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",Zu=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":!Zu&&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":AGENTIFY_SPACE_PAGE.test($u)||AGENTIFY_ACCOUNT_PAGE.test($u)?"agentify":"home"}const AGENTIFY_SPACE_PAGE=/^\/(?!docs\/)[^/]+\/[^/]+\/(?:decks|courses|course|lessons|exercises|assignments)(?:\/|$)/,AGENTIFY_ACCOUNT_PAGE=/^\/(?!docs\/)[^/]+\/courses$/;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-BUmmTwes.js").then(Au=>Au.r),[],import.meta.url).then(Au=>({default:Au.JupyterReactTheme})));let NotificationApi;isInsideJupyterLab()&&__vitePreload(()=>import("./chunks/index-BtwU5-oj.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(`
2327
+ 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 Zu;return zu?Zu=Hu:Uu?Zu=Vu:ju.route.Component?Zu=reactExports.createElement(ju.route.Component,null):ju.route.element?Zu=ju.route.element:Zu=Bu,reactExports.createElement(RenderedRoute,{match:ju,routeContext:{outlet:Bu,matches:Gu,isDataRoute:Ru!=null},children:Zu})};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 Zu=Pu.routes[Wu.route.id];!Zu||!Zu.hasLoader||(!Bu.some(Ju=>Ju.route.id===Wu.route.id)&&Wu.route.id in Du&&Ou[Wu.route.id]?.shouldRevalidate||Zu.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),Zu=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),vd=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":!Zu&&$u==="render"?"true":void 0});return td&&!Zu?reactExports.createElement(reactExports.Fragment,null,vd,reactExports.createElement(PrefetchPageLinks,{page:Yu})):vd});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,Zu=zu&&zu.navigation&&zu.navigation.location?zu.navigation.location.pathname:null;$u||(Wu=Wu.toLowerCase(),Zu=Zu?Zu.toLowerCase():null,Gu=Gu.toLowerCase()),Zu&&Hu&&(Zu=stripBasename(Zu,Hu)||Zu);const Ju=Gu!=="/"&&Gu.endsWith("/")?Gu.length-1:Gu.length;let Yu=Wu===Gu||!Iu&&Wu.startsWith(Gu)&&Wu.charAt(Ju)==="/",Xu=Zu!=null&&(Zu===Gu||!Iu&&Zu.startsWith(Gu)&&Zu.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",Zu=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":!Zu&&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":AGENTIFY_SPACE_PAGE.test($u)||AGENTIFY_ACCOUNT_PAGE.test($u)?"agentify":"home"}const AGENTIFY_SPACE_PAGE=/^\/(?!docs\/)[^/]+\/[^/]+\/(?:decks|spreadsheets|courses|course|lessons|exercises|assignments)(?:\/|$)/,AGENTIFY_ACCOUNT_PAGE=/^\/(?!docs\/)[^/]+\/courses$/;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-BUmmTwes.js").then(Au=>Au.r),[],import.meta.url).then(Au=>({default:Au.JupyterReactTheme})));let NotificationApi;isInsideJupyterLab()&&__vitePreload(()=>import("./chunks/index-BtwU5-oj.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(`
2328
2328
  `).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),Zu=isPublicPath(Ru.pathname||"");!(Ru.pathname===Wu||Ru.pathname.endsWith("/login"))&&!Zu&&(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 Zu=Gu===void 0?{type:Ou||"anonymous"}:typeof Gu=="string"?{type:Gu}:Gu;return Mu===void 0?(Bu?.send(Zu,Ru()),Wu):(Bu?.send({...Zu,type:`${Mu}/${Zu.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(`
2329
2329
  [zustand devtools middleware] Unsupported __setState action format.
2330
2330
  When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
@@ -2419,7 +2419,7 @@ ${lo}:`]}}function getResponseMetadata2({id:Au,model:lo,created:$u}){return{id:A
2419
2419
  `)?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(`
2420
2420
  `);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 withToolSummaries(Au,lo=[]){const $u=lo.filter(Pu=>Pu.summaryOf);if($u.length===0)return Au;let Ru=!1;const Iu=Au.map(Pu=>{if(!isToolCallMessage(Pu))return Pu;const Ou=Pu,Mu=$u.find(Lu=>Lu.name===Ou.toolName);if(!Mu?.summaryOf||Ou.result===void 0)return Pu;const Du=Mu.summaryOf(Ou.args,Ou.result)?.trim();return!Du||Du===Ou.summary?Pu:(Ru=!0,{...Ou,summary:Du})});return Ru?Iu:Au}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-J-pyZzZ8.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-DghIPf1A.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 Zu=JSON.parse(Wu.data);if(Zu&&Zu.action==="interrupt")return;const Ju=typeof Zu?.variant=="string"?Zu.variant:"";Pu({available:Ju!=="unavailable"&&Ju!=="error",sandbox_running:!!Zu?.sandbox_running,is_executing:!!Zu?.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.5",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"?Function.prototype.call.bind(Uint8Array.prototype.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$3=(Au,lo=!1)=>lo?_mkUriSafe(_encode(Au)):_encode(Au),encodeURI$1=Au=>encode$3(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$3(this,lo)}),Au("toBase64URI",function(){return encode$3(this,!0)}),Au("toBase64URL",function(){return encode$3(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$3,encode:encode$3,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,bd,wd){_d[bd]=wd.value},Pu=typeof Symbol=="function"?Symbol:{},Ou=Pu.iterator||"@@iterator",Mu=Pu.asyncIterator||"@@asyncIterator",Du=Pu.toStringTag||"@@toStringTag";function Lu(_d,bd,wd){return Object.defineProperty(_d,bd,{value:wd,enumerable:!0,configurable:!0,writable:!0}),_d[bd]}try{Lu({},"")}catch{Lu=function(wd,Ad,gd){return wd[Ad]=gd}}function Bu(_d,bd,wd,Ad){var gd=bd&&bd.prototype instanceof Gu?bd:Gu,dd=Object.create(gd.prototype),yd=new vd(Ad||[]);return Iu(dd,"_invoke",{value:od(_d,wd,yd)}),dd}function ju(_d,bd,wd){try{return{type:"normal",arg:_d.call(bd,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 Zu(){}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=Zu.prototype=Gu.prototype=Object.create(Ju);function td(_d){["next","throw","return"].forEach(function(bd){Lu(_d,bd,function(wd){return this._invoke(bd,wd)})})}function nd(_d,bd){function wd(gd,dd,yd,ld){var ud=ju(_d[gd],_d,dd);if(ud.type!=="throw"){var hd=ud.arg,md=hd.value;return md&&_typeof$6(md)=="object"&&Ru.call(md,"__await")?bd.resolve(md.__await).then(function(Ed){wd("next",Ed,yd,ld)},function(Ed){wd("throw",Ed,yd,ld)}):bd.resolve(md).then(function(Ed){hd.value=Ed,yd(hd)},function(Ed){return wd("throw",Ed,yd,ld)})}ld(ud.arg)}var Ad;Iu(this,"_invoke",{value:function(dd,yd){function ld(){return new bd(function(ud,hd){wd(dd,yd,ud,hd)})}return Ad=Ad?Ad.then(ld,ld):ld()}})}function od(_d,bd,wd){var Ad=Fu;return function(gd,dd){if(Ad===Uu)throw Error("Generator is already running");if(Ad===Hu){if(gd==="throw")throw dd;return{value:Au,done:!0}}for(wd.method=gd,wd.arg=dd;;){var yd=wd.delegate;if(yd){var ld=sd(yd,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,bd,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,bd){var wd=bd.method,Ad=_d.iterator[wd];if(Ad===Au)return bd.delegate=null,wd==="throw"&&_d.iterator.return&&(bd.method="return",bd.arg=Au,sd(_d,bd),bd.method==="throw")||wd!=="return"&&(bd.method="throw",bd.arg=new TypeError("The iterator does not provide a '"+wd+"' method")),Vu;var gd=ju(Ad,_d.iterator,bd.arg);if(gd.type==="throw")return bd.method="throw",bd.arg=gd.arg,bd.delegate=null,Vu;var dd=gd.arg;return dd?dd.done?(bd[_d.resultName]=dd.value,bd.next=_d.nextLoc,bd.method!=="return"&&(bd.method="next",bd.arg=Au),bd.delegate=null,Vu):dd:(bd.method="throw",bd.arg=new TypeError("iterator result is not an object"),bd.delegate=null,Vu)}function ad(_d){var bd={tryLoc:_d[0]};1 in _d&&(bd.catchLoc=_d[1]),2 in _d&&(bd.finallyLoc=_d[2],bd.afterLoc=_d[3]),this.tryEntries.push(bd)}function pd(_d){var bd=_d.completion||{};bd.type="normal",delete bd.arg,_d.completion=bd}function vd(_d){this.tryEntries=[{tryLoc:"root"}],_d.forEach(ad,this),this.reset(!0)}function Sd(_d){if(_d||_d===""){var bd=_d[Ou];if(bd)return bd.call(_d);if(typeof _d.next=="function")return _d;if(!isNaN(_d.length)){var wd=-1,Ad=function gd(){for(;++wd<_d.length;)if(Ru.call(_d,wd))return gd.value=_d[wd],gd.done=!1,gd;return gd.value=Au,gd.done=!0,gd};return Ad.next=Ad}}throw new TypeError(_typeof$6(_d)+" is not iterable")}return Wu.prototype=Zu,Iu(ed,"constructor",{value:Zu,configurable:!0}),Iu(Zu,"constructor",{value:Wu,configurable:!0}),Wu.displayName=Lu(Zu,Du,"GeneratorFunction"),lo.isGeneratorFunction=function(_d){var bd=typeof _d=="function"&&_d.constructor;return!!bd&&(bd===Wu||(bd.displayName||bd.name)==="GeneratorFunction")},lo.mark=function(_d){return Object.setPrototypeOf?Object.setPrototypeOf(_d,Zu):(_d.__proto__=Zu,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,bd,wd,Ad,gd){gd===void 0&&(gd=Promise);var dd=new nd(Bu(_d,bd,wd,Ad),gd);return lo.isGeneratorFunction(bd)?dd:dd.next().then(function(yd){return yd.done?yd.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 bd=Object(_d),wd=[];for(var Ad in bd)wd.push(Ad);return wd.reverse(),function gd(){for(;wd.length;){var dd=wd.pop();if(dd in bd)return gd.value=dd,gd.done=!1,gd}return gd.done=!0,gd}},lo.values=Sd,vd.prototype={constructor:vd,reset:function(bd){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),!bd)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 bd=this.tryEntries[0].completion;if(bd.type==="throw")throw bd.arg;return this.rval},dispatchException:function(bd){if(this.done)throw bd;var wd=this;function Ad(hd,md){return yd.type="throw",yd.arg=bd,wd.next=hd,md&&(wd.method="next",wd.arg=Au),!!md}for(var gd=this.tryEntries.length-1;gd>=0;--gd){var dd=this.tryEntries[gd],yd=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(bd,wd){for(var Ad=this.tryEntries.length-1;Ad>=0;--Ad){var gd=this.tryEntries[Ad];if(gd.tryLoc<=this.prev&&Ru.call(gd,"finallyLoc")&&this.prev<gd.finallyLoc){var dd=gd;break}}dd&&(bd==="break"||bd==="continue")&&dd.tryLoc<=wd&&wd<=dd.finallyLoc&&(dd=null);var yd=dd?dd.completion:{};return yd.type=bd,yd.arg=wd,dd?(this.method="next",this.next=dd.finallyLoc,Vu):this.complete(yd)},complete:function(bd,wd){if(bd.type==="throw")throw bd.arg;return bd.type==="break"||bd.type==="continue"?this.next=bd.arg:bd.type==="return"?(this.rval=this.arg=bd.arg,this.method="return",this.next="end"):bd.type==="normal"&&wd&&(this.next=wd),Vu},finish:function(bd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ad=this.tryEntries[wd];if(Ad.finallyLoc===bd)return this.complete(Ad.completion,Ad.afterLoc),pd(Ad),Vu}},catch:function(bd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ad=this.tryEntries[wd];if(Ad.tryLoc===bd){var gd=Ad.completion;if(gd.type==="throw"){var dd=gd.arg;pd(Ad)}return dd}}throw Error("illegal catch attempt")},delegateYield:function(bd,wd,Ad){return this.delegate={iterator:Sd(bd),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.
2421
2421
  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.
2422
- 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,bd,wd){_d[bd]=wd.value},Pu=typeof Symbol=="function"?Symbol:{},Ou=Pu.iterator||"@@iterator",Mu=Pu.asyncIterator||"@@asyncIterator",Du=Pu.toStringTag||"@@toStringTag";function Lu(_d,bd,wd){return Object.defineProperty(_d,bd,{value:wd,enumerable:!0,configurable:!0,writable:!0}),_d[bd]}try{Lu({},"")}catch{Lu=function(wd,Ad,gd){return wd[Ad]=gd}}function Bu(_d,bd,wd,Ad){var gd=bd&&bd.prototype instanceof Gu?bd:Gu,dd=Object.create(gd.prototype),yd=new vd(Ad||[]);return Iu(dd,"_invoke",{value:od(_d,wd,yd)}),dd}function ju(_d,bd,wd){try{return{type:"normal",arg:_d.call(bd,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 Zu(){}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=Zu.prototype=Gu.prototype=Object.create(Ju);function td(_d){["next","throw","return"].forEach(function(bd){Lu(_d,bd,function(wd){return this._invoke(bd,wd)})})}function nd(_d,bd){function wd(gd,dd,yd,ld){var ud=ju(_d[gd],_d,dd);if(ud.type!=="throw"){var hd=ud.arg,md=hd.value;return md&&_typeof$3(md)=="object"&&Ru.call(md,"__await")?bd.resolve(md.__await).then(function(Ed){wd("next",Ed,yd,ld)},function(Ed){wd("throw",Ed,yd,ld)}):bd.resolve(md).then(function(Ed){hd.value=Ed,yd(hd)},function(Ed){return wd("throw",Ed,yd,ld)})}ld(ud.arg)}var Ad;Iu(this,"_invoke",{value:function(dd,yd){function ld(){return new bd(function(ud,hd){wd(dd,yd,ud,hd)})}return Ad=Ad?Ad.then(ld,ld):ld()}})}function od(_d,bd,wd){var Ad=Fu;return function(gd,dd){if(Ad===Uu)throw Error("Generator is already running");if(Ad===Hu){if(gd==="throw")throw dd;return{value:Au,done:!0}}for(wd.method=gd,wd.arg=dd;;){var yd=wd.delegate;if(yd){var ld=sd(yd,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,bd,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,bd){var wd=bd.method,Ad=_d.iterator[wd];if(Ad===Au)return bd.delegate=null,wd==="throw"&&_d.iterator.return&&(bd.method="return",bd.arg=Au,sd(_d,bd),bd.method==="throw")||wd!=="return"&&(bd.method="throw",bd.arg=new TypeError("The iterator does not provide a '"+wd+"' method")),Vu;var gd=ju(Ad,_d.iterator,bd.arg);if(gd.type==="throw")return bd.method="throw",bd.arg=gd.arg,bd.delegate=null,Vu;var dd=gd.arg;return dd?dd.done?(bd[_d.resultName]=dd.value,bd.next=_d.nextLoc,bd.method!=="return"&&(bd.method="next",bd.arg=Au),bd.delegate=null,Vu):dd:(bd.method="throw",bd.arg=new TypeError("iterator result is not an object"),bd.delegate=null,Vu)}function ad(_d){var bd={tryLoc:_d[0]};1 in _d&&(bd.catchLoc=_d[1]),2 in _d&&(bd.finallyLoc=_d[2],bd.afterLoc=_d[3]),this.tryEntries.push(bd)}function pd(_d){var bd=_d.completion||{};bd.type="normal",delete bd.arg,_d.completion=bd}function vd(_d){this.tryEntries=[{tryLoc:"root"}],_d.forEach(ad,this),this.reset(!0)}function Sd(_d){if(_d||_d===""){var bd=_d[Ou];if(bd)return bd.call(_d);if(typeof _d.next=="function")return _d;if(!isNaN(_d.length)){var wd=-1,Ad=function gd(){for(;++wd<_d.length;)if(Ru.call(_d,wd))return gd.value=_d[wd],gd.done=!1,gd;return gd.value=Au,gd.done=!0,gd};return Ad.next=Ad}}throw new TypeError(_typeof$3(_d)+" is not iterable")}return Wu.prototype=Zu,Iu(ed,"constructor",{value:Zu,configurable:!0}),Iu(Zu,"constructor",{value:Wu,configurable:!0}),Wu.displayName=Lu(Zu,Du,"GeneratorFunction"),lo.isGeneratorFunction=function(_d){var bd=typeof _d=="function"&&_d.constructor;return!!bd&&(bd===Wu||(bd.displayName||bd.name)==="GeneratorFunction")},lo.mark=function(_d){return Object.setPrototypeOf?Object.setPrototypeOf(_d,Zu):(_d.__proto__=Zu,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,bd,wd,Ad,gd){gd===void 0&&(gd=Promise);var dd=new nd(Bu(_d,bd,wd,Ad),gd);return lo.isGeneratorFunction(bd)?dd:dd.next().then(function(yd){return yd.done?yd.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 bd=Object(_d),wd=[];for(var Ad in bd)wd.push(Ad);return wd.reverse(),function gd(){for(;wd.length;){var dd=wd.pop();if(dd in bd)return gd.value=dd,gd.done=!1,gd}return gd.done=!0,gd}},lo.values=Sd,vd.prototype={constructor:vd,reset:function(bd){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),!bd)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 bd=this.tryEntries[0].completion;if(bd.type==="throw")throw bd.arg;return this.rval},dispatchException:function(bd){if(this.done)throw bd;var wd=this;function Ad(hd,md){return yd.type="throw",yd.arg=bd,wd.next=hd,md&&(wd.method="next",wd.arg=Au),!!md}for(var gd=this.tryEntries.length-1;gd>=0;--gd){var dd=this.tryEntries[gd],yd=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(bd,wd){for(var Ad=this.tryEntries.length-1;Ad>=0;--Ad){var gd=this.tryEntries[Ad];if(gd.tryLoc<=this.prev&&Ru.call(gd,"finallyLoc")&&this.prev<gd.finallyLoc){var dd=gd;break}}dd&&(bd==="break"||bd==="continue")&&dd.tryLoc<=wd&&wd<=dd.finallyLoc&&(dd=null);var yd=dd?dd.completion:{};return yd.type=bd,yd.arg=wd,dd?(this.method="next",this.next=dd.finallyLoc,Vu):this.complete(yd)},complete:function(bd,wd){if(bd.type==="throw")throw bd.arg;return bd.type==="break"||bd.type==="continue"?this.next=bd.arg:bd.type==="return"?(this.rval=this.arg=bd.arg,this.method="return",this.next="end"):bd.type==="normal"&&wd&&(this.next=wd),Vu},finish:function(bd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ad=this.tryEntries[wd];if(Ad.finallyLoc===bd)return this.complete(Ad.completion,Ad.afterLoc),pd(Ad),Vu}},catch:function(bd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ad=this.tryEntries[wd];if(Ad.tryLoc===bd){var gd=Ad.completion;if(gd.type==="throw"){var dd=gd.arg;pd(Ad)}return dd}}throw Error("illegal catch attempt")},delegateYield:function(bd,wd,Ad){return this.delegate={iterator:Sd(bd),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),Zu=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,vd]=reactExports.useState(!1),Sd=reactExports.useRef(!1),_d=reactExports.useRef(null),bd=reactExports.useRef(!1),wd=reactExports.useRef($u);wd.current=$u;const Ad=!!lo&&locationOf(ju)==="cloud",gd=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]),yd=reactExports.useCallback(async()=>{try{const{iamStore:$d,coreStore:Id}=await __vitePreload(async()=>{const{iamStore:th,coreStore:Eh}=await import("./chunks/index-J-pyZzZ8.js");return{iamStore:th,coreStore:Eh}},[],import.meta.url),Vd=$d.getState().token||"",Wd=Id.getState().configuration?.aiAgentsUrl||"";return{token:Vd,aiAgentsUrl:Wd,runtimesUrl:dd}}catch{return{token:"",aiAgentsUrl:"",runtimesUrl:""}}},[dd]);reactExports.useEffect(()=>{!Lu||!gd||(Uu?[Uu.runtimeName,Uu.environmentName,Uu.jupyterBaseUrl||"",Uu.kernelId||""].join(":"):null)===gd||(Sd.current=!1,Zu(Lu))},[Lu,gd,Uu,Zu]);const ld=reactExports.useCallback(async $d=>{if(runsInBrowser(ju))return BROWSER_AGENT_CONNECTION;if(Ad){ed("launching"),nd(null);try{const Vd=(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:Vd,...Bu,runtimesUrl:dd});return ed("ready"),Md}catch(Id){const Vd=Id instanceof Error?Id.message:String(Id);throw nd(Vd),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(bd.current)throw new Error("Agent creation already in progress");bd.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 Vd={...DEFAULT_AGENT_CONFIG,...Id,...$u,...$d,name:$d?.name||$u?.name||(Ad&&lo?lo:Uu?.runtimeName)};return await Ju(Vd)}catch(Id){const Vd=Id instanceof Error?Id.message:String(Id);throw Ad&&(nd(Vd),ed("error")),Id}finally{bd.current=!1,sd(!1)}},[lo,$u,Pu,Ad,Uu,Ju]),hd=reactExports.useCallback(async()=>{const $d=Uu?.agentId,Id=Uu?.agentBaseUrl,Vd=$d&&Id?agentDeletionUrl(Id,$d,Fu):void 0;if(Vd)try{const{token:Md}=await yd();await fetch(Vd,{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,yd,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){vd(!0);return}let $d=!1;return(async()=>{try{const{token:Vd,runtimesUrl:Md}=await yd();if(!Vd)return;const{listRuntimes:Wd}=await __vitePreload(async()=>{const{listRuntimes:ih}=await import("./chunks/runtimes-D0qXa51n.js");return{listRuntimes:ih}},[],import.meta.url),ah=((await Wd(Vd,Md)).runtimes||[]).filter(ih=>ih.environment?.name!=="ai-agents-env"?!1:lo?ih.agent_spec_id===lo:!0).slice().sort((ih,Mh)=>{const qd=Number(ih.started_at||0);return Number(Mh.started_at||0)-qd})[0];if($d||!ah?.runtime_name||!ah?.ingress)return;Zu({runtimeName:ah.runtime_name,environmentName:ah.environment.name,jupyterBaseUrl:ah.ingress}),Sd.current=!1;const yh=ah,vh=typeof yh.status=="string"?yh.status.toLowerCase():"",Jd=RUNTIME_STATUS_MAP[vh]??"running",eh=Jd==="paused"?"paused":Jd==="resuming"||Jd==="resumed"?"resumed":"running";ed(eh==="paused"?"paused":eh==="resumed"?"resumed":"ready")}catch(Vd){console.warn("[useAgents] Failed to find existing runtime:",Vd)}finally{$d||vd(!0)}})(),()=>{$d=!0}},[Ad,Uu,Iu,Xu,yd,lo,Bu,Zu]),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 md=runsInBrowser(ju),Ed=md?"ready":Ad?Xu:Hu,Td=md?null:Ad&&td||Vu,Rd=md?!0:Ad?(Xu==="ready"||Xu==="resumed")&&!!Uu?.isReady:Hu==="ready"&&!!Uu?.isReady,jd=Uu?.endpoint||null,Cd=Uu?.serviceManager||null;return{runtime:Uu,status:Ed,isLaunching:Gu,launchRuntime:ld,connectToRuntime:Zu,disconnect:Yu,endpoint:jd,serviceManager:Cd,createAgent:ud,teardown:hd,isCreating:od,isReady:Rd,error:Td,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$f()(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 Zu=agentRuntimeStore.getState();if(Wu.type==="agent.snapshot"){Zu.applySnapshot(Wu.payload);return}if(Wu.type==="agent.subagent"){Zu.appendSubagentEvent(Wu.payload);return}if(Wu.type==="agent.compaction"){Zu.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:!0,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.
2422
+ 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,bd,wd){_d[bd]=wd.value},Pu=typeof Symbol=="function"?Symbol:{},Ou=Pu.iterator||"@@iterator",Mu=Pu.asyncIterator||"@@asyncIterator",Du=Pu.toStringTag||"@@toStringTag";function Lu(_d,bd,wd){return Object.defineProperty(_d,bd,{value:wd,enumerable:!0,configurable:!0,writable:!0}),_d[bd]}try{Lu({},"")}catch{Lu=function(wd,Ad,gd){return wd[Ad]=gd}}function Bu(_d,bd,wd,Ad){var gd=bd&&bd.prototype instanceof Gu?bd:Gu,dd=Object.create(gd.prototype),yd=new vd(Ad||[]);return Iu(dd,"_invoke",{value:od(_d,wd,yd)}),dd}function ju(_d,bd,wd){try{return{type:"normal",arg:_d.call(bd,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 Zu(){}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=Zu.prototype=Gu.prototype=Object.create(Ju);function td(_d){["next","throw","return"].forEach(function(bd){Lu(_d,bd,function(wd){return this._invoke(bd,wd)})})}function nd(_d,bd){function wd(gd,dd,yd,ld){var ud=ju(_d[gd],_d,dd);if(ud.type!=="throw"){var hd=ud.arg,md=hd.value;return md&&_typeof$3(md)=="object"&&Ru.call(md,"__await")?bd.resolve(md.__await).then(function(Ed){wd("next",Ed,yd,ld)},function(Ed){wd("throw",Ed,yd,ld)}):bd.resolve(md).then(function(Ed){hd.value=Ed,yd(hd)},function(Ed){return wd("throw",Ed,yd,ld)})}ld(ud.arg)}var Ad;Iu(this,"_invoke",{value:function(dd,yd){function ld(){return new bd(function(ud,hd){wd(dd,yd,ud,hd)})}return Ad=Ad?Ad.then(ld,ld):ld()}})}function od(_d,bd,wd){var Ad=Fu;return function(gd,dd){if(Ad===Uu)throw Error("Generator is already running");if(Ad===Hu){if(gd==="throw")throw dd;return{value:Au,done:!0}}for(wd.method=gd,wd.arg=dd;;){var yd=wd.delegate;if(yd){var ld=sd(yd,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,bd,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,bd){var wd=bd.method,Ad=_d.iterator[wd];if(Ad===Au)return bd.delegate=null,wd==="throw"&&_d.iterator.return&&(bd.method="return",bd.arg=Au,sd(_d,bd),bd.method==="throw")||wd!=="return"&&(bd.method="throw",bd.arg=new TypeError("The iterator does not provide a '"+wd+"' method")),Vu;var gd=ju(Ad,_d.iterator,bd.arg);if(gd.type==="throw")return bd.method="throw",bd.arg=gd.arg,bd.delegate=null,Vu;var dd=gd.arg;return dd?dd.done?(bd[_d.resultName]=dd.value,bd.next=_d.nextLoc,bd.method!=="return"&&(bd.method="next",bd.arg=Au),bd.delegate=null,Vu):dd:(bd.method="throw",bd.arg=new TypeError("iterator result is not an object"),bd.delegate=null,Vu)}function ad(_d){var bd={tryLoc:_d[0]};1 in _d&&(bd.catchLoc=_d[1]),2 in _d&&(bd.finallyLoc=_d[2],bd.afterLoc=_d[3]),this.tryEntries.push(bd)}function pd(_d){var bd=_d.completion||{};bd.type="normal",delete bd.arg,_d.completion=bd}function vd(_d){this.tryEntries=[{tryLoc:"root"}],_d.forEach(ad,this),this.reset(!0)}function Sd(_d){if(_d||_d===""){var bd=_d[Ou];if(bd)return bd.call(_d);if(typeof _d.next=="function")return _d;if(!isNaN(_d.length)){var wd=-1,Ad=function gd(){for(;++wd<_d.length;)if(Ru.call(_d,wd))return gd.value=_d[wd],gd.done=!1,gd;return gd.value=Au,gd.done=!0,gd};return Ad.next=Ad}}throw new TypeError(_typeof$3(_d)+" is not iterable")}return Wu.prototype=Zu,Iu(ed,"constructor",{value:Zu,configurable:!0}),Iu(Zu,"constructor",{value:Wu,configurable:!0}),Wu.displayName=Lu(Zu,Du,"GeneratorFunction"),lo.isGeneratorFunction=function(_d){var bd=typeof _d=="function"&&_d.constructor;return!!bd&&(bd===Wu||(bd.displayName||bd.name)==="GeneratorFunction")},lo.mark=function(_d){return Object.setPrototypeOf?Object.setPrototypeOf(_d,Zu):(_d.__proto__=Zu,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,bd,wd,Ad,gd){gd===void 0&&(gd=Promise);var dd=new nd(Bu(_d,bd,wd,Ad),gd);return lo.isGeneratorFunction(bd)?dd:dd.next().then(function(yd){return yd.done?yd.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 bd=Object(_d),wd=[];for(var Ad in bd)wd.push(Ad);return wd.reverse(),function gd(){for(;wd.length;){var dd=wd.pop();if(dd in bd)return gd.value=dd,gd.done=!1,gd}return gd.done=!0,gd}},lo.values=Sd,vd.prototype={constructor:vd,reset:function(bd){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),!bd)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 bd=this.tryEntries[0].completion;if(bd.type==="throw")throw bd.arg;return this.rval},dispatchException:function(bd){if(this.done)throw bd;var wd=this;function Ad(hd,md){return yd.type="throw",yd.arg=bd,wd.next=hd,md&&(wd.method="next",wd.arg=Au),!!md}for(var gd=this.tryEntries.length-1;gd>=0;--gd){var dd=this.tryEntries[gd],yd=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(bd,wd){for(var Ad=this.tryEntries.length-1;Ad>=0;--Ad){var gd=this.tryEntries[Ad];if(gd.tryLoc<=this.prev&&Ru.call(gd,"finallyLoc")&&this.prev<gd.finallyLoc){var dd=gd;break}}dd&&(bd==="break"||bd==="continue")&&dd.tryLoc<=wd&&wd<=dd.finallyLoc&&(dd=null);var yd=dd?dd.completion:{};return yd.type=bd,yd.arg=wd,dd?(this.method="next",this.next=dd.finallyLoc,Vu):this.complete(yd)},complete:function(bd,wd){if(bd.type==="throw")throw bd.arg;return bd.type==="break"||bd.type==="continue"?this.next=bd.arg:bd.type==="return"?(this.rval=this.arg=bd.arg,this.method="return",this.next="end"):bd.type==="normal"&&wd&&(this.next=wd),Vu},finish:function(bd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ad=this.tryEntries[wd];if(Ad.finallyLoc===bd)return this.complete(Ad.completion,Ad.afterLoc),pd(Ad),Vu}},catch:function(bd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ad=this.tryEntries[wd];if(Ad.tryLoc===bd){var gd=Ad.completion;if(gd.type==="throw"){var dd=gd.arg;pd(Ad)}return dd}}throw Error("illegal catch attempt")},delegateYield:function(bd,wd,Ad){return this.delegate={iterator:Sd(bd),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,unavailable_because:"",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,unavailable_because:"",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,unavailable_because:"",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:!1,unavailable_because:"the catalogue offers four harnesses today — Claude Code, Codex, OpenCode and Gemini CLI (28 October 2026); fast-agent is a framework served over ACP, not a coding agent, its adapter is a Python tool the runtime image does not carry, and it has not been drilled on Datalayer.",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,unavailable_because:"",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:!1,unavailable_because:"the catalogue offers four harnesses today — Claude Code, Codex, OpenCode and Gemini CLI (28 October 2026); goose is a binary of its own release, not an npm adapter, the runtime image does not carry it, and it has not been drilled on Datalayer.",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,unavailable_because:"",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:!1,unavailable_because:"the catalogue offers four harnesses today — Claude Code, Codex, OpenCode and Gemini CLI (28 October 2026); OpenHands' adapter is a Python tool the runtime image does not carry, and it has not been drilled on Datalayer.",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),Zu=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,vd]=reactExports.useState(!1),Sd=reactExports.useRef(!1),_d=reactExports.useRef(null),bd=reactExports.useRef(!1),wd=reactExports.useRef($u);wd.current=$u;const Ad=!!lo&&locationOf(ju)==="cloud",gd=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]),yd=reactExports.useCallback(async()=>{try{const{iamStore:$d,coreStore:Id}=await __vitePreload(async()=>{const{iamStore:th,coreStore:Eh}=await import("./chunks/index-J-pyZzZ8.js");return{iamStore:th,coreStore:Eh}},[],import.meta.url),Vd=$d.getState().token||"",Wd=Id.getState().configuration?.aiAgentsUrl||"";return{token:Vd,aiAgentsUrl:Wd,runtimesUrl:dd}}catch{return{token:"",aiAgentsUrl:"",runtimesUrl:""}}},[dd]);reactExports.useEffect(()=>{!Lu||!gd||(Uu?[Uu.runtimeName,Uu.environmentName,Uu.jupyterBaseUrl||"",Uu.kernelId||""].join(":"):null)===gd||(Sd.current=!1,Zu(Lu))},[Lu,gd,Uu,Zu]);const ld=reactExports.useCallback(async $d=>{if(runsInBrowser(ju))return BROWSER_AGENT_CONNECTION;if(Ad){ed("launching"),nd(null);try{const Vd=(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:Vd,...Bu,runtimesUrl:dd});return ed("ready"),Md}catch(Id){const Vd=Id instanceof Error?Id.message:String(Id);throw nd(Vd),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(bd.current)throw new Error("Agent creation already in progress");bd.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 Vd={...DEFAULT_AGENT_CONFIG,...Id,...$u,...$d,name:$d?.name||$u?.name||(Ad&&lo?lo:Uu?.runtimeName)};return await Ju(Vd)}catch(Id){const Vd=Id instanceof Error?Id.message:String(Id);throw Ad&&(nd(Vd),ed("error")),Id}finally{bd.current=!1,sd(!1)}},[lo,$u,Pu,Ad,Uu,Ju]),hd=reactExports.useCallback(async()=>{const $d=Uu?.agentId,Id=Uu?.agentBaseUrl,Vd=$d&&Id?agentDeletionUrl(Id,$d,Fu):void 0;if(Vd)try{const{token:Md}=await yd();await fetch(Vd,{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,yd,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){vd(!0);return}let $d=!1;return(async()=>{try{const{token:Vd,runtimesUrl:Md}=await yd();if(!Vd)return;const{listRuntimes:Wd}=await __vitePreload(async()=>{const{listRuntimes:ih}=await import("./chunks/runtimes-D0qXa51n.js");return{listRuntimes:ih}},[],import.meta.url),ah=((await Wd(Vd,Md)).runtimes||[]).filter(ih=>ih.environment?.name!=="ai-agents-env"?!1:lo?ih.agent_spec_id===lo:!0).slice().sort((ih,Mh)=>{const qd=Number(ih.started_at||0);return Number(Mh.started_at||0)-qd})[0];if($d||!ah?.runtime_name||!ah?.ingress)return;Zu({runtimeName:ah.runtime_name,environmentName:ah.environment.name,jupyterBaseUrl:ah.ingress}),Sd.current=!1;const yh=ah,vh=typeof yh.status=="string"?yh.status.toLowerCase():"",Jd=RUNTIME_STATUS_MAP[vh]??"running",eh=Jd==="paused"?"paused":Jd==="resuming"||Jd==="resumed"?"resumed":"running";ed(eh==="paused"?"paused":eh==="resumed"?"resumed":"ready")}catch(Vd){console.warn("[useAgents] Failed to find existing runtime:",Vd)}finally{$d||vd(!0)}})(),()=>{$d=!0}},[Ad,Uu,Iu,Xu,yd,lo,Bu,Zu]),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 md=runsInBrowser(ju),Ed=md?"ready":Ad?Xu:Hu,Td=md?null:Ad&&td||Vu,Rd=md?!0:Ad?(Xu==="ready"||Xu==="resumed")&&!!Uu?.isReady:Hu==="ready"&&!!Uu?.isReady,jd=Uu?.endpoint||null,Cd=Uu?.serviceManager||null;return{runtime:Uu,status:Ed,isLaunching:Gu,launchRuntime:ld,connectToRuntime:Zu,disconnect:Yu,endpoint:jd,serviceManager:Cd,createAgent:ud,teardown:hd,isCreating:od,isReady:Rd,error:Td,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$f()(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 Zu=agentRuntimeStore.getState();if(Wu.type==="agent.snapshot"){Zu.applySnapshot(Wu.payload);return}if(Wu.type==="agent.subagent"){Zu.appendSubagentEvent(Wu.payload);return}if(Wu.type==="agent.compaction"){Zu.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:!0,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.
2423
2423
  `,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.
2424
2424
  `,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.
2425
2425
  `,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.
@@ -3906,7 +3906,7 @@ ${Pu}\`\`\``}),lo}function ChatMarkdown({text:Au,density:lo="comfortable"}){retu
3906
3906
  50% { opacity: 0.4; }
3907
3907
  }
3908
3908
  `;function useInjectKeyframes(){reactExports.useEffect(()=>{const Au="__skills-pulse-keyframes__";if(document.getElementById(Au))return;const lo=document.createElement("style");lo.id=Au,lo.textContent=SKILLS_PULSE_KEYFRAMES,document.head.appendChild(lo)},[])}function deriveAggregate(Au,lo,$u){return Au<=0?"none":$u?"loading":lo>0?"active":"inactive"}function buildTooltip(Au,lo,$u){return Au==="loading"?`Skills loading (${$u}/${lo} enabled)`:Au==="active"?`Skills active (${$u}/${lo} enabled)`:`Skills available (${$u}/${lo} enabled)`}function SkillsStatusIndicator({skillsCount:Au,enabledCount:lo,loading:$u=!1}){useInjectKeyframes();const Ru=reactExports.useMemo(()=>deriveAggregate(Au,lo,$u),[Au,lo,$u]),Iu=reactExports.useMemo(()=>buildTooltip(Ru,Au,lo),[Ru,Au,lo]);return Ru==="none"?null:jsxRuntimeExports.jsx(Tooltip,{text:Iu,direction:"n",children:jsxRuntimeExports.jsx("button",{type:"button","aria-label":Iu,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",background:"none",cursor:"default",lineHeight:0},children:jsxRuntimeExports.jsx(Box,{as:"span",display:"inline-block",width:12,height:12,borderRadius:"50%",bg:SKILLS_STATUS_COLORS[Ru],flexShrink:0,animation:Ru==="loading"?"skills-pulse 1.5s ease-in-out infinite":void 0,reducedMotion:{animation:"none"}})})})}const ContextPie=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/ContextPie-Bz1HpYZy.js"),[],import.meta.url).then(Au=>({default:Au.ContextPie}))),EMPTY_TOOL_MAP=new Map,EMPTY_ID_SET=new Set;function InputPrompt({input:Au,setInput:lo,isLoading:$u,kernelStatus:Ru,connectionConfirmed:Iu,placeholder:Pu,typingSuggestions:Ou,autoFocus:Mu,focusTrigger:Du,padding:Lu,placement:Bu,floatingAnchor:ju="bottom",draggable:Fu=!1,container:zu,footerExtras:Uu,interim:Hu=!1,leadingPanel:Vu,trailingPanel:Gu,onSend:Wu,onStop:Zu,disableInputPrompt:Ju=!1,promptVariant:Yu,mentionableAgents:Xu,promptCommands:ed,promptHistory:td,headerContent:nd,showAgentsMenu:od=!1,showInlineAgentsMenu:sd=!0,agents:ad=[],selectedAgentId:pd,onSelectAgent:vd,showTokenUsage:Sd,showContextRing:_d=!1,agentUsage:bd,showModelSelector:wd,showToolsMenu:Ad,showSkillsMenu:gd,showSuggestionsMenu:dd=!0,suggestions:yd,codemodeEnabled:ld,onToggleCodemode:ud,isA2AProtocol:hd,hasConfigData:md,hasSkillsData:Ed,configLoading:Td=!1,models:Rd=[],decisions:jd,selectedModel:Cd="",onModelSelect:$d=()=>{},availableTools:Id=[],availableFrontendTools:Vd=[],mcpServers:Md=[],enabledMcpTools:Wd=EMPTY_TOOL_MAP,enabledMcpToolCount:rh=0,onToggleMcpTool:th=()=>{},onToggleAllMcpServerTools:Eh=()=>{},approvedMcpTools:ah=EMPTY_TOOL_MAP,onToggleMcpToolApproval:yh=()=>{},skills:vh=[],skillsLoading:Jd=!1,enabledSkills:eh=EMPTY_ID_SET,onToggleSkill:ih=()=>{},onToggleAllSkills:Mh=()=>{},approvedSkills:qd=EMPTY_ID_SET,onToggleSkillApproval:zd=()=>{},apiBase:Pd,authToken:Od,mcpStatusData:Gd}){const Dd=useChatWords(),Kd=Ru==="busy",Xd=od&&ad.length>0,hh=Xd&&sd,_h=wd,Sh=Ad,Zh=gd,Nd=yd??(Ou??[]).map(Ph=>({title:Ph,message:Ph})),xd=dd&&Nd.length>0,[Hd,Zd]=reactExports.useState(0),ph=Xd||_h||Sh||Zh,wh=!!Uu,kh=ph||(Ad&&!md&&Td||gd&&!Ed&&Jd)||wh,$h=!!(bd&&!bd.error),xh=jsxRuntimeExports.jsxs(Box,{"data-voice-interim":Hu?"":void 0,sx:Hu?{'& [contenteditable="true"], & textarea':{color:"fg.muted",fontStyle:"italic"}}:void 0,children:[Vu,jsxRuntimeExports.jsx(InputPromptBase,{variant:Yu,mentionableAgents:Xu,promptCommands:ed,promptHistory:td,headerContent:hh||nd?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[hh?jsxRuntimeExports.jsx(InlineAgentsMenu,{agents:ad,selectedAgentId:pd,onSelectAgent:vd}):null,nd]}):void 0,placeholder:Pu||Dd.typeMessage,typingSuggestions:Ou,isLoading:$u,isKernelBusy:Kd,disabled:Ju,readOnly:!Iu,onSend:Wu,onStop:Zu,autoFocus:Mu,focusTrigger:(Du??0)+Hd,padding:Lu,value:Au,onChange:lo,footerRightContent:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(McpStatusIndicator,{apiBase:Pd,authToken:Od,data:Gd}),jsxRuntimeExports.jsx(SkillsStatusIndicator,{skillsCount:vh.length,enabledCount:eh.size,loading:Jd})]})}),jsxRuntimeExports.jsx(BelowPromptHeader,{disabled:Ju,stacks:Sd?[{id:"context-usage",layout:"block",minHeight:$h&&bd?28:0,px:0,py:0,content:$h&&bd?jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(ContextPie,{agentUsage:bd,padding:Lu,showContextRing:_d})}):null}]:[]}),jsxRuntimeExports.jsx(BelowPromptFooter,{disabled:Ju,stacks:kh?[{id:"session-controls",px:Lu,clearsAssistant:!0,py:.5,minHeight:36,bordered:!0,subtle:!0,content:jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:ph||wh||xd?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Xd&&jsxRuntimeExports.jsx(AgentsMenu,{agents:ad,selectedAgentId:pd,onSelectAgent:vd}),Sh&&jsxRuntimeExports.jsx(ToolsMenu,{codemodeEnabled:ld,onToggleCodemode:ud,mcpServers:Md,enabledMcpTools:Wd,enabledMcpToolCount:rh,onToggleMcpTool:th,onToggleAllMcpServerTools:Eh,approvedMcpTools:ah,onToggleMcpToolApproval:yh,availableTools:Id,availableFrontendTools:Vd}),Zh&&jsxRuntimeExports.jsx(SkillsMenu,{skills:vh,skillsLoading:Jd,enabledSkills:eh,onToggleSkill:ih,onToggleAllSkills:Mh,approvedSkills:qd,onToggleSkillApproval:zd}),_h&&jsxRuntimeExports.jsx(ModelSelector,{models:Rd,decisions:jd,selectedModel:Cd,onModelSelect:$d,isA2AProtocol:hd}),xd&&jsxRuntimeExports.jsx(SuggestionsMenu,{suggestions:Nd,onPick:Ph=>{lo(Ph),Zd(rp=>rp+1)}}),wh&&jsxRuntimeExports.jsx(Box,{marginLeft:"auto",display:"inline-flex",alignItems:"center",gap:1,children:Uu})]}):jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:"Loading controls..."})})}]:[]}),Gu]}),Kh=(Bu??(Fu?"floating":"docked"))==="floating"?jsxRuntimeExports.jsx(FloatingCard,{anchor:ju,children:xh}):xh;return zu?reactDomExports.createPortal(Kh,zu):Kh}class PinRefused extends Error{}function pinOf(Au,lo){const $u=Au.replace(/\/+$/,"")+"/";if(!lo.startsWith($u))return;const[Ru,Iu,...Pu]=lo.slice($u.length).split("?")[0].split("/"),Ou=Pu.join("/"),Mu=SPEECH_MODEL_CATALOGUE[Iu];return Mu?.provider===Ru?Mu.files.find(Du=>Du.path===Ou):void 0}async function sha256Hex(Au){const lo=await crypto.subtle.digest("SHA-256",Au);return Array.from(new Uint8Array(lo)).map($u=>$u.toString(16).padStart(2,"0")).join("")}function headerOf(Au,lo){if(!Au)return null;if(typeof Headers<"u"&&Au instanceof Headers)return Au.get(lo);const Ru=(Array.isArray(Au)?Au:Object.entries(Au)).find(([Iu])=>Iu.toLowerCase()===lo);return Ru?Ru[1]:null}function pinnedFetch(Au,lo=($u,Ru)=>fetch($u,Ru)){const $u=Au.replace(/\/+$/,"")+"/";return async(Ru,Iu)=>{const Pu=typeof Ru=="string"?Ru:Ru.toString();if(!Pu.startsWith($u))throw new PinRefused(`Voice reads its models from ${$u} only, not ${Pu}.`);const Ou=await lo(Pu,Iu),Mu=pinOf(Au,Pu);if(!Mu||!Ou.ok)return Ou;const Du=headerOf(Iu?.headers,"range");if(Du!==null){if(Du.replace(/\s+/g,"")!=="bytes=0-0")throw new PinRefused(`${Pu.slice($u.length)} is read whole and checked, not in part (${Du}).`);return Ou}const Lu=await Ou.arrayBuffer();if(Lu.byteLength!==Mu.size||await sha256Hex(Lu)!==Mu.sha256)throw new PinRefused(`${Pu.slice($u.length)} is not the file the voice catalogue pins: refused.`);return new Response(Lu,{status:Ou.status,headers:Ou.headers})}}async function pinnedBytes(Au,lo,$u){const Ru=await pinnedFetch(Au,$u)(lo);if(!Ru.ok)throw new PinRefused(`${lo} could not be read (${Ru.status}).`);return Ru.arrayBuffer()}function modelFolder(Au){const lo=SPEECH_MODEL_CATALOGUE[Au];if(!lo)throw new PinRefused(`The voice catalogue has no speech model ${Au}.`);return`${lo.provider}/${lo.id}`}function downloadSize(Au){return(SPEECH_MODEL_CATALOGUE[Au]?.files??[]).reduce((lo,$u)=>lo+$u.size,0)}const HEARING_RATE=16e3;class MicrophoneRefused extends Error{}function levelOf(Au,lo){Au.getFloatTimeDomainData(lo);let $u=0;for(let Ru=0;Ru<lo.length;Ru+=1)$u+=lo[Ru]*lo[Ru];return Math.min(1,Math.sqrt($u/lo.length)*5)}function resample(Au,lo,$u=HEARING_RATE){if(lo===$u)return Au;const Ru=Math.round(Au.length*$u/lo),Iu=new Float32Array(Ru),Pu=lo/$u;for(let Ou=0;Ou<Ru;Ou+=1){const Mu=Ou*Pu,Du=Math.floor(Mu),Lu=Math.min(Du+1,Au.length-1);Iu[Ou]=Au[Du]+(Au[Lu]-Au[Du])*(Mu-Du)}return Iu}async function openMicrophone(Au){if(!navigator.mediaDevices?.getUserMedia)throw new MicrophoneRefused("This browser gives no page a microphone.");let lo;try{lo=await navigator.mediaDevices.getUserMedia({audio:{...Au?{deviceId:{exact:Au}}:{},channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})}catch(ju){const Fu=ju?.name;throw new MicrophoneRefused(Fu==="NotAllowedError"?"The microphone was not allowed: allow it for this page to talk, or type.":Fu==="NotFoundError"?"No microphone was found on this device.":"The microphone could not be opened.")}const $u=new AudioContext,Ru=$u.createMediaStreamSource(lo),Iu=$u.createAnalyser();Iu.fftSize=1024,Ru.connect(Iu);const Pu=$u.createScriptProcessor(4096,1,1),Ou=[];Pu.onaudioprocess=ju=>{Ou.push(new Float32Array(ju.inputBuffer.getChannelData(0)))},Ru.connect(Pu);const Mu=$u.createGain();Mu.gain.value=0,Pu.connect(Mu),Mu.connect($u.destination);const Du=new Float32Array(Iu.fftSize),Lu=()=>{const ju=Ou.reduce((Uu,Hu)=>Uu+Hu.length,0),Fu=new Float32Array(ju);let zu=0;for(const Uu of Ou)Fu.set(Uu,zu),zu+=Uu.length;return resample(Fu,$u.sampleRate)},Bu=()=>{Pu.onaudioprocess=null,lo.getTracks().forEach(ju=>ju.stop()),$u.close()};return{level:()=>levelOf(Iu,Du),peek:Lu,stop:async()=>{const ju=Lu();return Bu(),Ou.length=0,ju},cancel:()=>{Bu(),Ou.length=0}}}class NotHeardHere extends Error{}function runtimeFiles(Au,lo){return`${Au.replace(/\/+$/,"")}/onnxruntime-web/${lo}/`}function joinSegments(Au){const lo=new Float32Array(Au.reduce((Ru,Iu)=>Ru+Iu.length,0));let $u=0;for(const Ru of Au)lo.set(Ru,$u),$u+=Ru.length;return lo}class DeviceHearing{constructor(lo,$u){this.modelsUrl=lo,this.engines=$u}modelsUrl;engines;where="device";recognizers=new Map;vad;modelFor(lo){const $u=transcriberFor(lo);if(!$u)throw new NotHeardHere(`Nothing in this browser hears ${lo} yet: type, or choose English or French.`);return $u}sizeFor(lo){return downloadSize(this.modelFor(lo).id)+downloadSize("silero-vad")}async ready(lo,$u){await Promise.all([this.recognizer(lo,$u),this.activity()])}async readyToFindSpeech(lo){const $u=downloadSize("silero-vad");lo?.(0,$u),await this.activity(),lo?.($u,$u)}async findSpeech(lo){const{speech:$u,lastEnd:Ru}=await this.speechIn(lo),Iu=lo.length/HEARING_RATE*1e3;return{speech:$u,silentMs:Ru===void 0?0:Math.max(0,Iu-Ru)}}recognizer(lo,$u){const Ru=this.modelFor(lo);let Iu=this.recognizers.get(Ru.id);return Iu||(Iu=(async()=>{const Pu=await this.engines.transformers(),{env:Ou}=Pu;Ou.allowLocalModels=!1,Ou.allowRemoteModels=!0,Ou.remoteHost=`${this.modelsUrl.replace(/\/+$/,"")}/`,Ou.remotePathTemplate="{model}/",Ou.useBrowserCache=!0,Ou.fetch=pinnedFetch(this.modelsUrl);const Mu=Ou.backends.onnx.wasm,Du=Ou.backends.onnx.versions?.web;Mu&&Du&&(Mu.wasmPaths=runtimeFiles(this.modelsUrl,Du));const Lu=downloadSize(Ru.id),Bu=new Map,ju=await Pu.pipeline("automatic-speech-recognition",modelFolder(Ru.id),{dtype:Ru.dtype,device:"wasm",progress_callback:Fu=>{Fu?.status==="progress"&&typeof Fu.loaded=="number"&&(Bu.set(String(Fu.file),Fu.loaded),$u?.(Array.from(Bu.values()).reduce((zu,Uu)=>zu+Uu,0),Lu))}});return $u?.(Lu,Lu),ju})(),Iu.catch(()=>this.recognizers.delete(Ru.id)),this.recognizers.set(Ru.id,Iu)),Iu}activity(){if(!this.vad){const lo=SPEECH_MODEL_CATALOGUE["silero-vad"].files[0].path,$u=`${this.modelsUrl.replace(/\/+$/,"")}/${modelFolder("silero-vad")}/${lo}`;this.vad=this.engines.vad().then(Ru=>Ru.NonRealTimeVAD.new({modelURL:$u,modelFetcher:Iu=>pinnedBytes(this.modelsUrl,Iu),ortConfig:Iu=>{const Pu=Iu?.env?.versions?.web;Iu?.env?.wasm&&Pu&&(Iu.env.wasm.wasmPaths=runtimeFiles(this.modelsUrl,Pu))},minSpeechMs:150,preSpeechPadMs:200,redemptionMs:600})),this.vad.catch(()=>{this.vad=void 0})}return this.vad}async speechIn(lo){const $u=await this.activity(),Ru=[];let Iu;for await(const Pu of $u.run(lo,HEARING_RATE))Ru.push(Pu.audio),Iu=Pu.end;return{speech:joinSegments(Ru),lastEnd:Iu}}async words(lo,$u){const Ru=this.modelFor($u),Iu=await this.recognizer($u),Pu=Ru.id.startsWith("whisper")?{language:$u.startsWith("fr")?"french":"english",task:"transcribe"}:{},Ou=await Iu(lo,Pu);return(Array.isArray(Ou)?Ou.map(Mu=>Mu.text).join(" "):Ou.text).trim()}async spokeSoFar(lo,$u=.2){const{speech:Ru}=await this.findSpeech(lo);return Ru.length>=HEARING_RATE*$u}async quietSoFar(lo){const{speech:$u,silentMs:Ru}=await this.findSpeech(lo);return{text:"",spoke:$u.length>=HEARING_RATE*.2,silentMs:Ru}}async hearSoFar(lo,$u){const{speech:Ru,silentMs:Iu}=await this.findSpeech(lo);return Ru.length<HEARING_RATE*.2?{text:"",spoke:!1,silentMs:Iu}:{text:await this.words(Ru,$u),spoke:!0,silentMs:Iu}}async hear(lo,$u){const Ru=performance.now(),Iu=this.modelFor($u);await this.recognizer($u);const{speech:Pu}=await this.speechIn(lo);if(Pu.length<HEARING_RATE*.2)return;const Ou=await this.words(Pu,$u);if(Ou)return{text:Ou,metadata:{input:"voice",language:$u,engine:Iu.id,where:"device"},seconds:Pu.length/HEARING_RATE,ms:Math.round(performance.now()-Ru)}}}const KEY="datalayer-voice-consent";function consented(Au){try{return JSON.parse(window.localStorage.getItem(KEY)||"{}")?.[Au]===!0}catch{return!1}}function consent(Au){try{const lo=JSON.parse(window.localStorage.getItem(KEY)||"{}");window.localStorage.setItem(KEY,JSON.stringify({...lo,[Au]:!0}))}catch{}}const CONSENT_SENTENCE="What you say is transcribed on this device: the sound never leaves it, and is not kept. The words go in the message box, for you to send.",SERVER_CONSENT_SENTENCE="What you say is sent to Datalayer’s servers to be transcribed: the sound and the words are not kept there. The words go in the message box, for you to send.";function consentKeyFor(Au,lo,$u){const Ru=lo==="server"?`${Au}:server`:Au;return $u?`${Ru}:kept`:Ru}const HANDS_FREE_WORDS={off:"Talk with it",listening:"Listening…",thinking:"Thinking…",speaking:"Speaking…",paused:"Paused"},TURN_SILENCE_MS=500,IDLE_PAUSE_MS=5*6e4;function handsFreeState(Au){return Au.on?Au.paused?"paused":Au.speaking?"speaking":Au.running?"thinking":"listening":"off"}function turnEnded(Au,lo=TURN_SILENCE_MS){return Au.spoke&&Au.silentMs>=lo}const ECHO_SHARE=.6,VOICE_OVER_ECHO=.08;function heardOverPlayback(Au,lo=ECHO_SHARE){return Au.playback<=0?!0:Au.microphone>=Au.playback*lo+VOICE_OVER_ECHO}function bargedIn(Au,lo,$u){return!(Au==="speaking"||Au==="thinking")||!lo.spoke?!1:Au!=="speaking"||!$u||heardOverPlayback($u)}function answerSpokenOver(Au){for(let lo=Au.length-1;lo>=0;lo-=1){const $u=Au[lo].role;if($u==="user")return;if($u==="assistant")return Au[lo].id}}const AUDIO_KEPT_DAYS_AT_MOST=30,KEPT_SECONDS_AT_MOST=60;function keptAudioDays(Au){if(!Au?.include?.includes("audio"))return;const lo=Au.retentionDays||AUDIO_KEPT_DAYS_AT_MOST;return Math.max(1,Math.min(lo,AUDIO_KEPT_DAYS_AT_MOST))}const keptAudioSentence=Au=>`This application also keeps what you say as sound, with this conversation, for ${Au} ${Au===1?"day":"days"} at most: its owner can listen to it, and it is deleted with the conversation. Not now, and you type instead.`;function soundOf(Au){const lo=Au.subarray(0,HEARING_RATE*KEPT_SECONDS_AT_MOST),$u=new Uint8Array(44+lo.length*2),Ru=new DataView($u.buffer),Iu=(Ou,Mu)=>{for(let Du=0;Du<Mu.length;Du++)Ru.setUint8(Ou+Du,Mu.charCodeAt(Du))};Iu(0,"RIFF"),Ru.setUint32(4,36+lo.length*2,!0),Iu(8,"WAVE"),Iu(12,"fmt "),Ru.setUint32(16,16,!0),Ru.setUint16(20,1,!0),Ru.setUint16(22,1,!0),Ru.setUint32(24,HEARING_RATE,!0),Ru.setUint32(28,HEARING_RATE*2,!0),Ru.setUint16(32,2,!0),Ru.setUint16(34,16,!0),Iu(36,"data"),Ru.setUint32(40,lo.length*2,!0);for(let Ou=0;Ou<lo.length;Ou++){const Mu=Math.max(-1,Math.min(1,lo[Ou]));Ru.setInt16(44+Ou*2,Mu<0?Mu*32768:Mu*32767,!0)}let Pu="";for(let Ou=0;Ou<$u.length;Ou+=32768)Pu+=String.fromCharCode(...$u.subarray(Ou,Ou+32768));return{data:btoa(Pu),type:"audio/wav",seconds:Math.round(lo.length/HEARING_RATE*100)/100}}const WORDS={idle:"",asking:"",loading:"Getting ready to listen…",listening:"Listening… let go to stop, Esc to cancel",hearing:"Hearing what you said…"},CLICKED_WORDS="Listening… click the microphone or stop speaking to stop, Esc to cancel",CLICK_MS=300,INTERIM_MS=700,LONGEST_MS=6e4,pause$1=Au=>new Promise(lo=>setTimeout(lo,Au));function prefersStill(){return typeof window<"u"&&!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function VoiceInput({hearing:Au,language:lo,onTranscript:$u,onInterim:Ru,silenceMs:Iu=1500,microphoneId:Pu,onListen:Ou,consentKey:Mu,keepsAudio:Du,disabled:Lu=!1,speaking:Bu=!1,onStopSpeaking:ju}){const[Fu,zu]=reactExports.useState("idle"),[Uu,Hu]=reactExports.useState(""),[Vu,Gu]=reactExports.useState(),[Wu,Zu]=reactExports.useState(),Ju=reactExports.useRef(void 0),Yu=reactExports.useRef(0),Xu=reactExports.useRef(!1),[ed,td]=reactExports.useState(!1),nd=reactExports.useRef(!1);nd.current=ed;const od=reactExports.useRef(void 0),sd=reactExports.useRef(0),ad=reactExports.useRef(null),pd=reactExports.useRef(Fu);pd.current=Fu;const vd=reactExports.useCallback(async()=>{if(!(Lu||pd.current!=="idle")){if(!consented(consentKeyFor(Mu,Au.where,Du))){zu("asking");return}Gu(void 0),Ou?.();try{if(zu("loading"),await Au.ready(lo,(yd,ld)=>Zu(ld?Math.round(yd/ld*100):void 0)),Zu(void 0),pd.current!=="loading")return;Ju.current=await openMicrophone(Pu),sd.current=Date.now(),zu("listening"),Hu("Listening")}catch(yd){zu("idle"),Zu(void 0),Gu(yd instanceof MicrophoneRefused||yd instanceof Error?yd.message:"The microphone could not be opened.")}}},[Mu,Du,Lu,Au,lo,Pu,Ou]),Sd=reactExports.useCallback(async()=>{const yd=Ju.current;if(Ju.current=void 0,!yd){pd.current==="loading"&&zu("idle");return}zu("hearing"),td(!1);try{const ld=await yd.stop();await od.current?.catch(()=>{});const ud=await Au.hear(ld,lo);if(zu("idle"),!ud){Ru?.(""),Hu("Nothing was heard.");return}Hu(`Heard: ${ud.text}`),$u(Du?{...ud,metadata:{...ud.metadata,sound:soundOf(ld)}}:ud)}catch(ld){zu("idle"),Ru?.(""),Gu(ld instanceof Error?ld.message:"What you said could not be heard.")}},[Au,lo,Ru,$u]),_d=reactExports.useCallback(()=>{Ju.current?.cancel(),Ju.current=void 0,td(!1),pd.current!=="idle"&&(zu("idle"),Ru?.(""),Hu("Cancelled."))},[Ru]),bd=reactExports.useRef(Ru);bd.current=Ru;const wd=reactExports.useRef(Sd);wd.current=Sd,reactExports.useEffect(()=>{if(Fu!=="listening")return;let yd=!0;return(async()=>{for(;yd;){await pause$1(INTERIM_MS);const ld=Ju.current;if(!yd||!ld)return;if(Date.now()-sd.current>=LONGEST_MS){wd.current();return}if(await od.current?.catch(()=>{}),!yd||Ju.current!==ld)return;const ud=Au.hearSoFar(ld.peek(),lo);od.current=ud;let hd;try{hd=await ud}catch{hd=void 0}finally{od.current===ud&&(od.current=void 0)}if(!(!yd||Ju.current!==ld||!hd)&&(hd.text&&bd.current?.(hd.text),nd.current&&hd.spoke&&hd.silentMs>=Iu)){wd.current();return}}})(),()=>{yd=!1}},[Fu,Au,lo,Iu]),reactExports.useEffect(()=>{const yd=hd=>{hd.code==="Space"&&hd.ctrlKey&&!hd.repeat?(hd.preventDefault(),Yu.current=Date.now(),vd()):hd.key==="Escape"&&(pd.current!=="idle"?_d():Bu&&ju?.())},ld=hd=>{(hd.code==="Space"||hd.key==="Control")&&(pd.current==="listening"||pd.current==="loading")&&Sd()},ud=()=>{document.hidden&&_d()};return window.addEventListener("keydown",yd),window.addEventListener("keyup",ld),document.addEventListener("visibilitychange",ud),()=>{window.removeEventListener("keydown",yd),window.removeEventListener("keyup",ld),document.removeEventListener("visibilitychange",ud)}},[_d,ju,Bu,vd,Sd]),reactExports.useEffect(()=>{if(Fu!=="listening"||prefersStill())return;let yd=0;const ld=()=>{const ud=Ju.current?.level()??0;ad.current&&(ad.current.style.transform=`scaleX(${Math.max(.04,ud)})`),yd=requestAnimationFrame(ld)};return yd=requestAnimationFrame(ld),()=>cancelAnimationFrame(yd)},[Fu]),reactExports.useEffect(()=>()=>Ju.current?.cancel(),[]);const Ad=Fu==="listening",gd=Lu||Fu==="hearing",dd=Ad?ed?"Listening — click to stop":"Listening — let go to stop":"Click to talk, or hold (Ctrl+Space)";return jsxRuntimeExports.jsxs(Box,{"data-voice-input":Fu,display:"inline-flex",alignItems:"center",gap:1,position:"relative",children:[Bu&&ju&&jsxRuntimeExports.jsx(Tooltip,{text:"Stop speaking (Esc)",direction:"n",children:jsxRuntimeExports.jsx(IconButton,{icon:MuteIcon,"aria-label":"Stop speaking",size:"small",variant:"invisible","data-voice-stop":"",onClick:ju})}),Ad&&jsxRuntimeExports.jsx(Box,{"aria-hidden":"true",width:40,height:4,borderRadius:2,bg:"neutral.muted",overflow:"hidden",children:jsxRuntimeExports.jsx(Box,{ref:ad,width:"100%",height:"100%",bg:"danger.emphasis",transformOrigin:"left",transform:prefersStill()?"scaleX(1)":"scaleX(0.04)"})}),(Fu==="loading"||Fu==="hearing")&&jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},"data-voice-progress":"",children:Fu==="loading"&&Wu!==void 0?`${Wu}%`:"…"}),jsxRuntimeExports.jsx(Tooltip,{text:dd,direction:"n",children:jsxRuntimeExports.jsx(IconButton,{icon:()=>jsxRuntimeExports.jsx(ForwardRef$1,{size:16}),"aria-label":dd,"aria-pressed":Ad,size:"small",variant:Ad?"danger":"invisible","aria-disabled":gd||void 0,"data-voice-mic":"",onPointerDown:yd=>{gd||yd.button!==0||(Yu.current=Date.now(),Xu.current=pd.current==="listening",pd.current==="idle"&&vd())},onPointerUp:()=>{gd||(Xu.current||Date.now()-Yu.current>=CLICK_MS?(Xu.current=!1,Sd()):td(!0))},onKeyDown:yd=>{if(yd.key==="Enter"||yd.key===" "){if(yd.preventDefault(),gd)return;pd.current==="listening"?Sd():(td(!0),vd())}}})}),Fu==="asking"&&jsxRuntimeExports.jsxs(Box,{role:"dialog","aria-label":"Talk instead of typing","data-voice-consent":"",position:"absolute",bottom:"100%",right:0,mb:2,width:280,p:3,bg:"canvas.overlay",border:"1px solid",borderColor:"border.default",borderRadius:2,boxShadow:"shadow.large",zIndex:10,children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,mb:2},children:Au.where==="server"?SERVER_CONSENT_SENTENCE:CONSENT_SENTENCE}),Du?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,mb:2},"data-voice-consent-kept":"",children:keptAudioSentence(Du)}):null,jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,justifyContent:"flex-end",children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",onClick:()=>zu("idle"),children:"Not now"}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary","data-voice-consent-yes":"",onClick:()=>{consent(consentKeyFor(Mu,Au.where,Du)),pd.current="idle",zu("idle"),vd()},children:"Use the microphone"})]})]}),jsxRuntimeExports.jsx(Box,{as:"span",role:"status","aria-live":"polite",position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",children:(Fu==="listening"&&ed?CLICKED_WORDS:WORDS[Fu])||Uu}),Vu&&jsxRuntimeExports.jsx(Text$3,{role:"alert",sx:{fontSize:0,color:"danger.fg",maxWidth:220},"data-voice-problem":"",children:Vu})]})}const BARGE_IN_POLL_MS=150,BARGE_IN_WINDOW=Math.round(HEARING_RATE*1.5),BARGE_IN_SHORTEST=.12,pause=Au=>new Promise(lo=>setTimeout(lo,Au));function HandsFree({hearing:Au,language:lo,consentKey:$u,keepsAudio:Ru,microphoneId:Iu,turnSilenceMs:Pu=TURN_SILENCE_MS,send:Ou,onInterim:Mu,running:Du=!1,speaking:Lu=!1,playbackLevel:Bu,onStopSpeaking:ju,onStopRun:Fu,onInterrupted:zu,disabled:Uu=!1}){const[Hu,Vu]=reactExports.useState(!1),[Gu,Wu]=reactExports.useState(!1),[Zu,Ju]=reactExports.useState(!1),[Yu,Xu]=reactExports.useState(),ed=handsFreeState({on:Hu,paused:Gu,speaking:Lu,running:Du}),td=reactExports.useRef(ed);td.current=ed;const nd=reactExports.useRef(Du);nd.current=Du;const od=reactExports.useRef(void 0),sd=reactExports.useRef({send:Ou,onInterim:Mu,playbackLevel:Bu,onStopSpeaking:ju,onStopRun:Fu,onInterrupted:zu});sd.current={send:Ou,onInterim:Mu,playbackLevel:Bu,onStopSpeaking:ju,onStopRun:Fu,onInterrupted:zu};const ad=consentKeyFor($u,Au.where,Ru),pd=reactExports.useCallback(()=>{if(!consented(ad)){Ju(!0);return}Xu(void 0),Wu(!1),Vu(!0)},[ad]),vd=reactExports.useCallback(()=>{Vu(!1),Wu(!1),od.current?.cancel(),od.current=void 0,sd.current.onInterim?.("")},[]),Sd=reactExports.useRef("listening");return reactExports.useEffect(()=>{if(!Hu||Gu)return;let _d=!0,bd=Date.now();return(async()=>{try{await Au.ready(lo),od.current=await openMicrophone(Iu)}catch(gd){_d&&(Xu(gd instanceof Error?gd.message:"The microphone could not be opened."),Vu(!1));return}Sd.current=td.current==="listening"?"listening":"answering";let wd=!1,Ad=0;for(;_d;){const gd=!!Au.spokeSoFar&&(td.current==="thinking"||td.current==="speaking")||!!Au.quietSoFar&&wd&&td.current==="listening";await pause(gd?BARGE_IN_POLL_MS:INTERIM_MS);const dd=od.current;if(!_d||!dd)return;const yd=td.current,ld=yd==="thinking"||yd==="speaking";if(ld&&Sd.current==="listening"||!ld&&Sd.current==="answering"){dd.cancel();try{od.current=await openMicrophone(Iu)}catch{return}Sd.current=ld?"answering":"listening",bd=Date.now(),wd=!1;continue}let ud;try{if(ld&&Au.spokeSoFar){const Ed=dd.peek();ud={text:"",spoke:await Au.spokeSoFar(Ed.subarray(Math.max(0,Ed.length-BARGE_IN_WINDOW)),BARGE_IN_SHORTEST),silentMs:0}}else wd&&Au.quietSoFar&&Date.now()-Ad<INTERIM_MS?ud=await Au.quietSoFar(dd.peek()):(ud=await Au.hearSoFar(dd.peek(),lo),Ad=Date.now())}catch{ud=void 0}if(!_d||od.current!==dd||!ud)continue;ud.text&&sd.current.onInterim?.(ud.text),ud.spoke&&(bd=Date.now(),yd==="listening"&&(wd=!0));const hd=sd.current.playbackLevel,md=hd?{microphone:dd.level(),playback:hd()}:void 0;if(bargedIn(yd,ud,md)){sd.current.onStopSpeaking?.(),(yd==="thinking"||nd.current)&&sd.current.onStopRun?.(),sd.current.onInterrupted?.(),Sd.current="listening";continue}if(yd==="listening"&&turnEnded(ud,Pu)){od.current=void 0;const Ed=await dd.stop();let Td;try{Td=await Au.hear(Ed,lo)}catch(Rd){Td=void 0,_d&&Xu(Rd instanceof Error?Rd.message:"What you said could not be heard.")}if(!_d)return;sd.current.onInterim?.(""),Td&&sd.current.send(Td.text,Ru?{...Td.metadata,sound:soundOf(Ed)}:Td.metadata);try{od.current=await openMicrophone(Iu)}catch{return}Sd.current="listening",bd=Date.now(),wd=!1;continue}if(yd==="listening"&&Date.now()-bd>=IDLE_PAUSE_MS){Wu(!0);return}}})(),()=>{_d=!1,od.current?.cancel(),od.current=void 0}},[Hu,Gu,Au,lo,Iu,Pu,Ru]),reactExports.useEffect(()=>{if(!Hu)return;const _d=bd=>{bd.key==="Escape"&&!Gu&&(Wu(!0),od.current?.cancel(),od.current=void 0,sd.current.onInterim?.(""))};return window.addEventListener("keydown",_d),()=>window.removeEventListener("keydown",_d)},[Hu,Gu]),jsxRuntimeExports.jsxs(Box,{display:"inline-flex",alignItems:"center",sx:{gap:1,position:"relative"},"data-hands-free":ed,children:[jsxRuntimeExports.jsx(Tooltip,{text:Hu?"Stop talking with it":"Talk with it: speak, it answers, and listens on (hands-free)",direction:"n",children:jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:Hu?"primary":"invisible","aria-pressed":Hu,"aria-label":Hu?"Stop talking with it":"Talk with it","aria-disabled":Uu||void 0,"data-hands-free-toggle":"",onClick:()=>{Uu||(Hu?vd():pd())},children:HANDS_FREE_WORDS.off})}),Hu?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},role:"status","aria-live":"polite","data-hands-free-state":ed,children:HANDS_FREE_WORDS[ed]}),Gu?jsxRuntimeExports.jsx(IconButton,{icon:()=>jsxRuntimeExports.jsx("span",{"aria-hidden":"true",children:"▶"}),size:"small",variant:"invisible","aria-label":"Resume listening","data-hands-free-resume":"",onClick:()=>Wu(!1)}):jsxRuntimeExports.jsx(IconButton,{icon:()=>jsxRuntimeExports.jsx("span",{"aria-hidden":"true",children:"❚❚"}),size:"small",variant:"invisible","aria-label":"Pause listening (Esc)","data-hands-free-pause":"",onClick:()=>{Wu(!0),od.current?.cancel(),od.current=void 0,sd.current.onInterim?.("")}})]}):null,Yu?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"danger.fg"},"data-hands-free-problem":"",children:Yu}):null,Zu?jsxRuntimeExports.jsxs(Box,{role:"dialog","aria-label":"The microphone","data-hands-free-consent":"",position:"absolute",bottom:"100%",left:0,width:280,p:3,bg:"canvas.overlay",border:"1px solid",borderColor:"border.default",borderRadius:2,boxShadow:"shadow.large",zIndex:10,children:[jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,mb:2},children:Au.where==="server"?SERVER_CONSENT_SENTENCE:CONSENT_SENTENCE}),Ru?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:1,mb:2},"data-voice-consent-kept":"",children:keptAudioSentence(Ru)}):null,jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,justifyContent:"flex-end",children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",onClick:()=>Ju(!1),children:"Not now"}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary","data-hands-free-consent-yes":"",onClick:()=>{consent(ad),Ju(!1),Xu(void 0),Wu(!1),Vu(!0)},children:"Use the microphone"})]})]}):null]})}const TRANSCRIPTIONS_PATH="/api/ai-agents/v1/speech/transcriptions",TRANSCRIPTION_STREAM_PATH="/api/ai-agents/v1/speech/transcriptions/stream",STREAM_IDLE_MS=3e3,STREAM_FINAL_MS=6e4,STREAM_LOOKBACK_SAMPLES=HEARING_RATE/2,SERVER_HEARING_MODEL="whisper-large-v3-turbo",SHORTEST$1=HEARING_RATE*.2;class ServerRefused extends Error{}function hearingPlace(Au){return Au.speechUrl?Au.detect||Au.where==="server"?"server":Au.where==="device"||transcriberFor(Au.language)?"device":"server":"device"}function wavOf(Au,lo=HEARING_RATE){const $u=new ArrayBuffer(44+Au.length*2),Ru=new DataView($u),Iu=(Pu,Ou)=>{for(let Mu=0;Mu<Ou.length;Mu++)Ru.setUint8(Pu+Mu,Ou.charCodeAt(Mu))};Iu(0,"RIFF"),Ru.setUint32(4,36+Au.length*2,!0),Iu(8,"WAVE"),Iu(12,"fmt "),Ru.setUint32(16,16,!0),Ru.setUint16(20,1,!0),Ru.setUint16(22,1,!0),Ru.setUint32(24,lo,!0),Ru.setUint32(28,lo*2,!0),Ru.setUint16(32,2,!0),Ru.setUint16(34,16,!0),Iu(36,"data"),Ru.setUint32(40,Au.length*2,!0);for(let Pu=0;Pu<Au.length;Pu++){const Ou=Math.max(-1,Math.min(1,Au[Pu]));Ru.setInt16(44+Pu*2,Ou<0?Ou*32768:Ou*32767,!0)}return $u}function pcm16Of(Au){const lo=new ArrayBuffer(Au.length*2),$u=new DataView(lo);for(let Ru=0;Ru<Au.length;Ru++){const Iu=Math.max(-1,Math.min(1,Au[Ru]));$u.setInt16(Ru*2,Iu<0?Iu*32768:Iu*32767,!0)}return lo}function streamUrlOf(Au){return`${Au.replace(/\/+$/,"").replace(/^http/,"ws")}${TRANSCRIPTION_STREAM_PATH}`}class PressStream{sent=0;partial="";refused;socket;ready=!1;queued=[];final;waiting;closed=!1;idle;constructor(lo,$u,Ru,Iu=0){this.sent=Iu,this.socket=lo(streamUrlOf($u)),this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{this.socket.send(JSON.stringify({token:Ru.token??"",language:Ru.language??"",format:"pcm16"}))},this.socket.onmessage=Pu=>{let Ou;try{Ou=JSON.parse(String(Pu.data))}catch{return}if(Ou.type==="ready"){this.ready=!0;for(const Mu of this.queued.splice(0))this.socket.send(Mu)}else Ou.type==="partial"&&typeof Ou.text=="string"?this.partial=Ou.text.trim():Ou.type==="final"?(this.final={text:typeof Ou.text=="string"?Ou.text.trim():"",language:typeof Ou.language=="string"?Ou.language:"",why:typeof Ou.why=="string"?Ou.why:""},this.settle()):Ou.type==="refused"&&(this.refused=typeof Ou.detail=="string"&&Ou.detail?Ou.detail:"What you said could not be heard on Datalayer's servers.",this.settle())},this.socket.onclose=()=>{this.closed=!0,this.settle()},this.socket.onerror=()=>{},this.touch()}get silencedEmpty(){return this.final!==void 0&&this.final.why==="silence"&&!this.final.text}feed(lo){if(this.touch(),lo.length<=this.sent||this.closed)return;const $u=pcm16Of(lo.subarray(this.sent));this.sent=lo.length,this.ready?this.socket.send($u):this.queued.push($u)}finish(lo){return this.feed(lo),this.final||this.closed||this.refused?Promise.resolve(this.final):new Promise($u=>{const Ru=setTimeout(()=>{this.waiting=void 0,this.close(),$u(void 0)},STREAM_FINAL_MS);this.waiting=Pu=>{clearTimeout(Ru),$u(Pu)};const Iu=JSON.stringify({type:"end"});this.ready?this.socket.send(Iu):this.queued.push(Iu)})}close(){this.idle&&clearTimeout(this.idle),this.closed=!0;try{this.socket.close(1e3)}catch{}this.settle()}touch(){this.idle&&clearTimeout(this.idle),this.idle=setTimeout(()=>{this.waiting||this.close()},STREAM_IDLE_MS)}settle(){const lo=this.waiting;this.waiting=void 0,lo?.(this.final),(this.final||this.refused)&&this.idle&&clearTimeout(this.idle)}}class ServerHearing{constructor(lo,$u){this.finder=lo,this.options=$u}finder;options;where="server";ready(lo,$u){return this.finder.readyToFindSpeech($u)}press;streamFor(lo,$u){const Ru=this.options.socket??(typeof WebSocket>"u"?void 0:Pu=>new WebSocket(Pu));if(!Ru)return;let Iu=0;return this.press&&lo.length<this.press.sent?(this.press.close(),this.press=void 0):this.press?.silencedEmpty&&(Iu=Math.max(0,this.press.sent-STREAM_LOOKBACK_SAMPLES),this.press.close(),this.press=void 0),this.press||(this.press=new PressStream(Ru,this.options.speechUrl,{token:this.options.token,language:this.options.detect?"":$u},Iu)),this.press}async spokeSoFar(lo,$u=.2){const{speech:Ru}=await this.finder.findSpeech(lo);return Ru.length>=HEARING_RATE*$u}async quietSoFar(lo){const{speech:$u,silentMs:Ru}=await this.finder.findSpeech(lo);return{text:"",spoke:$u.length>=SHORTEST$1,silentMs:Ru}}async hearSoFar(lo,$u=""){const{speech:Ru,silentMs:Iu}=await this.finder.findSpeech(lo),Pu=Ru.length>=SHORTEST$1,Ou=this.streamFor(lo,$u);return Ou?.feed(lo),{text:Pu?Ou?.partial??"":"",spoke:Pu,silentMs:Iu}}async hear(lo,$u){const Ru=performance.now();this.press?.silencedEmpty&&lo.length>=this.press.sent&&this.streamFor(lo,$u);const Iu=this.press&&lo.length>=this.press.sent?this.press:void 0;this.press&&!Iu&&this.press.close(),this.press=void 0;const{speech:Pu}=await this.finder.findSpeech(lo);if(Pu.length<SHORTEST$1){Iu?.close();return}if(Iu){const Uu=await Iu.finish(lo);if(Iu.close(),Iu.refused)throw new ServerRefused(Iu.refused);if(!Uu)throw new Error("What you said could not be heard on Datalayer's servers: the stream ended before its words.");return Uu.text?{text:Uu.text,metadata:{input:"voice",language:Uu.language||$u,engine:SERVER_HEARING_MODEL,where:"server"},seconds:lo.length/HEARING_RATE,ms:Math.round(performance.now()-Ru)}:void 0}const{speechUrl:Ou,token:Mu,detect:Du,fetcher:Lu=fetch}=this.options,Bu=Du?"":`?language=${encodeURIComponent($u)}`,ju=await Lu(`${Ou.replace(/\/+$/,"")}${TRANSCRIPTIONS_PATH}${Bu}`,{method:"POST",headers:{"Content-Type":"audio/wav",...Mu?{Authorization:`Bearer ${Mu}`}:{}},body:wavOf(Pu)}),Fu=await ju.json().catch(()=>({}));if(!ju.ok)throw new ServerRefused(typeof Fu.detail=="string"&&Fu.detail?Fu.detail:`What you said could not be heard on Datalayer's servers (${ju.status}).`);const zu=typeof Fu.text=="string"?Fu.text.trim():"";if(zu)return{text:zu,metadata:{input:"voice",language:typeof Fu.language=="string"&&Fu.language?Fu.language:$u,engine:SERVER_HEARING_MODEL,where:"server"},seconds:Pu.length/HEARING_RATE,ms:Math.round(performance.now()-Ru)}}}const MOVED_TO_SERVER="This device could not load its model: what you say will be heard on Datalayer's servers instead. Press the microphone again to agree.";class AutoHearing{constructor(lo,$u,Ru,Iu=Pu=>!!transcriberFor(Pu)){this.device=lo,this.server=$u,this.hearsHere=Iu,this.place=Iu(Ru)?"device":"server"}device;server;hearsHere;place;deviceBroken=!1;get where(){return this.place}get current(){return this.place==="device"?this.device:this.server}async ready(lo,$u){if(this.place==="server"&&!this.deviceBroken&&this.hearsHere(lo)&&(this.place="device"),this.place==="device")try{await this.device.ready(lo,$u);return}catch{throw this.place="server",this.deviceBroken=!0,new Error(MOVED_TO_SERVER)}await this.server.ready(lo,$u)}hearSoFar(lo,$u){return this.current.hearSoFar(lo,$u)}async spokeSoFar(lo,$u){const Ru=this.current;return Ru.spokeSoFar?Ru.spokeSoFar(lo,$u):(await Ru.hearSoFar(lo,"")).spoke}quietSoFar(lo){const $u=this.current;return $u.quietSoFar?$u.quietSoFar(lo):$u.hearSoFar(lo,"")}async hear(lo,$u){if(this.place==="device")return this.device.hear(lo,$u);try{return await this.server.hear(lo,$u)}catch(Ru){if(!(Ru instanceof ServerRefused)||this.deviceBroken||!this.hearsHere($u))throw Ru;return this.place="device",await this.device.ready($u),this.device.hear(lo,$u)}}}function languageName(Au){try{return new Intl.DisplayNames(["en"],{type:"language"}).of(Au)??Au}catch{return Au}}function voiceLanguages(){const Au=new Set,lo=[];for(const $u of Object.values(VOICE_CATALOGUE))for(const Ru of $u.languages)!Au.has(Ru)&&transcriberFor(Ru)&&(Au.add(Ru),lo.push({value:Ru,label:languageName(Ru)}));return lo}function voicesSpeaking(Au){return Object.values(VOICE_CATALOGUE).filter(lo=>voiceSpeaks(lo,Au)||voiceSpeaks(lo,Au.split("-")[0]))}function catalogueVoiceSpeaks(Au,lo){return voicesSpeaking(lo).some($u=>$u.id===Au)}const RATE_CHOICES=[{value:.75,label:"Slower"},{value:1,label:"Normal"},{value:1.25,label:"Faster"},{value:1.5,label:"Fastest"}],PAUSE_CHOICES=[{value:1,label:"Usual"},{value:2,label:"Longer"},{value:3,label:"Much longer"}],VOLUME_CHOICES=[{value:.25,label:"Quiet"},{value:.5,label:"Half"},{value:.75,label:"Loud"},{value:1,label:"Full"}],OUTPUT_CHOICES=[{value:"off",label:"Never"},{value:"on_request",label:"When I ask (Read aloud)"},{value:"always",label:"Always, as they are written"}],VOICE_SETTINGS_KEY="datalayer-voice-settings",RATE_RANGE={min:.5,max:2},VOLUME_RANGE={min:0,max:1},PAUSE_RANGE={min:1,max:4};function clamp$1(Au,{min:lo,max:$u}){return Math.min($u,Math.max(lo,Au))}function saneVoiceSettings(Au){const lo=Au??{},$u={};return typeof lo.language=="string"&&lo.language.trim()&&($u.language=lo.language.trim()),typeof lo.voice=="string"&&lo.voice.trim()&&($u.voice=lo.voice.trim()),typeof lo.rate=="number"&&Number.isFinite(lo.rate)&&($u.rate=clamp$1(lo.rate,RATE_RANGE)),typeof lo.volume=="number"&&Number.isFinite(lo.volume)&&($u.volume=clamp$1(lo.volume,VOLUME_RANGE)),(lo.output==="off"||lo.output==="on_request"||lo.output==="always")&&($u.output=lo.output),typeof lo.sendWhatISay=="boolean"&&($u.sendWhatISay=lo.sendWhatISay),typeof lo.microphoneId=="string"&&lo.microphoneId.trim()&&($u.microphoneId=lo.microphoneId.trim()),typeof lo.onDeviceOnly=="boolean"&&($u.onDeviceOnly=lo.onDeviceOnly),typeof lo.detectLanguage=="boolean"&&($u.detectLanguage=lo.detectLanguage),typeof lo.pause=="number"&&Number.isFinite(lo.pause)&&($u.pause=clamp$1(lo.pause,PAUSE_RANGE)),$u}function keptVoiceSettings(){try{const Au=window.localStorage.getItem(VOICE_SETTINGS_KEY);return Au?saneVoiceSettings(JSON.parse(Au)):{}}catch{return{}}}let held;const listeners$5=new Set;function heldVoiceSettings(){return held===void 0&&(held=keptVoiceSettings()),held}function onVoiceSettingsChange(Au){return listeners$5.add(Au),()=>{listeners$5.delete(Au)}}function told(Au){held=Au;for(const lo of[...listeners$5])lo(Au)}typeof window<"u"&&window.addEventListener("storage",Au=>{(Au.key===VOICE_SETTINGS_KEY||Au.key===null)&&told(keptVoiceSettings())});function keepVoiceSettings(Au){const lo=saneVoiceSettings(Au);try{Object.keys(lo).length===0?window.localStorage.removeItem(VOICE_SETTINGS_KEY):window.localStorage.setItem(VOICE_SETTINGS_KEY,JSON.stringify(lo))}catch{}return told(lo),lo}function withVoiceSetting(Au,lo,$u,Ru){const Iu={...saneVoiceSettings(Au)};return $u===void 0?delete Iu[lo]:Iu[lo]=$u,lo==="language"&&typeof $u=="string"&&Iu.voice&&Ru&&!Ru(Iu.voice,$u)&&delete Iu.voice,saneVoiceSettings(Iu)}function browserLanguage(){try{return(navigator.languages?.[0]||navigator.language)?.trim()||void 0}catch{return}}function voiceForPerson(Au,lo={},$u=browserLanguage()){const Ru=saneVoiceSettings(lo),Iu=Au.output==="off",Pu=Mu=>Mu&&Mu.trim()?Mu.trim():void 0,Ou={...Au,language:Ru.language??Pu(Au.language)??Pu($u)??"en-US",voice:Ru.voice??Au.voice,output:Iu?"off":Ru.output??Au.output,rate:Ru.rate??Au.rate,volume:Ru.volume??Au.volume};return Ru.sendWhatISay!==void 0&&(Ou.sendWhatISay=Ru.sendWhatISay),Ru.microphoneId&&(Ou.microphoneId=Ru.microphoneId),Ru.detectLanguage&&(Ou.detect=!0),Ru.onDeviceOnly&&(Ou.speechUrl=void 0,Ou.token=void 0,Ou.output="off",Ou.where="device",Ou.detect=!1),Ou}function useVoiceSettings(){const[Au,lo]=reactExports.useState(heldVoiceSettings);reactExports.useEffect(()=>(lo(heldVoiceSettings()),onVoiceSettingsChange(lo)),[]);const $u=reactExports.useCallback(Ru=>{keepVoiceSettings(Ru)},[]);return[Au,$u]}async function microphones(){try{return(await navigator.mediaDevices.enumerateDevices()).filter(lo=>lo.kind==="audioinput")}catch{return[]}}function VoiceMenu({voice:Au,answers:lo,disabled:$u=!1}){const[Ru,Iu]=useVoiceSettings(),[Pu,Ou]=reactExports.useState([]),Mu=(Fu,zu)=>Iu(withVoiceSetting(Ru,Fu,zu,catalogueVoiceSpeaks)),Du=!!Ru.onDeviceOnly,Lu=!!Ru.detectLanguage,Bu=voicesSpeaking(Au.language),ju=Pu.filter(Fu=>Fu.label);return jsxRuntimeExports.jsxs(ActionMenu,{onOpenChange:Fu=>{Fu&&microphones().then(Ou)},children:[jsxRuntimeExports.jsx(ActionMenu.Anchor,{children:jsxRuntimeExports.jsx(IconButton,{icon:GearIcon,size:"small",variant:"invisible","aria-label":"Voice settings","data-voice-menu":"",disabled:$u})}),jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"medium",children:jsxRuntimeExports.jsxs(ActionList,{children:[jsxRuntimeExports.jsxs(ActionList.Group,{selectionVariant:"single",children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:"Language"}),voiceLanguages().map(Fu=>jsxRuntimeExports.jsx(ActionList.Item,{selected:Fu.value===Au.language,onSelect:()=>Mu("language",Fu.value),"data-voice-language":Fu.value,children:Fu.label},Fu.value))]}),lo&&!Du?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ActionList.Divider,{}),jsxRuntimeExports.jsxs(ActionList.Group,{selectionVariant:"single",children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:"Answers heard"}),OUTPUT_CHOICES.map(Fu=>jsxRuntimeExports.jsx(ActionList.Item,{selected:Fu.value===Au.output,onSelect:()=>Mu("output",Fu.value),"data-voice-output":Fu.value,children:Fu.label},Fu.value))]}),Bu.length>0?jsxRuntimeExports.jsxs(ActionList.Group,{selectionVariant:"single",children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:"Voice"}),Bu.map(Fu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Fu.id===Au.voice,onSelect:()=>Mu("voice",Fu.id),"data-voice-voice":Fu.id,children:[Fu.name,Fu.attribution?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:Fu.attribution}):null]},Fu.id))]}):null,jsxRuntimeExports.jsxs(ActionList.Group,{selectionVariant:"single",children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:"Speed"}),RATE_CHOICES.map(Fu=>jsxRuntimeExports.jsx(ActionList.Item,{selected:Fu.value===(Au.rate??1),onSelect:()=>Mu("rate",Fu.value),"data-voice-rate":Fu.value,children:Fu.label},Fu.value))]}),jsxRuntimeExports.jsxs(ActionList.Group,{selectionVariant:"single",children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:"Loudness"}),VOLUME_CHOICES.map(Fu=>jsxRuntimeExports.jsx(ActionList.Item,{selected:Fu.value===(Au.volume??1),onSelect:()=>Mu("volume",Fu.value),"data-voice-volume":Fu.value,children:Fu.label},Fu.value))]})]}):null,ju.length>1?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ActionList.Divider,{}),jsxRuntimeExports.jsxs(ActionList.Group,{selectionVariant:"single",children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:"Microphone"}),ju.map(Fu=>jsxRuntimeExports.jsx(ActionList.Item,{selected:Fu.deviceId===(Au.microphoneId??ju[0].deviceId),onSelect:()=>Mu("microphoneId",Fu.deviceId),"data-voice-microphone":Fu.deviceId,children:Fu.label},Fu.deviceId))]})]}):null,jsxRuntimeExports.jsx(ActionList.Divider,{}),jsxRuntimeExports.jsxs(ActionList.Group,{selectionVariant:"single",children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:"Pauses before I am done"}),PAUSE_CHOICES.map(Fu=>jsxRuntimeExports.jsx(ActionList.Item,{selected:Fu.value===(Ru.pause??1),onSelect:()=>Mu("pause",Fu.value===1?void 0:Fu.value),"data-voice-pause":Fu.value,children:Fu.label},Fu.value))]}),jsxRuntimeExports.jsx(ActionList.Divider,{}),jsxRuntimeExports.jsxs(ActionList.Group,{selectionVariant:"multiple",children:[jsxRuntimeExports.jsxs(ActionList.Item,{selected:!!Au.sendWhatISay,onSelect:()=>Mu("sendWhatISay",!Au.sendWhatISay),"data-voice-send-what-i-say":"",children:["Send what I say",jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:"Sent as soon as it is heard, not left in the box."})]}),Au.speechUrl&&!Du?jsxRuntimeExports.jsxs(ActionList.Item,{selected:Lu,onSelect:()=>Mu("detectLanguage",!Lu),"data-voice-detect":"",children:["Detect the language I speak",jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:"Heard on Datalayer’s servers by Whisper, which finds the language; nothing is kept there."})]}):null,jsxRuntimeExports.jsxs(ActionList.Item,{selected:Du,onSelect:()=>Mu("onDeviceOnly",!Du),"data-voice-on-device":"",children:["Keep speech on this device",jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:"Nothing is sent to Datalayer’s speech service: you are heard in the browser, answers are not spoken."})]})]}),Object.keys(Ru).length>0?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ActionList.Divider,{}),jsxRuntimeExports.jsx(ActionList.Item,{onSelect:()=>Iu({}),"data-voice-settings-reset":"",children:"Use the application’s"})]}):null]})})]})}function spokenOf(Au){const lo=Au;return lo?.input==="voice"&&typeof lo.language=="string"&&typeof lo.engine=="string"&&(lo.where==="device"||lo.where==="server")?lo:void 0}function ComposerVoice({voice:Au,input:lo,setInput:$u,onSpoken:Ru,send:Iu,disabled:Pu=!1,speaking:Ou=!1,onStopSpeaking:Mu,playbackLevel:Du,running:Lu=!1,onStopRun:Bu,onInterrupted:ju,onInterimChange:Fu,answers:zu=!1}){const Uu=hearingPlace(Au),Hu=reactExports.useMemo(()=>{if(Au.input==="off")return;const Wu=new DeviceHearing(Au.modelsUrl,Au.engines),Zu=Au.speechUrl?new ServerHearing(Wu,{speechUrl:Au.speechUrl,token:Au.token,detect:Au.detect}):void 0;return Zu&&!Au.detect&&(Au.where??"auto")==="auto"?new AutoHearing(Wu,Zu,Au.language):Uu==="server"&&Zu?Zu:Wu},[Au.input,Au.modelsUrl,Au.engines,Uu,Au.speechUrl,Au.token,Au.detect,Au.where,Au.language]),Vu=reactExports.useRef(""),Gu=Wu=>[Vu.current,Wu].filter(Boolean).join(" ");return Hu?jsxRuntimeExports.jsxs("span",{"data-composer-voice":"",style:{display:"inline-flex",alignItems:"center",gap:2},children:[jsxRuntimeExports.jsx(VoiceMenu,{voice:Au,answers:zu,disabled:Pu}),Au.input==="hands_free"?jsxRuntimeExports.jsx(HandsFree,{hearing:Hu,language:Au.language,consentKey:Au.consentKey??"chat",keepsAudio:Au.keepsAudio,microphoneId:Au.microphoneId,turnSilenceMs:Au.turnSilenceMs,disabled:Pu,running:Lu,speaking:Ou,playbackLevel:Du,onStopSpeaking:Mu,onStopRun:Bu,onInterrupted:ju,onInterim:Wu=>{$u(Wu?Gu(Wu):Vu.current),Fu?.(Wu!=="")},send:(Wu,Zu)=>{Fu?.(!1),$u(Vu.current),Iu(Wu,Zu)}}):null,jsxRuntimeExports.jsx(VoiceInput,{hearing:Hu,language:Au.language,consentKey:Au.consentKey??"chat",keepsAudio:Au.keepsAudio,silenceMs:Au.silenceMs,microphoneId:Au.microphoneId,disabled:Pu,speaking:Ou,onStopSpeaking:Mu,onListen:()=>{Vu.current=lo.trim(),Mu?.()},onInterim:Wu=>{$u(Gu(Wu)),Fu?.(Wu!=="")},onTranscript:Wu=>{if(Fu?.(!1),Au.sendWhatISay){$u(Vu.current),Iu(Wu.text,Wu.metadata);return}Ru(Wu.metadata),$u(Gu(Wu.text))}})]}):null}function plainWords(Au){return Au.replace(/```[\s\S]*?(```|$)/g," A code block. ").replace(/(^|\n)(\|[^\n]*\|[ \t]*(\n|$))+/g,`$1 A table.
3909
- `).replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm,"").replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/`([^`]*)`/g,"$1").replace(/^\s{0,3}#{1,6}\s+(.*)$/gm,"$1.").replace(/^\s*(?:[-*+]|\d+[.)])\s+/gm,"").replace(/^\s*>\s?/gm,"").replace(/[*_~]+/g,"").replace(/\.\s*\./g,".").replace(/\s+/g," ").trim()}const END=/[.!?…:;](?=["'»)\]]*(\s|$))/g,SHORTEST=12;class SentenceCutter{said=0;feed(lo){const $u=plainWords(lo),Ru=[];END.lastIndex=this.said;let Iu;for(;(Iu=END.exec($u))!==null;){const Pu=Iu.index+Iu[0].length;if(Pu>=$u.length)break;const Ou=$u.slice(this.said,Pu).trim();Ou.length>=SHORTEST&&(Ru.push(Ou),this.said=Pu)}return Ru}end(lo){const $u=plainWords(lo).slice(this.said).trim();return this.said=plainWords(lo).length,$u?[$u]:[]}}function readAloud(Au,lo){Au.unlock?.(),Au.stop();const $u=new SentenceCutter,Ru=[...$u.feed(lo),...$u.end(lo)];return Ru.forEach(Iu=>Au.say(Iu)),Ru}function readsAloud(Au,lo,$u){return Au.role==="assistant"&&!Au.live&&!Au.note&&Au.id!==$u&&lo.trim().length>0}function ReadAloud({onRead:Au}){return jsxRuntimeExports.jsx(Tooltip,{text:"Read aloud",direction:"n",children:jsxRuntimeExports.jsx(IconButton,{"data-read-aloud":"",icon:UnmuteIcon,"aria-label":"Read aloud",size:"small",variant:"invisible",onClick:Au})})}const DATALAYER_SPEECH_MODELS_URL="https://models-speech.datalayer.tech",DATALAYER_VOICE_ENGINES={transformers:()=>__vitePreload(()=>import("./chunks/transformers.web-CLaqP_Vm.js"),[],import.meta.url),vad:()=>__vitePreload(()=>import("./chunks/index-6MwCUMaU.js").then(Au=>Au.i),[],import.meta.url)};function chatVoiceOf(Au,lo,$u){if(!Au?.enabled||Au.input==="off"&&Au.output==="off")return;if(Au.output!=="off"&&!lo.speechUrl)throw new Error("Its answers are said by Datalayer’s speech service, and its host gave no address for it.");const Ru=Au.language||lo.language||"en-US";return{language:Ru,input:Au.input,output:Au.input==="hands_free"?"always":Au.output,voice:Au.voice||voiceFor(Ru)?.id||"",modelsUrl:lo.modelsUrl||DATALAYER_SPEECH_MODELS_URL,engines:DATALAYER_VOICE_ENGINES,speechUrl:lo.speechUrl,token:lo.token,consentKey:lo.consentKey,where:Au.where??"auto",...$u&&Au.input!=="off"?{keepsAudio:$u}:{}}}function voiceAskedAs(Au,lo){if(!Au)return;const $u=Au.token||lo;return $u?{...Au,token:$u}:{...Au}}const SILENCE_MS=1500;function settledVoice(Au,lo=heldVoiceSettings()){const $u=voiceForPerson(Au,lo),Ru=saneVoiceSettings(lo).pause??1,Iu=$u.output??"off";if(Iu!=="off"&&!$u.speechUrl)throw new Error(`A chat whose answers are heard (${Iu}) names the speech service: its speechUrl is missing.`);return{...$u,output:Iu,voice:$u.voice||voiceFor($u.language)?.id||"",modelsUrl:$u.modelsUrl||DATALAYER_SPEECH_MODELS_URL,engines:$u.engines??DATALAYER_VOICE_ENGINES,silenceMs:Math.round(($u.silenceMs??SILENCE_MS)*Ru),turnSilenceMs:Math.round(($u.turnSilenceMs??TURN_SILENCE_MS)*Ru)}}const SYNTHESES_PATH="/api/ai-agents/v1/speech/syntheses",STREAMED_SLICE_SECONDS=.25,SENTENCES_AHEAD=2,FIRST_CLAUSE_SPLIT_CHARS=60,SHORTEST_CLAUSE_CHARS=15;function firstClause(Au){if(Au.length<=FIRST_CLAUSE_SPLIT_CHARS)return[Au];const lo=/[,;:\u2013\u2014]\s+/g;let $u;for(;($u=lo.exec(Au))!==null;){const Ru=$u.index+1;if(Ru<SHORTEST_CLAUSE_CHARS)continue;const Iu=Au.slice($u.index+$u[0].length);if(Iu.length<SHORTEST_CLAUSE_CHARS)break;return[Au.slice(0,Ru),Iu]}return[Au]}class ServerSpeaker{constructor(lo){this.options=lo}options;context;analyser;gain;buffer;queue=[];playing;scheduled=[];running=!1;generation=0;state={speaking:!1};update(lo){this.options={...this.options,...lo}}unlock(){this.audio(),this.context?.resume()}audio(){return this.context||(this.context=new AudioContext,this.analyser=this.context.createAnalyser(),this.analyser.fftSize=512,this.gain=this.context.createGain(),this.analyser.connect(this.gain),this.gain.connect(this.context.destination),this.buffer=new Float32Array(this.analyser.fftSize)),this.context}level(){if(!this.analyser||!this.buffer||!this.state.speaking)return 0;this.analyser.getFloatTimeDomainData(this.buffer);let lo=0;for(const $u of this.buffer)lo+=$u*$u;return Math.min(1,Math.sqrt(lo/this.buffer.length)*6)}speed(){const lo=this.options.rate;return typeof lo=="number"&&Number.isFinite(lo)?Math.min(2,Math.max(.5,lo)):1}loudness(){const lo=this.options.volume;return typeof lo=="number"&&Number.isFinite(lo)?Math.min(1,Math.max(0,lo)):1}set(lo){this.state={...this.state,...lo},this.options.onState?.(this.state)}say(lo){const $u=lo.trim();if(!$u)return;const Ru=this.options.firstClauseFirst&&!this.options.streamed&&!this.queue.length&&!this.playing&&!this.running;for(const Iu of Ru?firstClause($u):[$u])this.queue.push({text:Iu,asked:performance.now()});this.state.speaking||this.set({speaking:!0,refused:void 0}),this.askAhead(),this.running||this.run(this.generation)}askAhead(){for(const lo of this.queue.slice(0,SENTENCES_AHEAD))lo.audio||(lo.audio=this.fetch(lo.text))}async fetch(lo){const{speechUrl:$u,voice:Ru,language:Iu,token:Pu,fetcher:Ou=fetch}=this.options;try{const Mu=await Ou(`${$u.replace(/\/+$/,"")}${SYNTHESES_PATH}`,{method:"POST",headers:{"Content-Type":"application/json",...Pu?{Authorization:`Bearer ${Pu}`}:{}},body:JSON.stringify({text:lo,voice:Ru,language:Iu,...this.options.streamed?{format:"pcm",stream:!0}:{format:"opus"}})});if(!Mu.ok){const Lu=await Mu.json().catch(()=>({}));return typeof Lu?.detail=="string"?Lu.detail:`The answer could not be spoken (${Mu.status}).`}const Du=Mu.headers.get("content-type")??"";return Du.toLowerCase().startsWith("audio/l16")?{kind:"pcm",rate:Number(Mu.headers.get("x-speech-rate"))||Number(/rate=(\d+)/i.exec(Du)?.[1])||24e3,body:Mu.body??await Mu.arrayBuffer()}:{kind:"whole",audio:await Mu.arrayBuffer()}}catch{return"Datalayer’s speech service could not be reached: the answer is still written here."}}async run(lo){this.running=!0;try{for(;this.queue.length&&lo===this.generation;){this.askAhead();const $u=this.queue[0],Ru=await $u.audio;if(lo!==this.generation)return;if(typeof Ru=="string"){this.queue=[],this.set({speaking:!1,sentence:void 0,refused:Ru});return}this.queue.shift(),this.askAhead();const Iu=this.audio();if(Ru.kind==="pcm"){await this.playStreamed(lo,$u,Ru);continue}const Pu=await Iu.decodeAudioData(Ru.audio);if(lo!==this.generation)return;await new Promise(Ou=>{const Mu=Iu.createBufferSource();Mu.buffer=Pu,Mu.playbackRate.value=this.speed(),this.gain&&(this.gain.gain.value=this.loudness()),Mu.connect(this.analyser),Mu.onended=()=>Ou(),this.playing=Mu,this.set({speaking:!0,sentence:$u.text,refused:void 0}),this.options.onFirstSound?.(Math.round(performance.now()-$u.asked)),Mu.start()}),this.playing=void 0}}finally{lo===this.generation&&(this.running=!1,this.state.speaking&&this.set({speaking:!1,sentence:void 0}))}}async playStreamed(lo,$u,Ru){const Iu=this.audio(),Pu=this.speed();this.gain&&(this.gain.gain.value=this.loudness());let Ou=0,Mu=!0,Du=new Uint8Array(0),Lu=Promise.resolve();const Bu=Math.round(Ru.rate*STREAMED_SLICE_SECONDS)*2,ju=zu=>{const Uu=new Float32Array(zu.length/2),Hu=new DataView(zu.buffer,zu.byteOffset,zu.length);for(let Wu=0;Wu<Uu.length;Wu++)Uu[Wu]=Hu.getInt16(Wu*2,!0)/32768;const Vu=Iu.createBuffer(1,Uu.length,Ru.rate);Vu.getChannelData(0).set(Uu);const Gu=Iu.createBufferSource();Gu.buffer=Vu,Gu.playbackRate.value=Pu,Gu.connect(this.analyser),Ou=Math.max(Ou,Iu.currentTime),Lu=new Promise(Wu=>{Gu.onended=()=>{this.scheduled=this.scheduled.filter(Zu=>Zu!==Gu),Wu()}}),this.scheduled.push(Gu),this.playing=Gu,Mu&&(Mu=!1,this.set({speaking:!0,sentence:$u.text,refused:void 0}),this.options.onFirstSound?.(Math.round(performance.now()-$u.asked))),Gu.start(Ou),Ou+=Vu.duration/Pu},Fu=(zu,Uu)=>{const Hu=new Uint8Array(Du.length+zu.length);for(Hu.set(Du),Hu.set(zu,Du.length),Du=Hu;Du.length>=Bu||Uu&&Du.length>=2;){const Vu=Math.min(Du.length,Math.max(Bu,2)),Gu=Vu-Vu%2;if(ju(Du.subarray(0,Gu)),Du=Du.slice(Gu),Uu&&Du.length<2)break}};if(Ru.body instanceof ArrayBuffer)Fu(new Uint8Array(Ru.body),!0);else{const zu=Ru.body.getReader();for(;;){const{done:Uu,value:Hu}=await zu.read();if(lo!==this.generation){zu.cancel().catch(()=>{});return}if(Uu){Fu(new Uint8Array(0),!0);break}Fu(Hu,!1)}}await Lu,this.playing=void 0}stop(){this.generation+=1,this.queue=[],this.running=!1;for(const lo of[...this.scheduled,...this.playing?[this.playing]:[]])try{lo.stop()}catch{}this.scheduled=[],this.playing=void 0,this.set({speaking:!1,sentence:void 0})}close(){this.stop(),this.context?.close(),this.context=void 0}}function useVoiceSpeaker(Au,lo=!0){const[$u,Ru]=reactExports.useState({speaking:!1}),Iu=lo&&!!Au&&Au.output!=="off"&&!!Au.speechUrl,Pu=reactExports.useMemo(()=>Iu&&Au?.speechUrl?new ServerSpeaker({speechUrl:Au.speechUrl,voice:Au.voice,language:Au.language,token:Au.token,rate:Au.rate,volume:Au.volume,onState:Ru,streamed:!0,firstClauseFirst:!0}):void 0,[Iu,Au?.speechUrl]);reactExports.useEffect(()=>{Pu?.update({voice:Au?.voice,language:Au?.language,token:Au?.token,rate:Au?.rate,volume:Au?.volume})},[Pu,Au?.voice,Au?.language,Au?.token,Au?.rate,Au?.volume]),reactExports.useEffect(()=>()=>Pu?.close(),[Pu]),reactExports.useEffect(()=>{if(!Pu)return;const Lu=()=>Pu.unlock();return window.addEventListener("pointerdown",Lu,{once:!0}),window.addEventListener("keydown",Lu,{once:!0}),()=>{window.removeEventListener("pointerdown",Lu),window.removeEventListener("keydown",Lu)}},[Pu]);const Ou=reactExports.useCallback(()=>Pu?.stop(),[Pu]),Mu=reactExports.useCallback(Lu=>{Pu&&readAloud(Pu,Lu)},[Pu]),Du=reactExports.useMemo(()=>Pu?()=>Pu.level():void 0,[Pu]);return{speaker:Pu,state:$u,stop:Ou,read:Mu,level:Du}}function answerText(Au){const lo=Au;if(!(!lo||lo.role!=="assistant"||typeof lo.toolName=="string")){if(typeof lo.content=="string")return lo.content;if(Array.isArray(lo.content))return lo.content.map($u=>$u&&typeof $u=="object"&&$u.type==="text"?String($u.text??""):"").join(" ")}}function useSpokenAnswers(Au,lo,$u,Ru){const Iu=reactExports.useRef(new Set),Pu=reactExports.useRef(void 0),Ou=reactExports.useRef(!1);reactExports.useEffect(()=>{if(!$u||!Ru){Ou.current=!1,Pu.current=void 0;return}const Mu=Au.map((Bu,ju)=>({id:String(Bu?.id??ju),text:answerText(Bu)})).filter(Bu=>Bu.text!==void 0);if(!Ou.current){Ou.current=!0,Mu.forEach(Bu=>Iu.current.add(Bu.id));return}const Du=Mu[Mu.length-1];if(!Du||Iu.current.has(Du.id)&&Pu.current?.id!==Du.id)return;Pu.current?.id!==Du.id&&(Iu.current.add(Du.id),Pu.current={id:Du.id,cutter:new SentenceCutter,ended:!1});const Lu=Pu.current;if(!Lu.ended){for(const Bu of Lu.cutter.feed(Du.text??""))Ru.say(Bu);if(!lo){for(const Bu of Lu.cutter.end(Du.text??""))Ru.say(Bu);Lu.ended=!0}}},[Au,lo,$u,Ru])}const SAID_HIGHLIGHT="voice-said",SAID_STYLE=`::highlight(${SAID_HIGHLIGHT}) {
3909
+ `).replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm,"").replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/`([^`]*)`/g,"$1").replace(/^\s{0,3}#{1,6}\s+(.*)$/gm,"$1.").replace(/^\s*(?:[-*+]|\d+[.)])\s+/gm,"").replace(/^\s*>\s?/gm,"").replace(/[*_~]+/g,"").replace(/\.\s*\./g,".").replace(/\s+/g," ").trim()}const END=/[.!?…:;](?=["'»)\]]*(\s|$))/g,SHORTEST=12;class SentenceCutter{said=0;feed(lo){const $u=plainWords(lo),Ru=[];END.lastIndex=this.said;let Iu;for(;(Iu=END.exec($u))!==null;){const Pu=Iu.index+Iu[0].length;if(Pu>=$u.length)break;const Ou=$u.slice(this.said,Pu).trim();Ou.length>=SHORTEST&&(Ru.push(Ou),this.said=Pu)}return Ru}end(lo){const $u=plainWords(lo).slice(this.said).trim();return this.said=plainWords(lo).length,$u?[$u]:[]}}function readAloud(Au,lo){Au.unlock?.(),Au.stop();const $u=new SentenceCutter,Ru=[...$u.feed(lo),...$u.end(lo)];return Ru.forEach(Iu=>Au.say(Iu)),Ru}function readsAloud(Au,lo,$u){return Au.role==="assistant"&&!Au.live&&!Au.note&&Au.id!==$u&&lo.trim().length>0}function ReadAloud({onRead:Au}){return jsxRuntimeExports.jsx(Tooltip,{text:"Read aloud",direction:"n",children:jsxRuntimeExports.jsx(IconButton,{"data-read-aloud":"",icon:UnmuteIcon,"aria-label":"Read aloud",size:"small",variant:"invisible",onClick:Au})})}const DATALAYER_SPEECH_MODELS_URL="https://models-speech.datalayer.tech",DATALAYER_VOICE_ENGINES={transformers:()=>__vitePreload(()=>import("./chunks/transformers.web-Br6X7w0a.js"),[],import.meta.url),vad:()=>__vitePreload(()=>import("./chunks/index-6MwCUMaU.js").then(Au=>Au.i),[],import.meta.url)};function chatVoiceOf(Au,lo,$u){if(!Au?.enabled||Au.input==="off"&&Au.output==="off")return;if(Au.output!=="off"&&!lo.speechUrl)throw new Error("Its answers are said by Datalayer’s speech service, and its host gave no address for it.");const Ru=Au.language||lo.language||"en-US";return{language:Ru,input:Au.input,output:Au.input==="hands_free"?"always":Au.output,voice:Au.voice||voiceFor(Ru)?.id||"",modelsUrl:lo.modelsUrl||DATALAYER_SPEECH_MODELS_URL,engines:DATALAYER_VOICE_ENGINES,speechUrl:lo.speechUrl,token:lo.token,consentKey:lo.consentKey,where:Au.where??"auto",...$u&&Au.input!=="off"?{keepsAudio:$u}:{}}}function voiceAskedAs(Au,lo){if(!Au)return;const $u=Au.token||lo;return $u?{...Au,token:$u}:{...Au}}const SILENCE_MS=1500;function settledVoice(Au,lo=heldVoiceSettings()){const $u=voiceForPerson(Au,lo),Ru=saneVoiceSettings(lo).pause??1,Iu=$u.output??"off";if(Iu!=="off"&&!$u.speechUrl)throw new Error(`A chat whose answers are heard (${Iu}) names the speech service: its speechUrl is missing.`);return{...$u,output:Iu,voice:$u.voice||voiceFor($u.language)?.id||"",modelsUrl:$u.modelsUrl||DATALAYER_SPEECH_MODELS_URL,engines:$u.engines??DATALAYER_VOICE_ENGINES,silenceMs:Math.round(($u.silenceMs??SILENCE_MS)*Ru),turnSilenceMs:Math.round(($u.turnSilenceMs??TURN_SILENCE_MS)*Ru)}}const SYNTHESES_PATH="/api/ai-agents/v1/speech/syntheses",STREAMED_SLICE_SECONDS=.25,SENTENCES_AHEAD=2,FIRST_CLAUSE_SPLIT_CHARS=60,SHORTEST_CLAUSE_CHARS=15;function firstClause(Au){if(Au.length<=FIRST_CLAUSE_SPLIT_CHARS)return[Au];const lo=/[,;:\u2013\u2014]\s+/g;let $u;for(;($u=lo.exec(Au))!==null;){const Ru=$u.index+1;if(Ru<SHORTEST_CLAUSE_CHARS)continue;const Iu=Au.slice($u.index+$u[0].length);if(Iu.length<SHORTEST_CLAUSE_CHARS)break;return[Au.slice(0,Ru),Iu]}return[Au]}class ServerSpeaker{constructor(lo){this.options=lo}options;context;analyser;gain;buffer;queue=[];playing;scheduled=[];running=!1;generation=0;state={speaking:!1};update(lo){this.options={...this.options,...lo}}unlock(){this.audio(),this.context?.resume()}audio(){return this.context||(this.context=new AudioContext,this.analyser=this.context.createAnalyser(),this.analyser.fftSize=512,this.gain=this.context.createGain(),this.analyser.connect(this.gain),this.gain.connect(this.context.destination),this.buffer=new Float32Array(this.analyser.fftSize)),this.context}level(){if(!this.analyser||!this.buffer||!this.state.speaking)return 0;this.analyser.getFloatTimeDomainData(this.buffer);let lo=0;for(const $u of this.buffer)lo+=$u*$u;return Math.min(1,Math.sqrt(lo/this.buffer.length)*6)}speed(){const lo=this.options.rate;return typeof lo=="number"&&Number.isFinite(lo)?Math.min(2,Math.max(.5,lo)):1}loudness(){const lo=this.options.volume;return typeof lo=="number"&&Number.isFinite(lo)?Math.min(1,Math.max(0,lo)):1}set(lo){this.state={...this.state,...lo},this.options.onState?.(this.state)}say(lo){const $u=lo.trim();if(!$u)return;const Ru=this.options.firstClauseFirst&&!this.options.streamed&&!this.queue.length&&!this.playing&&!this.running;for(const Iu of Ru?firstClause($u):[$u])this.queue.push({text:Iu,asked:performance.now()});this.state.speaking||this.set({speaking:!0,refused:void 0}),this.askAhead(),this.running||this.run(this.generation)}askAhead(){for(const lo of this.queue.slice(0,SENTENCES_AHEAD))lo.audio||(lo.audio=this.fetch(lo.text))}async fetch(lo){const{speechUrl:$u,voice:Ru,language:Iu,token:Pu,fetcher:Ou=fetch}=this.options;try{const Mu=await Ou(`${$u.replace(/\/+$/,"")}${SYNTHESES_PATH}`,{method:"POST",headers:{"Content-Type":"application/json",...Pu?{Authorization:`Bearer ${Pu}`}:{}},body:JSON.stringify({text:lo,voice:Ru,language:Iu,...this.options.streamed?{format:"pcm",stream:!0}:{format:"opus"}})});if(!Mu.ok){const Lu=await Mu.json().catch(()=>({}));return typeof Lu?.detail=="string"?Lu.detail:`The answer could not be spoken (${Mu.status}).`}const Du=Mu.headers.get("content-type")??"";return Du.toLowerCase().startsWith("audio/l16")?{kind:"pcm",rate:Number(Mu.headers.get("x-speech-rate"))||Number(/rate=(\d+)/i.exec(Du)?.[1])||24e3,body:Mu.body??await Mu.arrayBuffer()}:{kind:"whole",audio:await Mu.arrayBuffer()}}catch{return"Datalayer’s speech service could not be reached: the answer is still written here."}}async run(lo){this.running=!0;try{for(;this.queue.length&&lo===this.generation;){this.askAhead();const $u=this.queue[0],Ru=await $u.audio;if(lo!==this.generation)return;if(typeof Ru=="string"){this.queue=[],this.set({speaking:!1,sentence:void 0,refused:Ru});return}this.queue.shift(),this.askAhead();const Iu=this.audio();if(Ru.kind==="pcm"){await this.playStreamed(lo,$u,Ru);continue}const Pu=await Iu.decodeAudioData(Ru.audio);if(lo!==this.generation)return;await new Promise(Ou=>{const Mu=Iu.createBufferSource();Mu.buffer=Pu,Mu.playbackRate.value=this.speed(),this.gain&&(this.gain.gain.value=this.loudness()),Mu.connect(this.analyser),Mu.onended=()=>Ou(),this.playing=Mu,this.set({speaking:!0,sentence:$u.text,refused:void 0}),this.options.onFirstSound?.(Math.round(performance.now()-$u.asked)),Mu.start()}),this.playing=void 0}}finally{lo===this.generation&&(this.running=!1,this.state.speaking&&this.set({speaking:!1,sentence:void 0}))}}async playStreamed(lo,$u,Ru){const Iu=this.audio(),Pu=this.speed();this.gain&&(this.gain.gain.value=this.loudness());let Ou=0,Mu=!0,Du=new Uint8Array(0),Lu=Promise.resolve();const Bu=Math.round(Ru.rate*STREAMED_SLICE_SECONDS)*2,ju=zu=>{const Uu=new Float32Array(zu.length/2),Hu=new DataView(zu.buffer,zu.byteOffset,zu.length);for(let Wu=0;Wu<Uu.length;Wu++)Uu[Wu]=Hu.getInt16(Wu*2,!0)/32768;const Vu=Iu.createBuffer(1,Uu.length,Ru.rate);Vu.getChannelData(0).set(Uu);const Gu=Iu.createBufferSource();Gu.buffer=Vu,Gu.playbackRate.value=Pu,Gu.connect(this.analyser),Ou=Math.max(Ou,Iu.currentTime),Lu=new Promise(Wu=>{Gu.onended=()=>{this.scheduled=this.scheduled.filter(Zu=>Zu!==Gu),Wu()}}),this.scheduled.push(Gu),this.playing=Gu,Mu&&(Mu=!1,this.set({speaking:!0,sentence:$u.text,refused:void 0}),this.options.onFirstSound?.(Math.round(performance.now()-$u.asked))),Gu.start(Ou),Ou+=Vu.duration/Pu},Fu=(zu,Uu)=>{const Hu=new Uint8Array(Du.length+zu.length);for(Hu.set(Du),Hu.set(zu,Du.length),Du=Hu;Du.length>=Bu||Uu&&Du.length>=2;){const Vu=Math.min(Du.length,Math.max(Bu,2)),Gu=Vu-Vu%2;if(ju(Du.subarray(0,Gu)),Du=Du.slice(Gu),Uu&&Du.length<2)break}};if(Ru.body instanceof ArrayBuffer)Fu(new Uint8Array(Ru.body),!0);else{const zu=Ru.body.getReader();for(;;){const{done:Uu,value:Hu}=await zu.read();if(lo!==this.generation){zu.cancel().catch(()=>{});return}if(Uu){Fu(new Uint8Array(0),!0);break}Fu(Hu,!1)}}await Lu,this.playing=void 0}stop(){this.generation+=1,this.queue=[],this.running=!1;for(const lo of[...this.scheduled,...this.playing?[this.playing]:[]])try{lo.stop()}catch{}this.scheduled=[],this.playing=void 0,this.set({speaking:!1,sentence:void 0})}close(){this.stop(),this.context?.close(),this.context=void 0}}function useVoiceSpeaker(Au,lo=!0){const[$u,Ru]=reactExports.useState({speaking:!1}),Iu=lo&&!!Au&&Au.output!=="off"&&!!Au.speechUrl,Pu=reactExports.useMemo(()=>Iu&&Au?.speechUrl?new ServerSpeaker({speechUrl:Au.speechUrl,voice:Au.voice,language:Au.language,token:Au.token,rate:Au.rate,volume:Au.volume,onState:Ru,streamed:!0,firstClauseFirst:!0}):void 0,[Iu,Au?.speechUrl]);reactExports.useEffect(()=>{Pu?.update({voice:Au?.voice,language:Au?.language,token:Au?.token,rate:Au?.rate,volume:Au?.volume})},[Pu,Au?.voice,Au?.language,Au?.token,Au?.rate,Au?.volume]),reactExports.useEffect(()=>()=>Pu?.close(),[Pu]),reactExports.useEffect(()=>{if(!Pu)return;const Lu=()=>Pu.unlock();return window.addEventListener("pointerdown",Lu,{once:!0}),window.addEventListener("keydown",Lu,{once:!0}),()=>{window.removeEventListener("pointerdown",Lu),window.removeEventListener("keydown",Lu)}},[Pu]);const Ou=reactExports.useCallback(()=>Pu?.stop(),[Pu]),Mu=reactExports.useCallback(Lu=>{Pu&&readAloud(Pu,Lu)},[Pu]),Du=reactExports.useMemo(()=>Pu?()=>Pu.level():void 0,[Pu]);return{speaker:Pu,state:$u,stop:Ou,read:Mu,level:Du}}function answerText(Au){const lo=Au;if(!(!lo||lo.role!=="assistant"||typeof lo.toolName=="string")){if(typeof lo.content=="string")return lo.content;if(Array.isArray(lo.content))return lo.content.map($u=>$u&&typeof $u=="object"&&$u.type==="text"?String($u.text??""):"").join(" ")}}function useSpokenAnswers(Au,lo,$u,Ru){const Iu=reactExports.useRef(new Set),Pu=reactExports.useRef(void 0),Ou=reactExports.useRef(!1);reactExports.useEffect(()=>{if(!$u||!Ru){Ou.current=!1,Pu.current=void 0;return}const Mu=Au.map((Bu,ju)=>({id:String(Bu?.id??ju),text:answerText(Bu)})).filter(Bu=>Bu.text!==void 0);if(!Ou.current){Ou.current=!0,Mu.forEach(Bu=>Iu.current.add(Bu.id));return}const Du=Mu[Mu.length-1];if(!Du||Iu.current.has(Du.id)&&Pu.current?.id!==Du.id)return;Pu.current?.id!==Du.id&&(Iu.current.add(Du.id),Pu.current={id:Du.id,cutter:new SentenceCutter,ended:!1});const Lu=Pu.current;if(!Lu.ended){for(const Bu of Lu.cutter.feed(Du.text??""))Ru.say(Bu);if(!lo){for(const Bu of Lu.cutter.end(Du.text??""))Ru.say(Bu);Lu.ended=!0}}},[Au,lo,$u,Ru])}const SAID_HIGHLIGHT="voice-said",SAID_STYLE=`::highlight(${SAID_HIGHLIGHT}) {
3910
3910
  text-decoration: underline;
3911
3911
  text-decoration-thickness: 2px;
3912
3912
  text-underline-offset: 3px;
@@ -3914,7 +3914,7 @@ ${Pu}\`\`\``}),lo}function ChatMarkdown({text:Au,density:lo="comfortable"}){retu
3914
3914
  }`;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(`
3915
3915
 
3916
3916
  `)){const Ru=$u.split(`
3917
- `).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-qnhIdhNh.js"),[],import.meta.url).then(Au=>({default:Au.EphemeralDocument}))),loadAgentDetails=()=>__vitePreload(()=>import("./chunks/AgentDetails-hf2sunpH.js"),[],import.meta.url).then(Au=>({default:Au.AgentDetails})),loadEphemeralNotebook=()=>__vitePreload(()=>import("./chunks/EphemeralNotebook-Yi4YVrTs.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)}
3917
+ `).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-YiGgJGkL.js"),[],import.meta.url).then(Au=>({default:Au.EphemeralDocument}))),loadAgentDetails=()=>__vitePreload(()=>import("./chunks/AgentDetails-hf2sunpH.js"),[],import.meta.url).then(Au=>({default:Au.AgentDetails})),loadEphemeralNotebook=()=>__vitePreload(()=>import("./chunks/EphemeralNotebook-Yi4YVrTs.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)}
3918
3918
  ...`: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:Zu,disableReason:Ju,overlay:Yu,launching:Xu=!1,launchingMessage:ed,autoConnect:td=!0,codemodeEnabled:nd=!1,onToggleCodemode:od,initialModel:sd,availableModels:ad,mcpServers:pd,initialSkills:vd,className:Sd,loadingState:_d,headerActions:bd,kernelIndicatorState:wd,kernelIndicatorPlacement:Ad="left",kernelIndicatorPosition:gd="s",kernel:dd,kernelEnvironmentName:yd,kernelCpu:ld,kernelMemory:ud,kernelGpu:hd,themeVariant:md,colorMode:Ed,chatViewMode:Td,onChatViewModeChange:Rd,disabledViewModes:jd,useStore:Cd=!0,protocol:$d,onSendMessage:Id,onSendReady:Vd,onLoadingChange:Md,onSpeakingChange:Wd,onContextSnapshot:rh,enableStreaming:th=!1,brandIcon:Eh,avatarConfig:ah,headerButtons:yh,showPoweredBy:vh=!1,poweredByProps:Jd,emptyState:eh,renderHeader:ih,showTurnFooter:Mh=!0,renderMessageFooter:qd,notebookToolSurfacesId:zd,footerContent:Pd,welcome:Od,trailingContent:Gd,voice:Dd,voiceSpeaking:Kd=!1,voiceSentence:Xd,onStopSpeaking:hh,voiceLevel:_h,onReadAloud:Sh,showInformation:Zh=!1,onInformationClick:Nd,headerContent:xd,children:Hd,borderRadius:Zd,backgroundColor:ph,border:wh,boxShadow:Ch,compact:kh=!1,placeholder:$h,description:xh="Start a conversation with the AI agent.",onStateUpdate:Oh,onNewChat:Kh,onClear:Ph,onMessagesChange:rp,onItemsChange:sp,onDisplayItemsChange:hp,autoFocus:gp=!1,suggestions:Xh,submitOnSuggestionClick:_p=!0,hideMessagesAfterToolUI:ap=!1,focusTrigger:up,frontendTools:qh,enableEphemeralNotebook:Fh=!1,initialEphemeralNotebookOpen:Jh=!0,onEphemeralNotebookOpenChange:Of,enableEphemeralDocument:Ep=!1,initialEphemeralSurfaceMode:Rh,onEphemeralSurfaceModeChange:jh,collapsed:pf=!1,onExpandFromCollapsed:Bp,ephemeralNotebookToolbar:lf,ephemeralNotebookToolbarExtraItems:rf,ephemeralDocumentToolbarExtraItems:Qh,ephemeralNotebookCollaborationProvider:Jp,ephemeralNotebookCollaborationDocumentId:Mf,ephemeralDocumentCollaboration:om,ephemeralRuntimeOverride:$f,onToolCallStart:zf,onToolCallComplete:Kf,onToolCallUpdate:mp,inspector:Fp,onAuthorizationRequired:xp,connectedIdentities:Vp,runtimeId:Gp,thread:zp,historyEndpoint:nf,historyAuthToken:bp,pendingPrompt:Zf,contextSnapshot:vf,mcpStatusData:Cm,sandboxStatusData:Yf,showToolApprovalBanner:Om=!0,pendingApprovals:Up,onApproveApproval:mm,onRejectApproval:lm}){const wf=useChatWords();reactExports.useEffect(()=>{setupPrimerPortals()},[]);const Dh=useChatAvailability(),Ud=Zu??Dh.disabled,lh=Ju??Dh.disableReason,{theme:Nh}=useThemeStore(),Lh=getColorPalette(Nh,"dark").textLight,pp=useAgentRuntimeStore(Ld=>Ld.approvals),np=useAgentRuntimeStore(Ld=>Ld.historyVersion),Op=useAgentRuntimeStore(Ld=>Ld.mcpStatus),Sp=Cm??Op,ff=typeof $d=="object"?$d:void 0,Mp=useCoreStore(Ld=>Ld.configuration?.aiAgentsUrl),Hh=ff?.agentId||Gp,lp=Gp||Hh,im=ff?.authToken,Uf=reactExports.useRef(`ephemeral-notebook-${Math.random().toString(36).slice(2,10)}`),mf=Gp||ff?.agentId||Hh,Hf=Mf||(mf?`ephemeral-notebook-${mf}`:Uf.current),qm=useAgentRuntimeStore(Ld=>Ld.getEphemeralNotebookModel(Hf)),Vm=useAgentRuntimeStore(Ld=>Ld.setEphemeralNotebookModel),gm=reactExports.useCallback(Ld=>{Vm(Hf,Ld)},[Hf,Vm]),Ef=om?.roomId||(mf?`ephemeral-document-${mf}`:`ephemeral-document-${Uf.current}`),sm=useAgentRuntimeStore(Ld=>Ld.getEphemeralDocumentModel(Ef)),Df=useAgentRuntimeStore(Ld=>Ld.setEphemeralDocumentModel),Cf=reactExports.useCallback(Ld=>{Df(Ef,Ld)},[Ef,Df]),cm=Rh??(Fh&&Jh?"notebook":"none"),[yp,Jf]=reactExports.useState(cm),Xf=reactExports.useCallback(Ld=>{Jf(Ld),jh?.(Ld),Of?.(Ld==="notebook")},[jh,Of]),Vh=Fh&&yp==="notebook",Cp=Ep&&yp==="document",Wp=Vh||Cp,bf=Wp&&pf,_f=bf?{key:"ephemeral-surface",type:"custom",order:900,render:()=>jsxRuntimeExports.jsx(EphemeralSurfaceControl,{mode:yp,onChange:Xf,enableNotebook:Fh,enableDocument:Ep,enableChatOnly:!1})}:null,vm=_f?[...rf??[],_f]:rf,Qf=_f?[...Qh??[],_f]:Qh,[Tp,qf]=reactExports.useState(null);reactExports.useEffect(()=>{if(!Vh){qf(null);return}const Ld=()=>notebookStore.getState().selectNotebook(Hf)?.adapter?.kernel??null,Fd=()=>{const nh=Ld();qf(mh=>mh?.id===nh?.id?mh:nh)};Fd();const sh=window.setInterval(Fd,750),gh=notebookStore.subscribe(Fd);return()=>{window.clearInterval(sh),gh()}},[Vh,Hf]);const[Mm,cf]=reactExports.useState(null),Yh=reactExports.useCallback(Ld=>{cf(Fd=>Fd?.id===Ld?.id?Fd:Ld)},[]);reactExports.useEffect(()=>{Cp||cf(null)},[Cp]);const Dp=Wp&&isFloatingChatViewMode(Td),um=Td==="floating-small"||Td==="floating-draggable",of=useNotebookTools(Hf),[Tf,v0]=reactExports.useState([]),b0=reactExports.useCallback(Ld=>{v0(Ld)},[]),bm=reactExports.useMemo(()=>Vh?[...qh||[],...of]:Cp?[...qh||[],...Tf]:qh,[Vh,Cp,qh,of,Tf]),Tm=reactExports.useMemo(()=>normalizeAiAgentsBaseUrl(Mp||DEFAULT_SERVICE_URLS.AI_AGENTS),[Mp]),hg=reactExports.useRef(null),V0=reactExports.useRef(new Map),Zg=reactExports.useCallback((Ld,Fd,sh)=>{const gh=hg.current;if(!gh||gh.readyState!==WebSocket.OPEN)return logApprovalTrace("send_decision_skipped_ws_not_ready",{approvalId:Ld,approved:Fd,wsReadyState:gh?.readyState}),!1;try{return logApprovalTrace("send_decision",{approvalId:Ld,approved:Fd,hasNote:!!sh}),gh.send(JSON.stringify({type:"tool_approval_decision",approvalId:Ld,approved:Fd,...sh?{note:sh}:{}})),!0}catch{return logApprovalTrace("send_decision_failed",{approvalId:Ld,approved:Fd}),!1}},[]),Yg=reactExports.useCallback(()=>{const Ld=hg.current;if(!Ld||Ld.readyState!==WebSocket.OPEN)return!1;try{return Ld.send(JSON.stringify({type:"tool-approvals-history"})),logApprovalTrace("request_history",{}),!0}catch{return!1}},[]),y0=reactExports.useCallback(Ld=>{Ld&&(V0.current.set(Ld,Date.now()+RESOLVED_TOOL_CALL_SUPPRESSION_MS),logApprovalTrace("suppress_pending_for_tool_call",{toolCallId:Ld,windowMs:RESOLVED_TOOL_CALL_SUPPRESSION_MS}))},[]),F1=reactExports.useCallback(Ld=>{if(!Ld)return!1;const Fd=V0.current.get(Ld);return Fd?Fd<Date.now()?(V0.current.delete(Ld),!1):!0:!1},[]),Ag=reactExports.useCallback((Ld,Fd,sh)=>{window.setTimeout(()=>{if(!agentRuntimeStore.getState().approvals.some(mh=>mh.id===Ld&&mh.status==="pending"))return;const nh=Zg(Ld,Fd,sh);logApprovalTrace("retry_send_decision",{approvalId:Ld,approved:Fd,sent:nh}),nh&&Yg()},500)},[Yg,Zg]),S1=reactExports.useMemo(()=>Up||pp.filter(Ld=>Ld.status==="pending"&&isApprovalForAgent(Ld,Hh)).map(Ld=>({id:Ld.id,toolName:Ld.tool_name,toolDescription:Ld.note??void 0,args:Ld.tool_args??{},agentId:Ld.agent_id??"",requestedAt:Ld.created_at??new Date().toISOString()})),[Up,pp,Hh]),z1=reactExports.useCallback((Ld,Fd)=>{const sh=agentRuntimeStore.getState().approvals.find(Wh=>Wh.id===Ld),gh=sh?.tool_name;if(!gh)return;const mh=(()=>{if(gh.startsWith("skill:")){const Lp=gh.slice(6);return Lp?normalizeSkillApprovalId(Lp):null}if(!new Set(["run_skill_script","load_skill","read_skill_resource"]).has(gh))return null;const ip=sh?.tool_args??{},Gh=ip.skill_name??ip.skill??ip.name;return typeof Gh!="string"||!Gh?null:normalizeSkillApprovalId(Gh)})();if(mh){ym(ip=>{const Gh=new Map(ip);return Gh.set(mh,Fd),Gh}),agentRuntimeStore.getState().sendRawMessage({type:Fd?"skill_approve":"skill_unapprove",skillId:mh},Hh)||console.warn("[ChatBase] skill_approve persistence dropped: websocket not ready");return}const zh=gh.indexOf("__");if(zh!==-1){const Wh=gh.slice(0,zh),ip=gh.slice(zh+2);agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tool_approve",serverId:Wh,toolName:ip,approved:Fd},Hh)||console.warn("[ChatBase] mcp_server_tool_approve persistence dropped: websocket not ready")}},[Hh]),Jg=reactExports.useCallback(async(Ld,Fd,sh)=>{const nh=agentRuntimeStore.getState().approvals.find(Wh=>Wh.id===Ld)?.tool_call_id??sh;if(y0(nh),Up){await mm?.(Ld,Fd);return}const mh=Zg(Ld,!0,Fd);mh||console.warn("[ChatBase] ai-agents tool_approval_decision not sent: websocket not ready");const zh=agentRuntimeStore.getState().sendDecision(Ld,!0,Fd,nh,Hh);zh?z1(Ld,!0):console.warn("[ChatBase] tool_approval_decision dropped: websocket not ready"),(mh||zh)&&agentRuntimeStore.getState().removeApproval(Ld),Yg(),Ag(Ld,!0,Fd),await mm?.(Ld,Fd)},[Hh,y0,mm,Up,z1,Ag,Yg,Zg]),$g=reactExports.useCallback(async(Ld,Fd,sh)=>{const nh=agentRuntimeStore.getState().approvals.find(Wh=>Wh.id===Ld)?.tool_call_id??sh;if(y0(nh),Up){await lm?.(Ld,Fd);return}const mh=Zg(Ld,!1,Fd);mh||console.warn("[ChatBase] ai-agents tool_approval_decision not sent: websocket not ready");const zh=agentRuntimeStore.getState().sendDecision(Ld,!1,Fd,nh,Hh);zh||console.warn("[ChatBase] tool_approval_decision dropped: websocket not ready"),(mh||zh)&&agentRuntimeStore.getState().removeApproval(Ld),Yg(),Ag(Ld,!1,Fd),await lm?.(Ld,Fd)},[Hh,y0,lm,Up,Ag,Yg,Zg]),Dm=reactExports.useRef(null),pg=reactExports.useCallback(Ld=>{const Fd=agentRuntimeStore.getState(),sh=new Set([Ld.id]),nh=!!Ld.tool_name?approvalSignature(Ld.tool_name,Ld.tool_args??{}):null;for(const mh of Fd.approvals){if(mh.status!=="pending"||!isApprovalForAgent(mh,Hh))continue;if(mh.id===Ld.id){sh.add(mh.id);continue}if(Ld.tool_call_id&&mh.tool_call_id&&mh.tool_call_id===Ld.tool_call_id){sh.add(mh.id);continue}if(!nh||!mh.tool_name)continue;approvalSignature(mh.tool_name,mh.tool_args??{})===nh&&sh.add(mh.id)}for(const mh of sh)Fd.removeApproval(mh)},[Hh]);reactExports.useEffect(()=>{if(!Om||Up||!im)return;const Ld=toWsUrl(Tm,`${AI_AGENTS_API_PREFIX}/ws`,im);if(!Ld)return;let Fd=!1;const sh=new WebSocket(Ld);return hg.current=sh,sh.onopen=()=>{logApprovalTrace("ws_open_request_history",{activeAgentId:Hh}),sh.send(JSON.stringify({type:"tool-approvals-history"}))},sh.onmessage=gh=>{try{const nh=JSON.parse(String(gh.data)),mh=[],zh=typeof nh.type=="string"?nh.type:void 0,Wh=typeof nh.event=="string"?nh.event:void 0;if(zh==="tool-approvals-history"){const Lp=(nh.data&&typeof nh.data=="object"?nh.data:{}).approvals;if(Array.isArray(Lp))for(const Uh of Lp)Uh&&typeof Uh=="object"&&mh.push(Uh)}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 Lp=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:Lp}),mh.push(Lp&&typeof Gh.status!="string"?{...Gh,status:Lp}:Gh)}}if(mh.length===0)return;const ip=agentRuntimeStore.getState();for(const Gh of mh){let Lp=normalizeApprovalPayload(Gh);if(!Lp){const Rp=typeof Gh.id=="string"&&Gh.id||typeof Gh.approval_id=="string"&&Gh.approval_id||typeof Gh.approvalId=="string"&&Gh.approvalId||"",jp=typeof Gh.status=="string"&&Gh.status||"";if(Rp&&jp&&jp!=="pending"){const Qp=ip.approvals.find(Sm=>Sm.id===Rp);Qp&&(Lp={...Qp,status:jp})}}if(!Lp)continue;const Uh=Lp.agent_id||!Hh?Lp:{...Lp,agent_id:Hh};if(isApprovalForAgent(Uh,Hh)){if(Uh.status==="pending"&&F1(Uh.tool_call_id)){logApprovalTrace("drop_transient_pending",{approvalId:Uh.id,toolCallId:Uh.tool_call_id,status:Uh.status});continue}logApprovalTrace("apply_tool_approval_update",{approvalId:Uh.id,status:Uh.status,agentId:Uh.agent_id,activeAgentId:Hh}),Uh.status==="pending"?ip.upsertApproval(Uh):(pg(Uh),Dm.current?.(Uh,Uh.status==="approved",Uh.note??void 0))}}}catch{}},sh.onclose=()=>{Fd||(hg.current=null)},sh.onerror=()=>{hg.current=null},()=>{Fd=!0,hg.current=null,sh.close()}},[Om,Up,Tm,im,Hh,F1,pg]);const tp=typeof $d=="object"?$d:void 0,U1=tp?JSON.stringify(tp):"",H1="agent-runtimes",Vf=useChatStore(Ld=>Ld.clearMessages),Tv=tp?.type==="a2a",[Rg,_0]=reactExports.useState(()=>emptyConversation(BROWSER_LIMITS)),em=reactExports.useRef(Rg),G0=reactExports.useRef(!1),Rf=reactExports.useCallback(Ld=>{const Fd=Ld(em.current);Fd!==em.current&&(em.current=Fd,G0.current=!0,_0(Fd))},[]),[W0,K0]=reactExports.useState(emptyChatLayer),Ig=reactExports.useRef(W0),dm=reactExports.useCallback(Ld=>{const Fd=Ld(Ig.current);Fd!==Ig.current&&(Ig.current=Fd,K0(Fd))},[]),Gf=reactExports.useCallback(()=>{Rf(()=>emptyConversation(BROWSER_LIMITS)),dm(()=>emptyChatLayer())},[Rf,dm]),Xg=reactExports.useCallback(Ld=>{let Fd;try{Fd=reduceConversation(emptyConversation(BROWSER_LIMITS),snapshotOfMessages(Ld))}catch(gh){console.error("[ChatBase] Conversation not read again:",gh),Am(gh instanceof Error?gh:new Error(String(gh)));return}const sh=new Map;for(const gh of Ld){const{id:nh,role:mh,content:zh,toolCalls:Wh,...ip}=gh;sh.set(nh,ip)}dm(()=>({...emptyChatLayer(),extras:sh})),Rf(()=>Fd)},[Rf,dm]),hm=reactExports.useCallback(Ld=>Rf(Fd=>reduceConversation(Fd,Ld)),[Rf]),yf=reactExports.useCallback(Ld=>{const Fd=em.current.items.find(sh=>sh.kind==="tool"&&sh.id===Ld);return Fd&&Fd.kind==="tool"?toolCallOf(Fd):void 0},[]),Nm=reactExports.useCallback(()=>em.current.items.flatMap(Ld=>Ld.kind==="tool"?[toolCallOf(Ld)]:[]),[]),fg=reactExports.useRef(wf);fg.current=wf;const Qg=reactExports.useMemo(()=>conversationDrawer(Ld=>fg.current.error(Ld)),[]),Kp=reactExports.useMemo(()=>withToolSummaries(Qg(Rg,W0),bm),[Qg,Rg,W0,bm]),q1=reactExports.useRef(Kp);q1.current=Kp;const[km,Z0]=reactExports.useState(null),[Bh,Np]=reactExports.useState(!1),[Hp,Nf]=reactExports.useState(!1),[uf,ng]=reactExports.useState(),[mg,Lf]=reactExports.useState(!1),[og,Am]=reactExports.useState(null),[gg,Bf]=reactExports.useState("");reactExports.useEffect(()=>{if(!dd){ng(void 0);return}ng(dd.status);const Ld=(Fd,sh)=>{ng(sh)};return dd.statusChanged.connect(Ld),()=>{dd.statusChanged.disconnect(Ld)}},[dd]);const[vg,bg]=reactExports.useState(!lp),[V1,w1]=reactExports.useState(0),Y0=reactExports.useRef(new Map),E1=reactExports.useRef(emptyUiModel()),kv=reactExports.useRef(new Set),[Pg,Av]=reactExports.useState(!1),x0=reactExports.useRef(null),ig=Zf&&[Gp||nf||tp?.endpoint||tp?.agentId,Zf].filter(Boolean).join("::"),[yg,e0]=reactExports.useState(""),[t0,S0]=reactExports.useState(new Map),[pb,Og]=reactExports.useState(new Map),[dy,fb]=reactExports.useState([]),r0=useAgentRuntimeWsState(),G1=!!tp?.enableConfigQuery&&td,qp=useConfig(G1,tp?.configEndpoint,tp?.authToken,tp?.agentId),Mg=useSkills(G1&&Bu,tp?.configEndpoint,tp?.authToken),{enableSkill:w0,disableSkill:C1,approveSkill:W1,unapproveSkill:Gm}=useSkillActions(Hh),[T1,ym]=reactExports.useState(new Map);reactExports.useEffect(()=>{ym(new Map)},[Hh]);const _g=reactExports.useMemo(()=>{const Ld=new Set;for(const Fd of Mg.data?.skills??[])(Fd.status==="enabled"||Fd.status==="loaded")&&Ld.add(Fd.id);return Ld},[Mg.data]);reactExports.useEffect(()=>{if(!Hh||xm.current.has(Hh))return;const Ld=Mg.data?.skills??[];if(Ld.length===0)return;if(Ld.some(nh=>nh.status==="enabled"||nh.status==="loaded")){xm.current.add(Hh);return}const sh=Ld.filter(nh=>nh.status==="available").map(nh=>nh.id).filter(Boolean);if(sh.length===0){xm.current.add(Hh);return}sh.every(nh=>w0(nh))&&xm.current.add(Hh)},[Hh,Mg.data,w0]);const k1=reactExports.useMemo(()=>{const Ld=new Set;for(const Fd of Mg.data?.skills??[])Fd.approved===!0&&Ld.add(Fd.id);return T1.forEach((Fd,sh)=>{Fd?Ld.add(sh):Ld.delete(sh)}),Ld},[T1,Mg.data]),A1=reactExports.useMemo(()=>{const Ld=qp.data?.builtinTools??[],Fd=tp?.options?.frontendTools??[],sh=new Set(Ld.map(nh=>nh.name)),gh=[...bm??[],...Fd].filter(nh=>sh.has(nh.name)?!1:(sh.add(nh.name),!0)).map(nh=>({id:nh.name,name:nh.name}));return{runtime:Ld,frontend:gh}},[qp.data?.builtinTools,bm,tp?.options]),n0=reactExports.useMemo(()=>Vu??(Hh?[{id:Hh,name:Au||Hh,description:lo||xh}]:[]),[Vu,Hh,Au,lo,xh]),J0=typeof tp?.options?.model=="string"?(tp?.options).model:void 0,Lm=reactExports.useMemo(()=>{const Ld=ad||qp.data?.models||(qp.isError?[]:void 0);return offeredModels(Ld,()=>{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:J0?[{id:J0,name:J0,provider:"inference"}]:[]})},[ad,qp.data?.models,qp.isError,J0]),mb=reactExports.useMemo(()=>zu??n0.map(Ld=>({name:Ld.name,description:Ld.description,icon:Ld.icon,disabled:Ld.id===(Gu??n0[0]?.id),disabledReason:`You are already talking to ${Ld.name}`})),[zu,n0,Gu]),K1=useContextSnapshot(G1&&Ru,tp?.configEndpoint,tp?.agentId,tp?.authToken),X0=reactExports.useMemo(()=>tp?.enableConfigQuery?void 0:{totalTokens:km?.totalTokens??0,contextWindow:2e5,sumResponseInputTokens:km?.sessionInput??0,sumResponseOutputTokens:km?.sessionOutput??0,systemPromptTokens:0,userMessageTokens:0,assistantMessageTokens:0,toolTokens:0,toolCallTokens:0,toolReturnTokens:0,historyToolCallTokens:0,historyToolReturnTokens:0,currentToolCallTokens:0,currentToolReturnTokens:0,turnUsage:{inputTokens:km?.turnInput??0,outputTokens:km?.turnOutput??0,requests:0,toolCalls:0,toolNames:[],durationSeconds:0},sessionUsage:{inputTokens:km?.sessionInput??0,outputTokens:km?.sessionOutput??0,requests:0,toolCalls:0,turns:0,durationSeconds:0}},[km,tp?.enableConfigQuery]),gb=reactExports.useRef(Hh),$m=reactExports.useRef(null),E0=K1.data,xg=reactExports.useRef(E0);xg.current=E0,reactExports.useEffect(()=>{gb.current!==Hh&&(gb.current=Hh,Z0(null),$m.current=xg.current??null)},[Hh]);const vb=E0&&E0!==$m.current?E0:void 0,C0=vf??vb??X0;reactExports.useEffect(()=>{rh?.(C0)},[C0,rh]);const o0=useSandbox(G1&&$u&&!tp?.ownRoutesOnly,tp?.configEndpoint,tp?.authToken,tp?.agentId),_m=reactExports.useRef(null),$v=reactExports.useRef(null),Rm=reactExports.useRef(0),Rv=reactExports.useRef(new Set),xm=reactExports.useRef(new Set),T0=reactExports.useRef(new Set),Wm=reactExports.useRef(!1),Q0=reactExports.useRef(ap);Q0.current=ap;const sg=reactExports.useRef(zp?.id||generateMessageId()),Bm=reactExports.useRef(zp),jm=reactExports.useRef(zp?.messages.length?zp.id:null),Dg=reactExports.useCallback(()=>{const Ld=sg.current;jm.current!==Ld&&(jm.current=Ld,Bm.current?.onStarted?.(Ld))},[]),Im=reactExports.useRef(null),Pm=reactExports.useRef([]),ag=reactExports.useRef(new Set),Z1=tp?.uiSocket,$1=reactExports.useRef(tp?.authToken);$1.current=tp?.authToken;const R1=tp?.uiFiles,Y1=reactExports.useCallback(Ld=>R1?uploadFile(Ld,{url:R1,scope:sg.current,token:$1.current}):Promise.reject(new Error("This conversation takes no file.")),[R1]),kf=reactExports.useCallback(()=>{const Ld=Ig.current;return em.current.items.flatMap(Fd=>Fd.kind==="message"||Fd.kind==="error"?[{id:Fd.id,displays:Ld.displays.get(Fd.id),speaker:Ld.speakers.get(Fd.id)}]:[])},[]),Xp=reactExports.useCallback(Ld=>{const Fd=kf();let sh;try{sh=withUiOp(Fd,Ld)}catch(mh){console.error("[ChatBase] reactor.ui op not applied:",mh);return}const gh=new Set(sh.map(mh=>mh.id)),nh=Fd.filter(mh=>!gh.has(mh.id)).map(mh=>mh.id);dm(mh=>{const zh=new Map(mh.displays),Wh=new Map(mh.speakers);for(const ip of sh)ip.displays&&zh.set(ip.id,ip.displays),ip.speaker&&Wh.set(ip.id,ip.speaker);for(const ip of nh)zh.delete(ip),Wh.delete(ip);return{...mh,displays:zh,speakers:Wh}}),nh.length>0&&Rf(mh=>withoutItems(mh,nh))},[kf,dm,Rf]),kp=reactExports.useCallback((Ld,Fd)=>{if(Fd){if(Ld.op==="window")return;if((Ld.op==="show"||Ld.op==="ask")&&isStepDisplay(Ld.body)){ag.current.add(Ld.body.id);return}if((Ld.op==="patch"||Ld.op==="append")&&ag.current.has(Ld.id))return}let sh;try{sh=routeUiOp(Ld,E1.current,kv.current)}catch(nh){console.error("[ChatBase] reactor.ui op not applied:",nh);return}E1.current=sh.steps;const gh=sh.routed;if(gh.to==="window")tellLoopWindow(gh.data);else if(gh.to==="step"){const nh=gh.step;dm(mh=>{const zh=new Map(mh.steps.map(Gh=>[Gh.item.id,Gh.after])),Wh=em.current.items.at(-1)?.id??null,ip=withLoopStep(mh.steps.map(Gh=>Gh.item),nh);return{...mh,steps:ip.map(Gh=>({item:Gh,after:zh.has(Gh.id)?zh.get(Gh.id)??null:Wh}))}})}else if(gh.to==="element")kv.current.add(gh.change.id),applyLoopElement(gh.change);else if(placeable(kf(),gh.op))Xp(gh.op);else{const nh=gh.op.op==="show"||gh.op.op==="ask"?gh.op.body.data?.message_id:void 0;Fd&&typeof nh=="string"?(hm({type:"MESSAGE_SAID",messageId:nh,role:"assistant",text:"",streaming:!1}),Xp(gh.op)):Pm.current.push(gh.op)}},[Xp,kf,dm,hm]),Ng=reactExports.useRef(kp);Ng.current=kp,reactExports.useEffect(()=>{if(Pm.current.length===0)return;const Ld=Pm.current.splice(0);for(const Fd of Ld){if(!placeable(kf(),Fd)){Pm.current.push(Fd);continue}Xp(Fd)}},[Rg,Xp,kf]);const Fm=reactExports.useCallback(()=>{if(!Z1)return null;const Ld=sg.current,Fd=Im.current;if(Fd&&Fd.scope===Ld)return Fd.socket;Fd?.socket.close(),E1.current=emptyUiModel(),kv.current=new Set,Pm.current=[],ag.current=new Set;const sh=new UiSocket({url:Z1,scope:Ld,token:()=>$1.current??"",onOp:(gh,nh,mh)=>Ng.current(gh,mh),onStatus:(gh,nh)=>{(gh==="refused"||gh==="gone")&&console.error(`[ChatBase] ui socket ${gh}: ${nh??""}`)}});return Im.current={socket:sh,scope:Ld},sh.connect(),sh},[Z1]),I1=reactExports.useRef(Fm);I1.current=Fm,reactExports.useEffect(()=>(zp?.messages.length&&I1.current(),()=>{Im.current?.socket.close(),Im.current=null}),[]);const Sg=reactExports.useRef(null),Iv=reactExports.useRef(null),Lg=reactExports.useRef(null),Bg=reactExports.useRef(null),Km=reactExports.useRef(!1),J1=reactExports.useRef(Vp);J1.current=Vp;const k0=reactExports.useRef(bm);k0.current=bm;const X1=reactExports.useRef(zf);X1.current=zf;const i0=reactExports.useRef(Kf);i0.current=Kf;const lg=reactExports.useRef(mp);lg.current=mp;const s0=useAgentInspectorTracer(),zm=Fp??s0,Q1=reactExports.useRef("Agent");Q1.current=typeof Au=="string"&&Au||Hh||"Agent";const Zm=reactExports.useRef(null);zm&&Zm.current?.tracer!==zm?Zm.current={tracer:zm,recorder:chatSpanRecorder(zm,()=>Q1.current,{frontendTools:()=>(k0.current??[]).map(Ld=>Ld.name)})}:zm||(Zm.current=null);const jg=reactExports.useRef(""),P1=reactExports.useRef(void 0),Fg=reactExports.useRef(null);reactExports.useEffect(()=>{let Ld=agentRuntimeStore.getState().toolDecisionRequest?.seq??0;return agentRuntimeStore.subscribe(Fd=>Fd.toolDecisionRequest,Fd=>{if(!Fd||Fd.seq===Ld)return;Ld=Fd.seq;const sh=Fg.current;if(!sh)return;const gh=zh=>(zh??"").toLowerCase().replace(/[-_]/g,""),nh=Nm(),mh=nh.find(zh=>zh.result?.approvalId===Fd.approvalId)??nh.find(zh=>gh(zh.toolName)===gh(Fd.toolName)&&(zh.status==="executing"||zh.status==="inProgress"));mh&&sh(mh.toolCallId,{type:"tool-approval-decision",approved:Fd.approved,approvalId:Fd.approvalId,toolName:mh.toolName})})},[]);const Wf=reactExports.useCallback((Ld,Fd,sh)=>{if(!Ld?.id||Rv.current.has(Ld.id))return!1;let gh=Ld.tool_call_id;if(!gh)for(const mh of Nm()){if(mh.status!=="inProgress"&&mh.status!=="executing")continue;const zh=approvalSignature(mh.toolName,mh.args??{}),Wh=approvalSignature(Ld.tool_name,Ld.tool_args??{});if(zh===Wh){gh=mh.toolCallId;break}}if(!gh)return!1;const nh=yf(gh);return!nh||nh.status!=="inProgress"&&nh.status!=="executing"?!1:(Rv.current.add(Ld.id),Fg.current?.(gh,{type:"tool-approval-decision",approved:Fd,approvalId:Ld.id,toolName:Ld.tool_name||nh.toolName,_fromServerEcho:!0,_alreadyDispatched:!0,...sh?{message:sh}:{}}),!0)},[Hh]);Dm.current=Wf;const ev=!!(tp?.endpoint&&/\/api\/runtimes\/v1\/agent-nodes\/[^/]+\/ag-ui\/?$/.test(tp.endpoint)),Pv=tp?.configEndpoint?tp.configEndpoint.replace(/\/api\/v1\/(config|configure)\/?$/,""):tp?.endpoint?.replace(/\/api\/v1\/.*$/,"")??"";useAgentRuntimeWebSocket({enabled:!!tp&&!!Pv&&!ev&&!tp.ownRoutesOnly,baseUrl:Pv,authToken:tp?.authToken,agentId:tp?.agentId,onMessage:Ld=>{if(Ld.type!=="tool_approval_created"&&Ld.type!=="tool_approval_approved"&&Ld.type!=="tool_approval_rejected")return;const Fd=Ld.payload;if(Fd){if(Ld.type==="tool_approval_created"){isApprovalForAgent(Fd,Hh)&&agentRuntimeStore.getState().upsertApproval(Fd);return}pg(Fd),Wf(Fd,Ld.type==="tool_approval_approved",Fd.note??void 0)}}});const e1=reactExports.useCallback(Ld=>{if(!pd)return!0;const Fd=Ld.isConfig===!1?"catalog":"config";return pd.some(sh=>sh.id===Ld.id&&sh.origin===Fd)},[pd]);reactExports.useEffect(()=>{if(gp&&Lg.current){const Ld=setTimeout(()=>Lg.current?.focus(),100);return()=>clearTimeout(Ld)}},[gp]),reactExports.useEffect(()=>{if(up!==void 0&&up>0&&Lg.current){const Ld=setTimeout(()=>Lg.current?.focus(),150);return()=>clearTimeout(Ld)}},[up]);const bb=reactExports.useRef(!1);reactExports.useEffect(()=>{if(bb.current&&!Hp&&Lg.current){const Ld=setTimeout(()=>Lg.current?.focus(),50);return()=>clearTimeout(Ld)}bb.current=Hp},[Hp]);const tv=reactExports.useCallback(()=>{const Ld=Lg.current;if(Ld){Ld.style.height="auto";const Fd=120,gh=Math.min(Math.max(Ld.scrollHeight,40),Fd);Ld.style.height=`${gh}px`,Ld.style.overflowY=Ld.scrollHeight>Fd?"auto":"hidden"}},[]);reactExports.useEffect(()=>{tv()},[gg,tv]),reactExports.useEffect(()=>{const Ld=setTimeout(tv,0);return()=>clearTimeout(Ld)},[tv]),reactExports.useEffect(()=>{if(Lm.length===0||isOffered(Lm,yg))return;const Ld=initialModelId(Lm,sd||qp.data?.defaultModel||DEFAULT_MODEL);Ld&&Ld!==yg&&e0(Ld)},[Lm,yg,sd,qp.data?.defaultModel]);const If=reactExports.useRef(!1);reactExports.useEffect(()=>{if(Lm.length>0&&!If.current){If.current=!0;const Ld=qp.data?.builtinTools?.map(Fd=>Fd.id)||[];if(fb(Ld),qp.data?.mcpServers){const Fd=new Map;for(const sh of qp.data.mcpServers)if(sh.isAvailable&&sh.enabled&&e1(sh)){const nh=new Set(sh.tools.map(mh=>mh.name).filter(mh=>!!mh));Fd.set(sh.id,nh)}S0(Fd)}}},[qp.data,Lm,yg,sd,ad,pd,e1]),reactExports.useEffect(()=>{!qp.data?.mcpServers||!pd||S0(Ld=>{const Fd=new Map;for(const sh of qp.data?.mcpServers??[])if(e1(sh)&&Ld.has(sh.id)){const gh=Ld.get(sh.id);gh&&Fd.set(sh.id,gh)}else if(e1(sh)&&sh.isAvailable&&sh.enabled){const gh=new Set(sh.tools.map(nh=>nh.name).filter(nh=>!!nh));Fd.set(sh.id,gh)}return Fd})},[pd,qp.data?.mcpServers,e1]);const zg=reactExports.useRef(pd);zg.current=pd,reactExports.useEffect(()=>{const Ld=parseEnabledMcpToolsByServer(Sp);if(!Ld)return;const Fd=Hh||"__global__",sh=!T0.current.has(Fd)&&r0==="connected";S0(gh=>{const nh=new Map(gh);if(Ld.forEach((mh,zh)=>{(!zg.current||zg.current.some(ip=>ip.id===zh))&&mh.size!==0&&nh.set(zh,new Set(mh))}),sh){const mh=[];for(const Wh of qp.data?.mcpServers??[]){if(!(!zg.current||zg.current.some(Uh=>Uh.id===Wh.id))||!Wh.isAvailable||!Wh.enabled)continue;const Gh=Wh.tools.map(Uh=>Uh.name).filter(Uh=>!!Uh);if(Gh.length===0)continue;const Lp=nh.get(Wh.id);(!Lp||Lp.size===0)&&(nh.set(Wh.id,new Set(Gh)),mh.push({serverId:Wh.id,enabledToolNames:Gh}))}let zh=!0;for(const Wh of mh)agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tools_set",serverId:Wh.serverId,enabledToolNames:Wh.enabledToolNames},Hh)||(zh=!1,console.warn("[ChatBase] initial mcp_server_tools_set dropped: websocket not ready"));zh&&T0.current.add(Fd)}return nh})},[Sp,Hh,qp.data?.mcpServers,r0]),reactExports.useEffect(()=>{const Ld=parseApprovedMcpToolsByServer(Sp);Ld&&Og(()=>{const Fd=new Map;return Ld.forEach((sh,gh)=>{(!zg.current||zg.current.some(mh=>mh.id===gh))&&Fd.set(gh,new Set(sh))}),Fd})},[Sp]);const t1=reactExports.useRef("");reactExports.useEffect(()=>{const Ld=Sp?.servers;if(!Ld||Ld.length===0)return;const Fd=Ld.filter(mh=>mh.status==="started").map(mh=>mh.id).sort();if(Fd.length===0)return;const sh=qp.data?.mcpServers||[],gh=Fd.some(mh=>{const zh=sh.find(Wh=>Wh.id===mh);return!zh||zh.tools.length===0}),nh=Fd.join(",");gh&&nh!==t1.current&&qp.refetch&&(t1.current=nh,qp.refetch())},[Sp,qp]);const O1=reactExports.useCallback((Ld,Fd)=>{S0(sh=>{const gh=new Map(sh),nh=new Set(sh.get(Ld)||[]);return nh.has(Fd)?nh.delete(Fd):nh.add(Fd),gh.set(Ld,nh),agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tools_set",serverId:Ld,enabledToolNames:Array.from(nh)},Hh)||console.warn("[ChatBase] mcp_server_tools_set dropped: websocket not ready"),gh})},[Hh]),Ov=reactExports.useCallback((Ld,Fd,sh)=>{S0(gh=>{const nh=new Map(gh),mh=sh?new Set(Fd):new Set;return nh.set(Ld,mh),agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tools_set",serverId:Ld,enabledToolNames:Array.from(mh)},Hh)||console.warn("[ChatBase] mcp_server_tools_set dropped: websocket not ready"),nh})},[Hh]),r1=reactExports.useCallback(Ld=>{_g.has(Ld)?C1(Ld):w0(Ld)},[_g,w0,C1]),n1=reactExports.useCallback((Ld,Fd)=>{for(const sh of Ld)Fd?w0(sh):C1(sh)},[w0,C1]),hy=reactExports.useCallback((Ld,Fd)=>{Og(sh=>{const gh=new Map(sh),nh=new Set(sh.get(Ld)??[]),mh=nh.has(Fd);return mh?nh.delete(Fd):nh.add(Fd),gh.set(Ld,nh),agentRuntimeStore.getState().sendRawMessage({type:"mcp_server_tool_approve",serverId:Ld,toolName:Fd,approved:!mh},Hh)||console.warn("[ChatBase] mcp_server_tool_approve dropped: websocket not ready"),gh})},[Hh]),yb=reactExports.useCallback(Ld=>{k1.has(Ld)?(ym(Fd=>{const sh=new Map(Fd);return sh.set(Ld,!1),sh}),Gm(Ld)):(ym(Fd=>{const sh=new Map(Fd);return sh.set(Ld,!0),sh}),W1(Ld))},[k1,W1,Gm]),Mv=reactExports.useCallback(()=>{const Ld=[];return t0.forEach((Fd,sh)=>{(!pd||pd.some(gh=>gh.id===sh))&&Fd.forEach(gh=>Ld.push(gh))}),Ld},[t0,pd]),Dv=reactExports.useCallback(()=>Array.from(_g),[_g]);reactExports.useEffect(()=>{if(Cd&&!Gp){const Ld=useChatStore.getState().messages;Ld.length>0&&Xg(Ld)}},[Cd,Gp,Xg]);const a0=reactExports.useRef(void 0),rv=reactExports.useRef(0),o1=reactExports.useRef(!1),Nv=reactExports.useRef(null);reactExports.useEffect(()=>{if(lp!==a0.current&&(lp&&Y0.current.set(lp,0),a0.current=lp,Gf(),!lp)||!lp)return;const Ld=Bm.current;if(Ld){Nv.current!==Ld.id&&(Nv.current=Ld.id,useConversationStore.getState().setMessages(lp,Ld.messages),Xg(Ld.messages),useConversationStore.getState().markFetched(lp),bg(!0));return}np!==rv.current&&(rv.current=np,np>0&&(useConversationStore.getState().clearMessages(lp),Gf(),Y0.current.set(lp,0),o1.current=!0));const Fd=useConversationStore.getState(),sh=Fd.isFetching(lp),gh=Fd.getMessages(lp);if(gh.length>0&&(em.current.items.length===0&&Xg(gh),bg(!0)),sh)return;if(r0!=="connected"){gh.length===0&&bg(!1);return}Fd.setFetching(lp,!0);const nh=()=>extractChatMessagesFromFullContext(agentRuntimeStore.getState().fullContext),mh=jp=>{Fd.setMessages(lp,jp),Xg(jp),Y0.current.set(lp,0),Fd.markFetched(lp),bg(!0)},zh=o1.current?[]:nh();if(o1.current=!1,zh.length>0){mh(zh);return}const Wh=()=>{const jp=[Hh,ff?.agentId,Gp,lp,"default",void 0],Qp=new Set;for(const Sm of jp){const D0=typeof Sm=="string"?Sm.trim():void 0,uv=D0||"__global__";if(Qp.has(uv))continue;if(Qp.add(uv),agentRuntimeStore.getState().requestRefresh(D0))return!0}return!1};if(!Wh()){Fd.setFetching(lp,!1),gh.length===0&&bg(!1);return}let Gh=!1;const Lp=window.setTimeout(()=>{Gh||Wh()},500),Uh=agentRuntimeStore.subscribe(jp=>jp.fullContext,jp=>{if(Gh||!jp)return;const Qp=extractChatMessagesFromFullContext(jp);Gh=!0,Uh(),mh(Qp)}),Rp=window.setTimeout(()=>{if(Gh)return;Gh=!0,Uh(),Fd.setFetching(lp,!1),bg(gh.length>0);const jp=Y0.current.get(lp)??0;r0==="connected"&&jp<3?(Y0.current.set(lp,jp+1),Wh(),w1(Sm=>Sm+1)):bg(!0)},2e3);return()=>{window.clearTimeout(Lp),window.clearTimeout(Rp),Uh()}},[lp,nf,tp?.agentId,r0,Hh,V1,np,Gf,Xg]),reactExports.useEffect(()=>{if(lp&&Kp.length>0){const Ld=Kp.filter(Fd=>!isToolCallMessage(Fd));Ld.length>0&&useConversationStore.getState().setMessages(lp,Ld)}},[lp,Kp]),reactExports.useEffect(()=>{!Cd||!G0.current||useChatStore.getState().setMessages(Kp.filter(Ld=>!isToolCallMessage(Ld)))},[Cd,Kp]);const Ug=Kp.filter(Ld=>!isToolCallMessage(Ld)),nv=reactExports.useRef(0);reactExports.useEffect(()=>{const Ld=Ug.length;Ld!==nv.current&&(nv.current=Ld,rp?.(Ug))},[Kp,Ug,rp]),reactExports.useEffect(()=>{sp?.(Kp.filter(Ld=>!isToolCallMessage(Ld)))},[Kp,sp]),reactExports.useEffect(()=>{hp?.(Kp)},[Kp,hp]);const A0=kh?2:3,ov=reactExports.useMemo(()=>{if(tp?.configEndpoint)return{apiBaseUrl:getApiBaseFromConfig(tp.configEndpoint),authToken:tp.authToken}},[tp?.configEndpoint,tp?.authToken]),xb={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",...ah};reactExports.useEffect(()=>{if(!tp||!td||Ud)return;const Ld=createProtocolAdapter(tp);if(Ld)return _m.current=Ld,Av(!0),$v.current=Ld.subscribe(Fd=>{if(I1.current(),Km.current&&Fd.type!=="state-update"&&Fd.type!=="error"&&Fd.type!=="done")return;const sh=()=>{try{const nh=conversationEventsOf(Fd,em.current);Rf(mh=>nh.reduce((zh,Wh)=>reduceConversation(zh,Wh),mh))}catch(nh){console.error("[ChatBase] Protocol event not read:",nh),Am(nh instanceof Error?nh:new Error(String(nh)))}},gh=()=>{const nh=em.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"||hm({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(),mh=Math.max(0,Fd.usage.promptTokens??0),zh=Math.max(0,Fd.usage.completionTokens??0),Wh=Math.max(mh+zh,Fd.usage.totalTokens??0),ip=agentRuntimeStore.getState();ip.appendLocalTokenTurn({serviceName:H1,agentId:tp?.agentId,timestampMs:nh,promptTokens:mh,completionTokens:zh,totalTokens:Wh});const Gh=ip.costUsage?.cumulativeCostUsd;typeof Gh=="number"&&Number.isFinite(Gh)&&ip.upsertLocalCostPoint({serviceName:H1,agentId:tp?.agentId,timestampMs:nh,cumulativeUsd:Math.max(0,Gh)})}if(Wm.current)break;if(Fd.message){const nh=Fd.message.content;typeof nh=="string"&&nh&&(jg.current=sanitizeAssistantContent(nh)),sh()}break;case"tool-call":if(Fd.toolCall&&!Km.current){const nh=Fd.toolCall.toolCallId,mh=Fd.toolCall.toolName,zh=Fd.toolCall.args||{},Wh=Fd.toolCall.argsComplete,ip=yf(nh);sh();const Gh=yf(nh);if(!Gh)break;const Lp=k0.current?.find(Rp=>Rp.name===mh),Uh=Lp?.handler;ip?Uh&&ip.status==="executing"&&(Wh??Object.keys(zh).length>0)&&(Rm.current++,Lv(Uh,Gh,nh)):(X1.current?.({toolName:mh,toolCallId:nh,args:zh}),Zm.current?.recorder.toolStarted({id:nh,name:mh,args:zh}),Uh&&(Wh??(Object.keys(zh).length>0||!frontendToolExpectsArgs(Lp)))&&(Rm.current++,Lv(Uh,Gh,nh)))}break;case"tool-result":if(Fd.toolResult){const nh=Fd.toolResult.toolCallId??"",mh=yf(nh);sh();const zh=yf(nh);mh&&zh&&(Zm.current?.recorder.toolEnded(nh,{result:Fd.toolResult.result,error:Fd.toolResult.error??(zh.status==="error"?zh.executionError??"failed":void 0)}),i0.current?.({toolName:mh.toolName,toolCallId:nh,args:mh.args,result:Fd.toolResult.result,status:zh.status,error:Fd.toolResult.error}))}break;case"state-update":Oh?.(Fd.data),sh();break;case"activity":if(Fd.activity&&P1.current?.(Fd.activity),sh(),Fd.activity?.type===HARNESS_TOOL_CALL&&lg.current){const nh=Fd.activity.data,mh=nh&&typeof nh=="object"&&"id"in nh?String(nh.id??""):"",zh=em.current.items.find(Wh=>Wh.kind==="tool"&&Wh.id===mh);zh&&zh.kind==="tool"&&zh.display&&lg.current({toolName:zh.name,toolCallId:mh,args:zh.input??{},display:zh.display})}break;case"done":{Zm.current?.recorder.turnEnded({text:jg.current||void 0,usage:Fd.usage}),jg.current="";const nh=Fd.usage?.promptTokens??0,mh=Fd.usage?.completionTokens??0,zh=Fd.usage?.totalTokens??nh+mh;zh>0&&Z0(Wh=>({turnInput:nh,turnOutput:mh,sessionInput:(Wh?.sessionInput??0)+nh,sessionOutput:(Wh?.sessionOutput??0)+mh,totalTokens:zh}))}Wm.current&&Q0.current&&gh(),Km.current||sh(),Wm.current=!1,Rm.current=0,Nf(!1),Lf(!1),agentRuntimeStore.getState().requestRefresh(Hh);break;case"error":console.error("[ChatBase] Protocol error:",Fd.error),Zm.current?.recorder.turnEnded({error:Fd.error?.message??"error"}),Fd.error?.message&&/exceeded maximum retries/i.test(Fd.error.message)&&Q0.current&&gh(),sh(),Wm.current=!1,Am(Fd.error||new Error("Unknown error")),Rm.current=0,Nf(!1),Lf(!1),agentRuntimeStore.getState().requestRefresh(Hh);break;default:sh();break}}),Ld.connect().catch(console.error),()=>{$v.current?.(),_m.current?.disconnect()}},[U1,Oh,Cd,td]);function Lv(Ld,Fd,sh){(async()=>{if(Km.current){Rm.current--,Rm.current<0&&(Rm.current=0);return}try{const gh=await Ld(Fd.args);_m.current&&await _m.current.sendToolResult(sh,{toolCallId:sh,success:!0,result:gh}),Zm.current?.recorder.toolEnded(sh,{result:gh}),hm({type:"TOOL_CALL_DONE",toolCallId:sh,success:!0,result:gh})}catch(gh){console.error("[ChatBase] Frontend tool execution error:",gh),Zm.current?.recorder.toolEnded(sh,{error:gh.message}),hm({type:"TOOL_CALL_DONE",toolCallId:sh,success:!1,error:gh.message})}finally{Rm.current--,Rm.current<0&&(Rm.current=0)}})()}reactExports.useEffect(()=>{const Ld=Sg.current;if(Ld){Ld.scrollTo({top:Ld.scrollHeight,behavior:"smooth"});return}Iv.current?.scrollIntoView({behavior:"smooth"})},[Kp]);const Hg=reactExports.useRef(void 0),[l0]=useVoiceSettings(),$0=reactExports.useMemo(()=>Dd?settledVoice(Dd,l0):void 0,[Dd,l0]),[Sb,i1]=reactExports.useState(!1),qg=!!(Sh||hh),pm=useVoiceSpeaker($0,!qg);useSpokenAnswers(Kp,Hp,!qg&&$0?.output==="always",pm.speaker);const R0=Kd||pm.state.speaking,M1=qg?Xd:pm.state.sentence,Bv=reactExports.useRef(null);useSaidSentence(Bv,M1,Kp);const[c0,jv]=reactExports.useState("");P1.current=Ld=>{if(isVoiceInterrupted(Ld)){hh?hh():pm.speaker&&pm.stop();return}const Fd=lineToSay(Ld);Fd&&(jv(Fd),$0?.output==="always"&&(Sh?Sh(Fd):pm.speaker?.say(Fd)))},reactExports.useEffect(()=>{Hp||jv("")},[Hp]);const[Vg,Fv]=reactExports.useState(()=>new Set),iv=reactExports.useRef([]),wg=reactExports.useCallback(()=>{const Ld=answerSpokenOver(iv.current.filter(Fd=>!isToolCallMessage(Fd)));Ld&&Fv(Fd=>new Set([...Fd,Ld]))},[]),Eg=hh??(pm.speaker?pm.stop:void 0),I0=qg?_h:pm.level,s1=Sh??(pm.speaker?pm.read:void 0),Ym=reactExports.useCallback(async(Ld,Fd,sh)=>{const gh=(Ld??gg).trim();if(!gh||Hp||!_m.current&&!Id)return;if(Fd&&namesFiles(Fd))try{Fd=await withUploadedFiles(Fd,Y1)}catch(Uh){Am(Uh instanceof Error?Uh:new Error(String(Uh)));return}const nh=displayPressOf(Fd);if(nh&&Fd){const Uh=Im.current?.socket;if(!Uh){Am(new Error("This conversation’s ui channel is not open."));return}try{const Rp=await Uh.act(nh);if(!Rp.ok){Am(new Error(Rp.detail||`The press was refused (${Rp.status}).`));return}Fd=withPress(Fd,Rp.value)}catch(Rp){Am(Rp instanceof Error?Rp:new Error(String(Rp)));return}}Km.current=!1,jg.current="",Zm.current?.recorder.turnStarted(gh,yg||void 0),Wm.current=isToolCallOnlyPrompt(gh);const mh=sh??spokenOf(Fd?.voice)??(Ld===void 0?Hg.current:void 0);Hg.current=void 0;const zh=mh?{...Fd??{},voice:mh}:Fd;let Wh;if(mh){const{sound:Uh,...Rp}=mh;Wh=Rp}const ip=createUserMessage(gh,Wh?{...Wh}:void 0),Lp=[...Kp.filter(Uh=>!isToolCallMessage(Uh)),ip];{const{id:Uh,role:Rp,content:jp,...Qp}=ip;dm(Sm=>({...Sm,extras:new Map(Sm.extras).set(Uh,Qp)}))}Rf(Uh=>reduceConversation(withPrompt(Uh,ip.id,gh),{type:"RUN_STARTED"})),Bf(""),Nf(!0),Lf(!0),Am(null);try{if(Id)if(th){const Uh=generateMessageId(),Rp=(jp,Qp)=>hm({type:"MESSAGE_SAID",messageId:Uh,role:"assistant",text:jp,streaming:Qp});Rp("",!0),Cd&&useChatStore.getState().startStreaming(Uh),Bg.current=new AbortController,await Id(gh,Lp,{onChunk:jp=>{hm({type:"TEXT_MESSAGE_CONTENT",messageId:Uh,delta:jp})},onComplete:jp=>{Rp(jp,!1),Cd&&useChatStore.getState().stopStreaming()},onError:jp=>{Rp(wf.error(jp.message),!1),Cd&&useChatStore.getState().stopStreaming(),Am(jp)},signal:Bg.current.signal})}else{const Uh=await Id(gh,Lp);Uh&&hm({type:"MESSAGE_SAID",messageId:generateMessageId(),role:"assistant",text:Uh,streaming:!1})}else if(_m.current){const Uh=(bm||[]).map(Qp=>({name:Qp.name,description:Qp.description,parameters:Qp.parameters||{type:"object",properties:{}}}));console.warn("[ChatBase] frontendTools count:",bm?.length??0,"toolsForRequest:",Uh.map(Qp=>Qp.name));const Rp=Mv(),jp=Dv();Dg(),await _m.current.sendMessage(ip,{threadId:sg.current,messages:Lp,...yg&&{model:yg},tools:Uh,builtinTools:Rp,skills:jp,identities:J1.current,...zh?{forwardedProps:zh}:{}})}}catch(Uh){Uh.name!=="AbortError"&&(console.error("[ChatBase] Send error:",Uh),Rf(Rp=>withError(Rp,Uh.message)),Am(Uh))}finally{_m.current||(em.current.running&&hm({type:"RUN_FINISHED"}),Nf(!1),Lf(!1),agentRuntimeStore.getState().requestRefresh(Hh)),Wm.current=!1,Bg.current=null}},[gg,Hp,Kp,yg,bm,Cd,Id,Hh,th,Mv,Dv,Dg,wf,Y1,Rf,dm,hm]);reactExports.useEffect(()=>{if(!Zf||ig&&x0.current===ig)return;if(ig&&sentPendingPromptKeys.has(ig)){x0.current=ig;return}!vg&&!(!lp||r0!=="connected")||!Pg&&!Id||(x0.current=ig??null,ig&&sentPendingPromptKeys.add(ig),queueMicrotask(()=>Ym(Zf)))},[Zf,ig,vg,lp,r0,Pg,Ym,Id,Wf]);const u0=reactExports.useCallback(Ld=>{Km.current=!0,Bg.current?.abort();const Fd=_m.current;Fd&&(typeof Fd.stopGeneration=="function"&&Fd.stopGeneration(),Ld&&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")),Cd&&useChatStore.getState().stopStreaming(),Rm.current=0,Nf(!1),Lf(!1),agentRuntimeStore.getState().requestRefresh(Hh),agentRuntimeStore.getState().stopSubagentActivity(),Wm.current=!1,o0.interrupt(),dd&&dd.interrupt().catch(()=>{})},[dd,Cd,Hh,tp?.configEndpoint,tp?.authToken,tp?.agentId]),P0=reactExports.useCallback(()=>u0(!1),[u0]),sv=reactExports.useCallback(()=>u0(!0),[u0]),wb=reactExports.useCallback(Ld=>async Fd=>{const sh=Ld.actions?.find(mh=>mh.name===Fd.action);if(!sh)throw new Error(`“${Fd.action}” was not offered here.`);const gh=Fd.payload?.value,nh=Fd.action===ANSWER_ACTION?typeof gh=="string"?gh:isFileRef(gh)?gh.name:"Answered.":Fd.action;await Ym(nh,{loop:{action:{name:Fd.action,display_id:Ld.id,token:sh.token,payload:Fd.payload??{}}}})},[Ym]),d0=reactExports.useCallback(()=>{Gf(),Rm.current=0,Bf(""),sg.current=generateMessageId(),Cd&&Vf(),lp&&useConversationStore.getState().clearMessages(lp),Kh?.(),yh?.onNewChat?.()},[Vf,Kh,yh,Cd,Gp,Gf]);reactExports.useEffect(()=>{if(Vd){if(!Pg&&!Id){Vd(null);return}return Vd({send:(Ld,Fd)=>{Ym(Ld,Fd)},stop:P0,newChat:d0,thread:()=>sg.current,stopSpeaking:Eg,voiceLevel:I0,markInterrupted:wg,interrupt:sv}),()=>{Vd(null)}}},[Vd,Pg,Id,Ym,P0,sv,d0,Eg,I0,wg]),reactExports.useEffect(()=>{Md?.(Hp)},[Md,Hp]),reactExports.useEffect(()=>{Wd?.(R0)},[Wd,R0]);const av=reactExports.useCallback(()=>{window.confirm("Clear all messages?")&&(Gf(),Cd&&Vf(),lp&&useConversationStore.getState().clearMessages(lp),Ph?.(),yh?.onClear?.())},[Vf,Ph,yh,Cd,Gp,Gf]),Eb=reactExports.useCallback(Ld=>{const Fd=new Set(Ld),sh=q1.current.filter(gh=>Fd.has(gh.id)).map(rowIdOf);Rf(gh=>withoutItems(gh,sh)),dm(gh=>gh.steps.some(nh=>Fd.has(nh.item.id))?{...gh,steps:gh.steps.filter(nh=>!Fd.has(nh.item.id))}:gh)},[Rf,dm]),lv=reactExports.useCallback(async(Ld,Fd)=>{const sh=yf(Ld);if(sh&&(sh.status==="executing"||sh.status==="inProgress")){if(!!Fd&&typeof Fd=="object"&&Fd.type==="tool-approval-decision"&&typeof Fd.approved=="boolean"&&_m.current){const nh=Fd,mh=!!nh.approved,zh=nh._fromServerEcho===!0,Wh=nh._alreadyDispatched===!0,ip=sh.status==="inProgress",Gh=typeof nh.toolName=="string"?nh.toolName:sh.toolName,Lp=Gh.includes("__");if(mh){const Uh=Gh.indexOf("__");if(Uh!==-1){const Rp=Gh.slice(0,Uh),jp=Gh.slice(Uh+2);Og(Qp=>{const Sm=new Map(Qp),D0=new Set(Qp.get(Rp)??[]);return D0.add(jp),Sm.set(Rp,D0),Sm})}}try{const Uh=typeof Fd=="object"&&Fd!==null&&typeof Fd.approvalId=="string"?Fd.approvalId:void 0;if(!zh&&!ip){Uh&&(mh?await Jg?.(Uh,void 0,Ld):await $g?.(Uh,void 0,Ld));return}if(Uh&&!Wh&&(mh?await Jg?.(Uh,void 0,Ld):await $g?.(Uh,void 0,Ld)),Lp&&!ip)return;Rf(Rp=>reduceConversation(reduceConversation(Rp,{type:"TOOL_CALL_DONE",toolCallId:Ld,success:mh,result:Fd,answered:!0,...mh?{}:{error:"Tool approval rejected by user"}}),{type:"RUN_STARTED"})),Nf(!0),Lf(!0),await _m.current.sendToolResult(Ld,{toolCallId:Ld,success:mh,result:mh?{approved:!0,message:"Tool call approved by user.",...Uh?{approvalId:Uh}:{}}:{approved:!1,message:"Tool call rejected by user.",...Uh?{approvalId:Uh}:{}},...mh?{}:{error:"Tool approval rejected by user"}})}catch(Uh){console.error("[ChatBase] Approval continuation error:",Uh),Am(Uh)}return}if(hm({type:"TOOL_CALL_DONE",toolCallId:Ld,success:!0,result:Fd,answered:!0}),_m.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(ip=>ip.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 mh={id:generateMessageId(),role:"user",content:nh,createdAt:new Date};Nf(!0),Lf(!0),hm({type:"RUN_STARTED"});try{const zh=Kp.filter(Wh=>!isToolCallMessage(Wh));await _m.current.sendMessage(mh,{threadId:sg.current,messages:[...zh,mh]})}catch(zh){console.error("[ChatBase] HITL respond error:",zh)}}}},[Kp,Jg,$g,yf,Rf,hm]);Fg.current=lv;const zv=reactExports.useCallback(Ld=>{Ym(Ld.message)},[Ym]),Um=reactExports.useCallback(Ld=>{Bf(Ld),setTimeout(()=>Lg.current?.focus(),0)},[]),Jm=reactExports.useCallback(async(Ld,Fd)=>{await Jg?.(Ld,Fd)},[Jg]),h0=reactExports.useCallback(async(Ld,Fd)=>{await $g?.(Ld,Fd)},[$g]),D1=(qp.data?.mcpServers||[]).filter(Ld=>!pd||e1(Ld)),Uv=reactExports.useMemo(()=>{const Ld=D1.map(sh=>{const gh=Sp?.servers?.find(nh=>nh.id===sh.id);if(gh&&gh.status==="started"){const nh={};if(sh.isAvailable||(nh.isAvailable=!0),gh.tools&&gh.tools.length>0&&(nh.tools=gh.tools.map(mh=>({name:mh.name,description:mh.description||"",enabled:mh.enabled??!0}))),Object.keys(nh).length>0)return{...sh,...nh}}return sh}),Fd=new Set(D1.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))&&Ld.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 Ld},[D1,Sp,pd]),p0=tp?.configEndpoint?tp.configEndpoint.replace(/\/api\/v1\/(config|configure)\/?$/,""):void 0,Hm=!tp||!tp.enableConfigQuery||!!qp.data||!!Mg.data,Pf=xh||qp.data?.welcomeMessage||"",a1=qp.data?.suggestions,Cg=Xh&&Xh.length>0?Xh:Array.isArray(a1)&&a1.length>0?a1.map(Ld=>{if(typeof Ld=="string"){const gh=Ld.trim();return{title:gh,message:gh}}const Fd=(Ld?.text??"").trim();return{title:(Ld?.summary??"").trim()||Fd,message:Fd}}).filter(Ld=>Ld.message):void 0,vp=Od?[{id:"__welcome__",role:"assistant",content:Od,createdAt:WELCOME_AT},...Kp]:Kp;iv.current=vp;const tf=saidMessageId(vp,M1),jf=Hp||mg?[...vp].reverse().find(Ld=>!isToolCallMessage(Ld)&&Ld.role==="assistant")?.id:void 0,cv=s1||Vg.size||qd?(Ld,Fd)=>{const sh=getMessageText(Ld),gh=qd?.(Ld,Fd)??null,nh=Vg.has(Ld.id),mh=!!(s1&&readsAloud(Ld,sh,jf));return!gh&&!nh&&!mh?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[nh?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",fontStyle:"italic"},"data-interrupted":"",children:"interrupted"}):null,mh&&s1?jsxRuntimeExports.jsx(ReadAloud,{onRead:()=>s1(sh)}):null,gh]})}:void 0,O0=Hd||jsxRuntimeExports.jsxs(Box,{ref:Bv,display:"flex",flexDirection:"column",minHeight:0,width:"100%",maxWidth:920,mx:"auto",bg:"canvas.default",children:[jsxRuntimeExports.jsx(ChatMessageList,{displayItems:vp,actOn:tp?.uiSocket?wb:void 0,upload:tp?.uiFiles?Y1:void 0,isLoading:Hp,isStreaming:mg,showLoadingIndicator:Pu,hideMessagesAfterToolUI:ap,avatarConfig:xb,padding:A0,notebookToolSurfacesId:zd,approvalConfig:ov,messagesEndRef:Iv,onRespond:lv,showTurnFooters:Mh,renderMessageFooter:cv,saidMessageId:tf,agentUsage:C0,onRemoveItems:Eb,mcpServers:Uv,emptyContent:Xu?null:jsxRuntimeExports.jsx(ChatEmptyState,{emptyState:eh,brandIcon:Eh,description:Pf,suggestions:Cg,submitOnSuggestionClick:_p,onSuggestionSubmit:zv,onSuggestionFill:Um})}),Gd]}),f0=$0&&$0.input!=="off"?jsxRuntimeExports.jsx(ComposerVoice,{voice:$0,input:gg,setInput:Bf,disabled:Ud||Xu,speaking:R0,onStopSpeaking:Eg,playbackLevel:I0,running:Hp,onStopRun:sv,onInterrupted:wg,onInterimChange:i1,answers:!!(Dd?.output&&Dd.output!=="off"&&Dd.speechUrl),onSpoken:Ld=>{Hg.current=Ld},send:(Ld,Fd)=>{Ym(Ld,void 0,Fd)}}):void 0,N1=!qg&&pm.state.refused?jsxRuntimeExports.jsx(Text$3,{role:"alert",sx:{fontSize:0,color:"danger.fg",maxWidth:260},"data-voice-refused":"",children:pm.state.refused}):null,l1=c0?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"}),c0]}):null,M0=Mu?jsxRuntimeExports.jsx(InputPrompt,{footerExtras:N1||l1?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[l1,N1,f0]}):f0,interim:Sb,input:gg,setInput:Bf,isLoading:Hp,kernelStatus:uf,connectionConfirmed:Hm,placeholder:$h,typingSuggestions:Cg?.map(Ld=>Ld.message||Ld.title),autoFocus:gp,focusTrigger:up,padding:A0,onSend:()=>Ym(),onStop:P0,disableInputPrompt:ju||Ud||!!Yu||Xu,promptVariant:Fu,mentionableAgents:mb,promptCommands:Uu,promptHistory:qp.data?.promptHistory?.map(askedOf),showTokenUsage:Ru,showContextRing:Iu,agentUsage:C0,showModelSelector:Du,showToolsMenu:Lu,showSkillsMenu:Bu,codemodeEnabled:nd,onToggleCodemode:od,isA2AProtocol:Tv,showAgentsMenu:Hu,agents:n0,selectedAgentId:Gu??n0[0]?.id,onSelectAgent:Wu,hasConfigData:!!qp.data,hasSkillsData:!!Mg.data,configLoading:qp.isLoading,models:Lm,decisions:qp.data?{models:qp.data.decisionModels,note:qp.data.decisionsNote}:void 0,selectedModel:yg,onModelSelect:e0,availableTools:A1.runtime,availableFrontendTools:A1.frontend,mcpServers:Uv,enabledMcpTools:t0,enabledMcpToolCount:Mv().length,onToggleMcpTool:O1,onToggleAllMcpServerTools:Ov,approvedMcpTools:pb,onToggleMcpToolApproval:hy,skills:Mg.data?.skills||[],skillsLoading:!1,enabledSkills:_g,onToggleSkill:r1,onToggleAllSkills:n1,approvedSkills:k1,onToggleSkillApproval:yb,apiBase:p0,authToken:tp?.authToken,mcpStatusData:Sp}):null,Cb={title:Au,subtitle:lo,disableReason:Ud?lh:void 0,brandIcon:Eh,headerContent:xd,headerActions:bd,showInformation:Zh,onInformationClick:Nd??(()=>Np(!0)),padding:A0,kernelIndicatorState:wd,kernelIndicatorPlacement:Ad,kernelIndicatorPosition:gd,runtimeStatus:Yf??o0.data,kernel:Vh?Tp??dd:Cp?Mm??dd:dd,kernelEnvironmentName:yd,kernelCpu:ld,kernelMemory:ud,kernelGpu:hd,headerButtons:yh,messageCount:Ug.length,onNewChat:d0,onClear:av,chatViewMode:Td,onChatViewModeChange:Rd,disabledViewModes:jd,showEphemeralSurfaceControl:Fh||Ep,enableEphemeralNotebookOption:Fh,enableEphemeralDocumentOption:Ep,ephemeralSurfaceMode:yp,onEphemeralSurfaceModeChange:Xf},xf=$u?ih?ih(Cb):jsxRuntimeExports.jsx(ChatBaseHeader,{...Cb}):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:ph||"canvas.default",borderRadius:Zd,border:wh,boxShadow:Ch,overflow:"hidden",children:[!Wp&&xf,Bh&&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:Eh,protocol:tp?.type??"unknown",url:tp?.endpoint||"",messageCount:Kp.length,agentId:Hh,apiBase:tp?.configEndpoint,onBack:()=>Np(!1)}})}),Om&&S1&&S1.length>0&&jsxRuntimeExports.jsx(ToolApprovalBannerSection,{pendingApprovals:S1,onApprove:Jm,onReject:h0}),Ou&&og&&jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,p:A0,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:og.message})]}),Wp?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:Dp||bf?null:{borderRight:"1px solid",borderColor:"border.default"},children:Xu||Yu?jsxRuntimeExports.jsx(CompanionSurfaceSkeleton,{mode:Vh?"notebook":"document"}):Vh?jsxRuntimeExports.jsx(ReactorLazy,{load:loadEphemeralNotebook,errorFallback:ephemeralNotebookRefused,fallback:jsxRuntimeExports.jsx(CompanionSurfaceSkeleton,{mode:"notebook"}),props:{notebookId:Hf,runtimeName:Gp||Hh,runtimeOverride:$f,themeVariant:md,colorMode:Ed,nbformat:qm??void 0,onNbformatChange:gm,toolbarComponent:lf,toolbarExtraItems:vm,collaborationProvider:Jp}}):jsxRuntimeExports.jsx(vM.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(EphemeralDocument,{documentId:Ef,runtimeName:Gp||Hh,runtimeOverride:$f,themeVariant:md,colorMode:Ed,content:sm??void 0,onContentChange:Cf,onToolsReady:b0,onKernelChange:Yh,collaboration:om,toolbarExtraItems:Qf})})}),!bf&&jsxRuntimeExports.jsxs(Box,{sx:Dp?{position:"absolute",right:16,width:um?360:440,maxWidth:"calc(100% - 32px)",...um?{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:[xf,jsxRuntimeExports.jsx(Box,{ref:Sg,flex:1,minHeight:0,overflow:"auto",bg:"canvas.default",children:O0}),Pd,M0]}),bf&&Bp&&(Td==="sidebar"?jsxRuntimeExports.jsx(Box,{position:"absolute",top:8,right:8,zIndex:6,children:jsxRuntimeExports.jsx(IconButton,{icon:SidebarExpandIcon,"aria-label":"Open chat",onClick:Bp,variant:"default",size:"small"})}):jsxRuntimeExports.jsx(FloatingBrandButton,{isOpen:!1,onToggle:Bp,position:"bottom-right",tooltip:"Open chat"}))]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Box,{ref:Sg,"data-chat-history":"",flex:1,flexGrow:1,minHeight:0,overflow:"auto",bg:"canvas.default",children:O0}),Pd,M0]}),vh&&jsxRuntimeExports.jsx(PoweredByTag,{...Jd}),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$1({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$1,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";class AssistantCharacterFormatError extends Error{constructor(lo){super(lo),this.name="AssistantCharacterFormatError"}}async function blobBytes(Au){return typeof Au.arrayBuffer=="function"?new Uint8Array(await Au.arrayBuffer()):new Promise((lo,$u)=>{const Ru=new FileReader;Ru.onload=()=>lo(new Uint8Array(Ru.result)),Ru.onerror=()=>$u(Ru.error),Ru.readAsArrayBuffer(Au)})}function objectUrl(Au){if(typeof URL>"u"||typeof URL.createObjectURL!="function")throw new AssistantCharacterFormatError("This page cannot hold a picked file: it has no URL.createObjectURL.");return URL.createObjectURL(Au)}const IMAGE_SIGNATURES=[{type:"image/png",bytes:[137,80,78,71,13,10,26,10]},{type:"image/gif",bytes:[71,73,70,56]},{type:"image/jpeg",bytes:[255,216,255]}];function imageTypeOf(Au){for(const{type:lo,bytes:$u}of IMAGE_SIGNATURES)if($u.every((Ru,Iu)=>Au[Iu]===Ru))return lo;if(Au.length>=12&&String.fromCharCode(...Au.subarray(0,4))==="RIFF"&&String.fromCharCode(...Au.subarray(8,12))==="WEBP")return"image/webp"}const IDENTIFIER_START=/[A-Za-z_$]/,IDENTIFIER_PART=/[A-Za-z0-9_$]/,MAX_DEPTH=64;function readObjectLiteral(Au,lo,$u){let Ru=lo;const Iu=ju=>{const Fu=Au.slice(0,Ru).split(`
3919
3919
  `).length;throw new AssistantCharacterFormatError(`${$u} cannot be read at line ${Fu}: ${ju}.`)},Pu=()=>{for(;;){const ju=Au[Ru];if(ju===" "||ju===" "||ju===`
3920
3920
  `||ju==="\r"||ju==="\uFEFF")Ru++;else if(ju==="/"&&Au[Ru+1]==="/")for(;Ru<Au.length&&Au[Ru]!==`
@@ -4091,7 +4091,7 @@ ${Mu}`:ju,inputs:Mu,clear:Ou?[]:[DRAFT.path],loop:Lu()}:{refused:"Nothing to sen
4091
4091
  0%, 100% { opacity: 0.25; }
4092
4092
  50% { opacity: 1; }
4093
4093
  }`;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-BJiGUzsG.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-BUmmTwes.js").then(Au=>Au.r),[],import.meta.url).then(Au=>(jupyterReact=Au,Au))}const PREVIEW_LENGTH=56;function stripped(Au){const $u=(Au.split(`
4094
- `).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-DQMhvzcI.js").then(Mu=>Mu.a),[],import.meta.url).then(()=>__vitePreload(()=>import("./chunks/index-CaAB7eph.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-DUXxA4Qg.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 vd=Mu-1;vd>0;vd-=2)for(vd==6&&(vd-=1);;){for(let Sd=0;Sd<2;Sd+=1)if(Ou[od][vd-Sd]==null){let _d=!1;ad<ed.length&&(_d=(ed[ad]>>>sd&1)==1),pd(od,vd-Sd)&&(_d=!_d),Ou[od][vd-Sd]=_d,sd-=1,sd==-1&&(ad+=1,sd=7)}if(od+=nd,od<0||Mu<=od){od-=nd,nd=-nd;break}}},Zu=function(ed,td){let nd=0,od=0,sd=0;const ad=new Array(td.length),pd=new Array(td.length);for(let bd=0;bd<td.length;bd+=1){const wd=td[bd].dataCount,Ad=td[bd].totalCount-wd;od=Math.max(od,wd),sd=Math.max(sd,Ad),ad[bd]=new Array(wd);for(let ld=0;ld<ad[bd].length;ld+=1)ad[bd][ld]=255&ed.getBuffer()[ld+nd];nd+=wd;const gd=QRUtil.getErrorCorrectPolynomial(Ad),yd=qrPolynomial(ad[bd],gd.getLength()-1).mod(gd);pd[bd]=new Array(gd.getLength()-1);for(let ld=0;ld<pd[bd].length;ld+=1){const ud=ld+yd.getLength()-pd[bd].length;pd[bd][ld]=ud>=0?yd.getAt(ud):0}}let vd=0;for(let bd=0;bd<td.length;bd+=1)vd+=td[bd].totalCount;const Sd=new Array(vd);let _d=0;for(let bd=0;bd<od;bd+=1)for(let wd=0;wd<td.length;wd+=1)bd<ad[wd].length&&(Sd[_d]=ad[wd][bd],_d+=1);for(let bd=0;bd<sd;bd+=1)for(let wd=0;wd<td.length;wd+=1)bd<pd[wd].length&&(Sd[_d]=pd[wd][bd],_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 vd=nd[pd];sd.put(vd.getMode(),4),sd.put(vd.getLength(),QRUtil.getLengthInBits(vd.getMode(),ed)),vd.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 Zu(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,vd,Sd,_d,bd="",wd;for(wd="l"+ed+",0 0,"+ed+" -"+ed+",0 0,-"+ed+"z ",bd+='<svg version="1.1" xmlns="http://www.w3.org/2000/svg"',bd+=sd.scalable?"":' width="'+ad+'px" height="'+ad+'px"',bd+=' viewBox="0 0 '+ad+" "+ad+'" ',bd+=' preserveAspectRatio="xMinYMin meet"',bd+=od.text||nd.text?' role="img" aria-labelledby="'+Yu([od.id,nd.id].join(" ").trim())+'"':"",bd+=">",bd+=od.text?'<title id="'+Yu(od.id)+'">'+Yu(od.text)+"</title>":"",bd+=nd.text?'<description id="'+Yu(nd.id)+'">'+Yu(nd.text)+"</description>":"",bd+='<rect width="100%" height="100%" fill="white" cx="0" cy="0"/>',bd+='<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)&&(vd=pd*ed+td,bd+="M"+vd+","+_d+wd);return bd+='" stroke="transparent" fill="black"/>',bd+="</svg>",bd},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 vd=Math.floor((ad-od)/ed),Sd=Math.floor((pd-od)/ed);return Bu.isDark(Sd,vd)?0:1}else return 1})},Bu.createImgTag=function(ed,td,nd){ed=ed||2,td=typeof td>"u"?ed*4:td;const od=Bu.getModuleCount()*ed+td*2;let sd="";return sd+="<img",sd+=' src="',sd+=Bu.createDataURL(ed,td),sd+='"',sd+=' width="',sd+=od,sd+='"',sd+=' height="',sd+=od,sd+='"',nd&&(sd+=' alt="',sd+=Yu(nd),sd+='"'),sd+="/>",sd};const Yu=function(ed){let td="";for(let nd=0;nd<ed.length;nd+=1){const od=ed.charAt(nd);switch(od){case"<":td+="&lt;";break;case">":td+="&gt;";break;case"&":td+="&amp;";break;case'"':td+="&quot;";break;default:td+=od;break}}return td},Xu=function(ed){ed=typeof ed>"u"?2:ed;const nd=Bu.getModuleCount()*1+ed*2,od=ed,sd=nd-ed;let ad,pd,vd,Sd,_d;const bd={"██":"█","█ ":"▀"," █":"▄"," ":" "},wd={"██":"▀","█ ":"▀"," █":" "," ":" "};let Ad="";for(ad=0;ad<nd;ad+=2){for(vd=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(vd,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]:bd[_d];Ad+=`
4094
+ `).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-DQMhvzcI.js").then(Mu=>Mu.a),[],import.meta.url).then(()=>__vitePreload(()=>import("./chunks/index-BnyTIBRs.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-DUXxA4Qg.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 vd=Mu-1;vd>0;vd-=2)for(vd==6&&(vd-=1);;){for(let Sd=0;Sd<2;Sd+=1)if(Ou[od][vd-Sd]==null){let _d=!1;ad<ed.length&&(_d=(ed[ad]>>>sd&1)==1),pd(od,vd-Sd)&&(_d=!_d),Ou[od][vd-Sd]=_d,sd-=1,sd==-1&&(ad+=1,sd=7)}if(od+=nd,od<0||Mu<=od){od-=nd,nd=-nd;break}}},Zu=function(ed,td){let nd=0,od=0,sd=0;const ad=new Array(td.length),pd=new Array(td.length);for(let bd=0;bd<td.length;bd+=1){const wd=td[bd].dataCount,Ad=td[bd].totalCount-wd;od=Math.max(od,wd),sd=Math.max(sd,Ad),ad[bd]=new Array(wd);for(let ld=0;ld<ad[bd].length;ld+=1)ad[bd][ld]=255&ed.getBuffer()[ld+nd];nd+=wd;const gd=QRUtil.getErrorCorrectPolynomial(Ad),yd=qrPolynomial(ad[bd],gd.getLength()-1).mod(gd);pd[bd]=new Array(gd.getLength()-1);for(let ld=0;ld<pd[bd].length;ld+=1){const ud=ld+yd.getLength()-pd[bd].length;pd[bd][ld]=ud>=0?yd.getAt(ud):0}}let vd=0;for(let bd=0;bd<td.length;bd+=1)vd+=td[bd].totalCount;const Sd=new Array(vd);let _d=0;for(let bd=0;bd<od;bd+=1)for(let wd=0;wd<td.length;wd+=1)bd<ad[wd].length&&(Sd[_d]=ad[wd][bd],_d+=1);for(let bd=0;bd<sd;bd+=1)for(let wd=0;wd<td.length;wd+=1)bd<pd[wd].length&&(Sd[_d]=pd[wd][bd],_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 vd=nd[pd];sd.put(vd.getMode(),4),sd.put(vd.getLength(),QRUtil.getLengthInBits(vd.getMode(),ed)),vd.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 Zu(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,vd,Sd,_d,bd="",wd;for(wd="l"+ed+",0 0,"+ed+" -"+ed+",0 0,-"+ed+"z ",bd+='<svg version="1.1" xmlns="http://www.w3.org/2000/svg"',bd+=sd.scalable?"":' width="'+ad+'px" height="'+ad+'px"',bd+=' viewBox="0 0 '+ad+" "+ad+'" ',bd+=' preserveAspectRatio="xMinYMin meet"',bd+=od.text||nd.text?' role="img" aria-labelledby="'+Yu([od.id,nd.id].join(" ").trim())+'"':"",bd+=">",bd+=od.text?'<title id="'+Yu(od.id)+'">'+Yu(od.text)+"</title>":"",bd+=nd.text?'<description id="'+Yu(nd.id)+'">'+Yu(nd.text)+"</description>":"",bd+='<rect width="100%" height="100%" fill="white" cx="0" cy="0"/>',bd+='<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)&&(vd=pd*ed+td,bd+="M"+vd+","+_d+wd);return bd+='" stroke="transparent" fill="black"/>',bd+="</svg>",bd},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 vd=Math.floor((ad-od)/ed),Sd=Math.floor((pd-od)/ed);return Bu.isDark(Sd,vd)?0:1}else return 1})},Bu.createImgTag=function(ed,td,nd){ed=ed||2,td=typeof td>"u"?ed*4:td;const od=Bu.getModuleCount()*ed+td*2;let sd="";return sd+="<img",sd+=' src="',sd+=Bu.createDataURL(ed,td),sd+='"',sd+=' width="',sd+=od,sd+='"',sd+=' height="',sd+=od,sd+='"',nd&&(sd+=' alt="',sd+=Yu(nd),sd+='"'),sd+="/>",sd};const Yu=function(ed){let td="";for(let nd=0;nd<ed.length;nd+=1){const od=ed.charAt(nd);switch(od){case"<":td+="&lt;";break;case">":td+="&gt;";break;case"&":td+="&amp;";break;case'"':td+="&quot;";break;default:td+=od;break}}return td},Xu=function(ed){ed=typeof ed>"u"?2:ed;const nd=Bu.getModuleCount()*1+ed*2,od=ed,sd=nd-ed;let ad,pd,vd,Sd,_d;const bd={"██":"█","█ ":"▀"," █":"▄"," ":" "},wd={"██":"▀","█ ":"▀"," █":" "," ":" "};let Ad="";for(ad=0;ad<nd;ad+=2){for(vd=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(vd,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]:bd[_d];Ad+=`
4095
4095
  `}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,vd,Sd;const _d=Array(ed+1).join("██"),bd=Array(ed+1).join(" ");let wd="",Ad="";for(ad=0;ad<nd;ad+=1){for(vd=Math.floor((ad-od)/ed),Ad="",pd=0;pd<nd;pd+=1)Sd=1,od<=pd&&pd<sd&&od<=ad&&ad<sd&&Bu.isDark(vd,Math.floor((pd-od)/ed))&&(Sd=0),Ad+=Sd?_d:bd;for(vd=0;vd<ed;vd+=1)wd+=Ad+`
4096
4096
  `}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=`
4097
4097
  /*
@@ -4250,7 +4250,7 @@ ${Mu}`:ju,inputs:Mu,clear:Ou?[]:[DRAFT.path],loop:Lu()}:{refused:"Nothing to sen
4250
4250
  opacity: 0.6;
4251
4251
  border-top: 1px solid var(--cmdk-border);
4252
4252
  }
4253
- `;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,Zu)=>Wu.score-Zu.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(Zu){ju(Zu instanceof Error?Zu.message:String(Zu))}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),Zu=isApplePlatform();function Ju(Yu){if(PALETTE_CHORD&&matchesKeybinding(Yu,PALETTE_CHORD,Zu)){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,Zu)){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(Zu=>zu.length===0?0:(Zu+1)%zu.length);else if(Wu.key==="ArrowUp")Wu.preventDefault(),Mu(Zu=>zu.length===0?0:(Zu-1+zu.length)%zu.length);else if(Wu.key==="Enter"){Wu.preventDefault();const Zu=zu[Ou];Zu&&Zu.isEnabled?.()!==!1&&Hu(Zu)}},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,Zu)=>{const Ju=Wu.isEnabled?.()!==!1;return jsxRuntimeExports.jsx("li",{children:jsxRuntimeExports.jsxs("button",{type:"button",className:"dla-cmdk-item",id:optionId(Zu),role:"option","aria-selected":Zu===Ou,"aria-disabled":!Ju,disabled:!Ju,onMouseEnter:()=>Mu(Zu),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-Aird-zRf.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-6sufB3Oa.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-DDYrZrhd.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-DdrnCbwh.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-DZCx-Wsu.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(`
4253
+ `;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,Zu)=>Wu.score-Zu.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(Zu){ju(Zu instanceof Error?Zu.message:String(Zu))}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),Zu=isApplePlatform();function Ju(Yu){if(PALETTE_CHORD&&matchesKeybinding(Yu,PALETTE_CHORD,Zu)){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,Zu)){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(Zu=>zu.length===0?0:(Zu+1)%zu.length);else if(Wu.key==="ArrowUp")Wu.preventDefault(),Mu(Zu=>zu.length===0?0:(Zu-1+zu.length)%zu.length);else if(Wu.key==="Enter"){Wu.preventDefault();const Zu=zu[Ou];Zu&&Zu.isEnabled?.()!==!1&&Hu(Zu)}},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,Zu)=>{const Ju=Wu.isEnabled?.()!==!1;return jsxRuntimeExports.jsx("li",{children:jsxRuntimeExports.jsxs("button",{type:"button",className:"dla-cmdk-item",id:optionId(Zu),role:"option","aria-selected":Zu===Ou,"aria-disabled":!Ju,disabled:!Ju,onMouseEnter:()=>Mu(Zu),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-LE7AJ2BO.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-6sufB3Oa.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-DDYrZrhd.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-DdrnCbwh.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-DZCx-Wsu.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(`
4254
4254
 
4255
4255
  `);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:Zu="top",pageLayoutSize:Ju,pageLayoutTurnPanelFooter:Yu="full",localAgent:Xu,localAgentSpec:ed,datalayerAgentSpecId:td,datalayerCreatePayload:nd,datalayerVisitors:od,datalayerKept:sd,embedToken:ad,targetFixed:pd,themeVariant:vd,themeOverrides:Sd,colorMode:_d,presence:bd,showTokenUsage:wd,voice:Ad,thread:gd,floatingPrompt:dd=!1,editorSelector:yd=!1,editors:ld=!0,conversation:ud=!0,commandPalette:hd=!1,pluginsPanel:md=!1,windowFrame:Ed=!1,firstPromptHook:Td}=Au,Rd=Ru??(ld?"notebook":"none");return ud?[configurePlugin(ChatPlugin,{defaultSurface:Rd,showSurfaceSelector:ld&&Iu&&!yd,hideHeader:Pu,headerButtons:{newChat:Ou,clear:Ou},promptPlacement:dd?"floating":Mu,autoFocusPrompt:Du,suggestionLabels:Lu,fullScreenTopOffset:Bu,themeVariant:vd,themeOverrides:Sd,colorMode:_d,presence:bd,showTokenUsage:wd,...Ad?{voice:Ad}:{},...gd?{thread:gd}:{}}),configurePlugin(InputPromptPlugin,{firstPromptHook:Td}),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&&yd}),...dd?[PromptPlugin]:[],...Hu?[configurePlugin(LoopPageLayoutPlugin,{arrangement:Vu,turnPanel:Gu,turnPanelFooter:Yu,prompt:Wu,promptAnchor:Zu,pageSize:Ju})]:[],...hd?[LoopCommandsPlugin]:[],...md?[PluginsPanelPlugin]:[],...Ed?[WindowFramePlugin]:[]]:[ThemePlugin,configurePlugin(ShellPlugin,{defaultEditor:"none",showSelector:!1}),...hd?[LoopCommandsPlugin]:[],...md?[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-3LGMoZh8.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(`
4256
4256
  `):"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)}