@datalayer/agent-runtimes 1.5.54 → 1.5.57
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-embed/datalayer-app-main.js +4 -4
- package/lib/apps/plugins/pap-sign-in/PapSignInCard.js +8 -2
- package/lib/examples/pap/PapAuthorizationBoundaryView.js +4 -3
- package/lib/examples/pap/PapCompanyDiscoveryView.js +1 -1
- package/lib/examples/pap/PapGuidedJourneyView.js +4 -4
- package/lib/examples/pap/traces/account-tokens.json +5 -2
- package/lib/examples/pap/traces/conversation-control.json +5 -2
- package/lib/examples/pap/traces/conversation-streaming.json +5 -2
- package/lib/examples/pap/traces/mediated-sign-in.json +5 -2
- package/lib/examples/pap/traces/operations.json +5 -2
- package/lib/examples/pap/traces/two-companies.json +10 -4
- package/lib/examples/pap/traces/user-with-a-company.json +5 -2
- package/lib/portable/hosts/contracts.json +30 -0
- package/lib/portable/signIn.d.ts +13 -0
- package/lib/portable/signIn.js +16 -0
- package/lib/protocols/pap/index.d.ts +1 -1
- package/lib/protocols/pap/index.js +2 -2
- package/lib/specs/protocols.js +2 -2
- package/package.json +2 -2
|
@@ -120,7 +120,7 @@ ${Au}
|
|
|
120
120
|
:scope strong {
|
|
121
121
|
font-weight: var(--base-text-weight-semibold);
|
|
122
122
|
}
|
|
123
|
-
`,loopThemeStyles=buildThemeStyles(loopLight,loopDark,{fontFamily:loopFontFamily,css:loopOwnCss,shape:{radiusControl:loopShapeVars["--loop-radius-control"],radiusTable:loopShapeVars["--borderRadius-medium"],radiusOverlay:loopShapeVars["--loop-radius-card"],radiusCard:loopShapeVars["--loop-radius-card"],radiusBubble:loopShapeVars["--loop-radius-bubble"],radiusFrame:loopShapeVars["--loop-radius-frame"],shadow:loopShapeVars["--loop-shadow-frame"],motionStatus:loopMotionVars["--loop-motion-status"],motionMessage:loopMotionVars["--loop-motion-message"],motionPane:loopMotionVars["--loop-motion-pane"],motionEasing:loopMotionVars["--loop-motion-easing"],messageLink:"currentColor"},variables:{light:{...loopShapeVars,...loopTints("light"),...loopMotionVars,...loopShadows.light,...loopTypeVars(loopFontFamily),"--loop-hairline":loopHairline.light,"--borderColor-default":loopHairline.light,"--focus-outlineColor":loopFocusRing.light,"--underlineNav-borderColor-active":themeAccents.green.accent},dark:{...loopShapeVars,...loopTints("dark"),...loopMotionVars,...loopShadows.dark,...loopTypeVars(loopFontFamily),"--loop-hairline":loopHairline.dark,"--borderColor-default":loopHairline.dark,"--focus-outlineColor":loopFocusRing.dark,"--underlineNav-borderColor-active":themeAccents.green.accent}}});loopThemeStyles.css;const loopTheme={...theme$1,fontWeights:{light:loopFontWeights.regular,normal:loopFontWeights.regular,semibold:loopFontWeights.semibold,bold:loopFontWeights.semibold}},themeTokens={datalayer:{label:"Datalayer",description:"Default green palette — the classic Datalayer look.",brandColor:datalayerColors.greenBrand,defaultColorMode:"auto",themeStyles:datalayerThemeStyles,cardGradient:{light:{from:datalayerColors.greenBrand,to:datalayerColors.greenText},dark:{from:datalayerColors.greenAccent,to:datalayerColors.greenBrand}},brightPalette:{glow:datalayerColors.brightGlow,onGlow:"#1b1f24",pop:datalayerColors.brightPop,spark:datalayerColors.brightSpark,blaze:datalayerColors.brightBlaze,surge:datalayerColors.brightSurge,flame:datalayerColors.brightFlame,gold:datalayerColors.brightGold},brightPaletteLight:{glow:datalayerColors.brightLightGlow,onGlow:"#1b1f24",pop:datalayerColors.brightLightPop,spark:datalayerColors.brightLightSpark,blaze:datalayerColors.brightLightBlaze,surge:datalayerColors.brightLightSurge,flame:datalayerColors.brightLightFlame,gold:datalayerColors.brightLightGold}},spatial:{label:"Spatial",description:"Cosmic indigo & deep blues — inspired by space.",brandColor:spatialColors.indigoBrand,defaultColorMode:"auto",themeStyles:spatialThemeStyles,cardGradient:{light:{from:spatialColors.indigoBrand,to:spatialColors.indigoText},dark:{from:spatialColors.indigoAccent,to:spatialColors.indigoBrand}},brightPalette:{glow:spatialColors.brightGlow,onGlow:"#ffffff",pop:spatialColors.brightPop,spark:spatialColors.brightSpark,blaze:spatialColors.brightBlaze,surge:spatialColors.brightSurge,flame:spatialColors.brightFlame,gold:spatialColors.brightGold},brightPaletteLight:{glow:spatialColors.brightLightGlow,onGlow:"#ffffff",pop:spatialColors.brightLightPop,spark:spatialColors.brightLightSpark,blaze:spatialColors.brightLightBlaze,surge:spatialColors.brightLightSurge,flame:spatialColors.brightLightFlame,gold:spatialColors.brightLightGold}},lovely:{label:"Lovely",description:"Warm rose & magenta — soft and inviting.",brandColor:lovelyColors.roseBrand,defaultColorMode:"auto",themeStyles:lovelyThemeStyles,cardGradient:{light:{from:lovelyColors.roseBrand,to:lovelyColors.roseText},dark:{from:lovelyColors.roseAccent,to:lovelyColors.roseBrand}},brightPalette:{glow:lovelyColors.brightGlow,onGlow:"#ffffff",pop:lovelyColors.brightPop,spark:lovelyColors.brightSpark,blaze:lovelyColors.brightBlaze,surge:lovelyColors.brightSurge,flame:lovelyColors.brightFlame,gold:lovelyColors.brightGold},brightPaletteLight:{glow:lovelyColors.brightLightGlow,onGlow:"#ffffff",pop:lovelyColors.brightLightPop,spark:lovelyColors.brightLightSpark,blaze:lovelyColors.brightLightBlaze,surge:lovelyColors.brightLightSurge,flame:lovelyColors.brightLightFlame,gold:lovelyColors.brightLightGold}},matrix:{label:"Matrix",description:"Phosphor green on black — CRT terminal aesthetic.",brandColor:matrixColors.greenPhosphor,defaultColorMode:"dark",themeStyles:matrixThemeStyles,cardGradient:{light:{from:matrixColors.greenBrand,to:matrixColors.greenText},dark:{from:matrixColors.greenGlow,to:matrixColors.greenHover}},brightPalette:{glow:matrixColors.brightGlow,onGlow:"#1b1f24",pop:matrixColors.brightPop,spark:matrixColors.brightSpark,blaze:matrixColors.brightBlaze,surge:matrixColors.brightSurge,flame:matrixColors.brightFlame,gold:matrixColors.brightGold},brightPaletteLight:{glow:matrixColors.brightLightGlow,onGlow:"#1b1f24",pop:matrixColors.brightLightPop,spark:matrixColors.brightLightSpark,blaze:matrixColors.brightLightBlaze,surge:matrixColors.brightLightSurge,flame:matrixColors.brightLightFlame,gold:matrixColors.brightLightGold}},earth:{label:"Earth",description:"Ocean blues, forest greens & golden sun — the Blue Planet.",brandColor:earthColors.oceanBrand,defaultColorMode:"auto",themeStyles:earthThemeStyles,cardGradient:{light:{from:earthColors.oceanBrand,to:earthColors.oceanText},dark:{from:earthColors.oceanAccent,to:earthColors.oceanBrand}},brightPalette:{glow:earthColors.brightGlow,onGlow:"#ffffff",pop:earthColors.brightPop,spark:earthColors.brightSpark,blaze:earthColors.brightBlaze,surge:earthColors.brightSurge,flame:earthColors.brightFlame,gold:earthColors.brightGold},brightPaletteLight:{glow:earthColors.brightLightGlow,onGlow:"#ffffff",pop:earthColors.brightLightPop,spark:earthColors.brightLightSpark,blaze:earthColors.brightLightBlaze,surge:earthColors.brightLightSurge,flame:earthColors.brightLightFlame,gold:earthColors.brightLightGold}},sand:{label:"Sand",description:"Warm, pale desert neutrals with a golden accent — calm & editorial.",brandColor:sandColors.sandBrand,defaultColorMode:"light",themeStyles:sandThemeStyles,cardGradient:{light:{from:sandColors.sandBrand,to:sandColors.sandText},dark:{from:sandColors.sandAccent,to:sandColors.sandBrand}},brightPalette:{glow:sandColors.brightGlow,onGlow:"#211A12",pop:sandColors.brightPop,spark:sandColors.brightSpark,blaze:sandColors.brightBlaze,surge:sandColors.brightSurge,flame:sandColors.brightFlame,gold:sandColors.brightGold},brightPaletteLight:{glow:sandColors.brightLightGlow,onGlow:"#ffffff",pop:sandColors.brightLightPop,spark:sandColors.brightLightSpark,blaze:sandColors.brightLightBlaze,surge:sandColors.brightLightSurge,flame:sandColors.brightLightFlame,gold:sandColors.brightLightGold}},ivory:{label:"Ivory",description:"Soft, warm off-white that creates a calm, refined, and welcoming feeling.",brandColor:ivoryColors.ivoryBrand,defaultColorMode:"light",themeStyles:ivoryThemeStyles,cardGradient:{light:{from:ivoryColors.ivoryBrand,to:ivoryColors.ivoryText},dark:{from:ivoryColors.ivoryAccent,to:ivoryColors.ivoryBrand}},brightPalette:{glow:ivoryColors.brightGlow,onGlow:"#211A12",pop:ivoryColors.brightPop,spark:ivoryColors.brightSpark,blaze:ivoryColors.brightBlaze,surge:ivoryColors.brightSurge,flame:ivoryColors.brightFlame,gold:ivoryColors.brightGold},brightPaletteLight:{glow:ivoryColors.brightLightGlow,onGlow:"#ffffff",pop:ivoryColors.brightLightPop,spark:ivoryColors.brightLightSpark,blaze:ivoryColors.brightLightBlaze,surge:ivoryColors.brightLightSurge,flame:ivoryColors.brightLightFlame,gold:ivoryColors.brightLightGold}},sun:{label:"Sun",description:"Warm, radiant theme inspired by golden light, bringing energy, optimism, and a welcoming atmosphere.",brandColor:sunColors.sunBrand,defaultColorMode:"light",themeStyles:sunThemeStyles,cardGradient:{light:{from:sunColors.sunBrand,to:sunColors.sunText},dark:{from:sunColors.sunAccent,to:sunColors.sunBrand}},brightPalette:{glow:sunColors.brightGlow,onGlow:"#211A08",pop:sunColors.brightPop,spark:sunColors.brightSpark,blaze:sunColors.brightBlaze,surge:sunColors.brightSurge,flame:sunColors.brightFlame,gold:sunColors.brightGold},brightPaletteLight:{glow:sunColors.brightLightGlow,onGlow:"#ffffff",pop:sunColors.brightLightPop,spark:sunColors.brightLightSpark,blaze:sunColors.brightLightBlaze,surge:sunColors.brightLightSurge,flame:sunColors.brightLightFlame,gold:sunColors.brightLightGold}},loop:{label:"Loop",description:"Very clean: one soft accent, neutral everything else. The look of an application built in LOOP.",brandColor:loopColors.loopBrand,defaultColorMode:"light",themeStyles:loopThemeStyles,cardGradient:{light:{from:loopColors.loopBrand,to:loopColors.loopBrand},dark:{from:loopColors.loopBrand,to:loopColors.loopBrand}},brightPalette:{glow:loopColors.brightGlow,onGlow:loopColors.loopOn,pop:loopColors.brightPop,spark:loopColors.brightSpark,blaze:loopColors.brightBlaze,surge:loopColors.brightSurge,flame:loopColors.brightFlame,gold:loopColors.brightGold},brightPaletteLight:{glow:loopColors.brightLightGlow,onGlow:"#ffffff",pop:loopColors.brightLightPop,spark:loopColors.brightLightSpark,blaze:loopColors.brightLightBlaze,surge:loopColors.brightLightSurge,flame:loopColors.brightLightFlame,gold:loopColors.brightLightGold}}};function brightPaletteOf(Au,lo){const $u=themeTokens[Au]??themeTokens.datalayer;return lo==="light"?$u.brightPaletteLight??$u.brightPalette:$u.brightPalette}const primerThemes={datalayer:datalayerTheme,spatial:spatialTheme,lovely:lovelyTheme,matrix:matrixTheme,earth:earthTheme,sand:sandTheme,ivory:ivoryTheme,sun:sunTheme,loop:loopTheme},themeConfigs=Object.fromEntries(Object.keys(themeTokens).map(Au=>[Au,{...themeTokens[Au],primerTheme:primerThemes[Au]}]));function getThemeConfig(Au){return themeConfigs[Au]}const osMode=()=>typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";function getBrightPalette(Au="datalayer",lo){const $u=lo==="auto"?osMode():lo==="light"?"light":"dark";return brightPaletteOf(Au,$u)}const createStoreImpl$2=Au=>{let lo;const $u=new Set,Ru=(Lu,Bu)=>{const ju=typeof Lu=="function"?Lu(lo):Lu;if(!Object.is(ju,lo)){const Fu=lo;lo=Bu??(typeof ju!="object"||ju===null)?ju:Object.assign({},lo,ju),$u.forEach(zu=>zu(lo,Fu))}},Iu=()=>lo,Mu={setState:Ru,getState:Iu,getInitialState:()=>Du,subscribe:Lu=>($u.add(Lu),()=>$u.delete(Lu))},Du=lo=Au(Ru,Iu,Mu);return Mu},createStore$2=(Au=>Au?createStoreImpl$2(Au):createStoreImpl$2),identity$2=Au=>Au;function useStore$2(Au,lo=identity$2){const $u=vM.useSyncExternalStore(Au.subscribe,vM.useCallback(()=>lo(Au.getState()),[Au,lo]),vM.useCallback(()=>lo(Au.getInitialState()),[Au,lo]));return vM.useDebugValue($u),$u}const createImpl$2=Au=>{const lo=createStore$2(Au),$u=Ru=>useStore$2(lo,Ru);return Object.assign($u,lo),$u},create$h=(Au=>Au?createImpl$2(Au):createImpl$2);function createJSONStorage$1(Au,lo){let $u;try{$u=Au()}catch{return}return{getItem:Iu=>{var Pu;const Ou=Du=>Du===null?null:JSON.parse(Du,void 0),Mu=(Pu=$u.getItem(Iu))!=null?Pu:null;return Mu instanceof Promise?Mu.then(Ou):Ou(Mu)},setItem:(Iu,Pu)=>$u.setItem(Iu,JSON.stringify(Pu,void 0)),removeItem:Iu=>$u.removeItem(Iu)}}const toThenable$1=Au=>lo=>{try{const $u=Au(lo);return $u instanceof Promise?$u:{then(Ru){return toThenable$1(Ru)($u)},catch(Ru){return this}}}catch($u){return{then(Ru){return this},catch(Ru){return toThenable$1(Ru)($u)}}}},persistImpl$1=(Au,lo)=>($u,Ru,Iu)=>{let Pu={storage:createJSONStorage$1(()=>window.localStorage),partialize:Vu=>Vu,version:0,merge:(Vu,Gu)=>({...Gu,...Vu}),...lo},Ou=!1,Mu=0;const Du=new Set,Lu=new Set;let Bu=Pu.storage;if(!Bu)return Au((...Vu)=>{console.warn(`[zustand persist middleware] Unable to update item '${Pu.name}', the given storage is currently unavailable.`),$u(...Vu)},Ru,Iu);const ju=()=>{const Vu=Pu.partialize({...Ru()});return Bu.setItem(Pu.name,{state:Vu,version:Pu.version})},Fu=Iu.setState;Iu.setState=(Vu,Gu)=>(Fu(Vu,Gu),ju());const zu=Au((...Vu)=>($u(...Vu),ju()),Ru,Iu);Iu.getInitialState=()=>zu;let Uu;const Hu=()=>{var Vu,Gu;if(!Bu)return;const Wu=++Mu;Ou=!1,Du.forEach(Ju=>{var Yu;return Ju((Yu=Ru())!=null?Yu:zu)});const Ku=((Gu=Pu.onRehydrateStorage)==null?void 0:Gu.call(Pu,(Vu=Ru())!=null?Vu:zu))||void 0;return toThenable$1(Bu.getItem.bind(Bu))(Pu.name).then(Ju=>{if(Ju)if(typeof Ju.version=="number"&&Ju.version!==Pu.version){if(Pu.migrate){const Yu=Pu.migrate(Ju.state,Ju.version);return Yu instanceof Promise?Yu.then(Xu=>[!0,Xu]):[!0,Yu]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,Ju.state];return[!1,void 0]}).then(Ju=>{var Yu;if(Wu!==Mu)return;const[Xu,ed]=Ju;if(Uu=Pu.merge(ed,(Yu=Ru())!=null?Yu:zu),$u(Uu,!0),Xu)return ju()}).then(()=>{Wu===Mu&&(Ku?.(Ru(),void 0),Uu=Ru(),Ou=!0,Lu.forEach(Ju=>Ju(Uu)))}).catch(Ju=>{Wu===Mu&&Ku?.(void 0,Ju)})};return Iu.persist={setOptions:Vu=>{Pu={...Pu,...Vu},Vu.storage&&(Bu=Vu.storage)},clearStorage:()=>{++Mu,Bu?.removeItem(Pu.name)},getOptions:()=>Pu,rehydrate:()=>Hu(),hasHydrated:()=>Ou,onHydrate:Vu=>(Du.add(Vu),()=>{Du.delete(Vu)}),onFinishHydration:Vu=>(Lu.add(Vu),()=>{Lu.delete(Vu)})},Pu.skipHydration||Hu(),Uu||zu},persist$2=persistImpl$1,VARIANT_SCHEMA_VERSION=1;function normalizeVariantPreference(Au){return{theme:Au.theme,colorMode:Au.colorMode,version:typeof Au.version=="number"?Au.version:VARIANT_SCHEMA_VERSION}}function normalizeVariants(Au){if(!Au)return{};const lo={};for(const[$u,Ru]of Object.entries(Au))!Ru||typeof Ru!="object"||!("theme"in Ru)||!("colorMode"in Ru)||(lo[$u]=normalizeVariantPreference(Ru));return lo}function hasMissingVariantVersion(Au){return!Au||Object.keys(Au).length===0?!1:Object.values(Au).some(lo=>typeof lo?.version!="number")}const colorModeCycle={light:"dark",dark:"auto",auto:"light"};function createThemeStore(Au,lo){return create$h()(persist$2($u=>({colorMode:lo?.colorMode,theme:lo?.theme,activeVariant:null,variants:normalizeVariants(lo?.variants),toggleColorMode:()=>$u(Ru=>{const Iu=colorModeCycle[Ru.colorMode];return Ru.activeVariant&&Ru.variants[Ru.activeVariant]?{colorMode:Iu,variants:{...Ru.variants,[Ru.activeVariant]:{...Ru.variants[Ru.activeVariant],colorMode:Iu,version:VARIANT_SCHEMA_VERSION}}}:{colorMode:Iu}}),setColorMode:Ru=>$u(Iu=>Iu.activeVariant&&Iu.variants[Iu.activeVariant]?{colorMode:Ru,variants:{...Iu.variants,[Iu.activeVariant]:{...Iu.variants[Iu.activeVariant],colorMode:Ru,version:VARIANT_SCHEMA_VERSION}}}:{colorMode:Ru}),setTheme:(Ru,Iu=!0)=>$u(Pu=>{const Ou=Iu?themeConfigs[Ru].defaultColorMode:Pu.colorMode;return Pu.activeVariant&&Pu.variants[Pu.activeVariant]?{theme:Ru,colorMode:Ou,variants:{...Pu.variants,[Pu.activeVariant]:{theme:Ru,colorMode:Ou,version:VARIANT_SCHEMA_VERSION}}}:{theme:Ru,colorMode:Ou}}),registerVariants:Ru=>$u(Iu=>{const Pu={...Iu.variants};for(const[Ou,Mu]of Object.entries(Ru))Pu[Ou]?Pu[Ou]=normalizeVariantPreference({...Pu[Ou],version:Pu[Ou].version??VARIANT_SCHEMA_VERSION}):Pu[Ou]=normalizeVariantPreference(Mu);return{variants:Pu}}),setVariant:Ru=>$u(Iu=>{const Pu=Iu.variants[Ru];return Pu?{activeVariant:Ru,theme:Pu.theme,colorMode:Pu.colorMode}:{activeVariant:Ru}})}),{name:Au,version:3,storage:createJSONStorage$1(()=>localStorage),partialize:$u=>({colorMode:$u.colorMode,theme:$u.theme,activeVariant:$u.activeVariant,variants:$u.variants}),migrate:$u=>{const Ru=$u??{},Iu=Ru.variants,Pu=hasMissingVariantVersion(Iu),Ou=normalizeVariants(Iu);return Pu&&(Ou["agent-anonymous"]={theme:"matrix",colorMode:"dark",version:VARIANT_SCHEMA_VERSION}),{...Ru,variants:Ou,...Pu?{theme:Ru.activeVariant==="agent-anonymous"?"matrix":Ru.theme,colorMode:Ru.activeVariant==="agent-anonymous"?"dark":Ru.colorMode}:{}}},merge:($u,Ru)=>{const Iu=$u??{},Pu=normalizeVariants(Ru.variants);if(Iu.variants)for(const[Ou,Mu]of Object.entries(Iu.variants))Mu&&typeof Mu=="object"&&"theme"in Mu&&(Pu[Ou]=normalizeVariantPreference(Mu));return{...Ru,...Iu,variants:Pu}}}))}const useThemeStore=createThemeStore("datalayer-theme",{colorMode:"dark",theme:"matrix"}),dlBrightDark=getBrightPalette("datalayer"),dlBrightLight=getBrightPalette("datalayer","light"),spBrightDark=getBrightPalette("spatial"),spBrightLight=getBrightPalette("spatial","light"),lvBrightDark=getBrightPalette("lovely"),lvBrightLight=getBrightPalette("lovely","light"),mxBrightDark=getBrightPalette("matrix"),mxBrightLight=getBrightPalette("matrix","light"),eaBrightDark=getBrightPalette("earth"),eaBrightLight=getBrightPalette("earth","light"),saBrightDark=getBrightPalette("sand"),saBrightLight=getBrightPalette("sand","light"),ivBrightDark=getBrightPalette("ivory"),ivBrightLight=getBrightPalette("ivory","light"),suBrightDark=getBrightPalette("sun"),suBrightLight=getBrightPalette("sun","light"),loBrightDark=getBrightPalette("loop"),loBrightLight=getBrightPalette("loop","light"),palettes={datalayer:{light:{bg:"#f6f8fa",bgPanel:"#ffffff",bgAlt:"#f0f3f6",primary:datalayerColors.greenBrand,secondary:datalayerColors.greenText,accent:datalayerColors.greenBright,glow:dlBrightLight.glow,pop:dlBrightLight.pop,spark:dlBrightLight.spark,blaze:dlBrightLight.blaze,surge:dlBrightLight.surge,flame:dlBrightLight.flame,gold:dlBrightLight.gold,textLight:"#1f2328",textMuted:"#656d76",isLight:!0},dark:{bg:"#0d1117",bgPanel:"#161b22",bgAlt:"#1c2128",primary:datalayerColors.greenAccent,secondary:datalayerColors.greenBrand,accent:datalayerColors.greenBright,glow:dlBrightDark.glow,pop:dlBrightDark.pop,spark:dlBrightDark.spark,blaze:dlBrightDark.blaze,surge:dlBrightDark.surge,flame:dlBrightDark.flame,gold:dlBrightDark.gold,textLight:"#f0f6fc",textMuted:"#8b949e",isLight:!1}},spatial:{light:{bg:"#f0f2ff",bgPanel:"#ffffff",bgAlt:"#eef2ff",primary:spatialColors.indigoBrand,secondary:spatialColors.indigoText,accent:spatialColors.indigoBright,glow:spBrightLight.glow,pop:spBrightLight.pop,spark:spBrightLight.spark,blaze:spBrightLight.blaze,surge:spBrightLight.surge,flame:spBrightLight.flame,gold:spBrightLight.gold,textLight:"#1E1E3F",textMuted:spatialColors.gray,isLight:!0},dark:{bg:spatialColors.black,bgPanel:"#111827",bgAlt:"#1E293B",primary:spatialColors.indigoAccent,secondary:spatialColors.indigoBrand,accent:spatialColors.indigoBright,glow:spBrightDark.glow,pop:spBrightDark.pop,spark:spBrightDark.spark,blaze:spBrightDark.blaze,surge:spBrightDark.surge,flame:spBrightDark.flame,gold:spBrightDark.gold,textLight:"#E0E7FF",textMuted:"#94A3B8",isLight:!1}},lovely:{light:{bg:"#fff5f7",bgPanel:"#ffffff",bgAlt:lovelyColors.roseTint,primary:lovelyColors.roseBrand,secondary:lovelyColors.roseText,accent:lovelyColors.roseBright,glow:lvBrightLight.glow,pop:lvBrightLight.pop,spark:lvBrightLight.spark,blaze:lvBrightLight.blaze,surge:lvBrightLight.surge,flame:lvBrightLight.flame,gold:lvBrightLight.gold,textLight:"#2D1B28",textMuted:lovelyColors.gray,isLight:!0},dark:{bg:lovelyColors.black,bgPanel:"#250E1D",bgAlt:"#3D1530",primary:lovelyColors.roseAccent,secondary:lovelyColors.roseBrand,accent:lovelyColors.roseBright,glow:lvBrightDark.glow,pop:lvBrightDark.pop,spark:lvBrightDark.spark,blaze:lvBrightDark.blaze,surge:lvBrightDark.surge,flame:lvBrightDark.flame,gold:lvBrightDark.gold,textLight:"#FCE7F3",textMuted:"#D4A5BD",isLight:!1}},matrix:{light:{bg:"#f0fff0",bgPanel:"#ffffff",bgAlt:matrixColors.greenTint,primary:matrixColors.greenBrand,secondary:matrixColors.greenText,accent:matrixColors.greenAccent,glow:mxBrightLight.glow,pop:mxBrightLight.pop,spark:mxBrightLight.spark,blaze:mxBrightLight.blaze,surge:mxBrightLight.surge,flame:mxBrightLight.flame,gold:mxBrightLight.gold,textLight:"#0A2E1A",textMuted:matrixColors.gray,isLight:!0},dark:{bg:matrixColors.black,bgPanel:"#0A1F0A",bgAlt:"#122812",primary:matrixColors.greenPhosphor,secondary:matrixColors.greenGlow,accent:matrixColors.greenGlow,glow:mxBrightDark.glow,pop:mxBrightDark.pop,spark:mxBrightDark.spark,blaze:mxBrightDark.blaze,surge:mxBrightDark.surge,flame:mxBrightDark.flame,gold:mxBrightDark.gold,textLight:"#C8E6C9",textMuted:"#66BB6A",isLight:!1}},earth:{light:{bg:"#F0F5FA",bgPanel:"#ffffff",bgAlt:earthColors.oceanTint,primary:earthColors.oceanBrand,secondary:earthColors.oceanText,accent:earthColors.oceanAccent,glow:eaBrightLight.glow,pop:eaBrightLight.pop,spark:eaBrightLight.spark,blaze:eaBrightLight.blaze,surge:eaBrightLight.surge,flame:eaBrightLight.flame,gold:eaBrightLight.gold,textLight:"#1A2332",textMuted:earthColors.gray,isLight:!0},dark:{bg:earthColors.black,bgPanel:"#0E1D30",bgAlt:"#132840",primary:earthColors.oceanAccent,secondary:earthColors.oceanBrand,accent:earthColors.oceanBright,glow:eaBrightDark.glow,pop:eaBrightDark.pop,spark:eaBrightDark.spark,blaze:eaBrightDark.blaze,surge:eaBrightDark.surge,flame:eaBrightDark.flame,gold:eaBrightDark.gold,textLight:"#D4E4DC",textMuted:"#8A9BA8",isLight:!1}},sand:{light:{bg:"#FBF7EF",bgPanel:"#ffffff",bgAlt:sandColors.sandTint,primary:sandColors.sandBrand,secondary:sandColors.sandText,accent:sandColors.sandAccent,glow:saBrightLight.glow,pop:saBrightLight.pop,spark:saBrightLight.spark,blaze:saBrightLight.blaze,surge:saBrightLight.surge,flame:saBrightLight.flame,gold:saBrightLight.gold,textLight:"#2B2118",textMuted:sandColors.gray,isLight:!0},dark:{bg:sandColors.black,bgPanel:"#2A2118",bgAlt:"#33281A",primary:sandColors.sandAccent,secondary:sandColors.sandBrand,accent:sandColors.sandBright,glow:saBrightDark.glow,pop:saBrightDark.pop,spark:saBrightDark.spark,blaze:saBrightDark.blaze,surge:saBrightDark.surge,flame:saBrightDark.flame,gold:saBrightDark.gold,textLight:"#EDE3D3",textMuted:"#B7A793",isLight:!1}},ivory:{light:{bg:"#FBF6EC",bgPanel:"#ffffff",bgAlt:ivoryColors.ivoryTint,primary:ivoryColors.ivoryBrand,secondary:ivoryColors.ivoryText,accent:ivoryColors.ivoryAccent,glow:ivBrightLight.glow,pop:ivBrightLight.pop,spark:ivBrightLight.spark,blaze:ivBrightLight.blaze,surge:ivBrightLight.surge,flame:ivBrightLight.flame,gold:ivBrightLight.gold,textLight:"#2C2318",textMuted:ivoryColors.gray,isLight:!0},dark:{bg:ivoryColors.black,bgPanel:"#2A2219",bgAlt:"#33291B",primary:ivoryColors.ivoryAccent,secondary:ivoryColors.ivoryBrand,accent:ivoryColors.ivoryBright,glow:ivBrightDark.glow,pop:ivBrightDark.pop,spark:ivBrightDark.spark,blaze:ivBrightDark.blaze,surge:ivBrightDark.surge,flame:ivBrightDark.flame,gold:ivBrightDark.gold,textLight:"#EFE6D6",textMuted:"#BBAC97",isLight:!1}},sun:{light:{bg:"#FFF9EC",bgPanel:"#ffffff",bgAlt:sunColors.sunTint,primary:sunColors.sunBrand,secondary:sunColors.sunText,accent:sunColors.sunAccent,glow:suBrightLight.glow,pop:suBrightLight.pop,spark:suBrightLight.spark,blaze:suBrightLight.blaze,surge:suBrightLight.surge,flame:suBrightLight.flame,gold:suBrightLight.gold,textLight:"#2A2210",textMuted:sunColors.gray,isLight:!0},dark:{bg:sunColors.black,bgPanel:"#2A2109",bgAlt:"#33290C",primary:sunColors.sunAccent,secondary:sunColors.sunBrand,accent:sunColors.sunBright,glow:suBrightDark.glow,pop:suBrightDark.pop,spark:suBrightDark.spark,blaze:suBrightDark.blaze,surge:suBrightDark.surge,flame:suBrightDark.flame,gold:suBrightDark.gold,textLight:"#F3E9CF",textMuted:"#BEAC82",isLight:!1}},loop:{light:{bg:loopColors.white,bgPanel:"#ffffff",bgAlt:loopColors.subtle,primary:loopColors.loopBrand,secondary:loopColors.loopText,accent:loopColors.loopAccent,glow:loBrightLight.glow,pop:loBrightLight.pop,spark:loBrightLight.spark,blaze:loBrightLight.blaze,surge:loBrightLight.surge,flame:loBrightLight.flame,gold:loBrightLight.gold,textLight:loopColors.ink,textMuted:loopColors.gray,isLight:!0},dark:{bg:loopColors.black,bgPanel:"#19191B",bgAlt:loopColors.subtleDark,primary:loopColors.loopBrand,secondary:loopColors.loopBright,accent:loopColors.loopAccent,glow:loBrightDark.glow,pop:loBrightDark.pop,spark:loBrightDark.spark,blaze:loBrightDark.blaze,surge:loBrightDark.surge,flame:loBrightDark.flame,gold:loBrightDark.gold,textLight:loopColors.inkDark,textMuted:loopColors.grayDark,isLight:!1}}};function getColorPalette(Au="datalayer",lo="auto"){const $u=lo==="auto"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":lo;return palettes[Au]?.[$u]??palettes.datalayer.dark}function useColorPalette(){const{colorMode:Au,theme:lo}=useThemeStore();return getColorPalette(lo,Au)}const SHEET_SHADOW="0 1px 2px rgba(0,0,0,0.06), 0 24px 48px -28px rgba(0,0,0,0.35)";function Sheet(Au){return jsxRuntimeExports.jsx(Box,{bg:"canvas.default",border:"1px solid",borderColor:"border.default",borderRadius:"card",boxShadow:SHEET_SHADOW,...Au})}const sizeMap$2={small:16,medium:32,large:64};function _DlIconInverseColormode$2({mode:Au,children:lo}){const $u=reactExports.useRef(null),[Ru,Iu]=reactExports.useState({mode:typeof Au=="string"?Au:null,lightTheme:null,darkTheme:null});return reactExports.useLayoutEffect(()=>{if(typeof document>"u")return;let Pu=null,Ou=null,Mu=null,Du=$u.current&&$u.current.parentElement;for(;Du&&(!Pu||!Ou||!Mu);)Du.getAttribute&&(Pu=Pu||Du.getAttribute("data-color-mode"),Ou=Ou||Du.getAttribute("data-light-theme"),Mu=Mu||Du.getAttribute("data-dark-theme")),Du=Du.parentElement;(!Pu||Pu==="auto")&&(Pu=typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),Iu({mode:typeof Au=="string"?Au:Pu==="dark"?"light":"dark",lightTheme:Ou,darkTheme:Mu})},[Au]),reactExports.createElement("span",{ref:$u,"data-color-mode":Ru.mode||"light","data-light-theme":Ru.lightTheme||void 0,"data-dark-theme":Ru.darkTheme||void 0,style:{display:"inline-flex",lineHeight:0,color:"var(--fgColor-default, var(--color-fg-default, currentColor))"}},lo)}function AiAgentIcon({title:Au,titleId:lo,size:$u,colored:Ru,themed:Iu,colormode:Pu,...Ou},Mu){const Du=reactExports.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",fill:Iu?"var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor))":"var(--datalayer-icon-color, currentColor)",width:$u?typeof $u=="string"?sizeMap$2[$u]:$u:"16px","aria-hidden":"true",ref:Mu,"aria-labelledby":lo},Ou,{"data-datalayer-icon":"",style:Ou&&Ou.color!=null?Object.assign({},Ou.style,{"--datalayer-icon-color":Ou.color,color:Ou.color}):Ou&&Ou.style}),reactExports.createElement("style",null,'[data-color-mode="light"]{--datalayer-icon-color-scheme:light}[data-color-mode="dark"]{--datalayer-icon-color-scheme:dark}svg[data-datalayer-icon]{color-scheme:var(--datalayer-icon-color-scheme, light dark)}'),Au?reactExports.createElement("title",{id:lo},Au):null,reactExports.createElement("path",{d:"M5.75 7.5a.75.75 0 01.75.75v1.5a.75.75 0 01-1.5 0v-1.5a.75.75 0 01.75-.75zm5.25.75a.75.75 0 00-1.5 0v1.5a.75.75 0 001.5 0v-1.5z"}),reactExports.createElement("path",{d:"M6.25 0h2A.75.75 0 019 .75V3.5h3.25a2.25 2.25 0 012.25 2.25V8h.75a.75.75 0 010 1.5h-.75v2.75a2.25 2.25 0 01-2.25 2.25h-8.5a2.25 2.25 0 01-2.25-2.25V9.5H.75a.75.75 0 010-1.5h.75V5.75A2.25 2.25 0 013.75 3.5H7.5v-2H6.25a.75.75 0 010-1.5zM3 5.75v6.5c0 .414.336.75.75.75h8.5a.75.75 0 00.75-.75v-6.5a.75.75 0 00-.75-.75h-8.5a.75.75 0 00-.75.75z"}));return Pu?reactExports.createElement(_DlIconInverseColormode$2,{mode:typeof Pu=="string"?Pu:void 0},Du):Du}const ForwardRef$2=reactExports.forwardRef(AiAgentIcon),sizeMap$1={small:16,medium:32,large:64};function _DlIconInverseColormode$1({mode:Au,children:lo}){const $u=reactExports.useRef(null),[Ru,Iu]=reactExports.useState({mode:typeof Au=="string"?Au:null,lightTheme:null,darkTheme:null});return reactExports.useLayoutEffect(()=>{if(typeof document>"u")return;let Pu=null,Ou=null,Mu=null,Du=$u.current&&$u.current.parentElement;for(;Du&&(!Pu||!Ou||!Mu);)Du.getAttribute&&(Pu=Pu||Du.getAttribute("data-color-mode"),Ou=Ou||Du.getAttribute("data-light-theme"),Mu=Mu||Du.getAttribute("data-dark-theme")),Du=Du.parentElement;(!Pu||Pu==="auto")&&(Pu=typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),Iu({mode:typeof Au=="string"?Au:Pu==="dark"?"light":"dark",lightTheme:Ou,darkTheme:Mu})},[Au]),reactExports.createElement("span",{ref:$u,"data-color-mode":Ru.mode||"light","data-light-theme":Ru.lightTheme||void 0,"data-dark-theme":Ru.darkTheme||void 0,style:{display:"inline-flex",lineHeight:0,color:"var(--fgColor-default, var(--color-fg-default, currentColor))"}},lo)}function MicrophoneIcon({title:Au,titleId:lo,size:$u,colored:Ru,themed:Iu,colormode:Pu,...Ou},Mu){const Du=reactExports.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 72 72",fill:Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 72%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 62%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 72%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 62%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 72%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",width:$u?typeof $u=="string"?sizeMap$1[$u]:$u:"16px","aria-hidden":"true",ref:Mu,"aria-labelledby":lo},Ou,{"data-datalayer-icon":"",style:Ou&&Ou.color!=null?Object.assign({},Ou.style,{"--datalayer-icon-color":Ou.color,color:Ou.color}):Ou&&Ou.style}),reactExports.createElement("style",null,'[data-color-mode="light"]{--datalayer-icon-color-scheme:light}[data-color-mode="dark"]{--datalayer-icon-color-scheme:dark}svg[data-datalayer-icon]{color-scheme:var(--datalayer-icon-color-scheme, light dark)}'),Au?reactExports.createElement("title",{id:lo},Au):null,reactExports.createElement("path",{fill:Ru?"#3F3F3F":Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 41%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 93%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 41%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 93%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 41%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",d:"M39.4 29.52c-2.636-2.216-2.553-3.52-2.55-3.523-.109-.127-1.758-1.676-1.777-2.156l-.009-.082-2.556 3.283c.324-.446-6.322 10.406-6.322 10.406L14.393 53.686l3.373 3.372S42.18 35.781 41.828 36.161l3.403-3.356c-.107.004-3.193-1.068-5.83-3.284z"}),reactExports.createElement("path",{fill:Ru?"#D0CFCE":Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 71%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 63%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 71%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 63%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 71%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",d:"M54.62 30.18a.998.998 0 01-1.411.093l-16.62-14.58a1 1 0 01-.099-1.4c-.003.003-.007.004-.01.008l-.654.786a1 1 0 00.11 1.391L52.554 31.06a1 1 0 001.427-.113l.655-.787c.04-.047.055-.105.084-.157-.033.06-.054.123-.1.177z"}),reactExports.createElement("path",{fill:Ru?"#3F3F3F":Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 41%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 93%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 41%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 93%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 41%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",d:"M55.258 25.541c-1.162 3.4-5.283 5.562-5.283 5.562-1.926 1.097-4.032 1.62-6.038 1.52 0 0-.347-.081-.913-.272-1.828-.634-5.85-2.485-7.25-6.88-.377-2.002-.159-4.185.646-6.277 1.023-4.264 4.995-6.256 4.995-6.256 1.41-.956 2.94-1.59 4.479-1.871 2.82-.533 5.66.08 7.775 1.972 3.327 2.947 3.844 8.086 1.59 12.502z"}),reactExports.createElement("path",{fill:Ru?"#9B9B9A":Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 55%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 79%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 55%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 79%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 55%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",d:"M51.475 25.541c-1.172 3.4-5.283 5.562-5.283 5.562a12.08 12.08 0 01-3.168 1.247c-1.828-.633-5.85-2.484-7.25-6.88-.377-2.001-.159-4.184.646-6.276 1.022-4.264 4.995-6.256 4.995-6.256 1.41-.956 2.94-1.59 4.479-1.871 1.46.292 2.83.946 3.992 1.972 3.317 2.947 3.833 8.086 1.589 12.502z"}),reactExports.createElement("path",{d:"M30.75 38.941l4.02-4.619m14.744-3.892c-1.804 1.014-3.774 1.495-5.65 1.404m-2.36-18.184c3.737-2.497 8.405-2.591 11.465.093 3.108 2.727 3.59 7.471 1.489 11.545m-18.223-.065c-.354-1.844-.152-3.862.602-5.789m-3.52 8.196L14.393 53.686l3.373 3.373 23.34-21.572M15.497 56.001l-3.046 3.074m41.417-29.554L37.249 14.94",fill:"none",stroke:Ru?"#000":Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 38%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 96%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 38%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 96%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 38%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",strokeLinecap:"round",strokeLinejoin:"round",strokeMiterlimit:10,strokeWidth:2}));return Pu?reactExports.createElement(_DlIconInverseColormode$1,{mode:typeof Pu=="string"?Pu:void 0},Du):Du}const ForwardRef$1=reactExports.forwardRef(MicrophoneIcon),sizeMap={small:16,medium:32,large:64};function _DlIconInverseColormode({mode:Au,children:lo}){const $u=reactExports.useRef(null),[Ru,Iu]=reactExports.useState({mode:typeof Au=="string"?Au:null,lightTheme:null,darkTheme:null});return reactExports.useLayoutEffect(()=>{if(typeof document>"u")return;let Pu=null,Ou=null,Mu=null,Du=$u.current&&$u.current.parentElement;for(;Du&&(!Pu||!Ou||!Mu);)Du.getAttribute&&(Pu=Pu||Du.getAttribute("data-color-mode"),Ou=Ou||Du.getAttribute("data-light-theme"),Mu=Mu||Du.getAttribute("data-dark-theme")),Du=Du.parentElement;(!Pu||Pu==="auto")&&(Pu=typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),Iu({mode:typeof Au=="string"?Au:Pu==="dark"?"light":"dark",lightTheme:Ou,darkTheme:Mu})},[Au]),reactExports.createElement("span",{ref:$u,"data-color-mode":Ru.mode||"light","data-light-theme":Ru.lightTheme||void 0,"data-dark-theme":Ru.darkTheme||void 0,style:{display:"inline-flex",lineHeight:0,color:"var(--fgColor-default, var(--color-fg-default, currentColor))"}},lo)}function PlusCircleIcon({title:Au,titleId:lo,size:$u,colored:Ru,themed:Iu,colormode:Pu,...Ou},Mu){const Du=reactExports.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fillRule:"evenodd",clipRule:"evenodd",width:$u?typeof $u=="string"?sizeMap[$u]:$u:"16px",viewBox:"0 0 24 24",fill:Iu?"var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor))":"var(--datalayer-icon-color, currentColor)","aria-hidden":"true",ref:Mu,"aria-labelledby":lo},Ou,{"data-datalayer-icon":"",style:Ou&&Ou.color!=null?Object.assign({},Ou.style,{"--datalayer-icon-color":Ou.color,color:Ou.color}):Ou&&Ou.style}),reactExports.createElement("style",null,'[data-color-mode="light"]{--datalayer-icon-color-scheme:light}[data-color-mode="dark"]{--datalayer-icon-color-scheme:dark}svg[data-datalayer-icon]{color-scheme:var(--datalayer-icon-color-scheme, light dark)}'),Au?reactExports.createElement("title",{id:lo},Au):null,reactExports.createElement("path",{d:"M11.5 0C17.847 0 23 5.153 23 11.5S17.847 23 11.5 23 0 17.847 0 11.5 5.153 0 11.5 0zm0 1C17.295 1 22 5.705 22 11.5S17.295 22 11.5 22 1 17.295 1 11.5 5.705 1 11.5 1zm.5 10h6v1h-6v6h-1v-6H5v-1h6V5h1v6z"}));return Pu?reactExports.createElement(_DlIconInverseColormode,{mode:typeof Pu=="string"?Pu:void 0},Du):Du}const ForwardRef=reactExports.forwardRef(PlusCircleIcon),__vite_import_meta_env__$2={},createStoreImpl$1=Au=>{let lo;const $u=new Set,Ru=(Bu,ju)=>{const Fu=typeof Bu=="function"?Bu(lo):Bu;if(!Object.is(Fu,lo)){const zu=lo;lo=ju??(typeof Fu!="object"||Fu===null)?Fu:Object.assign({},lo,Fu),$u.forEach(Uu=>Uu(lo,zu))}},Iu=()=>lo,Du={setState:Ru,getState:Iu,getInitialState:()=>Lu,subscribe:Bu=>($u.add(Bu),()=>$u.delete(Bu)),destroy:()=>{(__vite_import_meta_env__$2?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),$u.clear()}},Lu=lo=Au(Ru,Iu,Du);return Du},createStore$1=Au=>Au?createStoreImpl$1(Au):createStoreImpl$1;var withSelector={exports:{}},withSelector_production={},shim={exports:{}},useSyncExternalStoreShim_production={};var hasRequiredUseSyncExternalStoreShim_production;function requireUseSyncExternalStoreShim_production(){if(hasRequiredUseSyncExternalStoreShim_production)return useSyncExternalStoreShim_production;hasRequiredUseSyncExternalStoreShim_production=1;var Au=requireReact();function lo(ju,Fu){return ju===Fu&&(ju!==0||1/ju===1/Fu)||ju!==ju&&Fu!==Fu}var $u=typeof Object.is=="function"?Object.is:lo,Ru=Au.useState,Iu=Au.useEffect,Pu=Au.useLayoutEffect,Ou=Au.useDebugValue;function Mu(ju,Fu){var zu=Fu(),Uu=Ru({inst:{value:zu,getSnapshot:Fu}}),Hu=Uu[0].inst,Vu=Uu[1];return Pu(function(){Hu.value=zu,Hu.getSnapshot=Fu,Du(Hu)&&Vu({inst:Hu})},[ju,zu,Fu]),Iu(function(){return Du(Hu)&&Vu({inst:Hu}),ju(function(){Du(Hu)&&Vu({inst:Hu})})},[ju]),Ou(zu),zu}function Du(ju){var Fu=ju.getSnapshot;ju=ju.value;try{var zu=Fu();return!$u(ju,zu)}catch{return!0}}function Lu(ju,Fu){return Fu()}var Bu=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Lu:Mu;return useSyncExternalStoreShim_production.useSyncExternalStore=Au.useSyncExternalStore!==void 0?Au.useSyncExternalStore:Bu,useSyncExternalStoreShim_production}var hasRequiredShim;function requireShim(){return hasRequiredShim||(hasRequiredShim=1,shim.exports=requireUseSyncExternalStoreShim_production()),shim.exports}var hasRequiredWithSelector_production;function requireWithSelector_production(){if(hasRequiredWithSelector_production)return withSelector_production;hasRequiredWithSelector_production=1;var Au=requireReact(),lo=requireShim();function $u(Lu,Bu){return Lu===Bu&&(Lu!==0||1/Lu===1/Bu)||Lu!==Lu&&Bu!==Bu}var Ru=typeof Object.is=="function"?Object.is:$u,Iu=lo.useSyncExternalStore,Pu=Au.useRef,Ou=Au.useEffect,Mu=Au.useMemo,Du=Au.useDebugValue;return withSelector_production.useSyncExternalStoreWithSelector=function(Lu,Bu,ju,Fu,zu){var Uu=Pu(null);if(Uu.current===null){var Hu={hasValue:!1,value:null};Uu.current=Hu}else Hu=Uu.current;Uu=Mu(function(){function Gu(Xu){if(!Wu){if(Wu=!0,Ku=Xu,Xu=Fu(Xu),zu!==void 0&&Hu.hasValue){var ed=Hu.value;if(zu(ed,Xu))return Ju=ed}return Ju=Xu}if(ed=Ju,Ru(Ku,Xu))return ed;var td=Fu(Xu);return zu!==void 0&&zu(ed,td)?(Ku=Xu,ed):(Ku=Xu,Ju=td)}var Wu=!1,Ku,Ju,Yu=ju===void 0?null:ju;return[function(){return Gu(Bu())},Yu===null?void 0:function(){return Gu(Yu())}]},[Bu,ju,Fu,zu]);var Vu=Iu(Lu,Uu[0],Uu[1]);return Ou(function(){Hu.hasValue=!0,Hu.value=Vu},[Vu]),Du(Vu),Vu},withSelector_production}var hasRequiredWithSelector;function requireWithSelector(){return hasRequiredWithSelector||(hasRequiredWithSelector=1,withSelector.exports=requireWithSelector_production()),withSelector.exports}var withSelectorExports=requireWithSelector();const useSyncExternalStoreExports=getDefaultExportFromCjs(withSelectorExports),__vite_import_meta_env__$1={},{useDebugValue}=vM,{useSyncExternalStoreWithSelector}=useSyncExternalStoreExports;let didWarnAboutEqualityFn=!1;const identity$1=Au=>Au;function useStore$1(Au,lo=identity$1,$u){(__vite_import_meta_env__$1?"production":void 0)!=="production"&&$u&&!didWarnAboutEqualityFn&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),didWarnAboutEqualityFn=!0);const Ru=useSyncExternalStoreWithSelector(Au.subscribe,Au.getState,Au.getServerState||Au.getInitialState,lo,$u);return useDebugValue(Ru),Ru}const createImpl$1=Au=>{(__vite_import_meta_env__$1?"production":void 0)!=="production"&&typeof Au!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const lo=typeof Au=="function"?createStore$1(Au):Au,$u=(Ru,Iu)=>useStore$1(lo,Ru,Iu);return Object.assign($u,lo),$u},create$g=Au=>Au?createImpl$1(Au):createImpl$1,CONTROL_PLANE_URL="https://prod1.datalayer.run",RUNTIMES_PLANE_URL="https://r1.datalayer.run",MCP_SERVER_URL="https://mcp.datalayer.run/mcp",DEFAULT_PLANE_URLS={iamUrl:CONTROL_PLANE_URL,managerUrl:CONTROL_PLANE_URL,libraryUrl:CONTROL_PLANE_URL,spacerUrl:CONTROL_PLANE_URL,otelUrl:CONTROL_PLANE_URL,growthUrl:CONTROL_PLANE_URL,inboundsUrl:CONTROL_PLANE_URL,successUrl:CONTROL_PLANE_URL,supportUrl:CONTROL_PLANE_URL,contentsUrl:RUNTIMES_PLANE_URL,runtimesUrl:RUNTIMES_PLANE_URL,schedulerUrl:RUNTIMES_PLANE_URL,aiAgentsUrl:RUNTIMES_PLANE_URL,aiInferenceUrl:RUNTIMES_PLANE_URL,datalayerMcpServerUrl:MCP_SERVER_URL};class Logger{scope;isDevelopment;constructor(lo){this.scope=lo,this.isDevelopment=!1}log(lo,$u,...Ru){if(!this.isDevelopment&&lo==="debug")return;const Pu=`[${new Date().toISOString()}] [${this.scope}] [${lo.toUpperCase()}]`;switch(lo){case"debug":console.debug(Pu,$u,...Ru);break;case"info":console.info(Pu,$u,...Ru);break;case"warn":console.warn(Pu,$u,...Ru);break;case"error":console.error(Pu,$u,...Ru);break}}debug(lo,...$u){this.log("debug",lo,...$u)}info(lo,...$u){this.log("info",lo,...$u)}warn(lo,...$u){this.log("warn",lo,...$u)}error(lo,...$u){this.log("error",lo,...$u)}}function createLogger(Au){return new Logger(Au)}const configLogger=createLogger("config");let loadConfigurationFromServer=!0,initialConfiguration={token:"",credits:0,cpuEnvironment:'ai-agents-env"',gpuEnvironment:"ai-env",useMock:!1,whiteLabel:!0,loadConfigurationFromServer:!0,jupyterServerless:!1,...DEFAULT_PLANE_URLS,launcher:{category:"Datalayer",name:"Datalayer",icon:null,rank:1},brand:{name:"Datalayer",about:"AI Agents for Data Analysis",logoUrl:"https://assets.datalayer.tech/datalayer-25.svg",logoSquareUrl:"https://assets.datalayer.tech/datalayer-square.png",copyright:"© 2025 Datalayer, Inc",docsUrl:"https://datalayer.ai/docs",supportUrl:"https://datalayer.ai/support",termsUrl:"https://datalayer.ai/terms",pricingUrl:"https://datalayer.ai/pricing",privacyUrl:"https://datalayer.ai/privacy"}};const pageConfiguration={};try{if(typeof document<"u"){const Au=document.getElementById("datalayer-config-data");if(Au?.innerText){const lo=JSON.parse(Au?.innerText||"{}");Object.assign(pageConfiguration,lo),lo.loadConfigurationFromServer!=null&&(loadConfigurationFromServer=lo.loadConfigurationFromServer),initialConfiguration={...initialConfiguration,...lo},configLogger.info("Datalayer configuration loaded from HTML page",initialConfiguration),window.document.title=`${initialConfiguration.brand.name} ☰ ${initialConfiguration.brand.about}`}}}catch(Au){configLogger.debug("No valid configuration found in the webpage.",Au)}const coreStore=createStore$1((Au,lo)=>({tab:0,getIntTab:()=>Math.floor(lo().tab),setTab:$u=>Au(Ru=>({tab:$u})),configuration:initialConfiguration,setConfiguration:$u=>{configLogger.debug("Setting Datalayer configuration",$u),Au(Ru=>({configuration:{...Ru.configuration,...$u}}))},version:"",setVersion:$u=>{$u&&!lo().version&&Au(Ru=>({version:$u}))},loadConfigurationFromServer,setLoadConfigurationFromServer:$u=>{Au(Ru=>({loadConfigurationFromServer:$u}))}}));function useCoreStore(Au){return useStore$1(coreStore,Au)}const getOtelConsumeUrl=()=>coreStore.getState().configuration.otelUrl,BACKEND_TOOL_ACTIONS={"create-plan":["read"],"current-time":["read"],decide:["read"],"display-recipe":["read"],"example-create-plan":["read"],"example-current-time":["read"],"example-display-recipe":["read"],"example-generate-haiku":["read"],"example-generate-task-steps":["read"],"example-get-weather":["read"],"example-render-a2ui-surface":["read"],"example-update-plan-step":["read"],"generate-haiku":["read"],"generate-task-steps":["read"],"get-weather":["read"],"runtime-echo":["read"],"runtime-send-mail":["send"],"runtime-sensitive-echo":["read"],"update-plan-step":["read"]},SERVER_ACTIONS={alphavantage:{default:[],tools:{},conditions:{},signs:{}},chart:{checked:"2026-10-02",default:[],tools:{generate_area_chart:["read"],generate_bar_chart:["read"],generate_boxplot_chart:["read"],generate_column_chart:["read"],generate_district_map:["read"],generate_dual_axes_chart:["read"],generate_fishbone_diagram:["read"],generate_flow_diagram:["read"],generate_funnel_chart:["read"],generate_histogram_chart:["read"],generate_line_chart:["read"],generate_liquid_chart:["read"],generate_mind_map:["read"],generate_network_graph:["read"],generate_organization_chart:["read"],generate_path_map:["read"],generate_pie_chart:["read"],generate_pin_map:["read"],generate_radar_chart:["read"],generate_sankey_chart:["read"],generate_scatter_chart:["read"],generate_treemap_chart:["read"],generate_venn_chart:["read"],generate_violin_chart:["read"],generate_waterfall_chart:["read"],generate_word_cloud_chart:["read"],generate_spreadsheet:["read"]},conditions:{},signs:{}},datalayer:{checked:"2026-10-05",default:[],tools:{read_notebook:["read"],read_cell:["read"],download_notebook:["read"],list_notebooks:["read"],list_spaces:["read"],list_space_notebooks:["read"],find_notebook:["read"],list_notebook_versions:["read"],list_kernels:["read"],list_files:["read"],list_sandboxes:["read"],list_toolsets:["read"],search_library:["read"],get_library_artifact:["read"],read_library_artifact:["read"],search_earth_datasets:["read"],search_earth_datagranules:["read"],download_earth_data_granules:["read"],odoo_get_context:["read"],odoo_get_account:["read"],odoo_get_settings:["read"],odoo_list_companies:["read"],odoo_set_company:["write"],odoo_list_models:["read"],odoo_get_fields:["read"],odoo_search_records:["read"],odoo_read_records:["read"],odoo_group_records:["read"],odoo_create_record:["write"],odoo_update_records:["write"],odoo_delete_records:["delete"],odoo_accounting_list_invoices:["read"],odoo_accounting_get_invoice:["read"],odoo_accounting_list_journal_entries:["read"],odoo_accounting_list_open_balances:["read"],odoo_accounting_list_accounts:["read"],odoo_accounting_list_journals:["read"],odoo_accounting_get_journal_entry:["read"],odoo_accounting_trial_balance:["read"],odoo_accounting_general_ledger:["read"],odoo_winauditor_preview_balance:["read"],odoo_winauditor_preview_general_journal:["read"],odoo_winauditor_preview_general_ledger:["read"],odoo_accounting_create_draft_invoice:["write"],odoo_accounting_post_invoice:["write"],odoo_accounting_create_draft_journal_entry:["write"],odoo_accounting_post_journal_entry:["write"],odoo_winauditor_import_balance:["write"],odoo_winauditor_import_general_journal:["write"],odoo_winauditor_import_general_ledger:["write"],odoo_winauditor_preview_import_file:["read"],odoo_winauditor_migration_status:["read"],odoo_winauditor_import_partners:["write"],odoo_winauditor_import_chart_of_accounts:["write"],odoo_winauditor_ensure_journals:["write"],odoo_winauditor_import_journal_items:["write"],odoo_winauditor_post_migration_entries:["write"],odoo_winauditor_reconcile_journal_items:["write"],odoo_winauditor_import_assets:["write"],odoo_winauditor_validate_assets:["write"],odoo_winauditor_rollback_migration:["delete"],odoo_winauditor_attach_document:["write"],odoo_winauditor_list_attachments:["read"],odoo_winauditor_validate_migration:["read"],odoo_accounting_list_partners:["read"],odoo_accounting_partner_ledger:["read"],odoo_accounting_aged_balance:["read"],odoo_accounting_list_taxes:["read"],odoo_accounting_list_assets:["read"],odoo_accounting_get_asset:["read"],odoo_accounting_reconcile_lines:["write"],odoo_accounting_unreconcile_lines:["write"],odoo_accounting_bank_status:["read"],odoo_accounting_list_bank_lines:["read"],odoo_accounting_get_bank_line:["read"],odoo_accounting_suggest_bank_matches:["read"],odoo_accounting_suggest_reconciliations:["read"],odoo_accounting_explain_account_balance:["read"],odoo_accounting_list_bank_feeds:["read"],odoo_accounting_list_currency_rates:["read"],odoo_accounting_get_lock_dates:["read"],odoo_accounting_book_bank_line:["write"],odoo_accounting_match_bank_line:["write"],odoo_accounting_reset_bank_line:["write"],odoo_accounting_remove_duplicate_bank_lines:["delete"],odoo_accounting_link_bank_feed:["write"],odoo_accounting_create_vendor_bill:["write"],odoo_accounting_create_customer_invoice:["write"],odoo_accounting_set_currency_rates:["write"],odoo_accounting_set_lock_date:["write"],odoo_accounting_create_matching_model:["write"],odoo_accounting_get_tax_settings:["read"],odoo_accounting_list_tax_returns:["read"],odoo_accounting_get_tax_return:["read"],odoo_accounting_tax_grids:["read"],odoo_accounting_list_tax_grid_lines:["read"],odoo_accounting_check_tax_period:["read"],odoo_accounting_list_untagged_tax_lines:["read"],odoo_accounting_set_tax_periodicity:["write"],odoo_accounting_set_tax_grids:["write"],read_benchmark:["read"],read_benchmark_task:["read"],read_benchmark_task_trajectory:["read"],list_benchmark_task_files:["read"],list_content_sources:["read"],describe_content_source:["read"],list_content_attachments:["read"],list_dataset_revisions:["read"],query_status:["read"],list_secrets:["read"],use_notebook:["read"],unuse_notebook:["read"],connect_to_jupyter:["read"],insert_cell:["write"],delete_cell:["delete"],move_cell:["write"],edit_cell_source:["write"],snapshot_notebook:["write"],restore_notebook:["write"],overwrite_cell_source:["write"],clear_cell_output:["write"],execute_cell:["write"],execute_code:["write"],restart_notebook:["write"],insert_execute_code_cell:["write"],launch_sandbox:["buy"],use_sandbox:["write"],terminate_sandbox:["delete"],snapshot_sandbox:["write","buy"],share_sandbox:["publish"],unshare_sandbox:["write"],marimo_run_cell:["write"],marimo_run_code:["write"],marimo_remove_cell:["delete"],marimo_plan:["read"],marimo_graph:["read"],enable_toolset:["write"],disable_toolset:["write"],attach_content:["write"],detach_content:["write"],query_source:["read"],cancel_query:["write"],save_query_as_revision:["write"],mount_local_folder:["read"]},conditions:{},signs:{}},earthdata:{checked:"2026-10-07",default:[],tools:{search_earth_datasets:["read"],search_earth_datagranules:["read"],download_earth_data_granules:["write"]},conditions:{},signs:{}},eurus:{default:[],tools:{},conditions:{},signs:{}},filesystem:{checked:"2026-10-02",default:[],tools:{read_file:["read"],read_text_file:["read"],read_media_file:["read"],read_multiple_files:["read"],write_file:["write"],edit_file:["write"],create_directory:["write"],list_directory:["read"],list_directory_with_sizes:["read"],directory_tree:["read"],move_file:["write","delete"],search_files:["read"],get_file_info:["read"],list_allowed_directories:["read"]},conditions:{},signs:{}},github:{default:[],tools:{},conditions:{},signs:{}},"google-workspace":{checked:"2026-10-02",default:[],tools:{start_google_auth:["write"],search_gmail_messages:["read"],get_gmail_message_content:["read"],get_gmail_messages_content_batch:["read"],get_gmail_attachment_content:["read","write"],send_gmail_message:["send"],draft_gmail_message:["write"],get_gmail_thread_content:["read"],get_gmail_threads_content_batch:["read"],list_gmail_labels:["read"],manage_gmail_label:["write"],list_gmail_filters:["read"],manage_gmail_filter:["write","send"],modify_gmail_message_labels:["write"],batch_modify_gmail_message_labels:["write"],search_drive_files:["read"],get_drive_file_content:["read"],get_drive_file_download_url:["read"],list_drive_items:["read"],create_drive_folder:["write"],create_drive_file:["write"],import_to_google_doc:["write"],import_to_google_slides:["write"],import_to_google_sheets:["write"],get_drive_file_permissions:["read"],check_drive_file_public_access:["read"],update_drive_file:["write"],get_drive_shareable_link:["read"],manage_drive_access:["publish","send","delete"],copy_drive_file:["write"],set_drive_file_permissions:["publish","write"],list_calendars:["read"],get_events:["read"],manage_event:["write","send"],manage_out_of_office:["write","send"],manage_focus_time:["write","send"],query_freebusy:["read"],create_calendar:["write"],search_docs:["read"],get_doc_content:["read"],list_docs_in_folder:["read"],create_doc:["write"],modify_doc_text:["write"],find_and_replace_doc:["write"],insert_doc_elements:["write"],insert_doc_image:["write"],update_doc_headers_footers:["write"],batch_update_doc:["write","delete"],inspect_doc_structure:["read"],debug_docs_runtime_info:["read"],create_table_with_data:["write"],debug_table_structure:["read"],export_doc_to_pdf:["write"],update_paragraph_style:["write"],get_doc_as_markdown:["read"],manage_doc_tab:["write"],list_document_comments:["read"],manage_document_comment:["write","send"],list_spreadsheets:["read"],get_spreadsheet_info:["read"],read_sheet_values:["read"],modify_sheet_values:["write"],format_sheet_range:["write"],manage_conditional_formatting:["write"],create_spreadsheet:["write"],create_sheet:["write"],list_sheet_tables:["read"],append_table_rows:["write"],manage_sheet_tab:["write"],resize_sheet_dimensions:["write","delete"],move_sheet_rows:["write","delete"],manage_named_range:["write"],list_spreadsheet_comments:["read"],manage_spreadsheet_comment:["write","send"],list_spaces:["read"],get_messages:["read"],send_message:["send","write"],search_messages:["read"],create_reaction:["send"],download_chat_attachment:["read","write"],create_form:["write"],get_form:["read"],set_publish_settings:["publish"],get_form_response:["read"],list_form_responses:["read"],batch_update_form:["write","delete"],create_presentation:["write"],get_presentation:["read"],batch_update_presentation:["write","delete"],get_page:["read"],get_page_thumbnail:["read"],list_presentation_comments:["read"],manage_presentation_comment:["write","send"],list_task_lists:["read"],get_task_list:["read"],manage_task_list:["write"],list_tasks:["read"],get_task:["read"],manage_task:["write"],list_contacts:["read"],get_contact:["read"],search_contacts:["read"],manage_contact:["write"],list_contact_groups:["read"],get_contact_group:["read"],manage_contacts_batch:["write"],manage_contact_group:["write"],search_custom:["read"],get_search_engine_info:["read"],get_script_project:["read"],manage_script_content:["write","delete"],run_script_function:["write","send","delete","publish"],manage_deployment:["publish"],list_script_deployments:["read"],manage_script_project:["write"],manage_script_version:["write"],get_script_version:["read"],get_script_activity:["read"],generate_trigger_code:["read"],manage_script_trigger:["write"]},conditions:{manage_gmail_label:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_gmail_filter:[{argument:"action",classes:["delete"],equals:["delete","update"]}],modify_gmail_message_labels:[{argument:"add_label_ids",classes:["delete"],includes:["TRASH","SPAM"]}],batch_modify_gmail_message_labels:[{argument:"add_label_ids",classes:["delete"],includes:["TRASH","SPAM"]}],update_drive_file:[{argument:"trashed",classes:["delete"],equals:[!0]}],manage_event:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_out_of_office:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_focus_time:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_doc_tab:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_conditional_formatting:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_sheet_tab:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_named_range:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_task_list:[{argument:"action",classes:["delete"],equals:["delete","clear_completed"]}],manage_task:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_contact:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_contacts_batch:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_contact_group:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_deployment:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_script_project:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_script_trigger:[{argument:"action",classes:["delete"],equals:["delete"]}]},signs:{send_gmail_message:"body",draft_gmail_message:"body",send_message:"message_text"}},huggingface:{default:[],tools:{},conditions:{},signs:{}},kaggle:{default:[],tools:{},conditions:{},signs:{}},odoo:{default:[],tools:{},conditions:{},signs:{}},"odoo-accounting":{checked:"2026-10-05",default:[],tools:{odoo_accounting_list_invoices:["read"],odoo_accounting_get_invoice:["read"],odoo_accounting_list_journal_entries:["read"],odoo_accounting_list_open_balances:["read"],odoo_accounting_list_accounts:["read"],odoo_accounting_list_journals:["read"],odoo_accounting_get_journal_entry:["read"],odoo_accounting_trial_balance:["read"],odoo_accounting_general_ledger:["read"],odoo_accounting_create_draft_invoice:["write"],odoo_accounting_post_invoice:["write"],odoo_accounting_create_draft_journal_entry:["write"],odoo_accounting_post_journal_entry:["write"],odoo_accounting_list_partners:["read"],odoo_accounting_partner_ledger:["read"],odoo_accounting_aged_balance:["read"],odoo_accounting_list_taxes:["read"],odoo_accounting_list_assets:["read"],odoo_accounting_get_asset:["read"],odoo_accounting_reconcile_lines:["write"],odoo_accounting_unreconcile_lines:["write"],odoo_accounting_bank_status:["read"],odoo_accounting_list_bank_lines:["read"],odoo_accounting_get_bank_line:["read"],odoo_accounting_suggest_bank_matches:["read"],odoo_accounting_suggest_reconciliations:["read"],odoo_accounting_explain_account_balance:["read"],odoo_accounting_list_bank_feeds:["read"],odoo_accounting_list_currency_rates:["read"],odoo_accounting_get_lock_dates:["read"],odoo_accounting_book_bank_line:["write"],odoo_accounting_match_bank_line:["write"],odoo_accounting_reset_bank_line:["write"],odoo_accounting_remove_duplicate_bank_lines:["delete"],odoo_accounting_link_bank_feed:["write"],odoo_accounting_create_vendor_bill:["write"],odoo_accounting_create_customer_invoice:["write"],odoo_accounting_set_currency_rates:["write"],odoo_accounting_set_lock_date:["write"],odoo_accounting_create_matching_model:["write"],odoo_accounting_get_tax_settings:["read"],odoo_accounting_list_tax_returns:["read"],odoo_accounting_get_tax_return:["read"],odoo_accounting_tax_grids:["read"],odoo_accounting_list_tax_grid_lines:["read"],odoo_accounting_check_tax_period:["read"],odoo_accounting_list_untagged_tax_lines:["read"],odoo_accounting_set_tax_periodicity:["write"],odoo_accounting_set_tax_grids:["write"]},conditions:{},signs:{}},salesforce:{default:[],tools:{},conditions:{},signs:{}},slack:{checked:"2026-10-02",default:[],tools:{slack_list_channels:["read"],slack_post_message:["send"],slack_reply_to_thread:["send"],slack_add_reaction:["send"],slack_get_channel_history:["read"],slack_get_thread_replies:["read"],slack_get_users:["read"],slack_get_user_profile:["read"]},conditions:{},signs:{slack_post_message:"text",slack_reply_to_thread:"text"}},tavily:{checked:"2026-10-02",default:[],tools:{tavily_search:["read"],tavily_extract:["read"],tavily_crawl:["read"],tavily_map:["read"],tavily_research:["read"]},conditions:{},signs:{}}},BEHAVIOURS=["do_it","if_asked","ask_first","leave_to_me"],DEFAULT_BEHAVIOURS={read:"do_it",write:"ask_first",send:"ask_first",buy:"ask_first",delete:"ask_first",publish:"ask_first"},SERVER_TOOL=/^([A-Za-z0-9_-]+)(?::\d+(?:\.\d+)*)?\.([A-Za-z_][A-Za-z0-9_-]*)$/,own$a=(Au,lo)=>Object.prototype.hasOwnProperty.call(Au,lo)?Au[lo]:void 0,idOf=Au=>{const lo=Au.lastIndexOf(":");return lo>0&&Au.slice(lo+1).includes(".")?Au.slice(0,lo):Au};function splitRef(Au){const lo=SERVER_TOOL.exec(Au);return lo?[lo[1],lo[2]]:[void 0,idOf(Au)]}const isPattern=Au=>/[*?]/.test(Au);function matchesPattern(Au,lo){const $u=Array.from(lo,Ru=>Ru==="*"?"[\\s\\S]*":Ru==="?"?"[\\s\\S]":Ru.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("");return new RegExp(`^${$u}$`).test(Au)}const isComparable=Au=>typeof Au=="string"||typeof Au=="boolean"||typeof Au=="number"&&Number.isFinite(Au)&&(!Number.isInteger(Au)||Number.isSafeInteger(Au)),same=(Au,lo)=>typeof Au=="string"&&typeof lo=="string"?Au.trim().toLowerCase()===lo.trim().toLowerCase():isComparable(Au)&&isComparable(lo)&&Au===lo;function conditionHolds(Au,lo){if(!Object.prototype.hasOwnProperty.call(lo,Au.argument))return!1;const $u=lo[Au.argument];return Au.equals?.some(Ru=>same($u,Ru))?!0:Au.includes?.length?(Array.isArray($u)?$u:[$u]).some(Iu=>Au.includes.some(Pu=>same(Iu,Pu))):!1}function entryOf$1(Au,lo){const $u=own$a(SERVER_ACTIONS,Au);if(!$u)return[[],[]];const Ru=own$a($u.tools,lo);if(Ru)return[[...Ru],own$a($u.conditions,lo)??[]];for(const[Iu,Pu]of Object.entries($u.tools))if(isPattern(Iu)&&matchesPattern(lo,Iu))return[[...Pu],own$a($u.conditions,Iu)??[]];return[[...$u.default],[]]}const FORWARDING={"google-workspace.send_gmail_message":{message:"forward_message_id",mailbox:"user_google_email",recipients:["to","cc","bcc"]}};function addresses(Au){return(Array.isArray(Au)?Au:[Au]).filter($u=>typeof $u=="string").flatMap($u=>$u.split(",")).map($u=>{const Ru=/<([^>]*)>/.exec($u);return(Ru?Ru[1]:$u).trim().toLowerCase()}).filter($u=>$u.includes("@"))}const domainOf=Au=>Au.slice(Au.lastIndexOf("@")+1).trim();function forwardsOutside(Au,lo,$u){const Ru=own$a(FORWARDING,`${Au}.${lo}`),Iu=Ru?$u[Ru.message]:void 0;if(!Ru||typeof Iu!="string"||!Iu.trim())return!1;const[Pu]=addresses($u[Ru.mailbox]);return Pu?Ru.recipients.flatMap(Ou=>addresses($u[Ou])).some(Ou=>domainOf(Ou)!==domainOf(Pu)):!0}function classesOf(Au,lo){const[$u,Ru]=splitRef(Au);if($u===void 0)return[...own$a(BACKEND_TOOL_ACTIONS,Ru)??[]];const[Iu,Pu]=entryOf$1($u,Ru);for(const Ou of Pu)if(lo===void 0||conditionHolds(Ou,lo))for(const Mu of Ou.classes)Iu.includes(Mu)||Iu.push(Mu);return lo!==void 0&&Iu.length>0&&!Iu.includes("publish")&&forwardsOutside($u,Ru,lo)&&Iu.push("publish"),Iu}const strictest=Au=>Au.reduce((lo,$u)=>BEHAVIOURS.indexOf($u)>BEHAVIOURS.indexOf(lo)?$u:lo),connectionTo=(Au,lo)=>Au.connections.find($u=>idOf($u.server)===lo),reaches=(Au,lo)=>Au.only.length===0||Au.only.some($u=>matchesPattern(lo,$u)),isClass$1=Au=>Object.prototype.hasOwnProperty.call(DEFAULT_BEHAVIOURS,Au),normal=Au=>{if(isClass$1(Au))return Au;const[lo,$u]=splitRef(Au);return lo!==void 0?`${lo}.${$u}`:$u},byClasses=(Au,lo)=>{const $u={};for(const Ru of Au.rules)for(const Iu of Ru.appliesTo)isClass$1(Iu)&&($u[Iu]=Ru.behaviour);return lo.map(Ru=>$u[Ru]??DEFAULT_BEHAVIOURS[Ru])};function behaviourFor(Au,lo,$u={}){const[Ru,Iu]=splitRef(lo);let Pu,Ou=[],Mu;if($u.classes?Pu=Mu=[...$u.classes]:(Mu=classesOf(lo),Pu=classesOf(lo,{}),Ou=($u.arguments===void 0?Mu:classesOf(lo,$u.arguments)).filter(Bu=>!Pu.includes(Bu))),Ru!==void 0){const Lu=connectionTo(Au,Ru);if(!Lu||!reaches(Lu,Iu)||Lu.access==="read"&&Mu.some(Bu=>Bu!=="read"))return"leave_to_me"}const Du=Ru!==void 0?`${Ru}.${Iu}`:Iu;for(const Lu of Au.rules)if(Lu.appliesTo.some(Bu=>!isClass$1(Bu)&&normal(Bu)===Du))return strictest([Lu.behaviour,...byClasses(Au,Ou)]);return Pu.length===0&&Ou.length===0?"leave_to_me":strictest(byClasses(Au,[...Pu,...Ou]))}const BEHAVIOUR_WORDS={do_it:{says:"Do it",means:"It does it without asking."},if_asked:{says:"Do it if I asked",means:"Only what you approved in advance."},ask_first:{says:"Ask me first",means:"It waits for your yes."},leave_to_me:{says:"Leave it to me",means:"It never does it, and hands it to you."}},ACTION_WORDS={read:"Read",write:"Create or change",send:"Send",buy:"Buy",delete:"Delete",publish:"Share or publish"};function coverOf(Au){const lo=own$a(ACTION_WORDS,Au);if(lo)return lo;const[$u,Ru]=splitRef(Au);return $u?`${Ru} (${$u})`:Ru}const A2A_PROTOCOL_0_0_1={id:"a2a",version:"0.0.1",name:"Agent2Agent",description:"How agents talk to agents: teams and scenes talk over it, an application's route serves it, and its Agent Card advertises its extensions.",publisher:"Google, now the Linux Foundation",layer:"transport",specUrl:"https://a2a-protocol.org",specVersion:"1.0",status:"shipped",connects:"Other agents, each at its address with its Agent Card",packages:{python:["fasta2a","a2a-sdk"],typescript:["@a2a-js/sdk"]},protocolTools:[],appspecBlock:"a2a"},A2UI_PROTOCOL_0_0_1={id:"a2ui",version:"0.0.1",name:"A2UI",description:"How an agent's answer becomes an interface: components the host renders from a declarative surface.",publisher:"Google",layer:"ui",specUrl:"https://a2ui.org",specVersion:"0.9",status:"shipped",connects:"The person, through components an answer draws",packages:{python:["agent-runtimes"],typescript:["@a2ui/react","@a2ui/web_core"]},protocolTools:[]},ACP_PROTOCOL_0_0_1={id:"acp",version:"0.0.1",name:"Agentic Commerce Protocol",description:"Checkout sessions at a seller, completed with a payment the model never sees. In applications at test merchants only, with no real payment token (decided 2026-10-13): each purchase asked of the person first, made at most once.",publisher:"OpenAI, Stripe",layer:"commerce",specUrl:"https://github.com/agentic-commerce-protocol/agentic-commerce-protocol",specVersion:"2026-04-17",status:"shipped",connects:"Sellers, to check out with a delegated payment",packages:{python:["agent-runtimes"],typescript:["@datalayer/agent-runtimes"]},protocolTools:["agentic-commerce"]},AG_UI_PROTOCOL_0_0_1={id:"ag-ui",version:"0.0.1",name:"AG-UI",description:"How an agent streams its run to a page: messages, tool calls and state as events.",publisher:"CopilotKit",layer:"ui",specUrl:"https://docs.ag-ui.com",specVersion:"0.0.57 (@ag-ui/core)",status:"shipped",connects:"The page a person talks to the agent on",packages:{python:["ag-ui-protocol"],typescript:["@ag-ui/client","@ag-ui/core"]},protocolTools:[]},MCP_PROTOCOL_0_0_1={id:"mcp",version:"0.0.1",name:"Model Context Protocol",description:"How an agent calls tools and reads resources: clients and servers in both languages, and the MCP gateway every connection goes through.",publisher:"Anthropic",layer:"transport",specUrl:"https://modelcontextprotocol.io/specification",specVersion:"2026-07-28 (Python), 2025-11-25 (TypeScript)",status:"shipped",connects:"Tools, resources and prompts served by MCP servers",packages:{python:["mcp"],typescript:["@modelcontextprotocol/sdk","@mcp-ui/client"]},protocolTools:[]},PACT_PROTOCOL_0_0_1={id:"pact",version:"0.0.1",name:"Personal Agent Consent & Trust",description:"A personal agent asking a business's agent over A2A, first as itself, then for a person who delegated some of their permissions.",publisher:"Decagon, Instinct",layer:"consent",specUrl:"https://openpactprotocol.org",specVersion:"1.0",status:"shipped",connects:"Businesses' agents, asked for a person with their delegation",packages:{python:["agent-runtimes"],typescript:["@datalayer/agent-runtimes"]},protocolTools:["pact"],appspecBlock:"pact"},PAP_PROTOCOL_0_0_1={id:"pap",version:"0.0.1",name:"Personal Agent Protocol",description:"A person's agent working with a company for them — signed out, then signed in at the company, its changes confirmed by the person — and an application being a company personal agents reach.",publisher:"Sierra, Meta",layer:"consent",specUrl:"https://poppy.md",specVersion:"draft 0.1",status:"shipped",connects:"Companies, as a person's agent there, or being one",packages:{python:["personal-agent-protocol"],typescript:["@datalayer/personal-agent-protocol"]},protocolTools:["pap"],appspecBlock:"pap"},TAP_PROTOCOL_0_0_1={id:"tap",version:"0.0.1",name:"Trusted Agent Protocol",description:"An agent-recognition profile over Web Bot Auth for merchants: a signature tagged agent-browser-auth to browse or agent-payer-auth to pay. Still a draft profile, built from Visa's public Merchant Specifications (2026-10-13) until Visa confirms it. In applications at test merchants only (decided 2026-10-14): the MCP gateway signs each UCP or ACP purchase with agent-payer-auth under the application's own key, and the test merchants verify it; browsing stays Web Bot Auth.",publisher:"Visa",layer:"identity",specUrl:"https://developer.visa.com/capabilities/trusted-agent-protocol/trusted-agent-protocol-specifications",specVersion:"draft (Merchant Specifications, read 2026-10-13)",status:"shipped",connects:"Merchants that recognise an agent by its signature",packages:{python:["agent-runtimes"],typescript:["@datalayer/agent-runtimes","http-message-sig"]},protocolTools:[]},UCP_PROTOCOL_0_0_1={id:"ucp",version:"0.0.1",name:"Universal Commerce Protocol",description:"Shopping at a merchant: catalogue, checkout and orders, every purchase an exact proposal the person approves. In applications at test merchants only, with no real payment (decided 2026-10-13): each purchase asked of the person first, made at most once.",publisher:"Google, with Shopify and retailers",layer:"commerce",specUrl:"https://github.com/Universal-Commerce-Protocol/ucp",specVersion:"2026-08-25",status:"shipped",connects:"Merchants, to search, check out and follow orders",packages:{python:["ucp-sdk","agent-runtimes"],typescript:["@ucp-js/sdk","@datalayer/agent-runtimes"]},protocolTools:["ucp"]},WEB_BOT_AUTH_PROTOCOL_0_0_1={id:"web-bot-auth",version:"0.0.1",name:"Web Bot Auth",description:"Signed outbound requests (RFC 9421) and the key directory a website checks them against. In applications, every request to a company, business or merchant is signed, and a signed fetch reads pages at the sites an application names, GET only (decided 2026-10-13).",publisher:"Cloudflare (IETF draft)",layer:"identity",specUrl:"https://datatracker.ietf.org/doc/draft-ietf-webbotauth-httpsig-protocol/",specVersion:"draft-ietf-webbotauth-httpsig-protocol-00",status:"shipped",connects:"Websites, which can tell the application's requests from someone pretending",packages:{python:["agent-runtimes"],typescript:["@datalayer/agent-runtimes","web-bot-auth"]},protocolTools:["signed-fetch"],appspecBlock:"signed_fetch"},PROTOCOL_CATALOGUE={a2a:A2A_PROTOCOL_0_0_1,a2ui:A2UI_PROTOCOL_0_0_1,acp:ACP_PROTOCOL_0_0_1,"ag-ui":AG_UI_PROTOCOL_0_0_1,mcp:MCP_PROTOCOL_0_0_1,pact:PACT_PROTOCOL_0_0_1,pap:PAP_PROTOCOL_0_0_1,tap:TAP_PROTOCOL_0_0_1,ucp:UCP_PROTOCOL_0_0_1,"web-bot-auth":WEB_BOT_AUTH_PROTOCOL_0_0_1},A2UI_SURFACE_UI_0_0_1={id:"a2ui-surface",version:"0.0.1",name:"Surfaces in the conversation",description:"Forms, tables and cards the agent draws in the conversation; what you fill in goes back to it.",emoji:"🪟",octicon:"browser",plugin:"@datalayer/loop-plugin-a2ui-surface",folder:"a2ui-surface",contributions:{slots:["loop.chatHeader"],points:["reactor.ui.renderer","reactor.ui.toolBinding"],commands:[]},contributionPoints:[],settings:{},renderers:["a2ui"],catalog:"a2ui/v0.9",components:[{id:"Text",name:"Text",category:"text",emoji:"🔤",description:"Words on the page: a heading, a paragraph, the answer — plain or Markdown.",version:"0.9.0",standard:!0,properties:{type:"object",required:["text"],properties:{text:{type:"string",title:"Words",description:"What it says, plain or in simple Markdown."},variant:{type:"string",title:"Style",description:"A heading of a level, a caption, or body text.",enum:["h1","h2","h3","h4","h5","caption","body"],default:"body"}}},events:[]},{id:"Image",name:"Image",category:"media",emoji:"🖼️",description:"A picture: a chart rendered elsewhere, a logo, a photo.",version:"0.9.0",standard:!0,properties:{type:"object",required:["url"],properties:{url:{type:"string",title:"Address",description:"Where the picture is."},description:{type:"string",title:"Description",description:"What it shows, for those who cannot see it."},fit:{type:"string",title:"Fit",description:"How it is resized to its place.",enum:["contain","cover","fill","none","scaleDown"],default:"fill"},variant:{type:"string",title:"Size",description:"An icon, an avatar, a feature or a header.",enum:["icon","avatar","smallFeature","mediumFeature","largeFeature","header"],default:"mediumFeature"}}},events:[]},{id:"Icon",name:"Icon",category:"media",emoji:"🔣",description:"A small drawing that says what something is: a check, a warning, a link.",version:"0.9.0",standard:!0,properties:{type:"object",required:["name"],properties:{name:{type:"string",title:"Icon",description:"Which drawing, by its name.",enum:["accountCircle","add","arrowBack","arrowForward","attachFile","calendarToday","call","camera","check","close","delete","download","edit","event","error","fastForward","favorite","favoriteOff","folder","help","home","info","locationOn","lock","lockOpen","mail","menu","moreVert","moreHoriz","notificationsOff","notifications","pause","payment","person","phone","photo","play","print","refresh","rewind","search","send","settings","share","shoppingCart","skipNext","skipPrevious","star","starHalf","starOff","stop","upload","visibility","visibilityOff","volumeDown","volumeMute","volumeOff","volumeUp","warning"]}}},events:[]},{id:"Video",name:"Video",category:"media",emoji:"🎬",description:"A film played in place.",version:"0.9.0",standard:!0,properties:{type:"object",required:["url"],properties:{url:{type:"string",title:"Address",description:"Where the film is."}}},events:[]},{id:"AudioPlayer",name:"Audio",category:"media",emoji:"🔊",description:"A sound played in place: a recording, a summary read aloud.",version:"0.9.0",standard:!0,properties:{type:"object",required:["url"],properties:{url:{type:"string",title:"Address",description:"Where the sound is."},description:{type:"string",title:"Description",description:"What it is: a title or a summary."}}},events:[]},{id:"Row",name:"Row",category:"layout",emoji:"➡️",description:"Children side by side, left to right.",version:"0.9.0",standard:!0,properties:{type:"object",required:["children"],properties:{children:{type:"array",title:"Blocks",description:"The blocks inside it, by id, left to right.",items:{type:"string"}},justify:{type:"string",title:"Spacing",description:"How the blocks share the width.",enum:["center","end","spaceAround","spaceBetween","spaceEvenly","start","stretch"],default:"start"},align:{type:"string",title:"Alignment",description:"How the blocks line up top to bottom.",enum:["start","center","end","stretch"],default:"stretch"}}},events:[]},{id:"Column",name:"Column",category:"layout",emoji:"⬇️",description:"Children one under the other.",version:"0.9.0",standard:!0,properties:{type:"object",required:["children"],properties:{children:{type:"array",title:"Blocks",description:"The blocks inside it, by id, top to bottom.",items:{type:"string"}},justify:{type:"string",title:"Spacing",description:"How the blocks share the height.",enum:["start","center","end","spaceBetween","spaceAround","spaceEvenly","stretch"],default:"start"},align:{type:"string",title:"Alignment",description:"How the blocks line up left to right.",enum:["center","end","start","stretch"],default:"stretch"}}},events:[]},{id:"List",name:"List",category:"layout",emoji:"📃",description:"Items one after the other, each drawn by the same children: results, alternatives, steps.",version:"0.9.0",standard:!0,properties:{type:"object",required:["children"],properties:{children:{type:"array",title:"Blocks",description:"The blocks inside it, by id, or the template repeated over a list.",items:{type:"string"}},direction:{type:"string",title:"Direction",description:"One under the other, or side by side.",enum:["vertical","horizontal"],default:"vertical"},align:{type:"string",title:"Alignment",description:"How the items line up across.",enum:["start","center","end","stretch"],default:"stretch"}}},events:[]},{id:"Card",name:"Card",category:"layout",emoji:"🗂️",description:"A framed group: what belongs together, set apart.",version:"0.9.0",standard:!0,properties:{type:"object",required:["child"],properties:{child:{type:"string",title:"Block",description:"The one block inside it, by id; a Row or Column for several."}}},events:[]},{id:"Tabs",name:"Tabs",category:"layout",emoji:"📑",description:"Several views of one place, one shown at a time.",version:"0.9.0",standard:!0,properties:{type:"object",required:["tabs"],properties:{tabs:{type:"array",title:"Tabs",description:"Each tab's title and the block it shows, by id.",minItems:1,items:{type:"object",required:["title","child"],properties:{title:{type:"string"},child:{type:"string"}}}}}},events:[]},{id:"Divider",name:"Divider",category:"layout",emoji:"➖",description:"A line between what comes before and after.",version:"0.9.0",standard:!0,properties:{type:"object",properties:{axis:{type:"string",title:"Direction",description:"Across or up and down.",enum:["horizontal","vertical"],default:"horizontal"}}},events:[]},{id:"Modal",name:"Modal",category:"layout",emoji:"🪟",description:"A window over the page, opened by a trigger: details, a confirmation.",version:"0.9.0",standard:!0,properties:{type:"object",required:["trigger","content"],properties:{trigger:{type:"string",title:"Opened by",description:"The block that opens it, by id: a button."},content:{type:"string",title:"Shows",description:"The block shown inside it, by id."}}},events:[]},{id:"Button",name:"Button",category:"action",emoji:"🔘",description:"An action the person takes: send, run, approve. One filled button per screen.",version:"0.9.0",standard:!0,properties:{type:"object",required:["child","action"],properties:{child:{type:"string",title:"Label",description:"The block on it, by id: a Text for its words."},variant:{type:"string",title:"Style",description:"Primary for the one main action, borderless for a link.",enum:["default","primary","borderless"],default:"default"},action:{type:"object",title:"Does",description:"What pressing it sends, by name, with what it reads."}}},events:[]},{id:"TextField",name:"Input",category:"input",emoji:"⌨️",description:"A field the person types in: a word, a sentence, a number, a date.",version:"0.9.0",standard:!0,properties:{type:"object",required:["label"],properties:{label:{type:"string",title:"Label",description:"What the person reads beside it."},value:{type:"string",title:"Value",description:"What is typed in it."},variant:{type:"string",title:"Kind",description:"A short or long text, a number, or hidden as typed.",enum:["longText","number","shortText","obscured"],default:"shortText"},validationRegexp:{type:"string",title:"Pattern",description:"A regular expression what is typed must match."}}},events:[]},{id:"CheckBox",name:"Checkbox",category:"input",emoji:"☑️",description:"Yes or no: an option on or off, a consent given.",version:"0.9.0",standard:!0,properties:{type:"object",required:["label","value"],properties:{label:{type:"string",title:"Label",description:"What the person reads beside it."},value:{type:"boolean",title:"Value",description:"Whether it is ticked."}}},events:[]},{id:"ChoicePicker",name:"Select",category:"input",emoji:"🔽",description:"One choice, or several, among options the builder lists or the data gives.",version:"0.9.0",standard:!0,properties:{type:"object",required:["options","value"],properties:{label:{type:"string",title:"Label",description:"What the person reads above the options."},variant:{type:"string",title:"Choice",description:"One of the options, or several.",enum:["multipleSelection","mutuallyExclusive"],default:"mutuallyExclusive"},options:{type:"array",title:"Options",description:"What may be chosen: the words read and the value sent.",items:{type:"object",required:["label","value"],properties:{label:{type:"string"},value:{type:"string"}}}},value:{type:"array",title:"Value",description:"The values chosen.",items:{type:"string"}},displayStyle:{type:"string",title:"Shown as",description:"Checkboxes or chips.",enum:["checkbox","chips"],default:"checkbox"},filterable:{type:"boolean",title:"Searchable",description:"A search field above the options.",default:!1}}},events:[]},{id:"Slider",name:"Slider",category:"input",emoji:"🎚️",description:"A number chosen along a range: a weight, a budget, a threshold.",version:"0.9.0",standard:!0,properties:{type:"object",required:["value","max"],properties:{label:{type:"string",title:"Label",description:"What the person reads beside it."},min:{type:"number",title:"Least",description:"The smallest value.",default:0},max:{type:"number",title:"Most",description:"The largest value."},value:{type:"number",title:"Value",description:"The value chosen."}}},events:[]},{id:"DateTimeInput",name:"Date and time",category:"input",emoji:"📅",description:"A date, a time, or both, chosen from a calendar.",version:"0.9.0",standard:!0,properties:{type:"object",required:["value"],properties:{value:{type:"string",title:"Value",description:"The date or time chosen, in ISO 8601."},enableDate:{type:"boolean",title:"Date",description:"A date may be chosen.",default:!1},enableTime:{type:"boolean",title:"Time",description:"A time may be chosen.",default:!1},min:{type:"string",title:"Earliest",description:"The earliest that may be chosen, in ISO 8601."},max:{type:"string",title:"Latest",description:"The latest that may be chosen, in ISO 8601."},label:{type:"string",title:"Label",description:"What the person reads beside it."}}},events:[]},{id:"Table",name:"Table",category:"data",emoji:"📋",description:"Rows the application found or keeps, with the columns the builder chooses.",version:"1.0.0",standard:!1,properties:{type:"object",required:["columns"],properties:{title:{type:"string",title:"Title",description:"What the table is, above it."},columns:{type:"array",title:"Columns",description:"The columns, in order.",minItems:1,items:{type:"string"}},page_size:{type:"integer",title:"Rows per page",description:"How many rows show at once.",minimum:1,maximum:500,default:20},selectable:{type:"boolean",title:"Selectable",description:"A row may be chosen, and its choice sent.",default:!1}}},bindings:{shows:["rows"],sends:["selected"]},events:["select"],example:{title:"Runs",columns:["model","pass rate","cost"]}},{id:"Chart",name:"Chart",category:"data",emoji:"📊",description:"Numbers drawn: a bar, a line, a scatter of what the application measured.",version:"1.0.0",standard:!1,properties:{type:"object",required:["kind","x","y"],properties:{title:{type:"string",title:"Title",description:"What the chart shows, above it."},kind:{type:"string",title:"Kind",description:"How the numbers are drawn.",enum:["bar","line","scatter","area"],default:"bar"},x:{type:"string",title:"Across",description:"The field along the bottom."},y:{type:"string",title:"Up",description:"The field measured."},series:{type:"string",title:"Series",description:"A field whose values are drawn apart."}}},bindings:{shows:["points"],sends:[]},events:[],example:{kind:"bar",x:"model",y:"pass rate"}},{id:"FileUpload",name:"File upload",category:"input",emoji:"📎",description:"A file the person gives the application: a document to read, a sheet to check.",version:"1.0.0",standard:!1,properties:{type:"object",required:["label"],properties:{label:{type:"string",title:"Label",description:"What the person reads beside it."},accept:{type:"array",title:"Accepts",description:"The kinds of file it takes, by extension.",items:{type:"string",pattern:"^\\.[a-z0-9]+$"}},multiple:{type:"boolean",title:"Several",description:"More than one file at once.",default:!1},max_mb:{type:"integer",title:"Largest (MB)",description:"The largest file it takes.",minimum:1,maximum:500,default:25}}},bindings:{shows:[],sends:["files"]},events:["upload"],example:{label:"The contract",accept:[".pdf",".docx"]}},{id:"Chat",name:"Chat",category:"conversation",emoji:"💬",description:"The conversation with the application: its welcome, its starters, the composer.",version:"1.0.0",standard:!1,properties:{type:"object",properties:{welcome:{type:"string",title:"Welcome",description:"What it says before anyone writes."},placeholder:{type:"string",title:"Composer hint",description:"Shown in the composer while it is empty.",default:"Ask anything"},starters:{type:"array",title:"Starters",description:"Questions offered before the first message.",maxItems:6,items:{type:"string"}},show_tools:{type:"boolean",title:"Shows its tools",description:"The tool calls are shown as they happen.",default:!0}}},bindings:{shows:["messages"],sends:["message"]},events:["send"],example:{welcome:"Ask me to research anything.",starters:["What changed in Python 3.13?"]}},{id:"Evidence",name:"Evidence",category:"data",emoji:"🔎",description:"What an answer rests on: the sources opened, the passages cited, each with its link.",version:"1.0.0",standard:!1,properties:{type:"object",properties:{title:{type:"string",title:"Title",description:"Above the sources.",default:"Sources"},show_passages:{type:"boolean",title:"Shows passages",description:"Each source with the passage cited from it.",default:!0},max_items:{type:"integer",title:"Most shown",description:"How many sources show before *more*.",minimum:1,maximum:50,default:5}}},bindings:{shows:["sources"],sends:[]},events:["open"],example:{title:"What this rests on"}},{id:"Form",name:"Form",category:"input",emoji:"🧾",description:"Several fields asked at once, from a JSON Schema, checked as they are filled and again when they arrive (drawn with @datalayer/primer-rjsf).",version:"1.1.0",standard:!1,properties:{type:"object",required:["schema"],properties:{title:{type:"string",title:"Title",description:"What the form is for, above it."},schema:{type:"object",title:"Fields",description:"The JSON Schema of what is asked: its fields, their types, what is required."},ui:{type:"object",title:"How its fields are drawn",description:"By field name, the ui: options @datalayer/primer-rjsf reads (a uiSchema): ui:widget one of select, radio, range, updown, switch, checkbox, text, textarea, date, checkboxes, tags; each field's own widget when unsaid."},submit_label:{type:"string",title:"Send button",description:"The words on its button.",default:"Send"}}},bindings:{shows:["values"],sends:["values"]},events:["submit"],example:{title:"The quote",schema:{type:"object",required:["seats"],properties:{seats:{type:"integer",minimum:1,title:"Seats"}}}}},{id:"Download",name:"File to download",category:"data",emoji:"📄",description:"A file the application gives, to save: a report, a sheet, an export — by its link, or the file itself as a data: URL.",version:"1.0.0",standard:!1,properties:{type:"object",required:["name","url"],properties:{name:{type:"string",title:"File name",description:"What the file is saved as, with its extension.",minLength:1},url:{type:"string",title:"Link",description:"Where the file is: an http(s) link, or the file itself as a data: URL.",pattern:"^(https?://|data:)"},media_type:{type:"string",title:"Kind",description:"Its media type (text/csv, application/pdf…), said beside its name."},size:{type:"integer",title:"Size (bytes)",description:"How large it is, said beside its name.",minimum:0},description:{type:"string",title:"Description",description:"A line under its name."}}},bindings:{shows:[],sends:[]},events:["download"],example:{name:"totals.csv",url:"data:text/csv;base64,bW9udGgsdG90YWwKSmFuLDEyMDAK",media_type:"text/csv",size:21,description:"The month's totals."}}]},A2UI_VIEW_UI_0_0_1={id:"a2ui-view",version:"0.0.1",name:"Surface view",description:"The last result of the code, shown as a page you can use rather than as raw output.",emoji:"🖼",octicon:"browser",plugin:"@datalayer/loop-plugin-a2ui",folder:"a2ui",contributions:{slots:[],points:["loop.command","loop.viewType"],commands:["a2ui"]},contributionPoints:[],settings:{},renderers:["a2ui"],catalog:"",components:[]},AGENTSPECS_UI_0_0_1={id:"agentspecs",version:"0.0.1",name:"Agent picker",description:"Choose which agent answers in this conversation.",emoji:"🤖",octicon:"people",plugin:"@datalayer/loop-plugin-agentspecs",folder:"agentspecs",contributions:{slots:["loop.header"],points:["loop.command"],commands:["agents"]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},APP_ACTIVITY_UI_0_0_1={id:"app-activity",version:"0.0.1",name:"Activity",description:"What your application did, is doing, and is about to do, beside its page.",emoji:"🕘",octicon:"pulse",plugin:"@datalayer/loop-plugin-app-activity",folder:"app-activity",per:"application",contributions:{slots:["loop.sidebar"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},APP_COMPONENTS_UI_0_0_1={id:"app-components",version:"0.0.1",name:"Your own components",description:"The components your application's developer wrote, on its page and in its answers.",emoji:"🧩",octicon:"apps",plugin:"@datalayer/loop-plugin-app-components",folder:"app-components",per:"application",contributions:{slots:[],points:["loop.a2ui.component","loop.canvas.block"],commands:[]},contributionPoints:[],settings:{},renderers:["a2ui"],catalog:"",components:[]},APP_COMPUTER_UI_0_0_1={id:"app-computer",version:"0.0.1",name:"Computer",description:"The computer your application works on: what ran there, its files, and taking it over.",emoji:"🖥️",octicon:"device-desktop",plugin:"@datalayer/loop-plugin-app-computer",folder:"app-computer",per:"application",contributions:{slots:["loop.sidebar"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},APP_ELEMENTS_UI_0_0_1={id:"app-elements",version:"0.0.1",name:"Side panel and pages",description:"What your application opens beside the conversation: a side panel, a page of its own, a question for you.",emoji:"🗂️",octicon:"sidebar-expand",plugin:"@datalayer/loop-plugin-app-elements",folder:"app-elements",contributions:{slots:["root"],points:["reactor.ui.renderer"],commands:[]},contributionPoints:[],settings:{},renderers:["a2ui"],catalog:"",components:[]},APP_PAGE_UI_0_0_1={id:"app-page",version:"0.0.1",name:"Application page",description:"Your application's page, drawn beside its conversation.",emoji:"📈",octicon:"browser",plugin:"@datalayer/loop-plugin-app-page",folder:"app-page",per:"application",contributions:{slots:[],points:["loop.chat.surface"],commands:[]},contributionPoints:[],settings:{},renderers:["a2ui","mcp-apps"],catalog:"",components:[]},APP_RULES_UI_0_0_1={id:"app-rules",version:"0.0.1",name:"Rules and approvals",description:"When your application acts alone, when it asks you, and the approvals waiting for your yes.",emoji:"🛡️",octicon:"shield-check",plugin:"@datalayer/loop-plugin-app-rules",folder:"app-rules",per:"application",contributions:{slots:["loop.sidebar"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CANVAS_BLOCKS_UI_0_0_1={id:"canvas-blocks",version:"0.0.1",name:"Blocks",description:"The blocks you place on your application's page in the visual editor, one set for each part that draws them.",emoji:"🧱",octicon:"apps",plugin:"@datalayer/loop-plugin-ui",folder:"canvas-blocks",per:"ui",contributions:{slots:[],points:["loop.canvas.block"],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CANVAS_PARTS_UI_0_0_1={id:"canvas-parts",version:"0.0.1",name:"Parts",description:"What you drop on your agent in the visual editor: connections, skills, models, rules, tests and events.",emoji:"🧰",octicon:"package",plugin:"@datalayer/loop-plugin-parts",folder:"canvas-parts",per:"source",contributions:{slots:[],points:["loop.canvas.part"],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CHAT_EXTRAS_UI_0_0_1={id:"chat-extras",version:"0.0.1",name:"Banner and status",description:"A live banner over the conversation and a status line under it, set by the page around it.",emoji:"📣",octicon:"megaphone",plugin:"@datalayer/loop-plugin-chat-extras",folder:"chat-extras",contributions:{slots:[],points:["loop.chat.extras"],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CHAT_HEADER_UI_0_0_1={id:"chat-header",version:"0.0.1",name:"Chat title bar",description:"The conversation's title bar: who answers, what it runs on, and its actions.",emoji:"🏷️",octicon:"rows",plugin:"@datalayer/loop-plugin-chat-header",folder:"chat-header",contributions:{slots:[],points:["loop.chat.header"],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CHAT_VIEW_UI_0_0_1={id:"chat-view",version:"0.0.1",name:"Chat button",description:"Back to the conversation alone, from under the composer.",emoji:"💬",octicon:"comment-discussion",plugin:"@datalayer/loop-plugin-chat-view",folder:"chat-view",contributions:{slots:["loop.promptAction"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CHAT_UI_0_0_1={id:"chat",version:"0.0.1",name:"Chat",description:"The conversation: what you ask, what it answers, and the work it opens beside it.",emoji:"💬",octicon:"comment-discussion",plugin:"@datalayer/loop-plugin-chat",folder:"chat",contributions:{slots:[],points:["loop.chat.turn","loop.command","loop.document.toolbar.item","loop.notebook.toolbar.item","loop.viewType"],commands:["chat"]},contributionPoints:["loop.agent.available","loop.chat.composer","loop.chat.extras","loop.chat.header","loop.chat.suggestion","loop.chat.turn","loop.frontendTool"],settings:{type:"object",properties:{placeholder:{type:"string",title:"Composer hint",description:"Shown in the composer while it is empty; the agent's own when unsaid.",default:""},defaultSurface:{type:"string",title:"Opens beside it",description:"What opens beside the conversation: notebook, document, a page, or none.",default:"notebook"},showSurfaceSelector:{type:"boolean",title:"Offers the switcher",description:"The strip that switches what is open beside the conversation.",default:!0},hideHeader:{type:"boolean",title:"Hides its title bar",description:"The conversation without its own title bar.",default:!1},headerButtons:{type:"object",title:"Title bar buttons",description:"Whether the title bar offers a new chat and clearing this one.",properties:{newChat:{type:"boolean",title:"New chat",description:"Start another conversation."},clear:{type:"boolean",title:"Clear",description:"Clear this conversation."}},default:{newChat:!1,clear:!1}},hidePrompt:{type:"boolean",title:"Hides the composer",description:"The conversation read without being written to.",default:!1},promptPlacement:{type:"string",title:"Composer place",description:"Where the composer sits.",enum:["top","bottom","bottom-chat","floating"],default:"bottom"},autoFocusPrompt:{type:"boolean",title:"Composer takes the caret",description:"The composer is ready to type in when the page opens.",default:!0},suggestionLabels:{type:"boolean",title:"Openers by the composer",description:"The openers shown as labels by the composer, not only in its menu.",default:!0},fullScreenTopOffset:{type:["number","string"],title:"Room kept at the top",description:"What full screen leaves at the top for the page's own header.",default:0}}},renderers:[],catalog:"",components:[]},COMMANDS_UI_0_0_1={id:"commands",version:"0.0.1",name:"Command palette",description:"Every command at hand, with Ctrl-K.",emoji:"⌘",octicon:"command-palette",plugin:"@datalayer/loop-plugin-commands",folder:"commands",contributions:{slots:["loop.status"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},DOCUMENT_TOOLBAR_UI_0_0_1={id:"document-toolbar",version:"0.0.1",name:"Document toolbar",description:"Shows what the document's code blocks run on.",emoji:"🔵",octicon:"circle",plugin:"@datalayer/loop-plugin-document-toolbar",folder:"document-toolbar",contributions:{slots:[],points:["loop.document.toolbar"],commands:[]},contributionPoints:["loop.document.toolbar.item"],settings:{},renderers:[],catalog:"",components:[]},DOCUMENT_VIEW_UI_0_0_1={id:"document-view",version:"0.0.1",name:"Document button",description:"The document beside the conversation, from under the composer.",emoji:"📄",octicon:"file",plugin:"@datalayer/loop-plugin-document-view",folder:"document-view",contributions:{slots:["loop.promptAction"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},DOCUMENT_UI_0_0_1={id:"document",version:"0.0.1",name:"Document",description:"A document beside the conversation, written with the agent.",emoji:"📄",octicon:"file",plugin:"@datalayer/loop-plugin-document",folder:"document",contributions:{slots:[],points:["loop.chat.surface","loop.command"],commands:["document"]},contributionPoints:["loop.document.opening","loop.document.toolbar"],settings:{},renderers:[],catalog:"",components:[]},INPUT_PROMPT_UI_0_0_1={id:"input-prompt",version:"0.0.1",name:"Composer",description:"Where you write to the agent, under or over the conversation.",emoji:"✏️",octicon:"pencil",plugin:"@datalayer/loop-plugin-input-prompt",folder:"input-prompt",contributions:{slots:[],points:["loop.chat.composer"],commands:[]},contributionPoints:["loop.prompt.panel"],settings:{},renderers:[],catalog:"",components:[]},MODELS_UI_0_0_1={id:"models",version:"0.0.1",name:"Models",description:"Which model answers, and the models you may choose from.",emoji:"🧠",octicon:"cpu",plugin:"@datalayer/loop-plugin-models",folder:"models",contributions:{slots:[],points:["loop.command"],commands:["models"]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},NOTEBOOK_TOOLBAR_UI_0_0_1={id:"notebook-toolbar",version:"0.0.1",name:"Notebook toolbar",description:"Shows what the notebook is running on.",emoji:"🟢",octicon:"circle",plugin:"@datalayer/loop-plugin-notebook-toolbar",folder:"notebook-toolbar",contributions:{slots:[],points:["loop.notebook.toolbar"],commands:[]},contributionPoints:["loop.notebook.toolbar.item"],settings:{},renderers:[],catalog:"",components:[]},NOTEBOOK_VIEW_UI_0_0_1={id:"notebook-view",version:"0.0.1",name:"Notebook button",description:"The notebook beside the conversation, from under the composer.",emoji:"📓",octicon:"rows",plugin:"@datalayer/loop-plugin-notebook-view",folder:"notebook-view",contributions:{slots:["loop.promptAction"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},NOTEBOOK_UI_0_0_1={id:"notebook",version:"0.0.1",name:"Notebook",description:"A notebook beside the conversation, its code run as you go.",emoji:"📓",octicon:"rows",plugin:"@datalayer/loop-plugin-notebook",folder:"notebook",contributions:{slots:[],points:["loop.chat.surface","loop.command"],commands:["notebook"]},contributionPoints:["loop.notebook.opening","loop.notebook.toolbar"],settings:{},renderers:[],catalog:"",components:[]},PAGE_LAYOUT_UI_0_0_1={id:"page-layout",version:"0.0.1",name:"Page layout",description:"The work on a centred sheet like a document, the composer above it and the conversation in a panel beside it; or the conversation and the work side by side.",emoji:"📄",octicon:"file",plugin:"@datalayer/loop-plugin-page-layout",folder:"page-layout",contributions:{slots:["loop.header"],points:["loop.chat.layout","loop.prompt.panel"],commands:[]},contributionPoints:[],settings:{type:"object",properties:{arrangement:{type:"string",title:"Arrangement",description:"The work on a sheet with the conversation in a panel, or both side by side.",enum:["page","split"],default:"page"},turnPanel:{type:"string",title:"Current turn",description:"Where the current turn hangs on the composer.",enum:["below","above","none"],default:"below"},turnPanelFooter:{type:"string",title:"Under the reply",description:"What is drawn under the reply: everything, its actions, or nothing.",enum:["full","actions","none"],default:"full"},prompt:{type:"string",title:"Composer",description:"Docked above the sheet, or floating over it.",enum:["docked","floating"],default:"docked"},promptAnchor:{type:"string",title:"Floating composer starts",description:"The edge a floating composer starts at.",enum:["top","bottom"],default:"top"},pageSize:{type:"object",title:"Sheet",description:"The sheet: free at its reading width when unsaid, or a paper (letter, a4) whose width it takes, with a width or a height of its own over either.",properties:{format:{type:"string",title:"Paper",description:"The paper the sheet is.",enum:["free","letter","a4"]},width:{type:"number",title:"Width",description:"The sheet's width in pixels; over a paper, it replaces the paper's."},height:{type:"number",title:"Height",description:"The sheet's least height in pixels; what is past it grows the sheet."}}}}},renderers:[],catalog:"",components:[]},PAP_SIGN_IN_UI_0_0_1={id:"pap-sign-in",version:"0.0.1",name:"Sign in at a company",description:"Where your agent asks you to sign in at a company: its page, the code, and until when.",emoji:"🔑",octicon:"sign-in",plugin:"@datalayer/loop-plugin-pap-sign-in",folder:"pap-sign-in",contributions:{slots:["loop.chatHeader"],points:["reactor.ui.renderer","reactor.ui.toolBinding"],commands:[]},contributionPoints:[],settings:{},renderers:["mcp-ui"],catalog:"",components:[]},PROMPT_UI_0_0_1={id:"prompt",version:"0.0.1",name:"Floating composer",description:"The composer in a card you move over the page, and the commands that bring it back or start over.",emoji:"🪶",octicon:"paper-airplane",plugin:"@datalayer/loop-plugin-prompt",folder:"prompt",contributions:{slots:["loop.promptAction"],points:["loop.command"],commands:["new","prompt"]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},SUBAGENT_ACTIVITY_UI_0_0_1={id:"subagent-activity",version:"0.0.1",name:"Delegated work",description:"The face of an agent yours handed work to, pulsing while it works.",emoji:"👥",octicon:"people",plugin:"@datalayer/loop-plugin-subagent-activity",folder:"subagent-activity",contributions:{slots:["loop.inpromptMenu"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},WINDOW_FRAME_UI_0_0_1={id:"window-frame",version:"0.0.1",name:"Window",description:"Draws the editor as a window, with room in its title bar for controls and actions.",emoji:"🪟",octicon:"browser",plugin:"@datalayer/loop-plugin-window-frame",folder:"window-frame",contributions:{slots:["loop.header","loop.window.controls"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},UI_CATALOGUE={"a2ui-surface":A2UI_SURFACE_UI_0_0_1,"a2ui-view":A2UI_VIEW_UI_0_0_1,agentspecs:AGENTSPECS_UI_0_0_1,"app-activity":APP_ACTIVITY_UI_0_0_1,"app-components":APP_COMPONENTS_UI_0_0_1,"app-computer":APP_COMPUTER_UI_0_0_1,"app-elements":APP_ELEMENTS_UI_0_0_1,"app-page":APP_PAGE_UI_0_0_1,"app-rules":APP_RULES_UI_0_0_1,"canvas-blocks":CANVAS_BLOCKS_UI_0_0_1,"canvas-parts":CANVAS_PARTS_UI_0_0_1,"chat-extras":CHAT_EXTRAS_UI_0_0_1,"chat-header":CHAT_HEADER_UI_0_0_1,"chat-view":CHAT_VIEW_UI_0_0_1,chat:CHAT_UI_0_0_1,commands:COMMANDS_UI_0_0_1,"document-toolbar":DOCUMENT_TOOLBAR_UI_0_0_1,"document-view":DOCUMENT_VIEW_UI_0_0_1,document:DOCUMENT_UI_0_0_1,"input-prompt":INPUT_PROMPT_UI_0_0_1,models:MODELS_UI_0_0_1,"notebook-toolbar":NOTEBOOK_TOOLBAR_UI_0_0_1,"notebook-view":NOTEBOOK_VIEW_UI_0_0_1,notebook:NOTEBOOK_UI_0_0_1,"page-layout":PAGE_LAYOUT_UI_0_0_1,"pap-sign-in":PAP_SIGN_IN_UI_0_0_1,prompt:PROMPT_UI_0_0_1,"subagent-activity":SUBAGENT_ACTIVITY_UI_0_0_1,"window-frame":WINDOW_FRAME_UI_0_0_1};function listUI(){return Object.values(UI_CATALOGUE)}const COMPONENT_CATALOGUE=Object.fromEntries(Object.values(UI_CATALOGUE).flatMap(Au=>Au.components.map(lo=>[lo.id,lo]))),A2UI_UI_RENDERER_0_0_1={id:"a2ui",version:"0.0.1",name:"A2UI",description:"An agent describes an interface — a form, a table, a card — as a tree of components from a catalogue the host allows, and the host renders it; what the user does in it comes back to the agent as an action.",docsUrl:"https://a2ui.org/",enabled:!0},MCP_APPS_UI_RENDERER_0_0_1={id:"mcp-apps",version:"0.0.1",name:"MCP Apps",description:"An MCP server ships an interactive app with a tool: the host renders it in a sandboxed frame beside the conversation, and the app calls the server's tools through the host.",docsUrl:"https://modelcontextprotocol.io/docs/extensions/apps",enabled:!1},MCP_UI_UI_RENDERER_0_0_1={id:"mcp-ui",version:"0.0.1",name:"MCP UI",description:"An MCP tool answers with a UI resource — HTML, a remote page or a component — that the host renders in place of plain text.",docsUrl:"https://mcpui.dev/",enabled:!1},UI_RENDERER_CATALOGUE={a2ui:A2UI_UI_RENDERER_0_0_1,"mcp-apps":MCP_APPS_UI_RENDERER_0_0_1,"mcp-ui":MCP_UI_UI_RENDERER_0_0_1},DEFAULT_UPLOAD_MB=10,DEFAULT_MAX_FILES=5;function kindTakes(Au,lo){const $u=Au.trim().toLowerCase();if($u.startsWith("."))return lo.name.toLowerCase().endsWith($u);const Ru=(lo.type||"").split(";",1)[0].trim().toLowerCase();return $u.endsWith("/*")?Ru.startsWith($u.slice(0,-1)):Ru===$u}const acceptsFile=(Au,lo)=>!Au?.length||Au.some($u=>kindTakes($u,lo)),megabytes=Au=>`${(Au/(1024*1024)).toFixed(1)} MB`,uploadsAccept=Au=>Au.kinds.map(lo=>lo.type).join(",");function uploadsRefusal(Au,lo){if(lo.length===0)return null;const $u=Au.interface.uploads;if(!$u)return`${Au.name} takes no file sent with a message: its Appspec names none it takes (interface.uploads).`;if(lo.length>$u.maxFiles)return`${lo.length} files were sent at once: ${Au.name} takes at most ${$u.maxFiles}.`;for(const Ru of lo){const Iu=$u.kinds.find(Pu=>kindTakes(Pu.type,Ru));if(!Iu){const Pu=$u.kinds.map(Ou=>Ou.type).join(", ");return`${Ru.name} is not a kind of file ${Au.name} takes: it takes ${Pu}.`}if(Ru.size>Iu.maxMb*1024*1024)return`${Ru.name} is ${megabytes(Ru.size)}: ${Au.name} takes ${Iu.type} of at most ${Iu.maxMb} MB.`}return null}function uploadsInWords(Au){return`Takes ${Au.kinds.map($u=>`${$u.type} up to ${$u.maxMb} MB`).join(", ")}; ${Au.maxFiles} at most at once.`}const APP_SCHEMA="loop.app/v1",DEFAULT_LANGUAGE="en",DEFAULT_EMOJI="👀",APP_KINDS=["chat","widget","decision","worker"],APP_ACCENTS=["green","rose","sky","lime","sun","violet"],APP_THEME_VARIANTS=["datalayer","spatial","lovely","matrix","earth","sand","ivory","sun","loop"],APP_THEME_MODES=["light","dark","auto"],APP_EMBED_MODES=["inline","bubble","panel","assistant"],APP_ASSISTANT_CHARACTER_ID=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function isAssistantCharacterId(Au){return typeof Au=="string"&&Au.length<=64&&APP_ASSISTANT_CHARACTER_ID.test(Au)}const ACTION_CLASS_NAMES=["read","write","send","buy","delete","publish"],DEFAULT_LAYOUTS={chat:"chat",widget:"page",decision:"page",worker:"split"},A2UI_OUTPUT="application/json+a2ui";function uiFor(Au,lo={}){if(Au==="decision")return[{plugin:"app-page"}];const $u=[{plugin:"chat"}];return lo.outputs?.includes(A2UI_OUTPUT)&&$u.push({plugin:"a2ui-surface",renderer:"a2ui"}),lo.signsIn&&$u.push({plugin:"pap-sign-in"}),(lo.layout??DEFAULT_LAYOUTS[Au])!=="chat"&&$u.push({plugin:"page-layout"},{plugin:"app-page"},{plugin:"canvas-blocks"}),lo.ownComponents&&$u.push({plugin:"app-components"}),$u}const DEFAULT_RECORD_INCLUDE=["conversations","actions","approvals"],DEFAULT_KEEP_FOR="1_years",DEFAULT_READY_AT=.8,DEFAULT_PROTOCOL="a2ui/v0.9",DEFAULT_ICON="apps",DEFAULT_VERSION="0.0.1",NO_HOST_PARAMETERS={type:"object",properties:{}},isData=Au=>!!Au&&typeof Au=="object"&&!Array.isArray(Au),text$k=(Au,lo="")=>typeof Au=="string"?Au:lo,flag=(Au,lo)=>typeof Au=="boolean"?Au:lo,numberOf=(Au,lo)=>typeof Au=="number"&&Number.isFinite(Au)?Au:lo,texts=Au=>Array.isArray(Au)?Au.filter(lo=>typeof lo=="string"):[],records=Au=>Array.isArray(Au)?Au.filter(isData):[],uiChoices=Au=>Array.isArray(Au)?Au.filter(isData).map(lo=>({plugin:text$k(lo.plugin),...text$k(lo.renderer)?{renderer:text$k(lo.renderer)}:{}})):[],uiShapeProblems=Au=>Array.isArray(Au)?Au.filter(lo=>!isData(lo)).map(lo=>`\`ui\` lists UI plugins, each as \`{plugin, renderer}\`: ${JSON.stringify(lo)} is not one`+(typeof lo=="string"&&UI_RENDERER_CATALOGUE[lo]?` (${JSON.stringify(lo)} is a UI renderer: name the plugin it renders, and say it as its \`renderer\`).`:".")):[];function parseTestTurn(Au){return{...text$k(Au.say)?{say:text$k(Au.say)}:{},...text$k(Au.choose)?{choose:text$k(Au.choose)}:{},...text$k(Au.press)?{press:text$k(Au.press)}:{},...isData(Au.payload)&&Object.keys(Au.payload).length?{payload:{...Au.payload}}:{}}}const oneOf$3=(Au,lo,$u)=>lo.includes(Au)?Au:$u,RETENTION$1=/^([1-9]\d*)_(day|days|month|months|year|years)$/,DAYS={day:1,month:30,year:365};function retentionDays(Au){const lo=RETENTION$1.exec(Au.trim());return lo?Number(lo[1])*DAYS[lo[2].replace(/s$/,"")]:0}function emptyAppspec(Au="chat"){return{schema:APP_SCHEMA,id:"",version:DEFAULT_VERSION,name:"",kind:Au,description:"",owner:"",agent:"",team:"",instructions:"",model:"",skills:[],backendTools:[],context:[],contents:[],connections:[],protocols:[],ui:uiFor(Au),rules:[],permissions:{spaces:[],computer:{browse:!1,files:!1,shell:!1}},interface:{layout:DEFAULT_LAYOUTS[Au],welcome:"",starters:[],commands:[],modes:[],actions:[],profiles:[],language:DEFAULT_LANGUAGE,translations:{},components:[],outputs:[]},tests:{readyAt:DEFAULT_READY_AT,evalset:"",cases:[],verified:{live:[],recorded:[],unverified:[]}},record:{keepFor:DEFAULT_KEEP_FOR,retentionDays:retentionDays(DEFAULT_KEEP_FOR),include:[...DEFAULT_RECORD_INCLUDE],suggestTests:!1},checks:{guards:[],gates:[],track:""},deployment:{},goal:"",triggers:[],memory:"",notifications:[],samples:{documents:[],alternatives:[]},setup:[],enabled:!0,unavailable_because:"",tags:[],icon:DEFAULT_ICON,emoji:DEFAULT_EMOJI,avatar:"",banner:""}}const KNOWN_KEYS=["schema","id","version","name","kind","description","owner","agent","team","instructions","model","skills","backend_tools","tools","context","contents","connections","protocols","ui","pap","pact","commerce","signed_fetch","pair","a2a","rules","permissions","interface","tests","record","checks","deployment","goal","triggers","memory","notifications","decision","samples","enabled","unavailable_because","tags","icon","emoji","avatar","banner"],CHECK_STAGES=["answer","tool_call"];function parseTool(Au){return{name:text$k(Au.name),description:text$k(Au.description),parameters:isData(Au.parameters)?Au.parameters:{...NO_HOST_PARAMETERS},does:texts(Au.does)}}function parseConnection(Au){return{server:text$k(Au.server),access:oneOf$3(Au.access,["read","write"],"read"),as:oneOf$3(Au.as,["owner","user"],"owner"),only:texts(Au.only)}}const PAP_PROFILES=["draft-01"],PAP_PROFILE=PAP_PROFILES[PAP_PROFILES.length-1];function papProfileProblem(Au){if(Au==null||Au==="")return`Its \`pap\` block names no Personal Agent Protocol profile: add \`profile: ${PAP_PROFILE}\`.`;if(!PAP_PROFILES.includes(Au))return`This application asks for Personal Agent Protocol profile “${String(Au)}”; Datalayer speaks ${PAP_PROFILES.join(" or ")}.`}const PAP_INTERFACES=["agent","openapi","mcp","web"],PAP_SIGN_IN=["direct","device","mediated"],PAP_DEFAULT_INTERFACES=["agent"],PAP_DEFAULT_SIGN_IN=["direct","device"],enumsOf=(Au,lo,$u)=>Array.isArray(Au)?Au.filter(Ru=>lo.includes(Ru)):[...$u];function parsePap(Au){const lo=isData(Au.company)?Au.company:{};return{profile:Au.profile,connections:records(Au.connections).map($u=>({id:text$k($u.id),company:text$k($u.company),access:oneOf$3($u.access,["read","write"],"read"),as:oneOf$3($u.as,["owner","user"],"user"),scopes:texts($u.scopes),interfaces:enumsOf($u.interfaces,PAP_INTERFACES,PAP_DEFAULT_INTERFACES),signIn:enumsOf($u.sign_in,PAP_SIGN_IN,PAP_DEFAULT_SIGN_IN),extensions:texts($u.extensions)})),company:{enabled:flag(lo.enabled,!1),signedOut:flag(lo.signed_out,!0),interfaces:enumsOf(lo.interfaces,PAP_INTERFACES,PAP_DEFAULT_INTERFACES),scopes:texts(lo.scopes),extensions:texts(lo.extensions),personalAgents:oneOf$3(lo.personal_agents,["any","registered"],"any"),registeredAgents:texts(lo.registered_agents),operations:records(lo.operations).map($u=>({action:text$k($u.action),tool:text$k($u.tool),...isData($u.allows)?{allows:parsePapStanding($u.allows)}:{},summary:text$k($u.summary),userApprovalRequired:flag($u.user_approval_required,!0)}))}}}function parsePapStanding(Au){return{connection:text$k(Au.connection),action:oneOf$3(Au.action,["write","buy"],"buy"),limits:records(Au.limits).map(lo=>({path:text$k(lo.path),...typeof lo.maximum=="string"?{maximum:text$k(lo.maximum)}:{},...typeof lo.allowed=="string"?{allowed:text$k(lo.allowed)}:{}})),uses:text$k(Au.uses),days:text$k(Au.days)}}function dumpPapStanding(Au){return{connection:Au.connection,action:Au.action,limits:Au.limits.map(lo=>({path:lo.path,...lo.maximum!==void 0?{maximum:lo.maximum}:{},...lo.allowed!==void 0?{allowed:lo.allowed}:{}})),uses:Au.uses,days:Au.days}}function dumpPap(Au){return Au?new Writer().text("profile",Au.profile,"\0").list("connections",Au.connections.map(lo=>new Writer().text("id",lo.id,"\0").text("company",lo.company,"\0").value("access",lo.access,"read").value("as",lo.as,"user").list("scopes",lo.scopes).list("interfaces",lo.interfaces,[...PAP_DEFAULT_INTERFACES]).list("sign_in",lo.signIn,[...PAP_DEFAULT_SIGN_IN]).list("extensions",lo.extensions).data)).part("company",new Writer().value("enabled",Au.company.enabled,!1).value("signed_out",Au.company.signedOut,!0).list("interfaces",Au.company.interfaces,[...PAP_DEFAULT_INTERFACES]).list("scopes",Au.company.scopes).list("extensions",Au.company.extensions).value("personal_agents",Au.company.personalAgents,"any").list("registered_agents",Au.company.registeredAgents).list("operations",Au.company.operations.map(lo=>new Writer().text("action",lo.action,"\0").text("tool",lo.tool,lo.allows?"":"\0").present("allows",lo.allows?dumpPapStanding(lo.allows):void 0).text("summary",lo.summary,"\0").value("user_approval_required",lo.userApprovalRequired,!0).data)).data).data:{}}function parsePact(Au){const lo=isData(Au.business)?Au.business:{},$u={};if(isData(lo.scopes))for(const[Ru,Iu]of Object.entries(lo.scopes))$u[Ru]=text$k(Iu);return{connections:records(Au.connections).map(Ru=>({id:text$k(Ru.id),brand:text$k(Ru.brand),audience:text$k(Ru.audience),access:oneOf$3(Ru.access,["read","write"],"read"),scopes:texts(Ru.scopes)})),business:{enabled:flag(lo.enabled,!1),brand:text$k(lo.brand),scopes:$u,registeredAgents:records(lo.registered_agents).map(Ru=>({issuer:text$k(Ru.issuer),jwksUri:text$k(Ru.jwks_uri)}))}}}function parseCommerce(Au){return{merchants:records(Au.merchants).map(lo=>({id:text$k(lo.id),protocol:oneOf$3(lo.protocol,["ucp","acp"],"ucp"),merchant:text$k(lo.merchant),access:oneOf$3(lo.access,["read","write"],"read"),...isData(lo.limit)?{limit:{amount:text$k(lo.limit.amount),currency:text$k(lo.limit.currency)}}:{}}))}}function dumpCommerce(Au){return Au?new Writer().list("merchants",Au.merchants.map(lo=>new Writer().text("id",lo.id,"\0").text("protocol",lo.protocol,"\0").text("merchant",lo.merchant,"\0").value("access",lo.access,"read").part("limit",lo.limit?{amount:lo.limit.amount,currency:lo.limit.currency}:{}).data)).data:{}}function parseSignedFetch(Au){return{sites:records(Au.sites).map(lo=>({id:text$k(lo.id),site:text$k(lo.site)}))}}function dumpSignedFetch(Au){return Au?new Writer().list("sites",Au.sites.map(lo=>new Writer().text("id",lo.id,"\0").text("site",lo.site,"\0").data)).data:{}}function parsePair(Au){const lo=text$k(Au.id),$u=text$k(Au.role);return/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(lo)?$u!=="business"&&$u!=="personal_agent"?`One of a pair is its business or its personal_agent, not ${JSON.stringify($u)}.`:{id:lo,role:$u}:`A pair's id is lower-case letters, digits and hyphens: ${JSON.stringify(lo)}.`}function dumpPact(Au){if(!Au)return{};const lo=Au.business??{enabled:!1,brand:"",scopes:{},registeredAgents:[]};return new Writer().list("connections",Au.connections.map($u=>new Writer().text("id",$u.id,"\0").text("brand",$u.brand,"\0").text("audience",$u.audience,"\0").value("access",$u.access,"read").list("scopes",$u.scopes).data)).part("business",new Writer().value("enabled",lo.enabled,!1).text("brand",lo.brand).part("scopes",{...lo.scopes}).list("registered_agents",lo.registeredAgents.map($u=>new Writer().text("issuer",$u.issuer,"\0").text("jwks_uri",$u.jwksUri,"\0").data)).data).data}function parseA2A(Au){return{extensions:records(Au.extensions).map(lo=>({uri:text$k(lo.uri),description:text$k(lo.description),required:flag(lo.required,!1),params:isData(lo.params)?{...lo.params}:{}}))}}function dumpA2A(Au){return Au?new Writer().list("extensions",Au.extensions.map(lo=>new Writer().text("uri",lo.uri,"\0").text("description",lo.description).value("required",lo.required,!1).part("params",lo.params).data)).data:{}}function parseRule$1(Au){return{action:text$k(Au.action),appliesTo:typeof Au.applies_to=="string"?[Au.applies_to]:texts(Au.applies_to),behaviour:oneOf$3(Au.behaviour,BEHAVIOURS,"ask_first")}}function parseAction(Au){const lo={name:text$k(Au.name)};return text$k(Au.description)&&(lo.description=text$k(Au.description)),isData(Au.payload)&&(lo.payload=JSON.parse(JSON.stringify(Au.payload))),lo}function parseCommand$1(Au){return{name:text$k(Au.name),description:text$k(Au.description),prompt:text$k(Au.prompt)}}function parseModeOption(Au){const lo={id:text$k(Au.id),label:text$k(Au.label)};for(const $u of["description","instructions","model"])typeof Au[$u]=="string"&&Au[$u]&&(lo[$u]=Au[$u]);return lo}function parseMode(Au){const lo={id:text$k(Au.id),label:text$k(Au.label),options:records(Au.options).map(parseModeOption)};return typeof Au.default=="string"&&Au.default&&(lo.default=Au.default),lo}function parseStarter(Au){const lo={label:text$k(Au.label),message:text$k(Au.message)};return typeof Au.category=="string"&&Au.category&&(lo.category=Au.category),lo}function parseProfile(Au){return{id:text$k(Au.id),label:text$k(Au.label),description:text$k(Au.description),instructions:text$k(Au.instructions),model:typeof Au.model=="string"&&Au.model?Au.model:null,starters:records(Au.starters).map(parseStarter)}}function wordsBy(Au){return Object.fromEntries(Object.entries(isData(Au)?Au:{}).filter(lo=>typeof lo[1]=="string"))}function recordsBy(Au){return Object.fromEntries(Object.entries(isData(Au)?Au:{}).filter(lo=>isData(lo[1])))}const mapValues=(Au,lo)=>Object.fromEntries(Object.entries(Au).map(([$u,Ru])=>[$u,lo(Ru)]));function parseTranslation(Au){return{name:text$k(Au.name),description:text$k(Au.description),welcome:text$k(Au.welcome),starters:mapValues(recordsBy(Au.starters),lo=>({label:text$k(lo.label),message:text$k(lo.message)})),categories:wordsBy(Au.categories),settings:mapValues(recordsBy(Au.settings),lo=>({title:text$k(lo.title),description:text$k(lo.description),options:wordsBy(lo.options)})),commands:wordsBy(Au.commands),modes:mapValues(recordsBy(Au.modes),lo=>({label:text$k(lo.label),options:mapValues(recordsBy(lo.options),$u=>({label:text$k($u.label),description:text$k($u.description)}))})),profiles:mapValues(recordsBy(Au.profiles),lo=>({label:text$k(lo.label),description:text$k(lo.description)}))}}function parseSurface(Au){return{protocol:text$k(Au.protocol,DEFAULT_PROTOCOL),components:records(Au.components).filter(lo=>typeof lo.id=="string"&&typeof lo.component=="string"),composedBy:text$k(Au.composed_by),composedAt:text$k(Au.composed_at)}}const DEFAULT_VOICE={enabled:!1,input:"push_to_talk",output:"on_request",where:"auto"};function parseVoice(Au){const lo=isData(Au)?Au:{};return{enabled:lo.enabled===!0,input:oneOf$3(lo.input,["off","push_to_talk","hands_free"],DEFAULT_VOICE.input),output:oneOf$3(lo.output,["off","on_request","always"],DEFAULT_VOICE.output),voice:text$k(lo.voice),language:text$k(lo.language),where:oneOf$3(lo.where,["auto","device","server"],DEFAULT_VOICE.where)}}function parseUploads(Au){return{kinds:records(Au.kinds).map(lo=>({type:text$k(lo.type),maxMb:numberOf(lo.max_mb,DEFAULT_UPLOAD_MB)})),maxFiles:numberOf(Au.max_files,DEFAULT_MAX_FILES)}}const PAGE_OUTPUT_SHOWS={Text:"text",Image:"url",Table:"rows",Chart:"points"},DEFAULT_CUSTOM_HEIGHT=240;function parseCustomComponent(Au){const lo={name:text$k(Au.name),description:text$k(Au.description),props:isData(Au.props)?JSON.parse(JSON.stringify(Au.props)):{type:"object",properties:{}},shows:texts(Au.shows),sends:texts(Au.sends),source:text$k(Au.source),integrity:text$k(Au.integrity),height:numberOf(Au.height,DEFAULT_CUSTOM_HEIGHT)};return isData(Au.example)&&(lo.example=JSON.parse(JSON.stringify(Au.example))),lo}function dumpCustomComponent(Au){const lo=new Writer().text("name",Au.name,"\0").text("description",Au.description,"\0");return lo.data.props=JSON.parse(JSON.stringify(Au.props)),lo.list("shows",Au.shows).list("sends",Au.sends).text("source",Au.source,"\0").text("integrity",Au.integrity).value("height",Au.height,DEFAULT_CUSTOM_HEIGHT),Au.example&&(lo.data.example=JSON.parse(JSON.stringify(Au.example))),lo.data}function pageOutputShows(Au,lo=[]){return Au in PAGE_OUTPUT_SHOWS?PAGE_OUTPUT_SHOWS[Au]:lo.find($u=>$u.name===Au)?.shows[0]}function parsePage(Au){const lo={function:text$k(Au.function),inputs:isData(Au.inputs)?JSON.parse(JSON.stringify(Au.inputs)):{},outputs:records(Au.outputs).map($u=>({name:text$k($u.name),title:text$k($u.title),component:text$k($u.component,"Text"),props:isData($u.props)?JSON.parse(JSON.stringify($u.props)):{}})),live:Au.live!==!1};return isData(Au.inputs_ui)&&(lo.inputsUi=JSON.parse(JSON.stringify(Au.inputs_ui))),lo}function dumpPage(Au){const lo=new Writer().text("function",Au.function,"\0");return lo.data.inputs=JSON.parse(JSON.stringify(Au.inputs)),Au.inputsUi&&(lo.data.inputs_ui={...Au.inputsUi}),lo.list("outputs",Au.outputs.map($u=>new Writer().text("name",$u.name,"\0").text("title",$u.title).text("component",$u.component,"Text").part("props",{...$u.props}).data)),lo.value("live",Au.live,!0).data}function parseInterface(Au,lo){const $u={layout:oneOf$3(Au.layout,["chat","page","split"],DEFAULT_LAYOUTS[lo]),accent:APP_ACCENTS.includes(Au.accent)?Au.accent:void 0,welcome:text$k(Au.welcome),starters:records(Au.starters).map(parseStarter),commands:records(Au.commands).map(parseCommand$1),modes:records(Au.modes).map(parseMode),actions:records(Au.actions).map(parseAction),profiles:records(Au.profiles).map(parseProfile),language:text$k(Au.language,DEFAULT_LANGUAGE),translations:mapValues(recordsBy(Au.translations),parseTranslation),components:texts(Au.components),voice:parseVoice(Au.voice),outputs:texts(Au.outputs)};return isData(Au.settings)&&($u.settings=JSON.parse(JSON.stringify(Au.settings))),isData(Au.settings_ui)&&($u.settingsUi=JSON.parse(JSON.stringify(Au.settings_ui))),isData(Au.uploads)&&($u.uploads=parseUploads(Au.uploads)),Array.isArray(Au.custom_components)&&($u.customComponents=records(Au.custom_components).map(parseCustomComponent)),isData(Au.surface)&&($u.surface=parseSurface(Au.surface)),isData(Au.page)&&($u.page=parsePage(Au.page)),isAssistantCharacterId(Au.assistant)&&($u.assistant=Au.assistant),(Au.balloon==="history"||Au.balloon==="current")&&($u.balloon=Au.balloon),isData(Au.theme)&&APP_THEME_VARIANTS.includes(Au.theme.variant)&&($u.theme={variant:Au.theme.variant},APP_THEME_MODES.includes(Au.theme.mode)&&($u.theme.mode=Au.theme.mode)),$u}function parseCriterion(Au){return{name:text$k(Au.name),kind:oneOf$3(Au.kind,["metric","noul","choice","score"],"metric"),weight:Math.max(0,numberOf(Au.weight,1)),instructions:text$k(Au.instructions),options:texts(Au.options),direction:Au.direction==="lower"?"lower":"higher",measure:oneOf$3(Au.measure,["","pass_rate","cost_per_task","seconds_per_task"],"")}}function parseDecision(Au){return{question:text$k(Au.question),alternatives:texts(Au.alternatives),criteria:records(Au.criteria).map(parseCriterion),minConfidence:Math.min(1,Math.max(0,numberOf(Au.min_confidence,0))),scenarios:records(Au.scenarios).map(lo=>({name:text$k(lo.name),weights:Object.fromEntries(Object.entries(isData(lo.weights)?lo.weights:{}).filter($u=>typeof $u[1]=="number"))})),decisionModel:text$k(Au.decision_model)}}function parseSamples(Au){return{documents:records(Au.documents).map(lo=>({name:text$k(lo.name),file:text$k(lo.file),text:text$k(lo.text)})),alternatives:records(Au.alternatives).map(lo=>({name:text$k(lo.name),evidence:text$k(lo.evidence),metrics:Object.fromEntries(Object.entries(isData(lo.metrics)?lo.metrics:{}).filter($u=>typeof $u[1]=="number"))}))}}function parseDeployment(Au){const lo={};return isData(Au.hosted)&&(lo.hosted={visibility:oneOf$3(Au.hosted.visibility,["private","invited","organization","link","public"],"private"),slug:text$k(Au.hosted.slug),...Au.hosted.character_alone===!0?{characterAlone:!0}:{}}),isData(Au.embedded)&&(lo.embedded={mode:oneOf$3(Au.embedded.mode,APP_EMBED_MODES,"inline"),origins:texts(Au.embedded.origins),...isData(Au.embedded.host)?{host:{context:texts(Au.embedded.host.context),...Au.embedded.host.user!==void 0?{user:text$k(Au.embedded.host.user)}:{},functions:records(Au.embedded.host.functions).map($u=>({name:text$k($u.name),description:text$k($u.description),parameters:isData($u.parameters)?$u.parameters:{...NO_HOST_PARAMETERS}}))}}:{}}),lo}function parseTrigger(Au){return{type:oneOf$3(Au.type,["schedule","event","once"],"schedule"),cron:text$k(Au.cron),event:text$k(Au.event),at:text$k(Au.at),description:text$k(Au.description),prompt:text$k(Au.prompt)}}function parseAppspec(Au){const lo=[];if(!isData(Au))return{app:emptyAppspec(),problems:["The document is not an application."]};const $u=Au;for(const Uu of Object.keys($u))KNOWN_KEYS.includes(Uu)||lo.push(`\`${Uu}\` is not a field of the spec.`);lo.push(...uiShapeProblems($u.ui));const Ru=text$k($u.schema,APP_SCHEMA);Ru!==APP_SCHEMA&&lo.push(`This reads ${APP_SCHEMA}; the application is written in ${Ru}.`),APP_KINDS.includes($u.kind)||lo.push($u.kind===void 0?"The application does not say its `kind`.":`\`${String($u.kind)}\` is not a kind: chat, widget, decision or worker.`);const Iu=oneOf$3($u.kind,APP_KINDS,"chat"),Pu=emptyAppspec(Iu),Ou=isData($u.permissions)?$u.permissions:{},Mu=isData(Ou.computer)?Ou.computer:{},Du=isData($u.tests)?$u.tests:{},Lu=isData(Du.verified)?Du.verified:{},Bu=isData($u.record)?$u.record:{},ju=isData($u.checks)?$u.checks:{};for(const Uu of records(ju.code))CHECK_STAGES.includes(Uu.on)||lo.push(`The check \`${text$k(Uu.name)}\` of its code runs on answer or tool_call, not \`${String(Uu.on)}\`.`);const Fu=text$k(Bu.keep_for,DEFAULT_KEEP_FOR);retentionDays(Fu)===0&&lo.push(`Cannot read the retention \`${Fu}\`: write 90_days, 18_months or 1_years.`);const zu={...Pu,schema:APP_SCHEMA,id:text$k($u.id),version:text$k($u.version,DEFAULT_VERSION),name:text$k($u.name),kind:Iu,description:text$k($u.description),owner:text$k($u.owner),agent:text$k($u.agent),team:text$k($u.team),instructions:text$k($u.instructions),model:text$k($u.model),skills:texts($u.skills),backendTools:texts($u.backend_tools),tools:records($u.tools).map(parseTool),context:texts($u.context),contents:texts($u.contents),connections:records($u.connections).map(parseConnection),protocols:texts($u.protocols),ui:uiChoices($u.ui),rules:records($u.rules).map(parseRule$1),permissions:{spaces:records(Ou.spaces).map(Uu=>({space:text$k(Uu.space),access:oneOf$3(Uu.access,["read","write"],"read")})),computer:{browse:flag(Mu.browse,!1),files:flag(Mu.files,!1),shell:flag(Mu.shell,!1)}},interface:parseInterface(isData($u.interface)?$u.interface:{},Iu),tests:{readyAt:Math.min(1,Math.max(0,numberOf(Du.ready_at,DEFAULT_READY_AT))),evalset:text$k(Du.evalset),cases:records(Du.cases).map(Uu=>({ask:text$k(Uu.ask),...records(Uu.turns).length?{turns:records(Uu.turns).map(parseTestTurn)}:{},expect:text$k(Uu.expect),...text$k(Uu.code)?{code:text$k(Uu.code)}:{},...records(Uu.files).length?{files:records(Uu.files).map(Hu=>({name:text$k(Hu.name),text:text$k(Hu.text)}))}:{}})),verified:{live:texts(Lu.live),recorded:texts(Lu.recorded),unverified:texts(Lu.unverified)}},record:{keepFor:Fu,retentionDays:retentionDays(Fu),include:Array.isArray(Bu.include)?texts(Bu.include):[...DEFAULT_RECORD_INCLUDE],suggestTests:Bu.suggest_tests===!0},checks:{guards:texts(ju.guards),gates:texts(ju.gates),track:text$k(ju.track),code:records(ju.code).map(Uu=>({name:text$k(Uu.name),on:oneOf$3(Uu.on,CHECK_STAGES,"answer"),description:text$k(Uu.description)}))},deployment:parseDeployment(isData($u.deployment)?$u.deployment:{}),goal:text$k($u.goal),triggers:records($u.triggers).map(parseTrigger),memory:text$k($u.memory),notifications:texts($u.notifications),samples:parseSamples(isData($u.samples)?$u.samples:{}),enabled:flag($u.enabled,!0),unavailable_because:text$k($u.unavailable_because),tags:texts($u.tags),icon:text$k($u.icon,DEFAULT_ICON),emoji:text$k($u.emoji,DEFAULT_EMOJI)||DEFAULT_EMOJI,avatar:text$k($u.avatar).trim(),banner:text$k($u.banner).trim()};if(isData($u.decision)&&(zu.decision=parseDecision($u.decision)),isData($u.pap)&&Object.keys($u.pap).length>0){const Uu=papProfileProblem($u.pap.profile);Uu?lo.push(Uu):zu.pap=parsePap($u.pap)}if(isData($u.pact)&&(zu.pact=parsePact($u.pact)),isData($u.commerce)&&(zu.commerce=parseCommerce($u.commerce)),isData($u.signed_fetch)&&(zu.signed_fetch=parseSignedFetch($u.signed_fetch)),isData($u.pair)){const Uu=parsePair($u.pair);typeof Uu=="string"?lo.push(Uu):zu.pair=Uu}return isData($u.a2a)&&(zu.a2a=parseA2A($u.a2a)),lo.push(...protocolsProblems(zu),...uiProblems(zu)),{app:zu,problems:lo}}function uiProblems(Au){const lo=[],$u=[];for(const Ru of Au.ui){const Iu=Ru.plugin;if($u.includes(Iu)){lo.push(`It lists the UI plugin '${Iu}' twice.`);continue}$u.push(Iu);const Pu=UI_CATALOGUE[Iu];if(!Pu){lo.push(`There is no UI plugin named '${Iu}': one of ${Object.keys(UI_CATALOGUE).sort().join(", ")}.`+(UI_RENDERER_CATALOGUE[Iu]?` '${Iu}' is a UI renderer: say it as a plugin's \`renderer\`.`:""));continue}if(Ru.renderer===void 0)continue;const Ou=UI_RENDERER_CATALOGUE[Ru.renderer];Ou?Pu.renderers.includes(Ou.id)?Au.enabled&&!Ou.enabled&&lo.push(`The UI renderer ${Ou.name} ('${Ou.id}') is not enabled: an application cannot be exposed through it yet.`):lo.push(`The UI plugin ${Pu.name} ('${Iu}') is not exposed through ${Ou.name}: `+(Pu.renderers.length>0?`through ${Pu.renderers.join(", ")} only.`:"through no renderer.")):lo.push(`There is no UI renderer named '${Ru.renderer}': one of ${Object.keys(UI_RENDERER_CATALOGUE).sort().join(", ")}.`)}return lo}function protocolsProblems(Au){const lo=[],$u=[];for(const Iu of Au.protocols){if($u.includes(Iu)){lo.push(`It lists the protocol '${Iu}' twice.`);continue}$u.push(Iu);const Pu=PROTOCOL_CATALOGUE[Iu];Pu?Au.enabled&&Pu.status==="planned"&&lo.push(`${Pu.name} ('${Iu}') is planned, not shipped: an application cannot speak it yet.`):lo.push(`There is no protocol named '${Iu}': one of ${Object.keys(PROTOCOL_CATALOGUE).sort().join(", ")}.`)}const Ru={pap:!!(Au.pap&&(Au.pap.connections.length>0||Au.pap.company.enabled)),pact:!!(Au.pact&&(Au.pact.connections.length>0||Au.pact.business?.enabled)),a2a:!!(Au.a2a&&Au.a2a.extensions.length>0),signed_fetch:!!(Au.signed_fetch&&Au.signed_fetch.sites.length>0)};for(const Iu of Object.values(PROTOCOL_CATALOGUE)){const Pu=Iu.appspecBlock;Pu&&Ru[Pu]&&!Au.protocols.includes(Iu.id)&&lo.push(`Its \`${Pu}\` block configures ${Iu.name}, which it does not list: add '${Iu.id}' to \`protocols\`.`)}for(const Iu of new Set((Au.commerce?.merchants??[]).map(Pu=>Pu.protocol)))Au.protocols.includes(Iu)||lo.push(`Its \`commerce\` block shops over ${Iu.toUpperCase()}, which it does not list: add '${Iu}' to \`protocols\`.`);return lo}const sameList=(Au,lo)=>Au.length===lo.length&&Au.every(($u,Ru)=>$u===lo[Ru]);class Writer{data={};text(lo,$u,Ru=""){return $u!==Ru&&(this.data[lo]=$u),this}value(lo,$u,Ru){return $u!==Ru&&(this.data[lo]=$u),this}list(lo,$u,Ru=[]){return sameList($u,Ru)||(this.data[lo]=$u),this}part(lo,$u){return Object.keys($u).length>0&&(this.data[lo]=$u),this}present(lo,$u){return $u!==void 0&&(this.data[lo]=$u),this}}function sorted(Au){return Array.isArray(Au)?Au.map(sorted):isData(Au)?Object.fromEntries(Object.keys(Au).sort((lo,$u)=>lo<$u?-1:lo>$u?1:0).map(lo=>[lo,sorted(Au[lo])])):Au}function dumpComponent(Au){const{id:lo,component:$u,...Ru}=Au;return{id:lo,component:$u,...sorted(Ru)}}function dumpSurface(Au){return new Writer().text("protocol",Au.protocol,DEFAULT_PROTOCOL).list("components",Au.components.map(dumpComponent)).text("composed_by",Au.composedBy).text("composed_at",Au.composedAt).data}function dumpStarter(Au){return new Writer().text("label",Au.label,"\0").text("message",Au.message,"\0").text("category",Au.category??"").data}const saidWords=Au=>Object.fromEntries(Object.entries(Au).filter(([,lo])=>lo!==""));function dumpTranslation(Au){const lo=($u,Ru)=>Object.fromEntries(Object.entries($u).map(([Iu,Pu])=>[Iu,Ru(Pu)]));return new Writer().text("name",Au.name).text("description",Au.description).text("welcome",Au.welcome).part("starters",lo(Au.starters,$u=>new Writer().text("label",$u.label).text("message",$u.message).data)).part("categories",saidWords(Au.categories)).part("settings",lo(Au.settings,$u=>new Writer().text("title",$u.title).text("description",$u.description).part("options",saidWords($u.options)).data)).part("commands",saidWords(Au.commands)).part("modes",lo(Au.modes,$u=>new Writer().text("label",$u.label).part("options",lo($u.options,Ru=>new Writer().text("label",Ru.label).text("description",Ru.description).data)).data)).part("profiles",lo(Au.profiles,$u=>new Writer().text("label",$u.label).text("description",$u.description).data)).data}function dumpInterface(Au,lo){const $u=new Writer().value("layout",Au.layout,DEFAULT_LAYOUTS[lo]).value("accent",Au.accent,void 0).text("welcome",Au.welcome).list("starters",Au.starters.map(dumpStarter)).list("commands",Au.commands.map(Ru=>({name:Ru.name,description:Ru.description,prompt:Ru.prompt}))).list("modes",Au.modes.map(Ru=>{const Iu=new Writer().text("id",Ru.id,"\0").text("label",Ru.label,"\0").list("options",Ru.options.map(Pu=>new Writer().text("id",Pu.id,"\0").text("label",Pu.label,"\0").text("description",Pu.description??"").text("instructions",Pu.instructions??"").text("model",Pu.model??"").data));return Ru.default&&(Iu.data.default=Ru.default),Iu.data})).list("actions",(Au.actions??[]).map(Ru=>{const Iu=new Writer().text("name",Ru.name,"\0").text("description",Ru.description??"");return Ru.payload&&(Iu.data.payload={...Ru.payload}),Iu.data})).list("profiles",(Au.profiles??[]).map(Ru=>new Writer().text("id",Ru.id,"\0").text("label",Ru.label,"\0").text("description",Ru.description).text("instructions",Ru.instructions).text("model",Ru.model??"").list("starters",Ru.starters.map(dumpStarter)).data)).part("settings",Au.settings?{...Au.settings}:{});return Au.settingsUi&&($u.data.settings_ui={...Au.settingsUi}),$u.text("language",Au.language??DEFAULT_LANGUAGE,DEFAULT_LANGUAGE).part("translations",mapValues(Au.translations??{},dumpTranslation)),Au.uploads&&($u.data.uploads=new Writer().list("kinds",Au.uploads.kinds.map(Ru=>new Writer().text("type",Ru.type,"\0").value("max_mb",Ru.maxMb,DEFAULT_UPLOAD_MB).data)).value("max_files",Au.uploads.maxFiles,DEFAULT_MAX_FILES).data),$u.list("components",Au.components),$u.list("custom_components",(Au.customComponents??[]).map(dumpCustomComponent)),Au.surface&&($u.data.surface=dumpSurface(Au.surface)),Au.page&&($u.data.page=dumpPage(Au.page)),Au.assistant&&($u.data.assistant=Au.assistant),Au.balloon&&($u.data.balloon=Au.balloon),Au.theme&&($u.data.theme=Au.theme.mode?{variant:Au.theme.variant,mode:Au.theme.mode}:{variant:Au.theme.variant}),Au.voice&&$u.part("voice",new Writer().value("enabled",Au.voice.enabled,DEFAULT_VOICE.enabled).value("input",Au.voice.input,DEFAULT_VOICE.input).value("output",Au.voice.output,DEFAULT_VOICE.output).text("voice",Au.voice.voice).text("language",Au.voice.language).value("where",Au.voice.where,DEFAULT_VOICE.where).data),$u.list("outputs",Au.outputs??[]),$u.data}function dumpDecision(Au){return new Writer().text("question",Au.question,"\0").list("alternatives",Au.alternatives).list("criteria",Au.criteria.map(lo=>new Writer().text("name",lo.name,"\0").value("kind",lo.kind,"metric").value("weight",lo.weight,1).text("instructions",lo.instructions).list("options",lo.options).value("direction",lo.direction,"higher").value("measure",lo.measure,"").data)).value("min_confidence",Au.minConfidence,0).list("scenarios",Au.scenarios.map(lo=>new Writer().text("name",lo.name,"\0").part("weights",sorted(lo.weights)).data)).text("decision_model",Au.decisionModel).data}function dumpSamples(Au){return new Writer().list("documents",Au.documents.map(lo=>new Writer().text("name",lo.name,"\0").text("file",lo.file,"\0").text("text",lo.text,"\0").data)).list("alternatives",Au.alternatives.map(lo=>new Writer().text("name",lo.name,"\0").text("evidence",lo.evidence,"\0").part("metrics",{...lo.metrics}).data)).data}function dumpAppspec(Au){const lo=new Writer().value("browse",Au.permissions.computer.browse,!1).value("files",Au.permissions.computer.files,!1).value("shell",Au.permissions.computer.shell,!1).data,$u=new Writer;return $u.data.schema=APP_SCHEMA,$u.text("id",Au.id,"\0").text("version",Au.version,DEFAULT_VERSION).text("name",Au.name,"\0").text("kind",Au.kind,"\0").text("description",Au.description).text("owner",Au.owner).text("agent",Au.agent).text("team",Au.team).text("instructions",Au.instructions).text("model",Au.model).list("skills",Au.skills).list("backend_tools",Au.backendTools).list("tools",(Au.tools??[]).map(Ru=>({name:Ru.name,description:Ru.description,...JSON.stringify(Ru.parameters)===JSON.stringify(NO_HOST_PARAMETERS)?{}:{parameters:Ru.parameters},does:Ru.does}))).list("context",Au.context).list("contents",Au.contents).list("connections",Au.connections.map(Ru=>new Writer().text("server",Ru.server,"\0").value("access",Ru.access,"read").value("as",Ru.as,"owner").list("only",Ru.only).data)).list("protocols",Au.protocols).list("ui",Au.ui.map(Ru=>Ru.renderer?{plugin:Ru.plugin,renderer:Ru.renderer}:{plugin:Ru.plugin})).part("pap",dumpPap(Au.pap)).part("pact",dumpPact(Au.pact)).part("commerce",dumpCommerce(Au.commerce)).part("signed_fetch",dumpSignedFetch(Au.signed_fetch)).part("pair",Au.pair?{id:Au.pair.id,role:Au.pair.role}:{}).part("a2a",dumpA2A(Au.a2a)).list("rules",Au.rules.map(Ru=>({action:Ru.action,applies_to:Ru.appliesTo.length===1&&ACTION_CLASS_NAMES.includes(Ru.appliesTo[0])?Ru.appliesTo[0]:Ru.appliesTo,behaviour:Ru.behaviour}))).part("permissions",new Writer().list("spaces",Au.permissions.spaces.map(Ru=>new Writer().text("space",Ru.space,"\0").value("access",Ru.access,"read").data)).part("computer",lo).data).part("interface",dumpInterface(Au.interface,Au.kind)).part("tests",new Writer().value("ready_at",Au.tests.readyAt,DEFAULT_READY_AT).text("evalset",Au.tests.evalset).list("cases",Au.tests.cases.map(Ru=>({...Ru.turns?.length?{turns:Ru.turns.map(Iu=>parseTestTurn({...Iu}))}:{ask:Ru.ask},expect:Ru.expect,...Ru.code?{code:Ru.code}:{},...Ru.files?.length?{files:Ru.files.map(Iu=>({name:Iu.name,text:Iu.text}))}:{}}))).part("verified",new Writer().list("live",Au.tests.verified.live).list("recorded",Au.tests.verified.recorded).list("unverified",Au.tests.verified.unverified).data).data).part("record",new Writer().text("keep_for",Au.record.keepFor,DEFAULT_KEEP_FOR).list("include",Au.record.include,DEFAULT_RECORD_INCLUDE).value("suggest_tests",Au.record.suggestTests,!1).data).part("checks",new Writer().list("guards",Au.checks.guards).list("gates",Au.checks.gates).text("track",Au.checks.track).list("code",(Au.checks.code??[]).map(Ru=>({name:Ru.name,on:Ru.on,description:Ru.description}))).data).part("deployment",new Writer().present("hosted",Au.deployment.hosted&&new Writer().value("visibility",Au.deployment.hosted.visibility,"private").text("slug",Au.deployment.hosted.slug).value("character_alone",Au.deployment.hosted.characterAlone===!0,!1).data).present("embedded",Au.deployment.embedded&&new Writer().value("mode",Au.deployment.embedded.mode,"inline").list("origins",Au.deployment.embedded.origins).present("host",Au.deployment.embedded.host&&new Writer().list("context",Au.deployment.embedded.host.context).list("functions",Au.deployment.embedded.host.functions.map(Ru=>({name:Ru.name,description:Ru.description,...JSON.stringify(Ru.parameters)===JSON.stringify(NO_HOST_PARAMETERS)?{}:{parameters:Ru.parameters}}))).value("user",Au.deployment.embedded.host.user??"claimed","claimed").data).data).data).text("goal",Au.goal).list("triggers",Au.triggers.map(Ru=>new Writer().text("type",Ru.type,"\0").text("cron",Ru.cron).text("event",Ru.event).text("at",Ru.at).text("description",Ru.description).text("prompt",Ru.prompt).data)).text("memory",Au.memory).list("notifications",Au.notifications),Au.decision&&($u.data.decision=dumpDecision(Au.decision)),$u.part("samples",dumpSamples(Au.samples)).value("enabled",Au.enabled,!0).text("unavailable_because",Au.unavailable_because).list("tags",Au.tags).text("icon",Au.icon??DEFAULT_ICON,DEFAULT_ICON).text("emoji",Au.emoji,DEFAULT_EMOJI).text("avatar",Au.avatar??"","").text("banner",Au.banner??"",""),$u.data}const ALIAS=Symbol.for("yaml.alias"),DOC=Symbol.for("yaml.document"),MAP$1=Symbol.for("yaml.map"),PAIR=Symbol.for("yaml.pair"),SCALAR$1=Symbol.for("yaml.scalar"),SEQ=Symbol.for("yaml.seq"),NODE_TYPE$1=Symbol.for("yaml.node.type"),isAlias=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===ALIAS,isDocument=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===DOC,isMap=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===MAP$1,isPair=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===PAIR,isScalar=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===SCALAR$1,isSeq$1=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===SEQ;function isCollection(Au){if(Au&&typeof Au=="object")switch(Au[NODE_TYPE$1]){case MAP$1:case SEQ:return!0}return!1}function isNode$1(Au){if(Au&&typeof Au=="object")switch(Au[NODE_TYPE$1]){case ALIAS:case MAP$1:case SCALAR$1:case SEQ:return!0}return!1}const hasAnchor=Au=>(isScalar(Au)||isCollection(Au))&&!!Au.anchor,BREAK=Symbol("break visit"),SKIP$1=Symbol("skip children"),REMOVE=Symbol("remove node");function visit$4(Au,lo){const $u=initVisitor(lo);isDocument(Au)?visit_(null,Au.contents,$u,Object.freeze([Au]))===REMOVE&&(Au.contents=null):visit_(null,Au,$u,Object.freeze([]))}visit$4.BREAK=BREAK;visit$4.SKIP=SKIP$1;visit$4.REMOVE=REMOVE;function visit_(Au,lo,$u,Ru){const Iu=callVisitor(Au,lo,$u,Ru);if(isNode$1(Iu)||isPair(Iu))return replaceNode(Au,Ru,Iu),visit_(Au,Iu,$u,Ru);if(typeof Iu!="symbol"){if(isCollection(lo)){Ru=Object.freeze(Ru.concat(lo));for(let Pu=0;Pu<lo.items.length;++Pu){const Ou=visit_(Pu,lo.items[Pu],$u,Ru);if(typeof Ou=="number")Pu=Ou-1;else{if(Ou===BREAK)return BREAK;Ou===REMOVE&&(lo.items.splice(Pu,1),Pu-=1)}}}else if(isPair(lo)){Ru=Object.freeze(Ru.concat(lo));const Pu=visit_("key",lo.key,$u,Ru);if(Pu===BREAK)return BREAK;Pu===REMOVE&&(lo.key=null);const Ou=visit_("value",lo.value,$u,Ru);if(Ou===BREAK)return BREAK;Ou===REMOVE&&(lo.value=null)}}return Iu}function initVisitor(Au){return typeof Au=="object"&&(Au.Collection||Au.Node||Au.Value)?Object.assign({Alias:Au.Node,Map:Au.Node,Scalar:Au.Node,Seq:Au.Node},Au.Value&&{Map:Au.Value,Scalar:Au.Value,Seq:Au.Value},Au.Collection&&{Map:Au.Collection,Seq:Au.Collection},Au):Au}function callVisitor(Au,lo,$u,Ru){if(typeof $u=="function")return $u(Au,lo,Ru);if(isMap(lo))return $u.Map?.(Au,lo,Ru);if(isSeq$1(lo))return $u.Seq?.(Au,lo,Ru);if(isPair(lo))return $u.Pair?.(Au,lo,Ru);if(isScalar(lo))return $u.Scalar?.(Au,lo,Ru);if(isAlias(lo))return $u.Alias?.(Au,lo,Ru)}function replaceNode(Au,lo,$u){const Ru=lo[lo.length-1];if(isCollection(Ru))Ru.items[Au]=$u;else if(isPair(Ru))Au==="key"?Ru.key=$u:Ru.value=$u;else if(isDocument(Ru))Ru.contents=$u;else{const Iu=isAlias(Ru)?"alias":"scalar";throw new Error(`Cannot replace node with ${Iu} parent`)}}const escapeChars={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},escapeTagName=Au=>Au.replace(/[!,[\]{}]/g,lo=>escapeChars[lo]);class Directives{constructor(lo,$u){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Directives.defaultYaml,lo),this.tags=Object.assign({},Directives.defaultTags,$u)}clone(){const lo=new Directives(this.yaml,this.tags);return lo.docStart=this.docStart,lo}atDocument(){const lo=new Directives(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Directives.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Directives.defaultTags);break}return lo}add(lo,$u){this.atNextDocument&&(this.yaml={explicit:Directives.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Directives.defaultTags),this.atNextDocument=!1);const Ru=lo.trim().split(/[ \t]+/),Iu=Ru.shift();switch(Iu){case"%TAG":{if(Ru.length!==2&&($u(0,"%TAG directive should contain exactly two parts"),Ru.length<2))return!1;const[Pu,Ou]=Ru;return this.tags[Pu]=Ou,!0}case"%YAML":{if(this.yaml.explicit=!0,Ru.length!==1)return $u(0,"%YAML directive should contain exactly one part"),!1;const[Pu]=Ru;if(Pu==="1.1"||Pu==="1.2")return this.yaml.version=Pu,!0;{const Ou=/^\d+\.\d+$/.test(Pu);return $u(6,`Unsupported YAML version ${Pu}`,Ou),!1}}default:return $u(0,`Unknown directive ${Iu}`,!0),!1}}tagName(lo,$u){if(lo==="!")return"!";if(lo[0]!=="!")return $u(`Not a valid tag: ${lo}`),null;if(lo[1]==="<"){const Ou=lo.slice(2,-1);return Ou==="!"||Ou==="!!"?($u(`Verbatim tags aren't resolved, so ${lo} is invalid.`),null):(lo[lo.length-1]!==">"&&$u("Verbatim tags must end with a >"),Ou)}const[,Ru,Iu]=lo.match(/^(.*!)([^!]*)$/s);Iu||$u(`The ${lo} tag has no suffix`);const Pu=this.tags[Ru];if(Pu)try{return Pu+decodeURIComponent(Iu)}catch(Ou){return $u(String(Ou)),null}return Ru==="!"?lo:($u(`Could not resolve tag: ${lo}`),null)}tagString(lo){for(const[$u,Ru]of Object.entries(this.tags))if(lo.startsWith(Ru))return $u+escapeTagName(lo.substring(Ru.length));return lo[0]==="!"?lo:`!<${lo}>`}toString(lo){const $u=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],Ru=Object.entries(this.tags);let Iu;if(lo&&Ru.length>0&&isNode$1(lo.contents)){const Pu={};visit$4(lo.contents,(Ou,Mu)=>{isNode$1(Mu)&&Mu.tag&&(Pu[Mu.tag]=!0)}),Iu=Object.keys(Pu)}else Iu=[];for(const[Pu,Ou]of Ru)Pu==="!!"&&Ou==="tag:yaml.org,2002:"||(!lo||Iu.some(Mu=>Mu.startsWith(Ou)))&&$u.push(`%TAG ${Pu} ${Ou}`);return $u.join(`
|
|
123
|
+
`,loopThemeStyles=buildThemeStyles(loopLight,loopDark,{fontFamily:loopFontFamily,css:loopOwnCss,shape:{radiusControl:loopShapeVars["--loop-radius-control"],radiusTable:loopShapeVars["--borderRadius-medium"],radiusOverlay:loopShapeVars["--loop-radius-card"],radiusCard:loopShapeVars["--loop-radius-card"],radiusBubble:loopShapeVars["--loop-radius-bubble"],radiusFrame:loopShapeVars["--loop-radius-frame"],shadow:loopShapeVars["--loop-shadow-frame"],motionStatus:loopMotionVars["--loop-motion-status"],motionMessage:loopMotionVars["--loop-motion-message"],motionPane:loopMotionVars["--loop-motion-pane"],motionEasing:loopMotionVars["--loop-motion-easing"],messageLink:"currentColor"},variables:{light:{...loopShapeVars,...loopTints("light"),...loopMotionVars,...loopShadows.light,...loopTypeVars(loopFontFamily),"--loop-hairline":loopHairline.light,"--borderColor-default":loopHairline.light,"--focus-outlineColor":loopFocusRing.light,"--underlineNav-borderColor-active":themeAccents.green.accent},dark:{...loopShapeVars,...loopTints("dark"),...loopMotionVars,...loopShadows.dark,...loopTypeVars(loopFontFamily),"--loop-hairline":loopHairline.dark,"--borderColor-default":loopHairline.dark,"--focus-outlineColor":loopFocusRing.dark,"--underlineNav-borderColor-active":themeAccents.green.accent}}});loopThemeStyles.css;const loopTheme={...theme$1,fontWeights:{light:loopFontWeights.regular,normal:loopFontWeights.regular,semibold:loopFontWeights.semibold,bold:loopFontWeights.semibold}},themeTokens={datalayer:{label:"Datalayer",description:"Default green palette — the classic Datalayer look.",brandColor:datalayerColors.greenBrand,defaultColorMode:"auto",themeStyles:datalayerThemeStyles,cardGradient:{light:{from:datalayerColors.greenBrand,to:datalayerColors.greenText},dark:{from:datalayerColors.greenAccent,to:datalayerColors.greenBrand}},brightPalette:{glow:datalayerColors.brightGlow,onGlow:"#1b1f24",pop:datalayerColors.brightPop,spark:datalayerColors.brightSpark,blaze:datalayerColors.brightBlaze,surge:datalayerColors.brightSurge,flame:datalayerColors.brightFlame,gold:datalayerColors.brightGold},brightPaletteLight:{glow:datalayerColors.brightLightGlow,onGlow:"#1b1f24",pop:datalayerColors.brightLightPop,spark:datalayerColors.brightLightSpark,blaze:datalayerColors.brightLightBlaze,surge:datalayerColors.brightLightSurge,flame:datalayerColors.brightLightFlame,gold:datalayerColors.brightLightGold}},spatial:{label:"Spatial",description:"Cosmic indigo & deep blues — inspired by space.",brandColor:spatialColors.indigoBrand,defaultColorMode:"auto",themeStyles:spatialThemeStyles,cardGradient:{light:{from:spatialColors.indigoBrand,to:spatialColors.indigoText},dark:{from:spatialColors.indigoAccent,to:spatialColors.indigoBrand}},brightPalette:{glow:spatialColors.brightGlow,onGlow:"#ffffff",pop:spatialColors.brightPop,spark:spatialColors.brightSpark,blaze:spatialColors.brightBlaze,surge:spatialColors.brightSurge,flame:spatialColors.brightFlame,gold:spatialColors.brightGold},brightPaletteLight:{glow:spatialColors.brightLightGlow,onGlow:"#ffffff",pop:spatialColors.brightLightPop,spark:spatialColors.brightLightSpark,blaze:spatialColors.brightLightBlaze,surge:spatialColors.brightLightSurge,flame:spatialColors.brightLightFlame,gold:spatialColors.brightLightGold}},lovely:{label:"Lovely",description:"Warm rose & magenta — soft and inviting.",brandColor:lovelyColors.roseBrand,defaultColorMode:"auto",themeStyles:lovelyThemeStyles,cardGradient:{light:{from:lovelyColors.roseBrand,to:lovelyColors.roseText},dark:{from:lovelyColors.roseAccent,to:lovelyColors.roseBrand}},brightPalette:{glow:lovelyColors.brightGlow,onGlow:"#ffffff",pop:lovelyColors.brightPop,spark:lovelyColors.brightSpark,blaze:lovelyColors.brightBlaze,surge:lovelyColors.brightSurge,flame:lovelyColors.brightFlame,gold:lovelyColors.brightGold},brightPaletteLight:{glow:lovelyColors.brightLightGlow,onGlow:"#ffffff",pop:lovelyColors.brightLightPop,spark:lovelyColors.brightLightSpark,blaze:lovelyColors.brightLightBlaze,surge:lovelyColors.brightLightSurge,flame:lovelyColors.brightLightFlame,gold:lovelyColors.brightLightGold}},matrix:{label:"Matrix",description:"Phosphor green on black — CRT terminal aesthetic.",brandColor:matrixColors.greenPhosphor,defaultColorMode:"dark",themeStyles:matrixThemeStyles,cardGradient:{light:{from:matrixColors.greenBrand,to:matrixColors.greenText},dark:{from:matrixColors.greenGlow,to:matrixColors.greenHover}},brightPalette:{glow:matrixColors.brightGlow,onGlow:"#1b1f24",pop:matrixColors.brightPop,spark:matrixColors.brightSpark,blaze:matrixColors.brightBlaze,surge:matrixColors.brightSurge,flame:matrixColors.brightFlame,gold:matrixColors.brightGold},brightPaletteLight:{glow:matrixColors.brightLightGlow,onGlow:"#1b1f24",pop:matrixColors.brightLightPop,spark:matrixColors.brightLightSpark,blaze:matrixColors.brightLightBlaze,surge:matrixColors.brightLightSurge,flame:matrixColors.brightLightFlame,gold:matrixColors.brightLightGold}},earth:{label:"Earth",description:"Ocean blues, forest greens & golden sun — the Blue Planet.",brandColor:earthColors.oceanBrand,defaultColorMode:"auto",themeStyles:earthThemeStyles,cardGradient:{light:{from:earthColors.oceanBrand,to:earthColors.oceanText},dark:{from:earthColors.oceanAccent,to:earthColors.oceanBrand}},brightPalette:{glow:earthColors.brightGlow,onGlow:"#ffffff",pop:earthColors.brightPop,spark:earthColors.brightSpark,blaze:earthColors.brightBlaze,surge:earthColors.brightSurge,flame:earthColors.brightFlame,gold:earthColors.brightGold},brightPaletteLight:{glow:earthColors.brightLightGlow,onGlow:"#ffffff",pop:earthColors.brightLightPop,spark:earthColors.brightLightSpark,blaze:earthColors.brightLightBlaze,surge:earthColors.brightLightSurge,flame:earthColors.brightLightFlame,gold:earthColors.brightLightGold}},sand:{label:"Sand",description:"Warm, pale desert neutrals with a golden accent — calm & editorial.",brandColor:sandColors.sandBrand,defaultColorMode:"light",themeStyles:sandThemeStyles,cardGradient:{light:{from:sandColors.sandBrand,to:sandColors.sandText},dark:{from:sandColors.sandAccent,to:sandColors.sandBrand}},brightPalette:{glow:sandColors.brightGlow,onGlow:"#211A12",pop:sandColors.brightPop,spark:sandColors.brightSpark,blaze:sandColors.brightBlaze,surge:sandColors.brightSurge,flame:sandColors.brightFlame,gold:sandColors.brightGold},brightPaletteLight:{glow:sandColors.brightLightGlow,onGlow:"#ffffff",pop:sandColors.brightLightPop,spark:sandColors.brightLightSpark,blaze:sandColors.brightLightBlaze,surge:sandColors.brightLightSurge,flame:sandColors.brightLightFlame,gold:sandColors.brightLightGold}},ivory:{label:"Ivory",description:"Soft, warm off-white that creates a calm, refined, and welcoming feeling.",brandColor:ivoryColors.ivoryBrand,defaultColorMode:"light",themeStyles:ivoryThemeStyles,cardGradient:{light:{from:ivoryColors.ivoryBrand,to:ivoryColors.ivoryText},dark:{from:ivoryColors.ivoryAccent,to:ivoryColors.ivoryBrand}},brightPalette:{glow:ivoryColors.brightGlow,onGlow:"#211A12",pop:ivoryColors.brightPop,spark:ivoryColors.brightSpark,blaze:ivoryColors.brightBlaze,surge:ivoryColors.brightSurge,flame:ivoryColors.brightFlame,gold:ivoryColors.brightGold},brightPaletteLight:{glow:ivoryColors.brightLightGlow,onGlow:"#ffffff",pop:ivoryColors.brightLightPop,spark:ivoryColors.brightLightSpark,blaze:ivoryColors.brightLightBlaze,surge:ivoryColors.brightLightSurge,flame:ivoryColors.brightLightFlame,gold:ivoryColors.brightLightGold}},sun:{label:"Sun",description:"Warm, radiant theme inspired by golden light, bringing energy, optimism, and a welcoming atmosphere.",brandColor:sunColors.sunBrand,defaultColorMode:"light",themeStyles:sunThemeStyles,cardGradient:{light:{from:sunColors.sunBrand,to:sunColors.sunText},dark:{from:sunColors.sunAccent,to:sunColors.sunBrand}},brightPalette:{glow:sunColors.brightGlow,onGlow:"#211A08",pop:sunColors.brightPop,spark:sunColors.brightSpark,blaze:sunColors.brightBlaze,surge:sunColors.brightSurge,flame:sunColors.brightFlame,gold:sunColors.brightGold},brightPaletteLight:{glow:sunColors.brightLightGlow,onGlow:"#ffffff",pop:sunColors.brightLightPop,spark:sunColors.brightLightSpark,blaze:sunColors.brightLightBlaze,surge:sunColors.brightLightSurge,flame:sunColors.brightLightFlame,gold:sunColors.brightLightGold}},loop:{label:"Loop",description:"Very clean: one soft accent, neutral everything else. The look of an application built in LOOP.",brandColor:loopColors.loopBrand,defaultColorMode:"light",themeStyles:loopThemeStyles,cardGradient:{light:{from:loopColors.loopBrand,to:loopColors.loopBrand},dark:{from:loopColors.loopBrand,to:loopColors.loopBrand}},brightPalette:{glow:loopColors.brightGlow,onGlow:loopColors.loopOn,pop:loopColors.brightPop,spark:loopColors.brightSpark,blaze:loopColors.brightBlaze,surge:loopColors.brightSurge,flame:loopColors.brightFlame,gold:loopColors.brightGold},brightPaletteLight:{glow:loopColors.brightLightGlow,onGlow:"#ffffff",pop:loopColors.brightLightPop,spark:loopColors.brightLightSpark,blaze:loopColors.brightLightBlaze,surge:loopColors.brightLightSurge,flame:loopColors.brightLightFlame,gold:loopColors.brightLightGold}}};function brightPaletteOf(Au,lo){const $u=themeTokens[Au]??themeTokens.datalayer;return lo==="light"?$u.brightPaletteLight??$u.brightPalette:$u.brightPalette}const primerThemes={datalayer:datalayerTheme,spatial:spatialTheme,lovely:lovelyTheme,matrix:matrixTheme,earth:earthTheme,sand:sandTheme,ivory:ivoryTheme,sun:sunTheme,loop:loopTheme},themeConfigs=Object.fromEntries(Object.keys(themeTokens).map(Au=>[Au,{...themeTokens[Au],primerTheme:primerThemes[Au]}]));function getThemeConfig(Au){return themeConfigs[Au]}const osMode=()=>typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";function getBrightPalette(Au="datalayer",lo){const $u=lo==="auto"?osMode():lo==="light"?"light":"dark";return brightPaletteOf(Au,$u)}const createStoreImpl$2=Au=>{let lo;const $u=new Set,Ru=(Lu,Bu)=>{const ju=typeof Lu=="function"?Lu(lo):Lu;if(!Object.is(ju,lo)){const Fu=lo;lo=Bu??(typeof ju!="object"||ju===null)?ju:Object.assign({},lo,ju),$u.forEach(zu=>zu(lo,Fu))}},Iu=()=>lo,Mu={setState:Ru,getState:Iu,getInitialState:()=>Du,subscribe:Lu=>($u.add(Lu),()=>$u.delete(Lu))},Du=lo=Au(Ru,Iu,Mu);return Mu},createStore$2=(Au=>Au?createStoreImpl$2(Au):createStoreImpl$2),identity$2=Au=>Au;function useStore$2(Au,lo=identity$2){const $u=vM.useSyncExternalStore(Au.subscribe,vM.useCallback(()=>lo(Au.getState()),[Au,lo]),vM.useCallback(()=>lo(Au.getInitialState()),[Au,lo]));return vM.useDebugValue($u),$u}const createImpl$2=Au=>{const lo=createStore$2(Au),$u=Ru=>useStore$2(lo,Ru);return Object.assign($u,lo),$u},create$h=(Au=>Au?createImpl$2(Au):createImpl$2);function createJSONStorage$1(Au,lo){let $u;try{$u=Au()}catch{return}return{getItem:Iu=>{var Pu;const Ou=Du=>Du===null?null:JSON.parse(Du,void 0),Mu=(Pu=$u.getItem(Iu))!=null?Pu:null;return Mu instanceof Promise?Mu.then(Ou):Ou(Mu)},setItem:(Iu,Pu)=>$u.setItem(Iu,JSON.stringify(Pu,void 0)),removeItem:Iu=>$u.removeItem(Iu)}}const toThenable$1=Au=>lo=>{try{const $u=Au(lo);return $u instanceof Promise?$u:{then(Ru){return toThenable$1(Ru)($u)},catch(Ru){return this}}}catch($u){return{then(Ru){return this},catch(Ru){return toThenable$1(Ru)($u)}}}},persistImpl$1=(Au,lo)=>($u,Ru,Iu)=>{let Pu={storage:createJSONStorage$1(()=>window.localStorage),partialize:Vu=>Vu,version:0,merge:(Vu,Gu)=>({...Gu,...Vu}),...lo},Ou=!1,Mu=0;const Du=new Set,Lu=new Set;let Bu=Pu.storage;if(!Bu)return Au((...Vu)=>{console.warn(`[zustand persist middleware] Unable to update item '${Pu.name}', the given storage is currently unavailable.`),$u(...Vu)},Ru,Iu);const ju=()=>{const Vu=Pu.partialize({...Ru()});return Bu.setItem(Pu.name,{state:Vu,version:Pu.version})},Fu=Iu.setState;Iu.setState=(Vu,Gu)=>(Fu(Vu,Gu),ju());const zu=Au((...Vu)=>($u(...Vu),ju()),Ru,Iu);Iu.getInitialState=()=>zu;let Uu;const Hu=()=>{var Vu,Gu;if(!Bu)return;const Wu=++Mu;Ou=!1,Du.forEach(Ju=>{var Yu;return Ju((Yu=Ru())!=null?Yu:zu)});const Ku=((Gu=Pu.onRehydrateStorage)==null?void 0:Gu.call(Pu,(Vu=Ru())!=null?Vu:zu))||void 0;return toThenable$1(Bu.getItem.bind(Bu))(Pu.name).then(Ju=>{if(Ju)if(typeof Ju.version=="number"&&Ju.version!==Pu.version){if(Pu.migrate){const Yu=Pu.migrate(Ju.state,Ju.version);return Yu instanceof Promise?Yu.then(Xu=>[!0,Xu]):[!0,Yu]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,Ju.state];return[!1,void 0]}).then(Ju=>{var Yu;if(Wu!==Mu)return;const[Xu,ed]=Ju;if(Uu=Pu.merge(ed,(Yu=Ru())!=null?Yu:zu),$u(Uu,!0),Xu)return ju()}).then(()=>{Wu===Mu&&(Ku?.(Ru(),void 0),Uu=Ru(),Ou=!0,Lu.forEach(Ju=>Ju(Uu)))}).catch(Ju=>{Wu===Mu&&Ku?.(void 0,Ju)})};return Iu.persist={setOptions:Vu=>{Pu={...Pu,...Vu},Vu.storage&&(Bu=Vu.storage)},clearStorage:()=>{++Mu,Bu?.removeItem(Pu.name)},getOptions:()=>Pu,rehydrate:()=>Hu(),hasHydrated:()=>Ou,onHydrate:Vu=>(Du.add(Vu),()=>{Du.delete(Vu)}),onFinishHydration:Vu=>(Lu.add(Vu),()=>{Lu.delete(Vu)})},Pu.skipHydration||Hu(),Uu||zu},persist$2=persistImpl$1,VARIANT_SCHEMA_VERSION=1;function normalizeVariantPreference(Au){return{theme:Au.theme,colorMode:Au.colorMode,version:typeof Au.version=="number"?Au.version:VARIANT_SCHEMA_VERSION}}function normalizeVariants(Au){if(!Au)return{};const lo={};for(const[$u,Ru]of Object.entries(Au))!Ru||typeof Ru!="object"||!("theme"in Ru)||!("colorMode"in Ru)||(lo[$u]=normalizeVariantPreference(Ru));return lo}function hasMissingVariantVersion(Au){return!Au||Object.keys(Au).length===0?!1:Object.values(Au).some(lo=>typeof lo?.version!="number")}const colorModeCycle={light:"dark",dark:"auto",auto:"light"};function createThemeStore(Au,lo){return create$h()(persist$2($u=>({colorMode:lo?.colorMode,theme:lo?.theme,activeVariant:null,variants:normalizeVariants(lo?.variants),toggleColorMode:()=>$u(Ru=>{const Iu=colorModeCycle[Ru.colorMode];return Ru.activeVariant&&Ru.variants[Ru.activeVariant]?{colorMode:Iu,variants:{...Ru.variants,[Ru.activeVariant]:{...Ru.variants[Ru.activeVariant],colorMode:Iu,version:VARIANT_SCHEMA_VERSION}}}:{colorMode:Iu}}),setColorMode:Ru=>$u(Iu=>Iu.activeVariant&&Iu.variants[Iu.activeVariant]?{colorMode:Ru,variants:{...Iu.variants,[Iu.activeVariant]:{...Iu.variants[Iu.activeVariant],colorMode:Ru,version:VARIANT_SCHEMA_VERSION}}}:{colorMode:Ru}),setTheme:(Ru,Iu=!0)=>$u(Pu=>{const Ou=Iu?themeConfigs[Ru].defaultColorMode:Pu.colorMode;return Pu.activeVariant&&Pu.variants[Pu.activeVariant]?{theme:Ru,colorMode:Ou,variants:{...Pu.variants,[Pu.activeVariant]:{theme:Ru,colorMode:Ou,version:VARIANT_SCHEMA_VERSION}}}:{theme:Ru,colorMode:Ou}}),registerVariants:Ru=>$u(Iu=>{const Pu={...Iu.variants};for(const[Ou,Mu]of Object.entries(Ru))Pu[Ou]?Pu[Ou]=normalizeVariantPreference({...Pu[Ou],version:Pu[Ou].version??VARIANT_SCHEMA_VERSION}):Pu[Ou]=normalizeVariantPreference(Mu);return{variants:Pu}}),setVariant:Ru=>$u(Iu=>{const Pu=Iu.variants[Ru];return Pu?{activeVariant:Ru,theme:Pu.theme,colorMode:Pu.colorMode}:{activeVariant:Ru}})}),{name:Au,version:3,storage:createJSONStorage$1(()=>localStorage),partialize:$u=>({colorMode:$u.colorMode,theme:$u.theme,activeVariant:$u.activeVariant,variants:$u.variants}),migrate:$u=>{const Ru=$u??{},Iu=Ru.variants,Pu=hasMissingVariantVersion(Iu),Ou=normalizeVariants(Iu);return Pu&&(Ou["agent-anonymous"]={theme:"matrix",colorMode:"dark",version:VARIANT_SCHEMA_VERSION}),{...Ru,variants:Ou,...Pu?{theme:Ru.activeVariant==="agent-anonymous"?"matrix":Ru.theme,colorMode:Ru.activeVariant==="agent-anonymous"?"dark":Ru.colorMode}:{}}},merge:($u,Ru)=>{const Iu=$u??{},Pu=normalizeVariants(Ru.variants);if(Iu.variants)for(const[Ou,Mu]of Object.entries(Iu.variants))Mu&&typeof Mu=="object"&&"theme"in Mu&&(Pu[Ou]=normalizeVariantPreference(Mu));return{...Ru,...Iu,variants:Pu}}}))}const useThemeStore=createThemeStore("datalayer-theme",{colorMode:"dark",theme:"matrix"}),dlBrightDark=getBrightPalette("datalayer"),dlBrightLight=getBrightPalette("datalayer","light"),spBrightDark=getBrightPalette("spatial"),spBrightLight=getBrightPalette("spatial","light"),lvBrightDark=getBrightPalette("lovely"),lvBrightLight=getBrightPalette("lovely","light"),mxBrightDark=getBrightPalette("matrix"),mxBrightLight=getBrightPalette("matrix","light"),eaBrightDark=getBrightPalette("earth"),eaBrightLight=getBrightPalette("earth","light"),saBrightDark=getBrightPalette("sand"),saBrightLight=getBrightPalette("sand","light"),ivBrightDark=getBrightPalette("ivory"),ivBrightLight=getBrightPalette("ivory","light"),suBrightDark=getBrightPalette("sun"),suBrightLight=getBrightPalette("sun","light"),loBrightDark=getBrightPalette("loop"),loBrightLight=getBrightPalette("loop","light"),palettes={datalayer:{light:{bg:"#f6f8fa",bgPanel:"#ffffff",bgAlt:"#f0f3f6",primary:datalayerColors.greenBrand,secondary:datalayerColors.greenText,accent:datalayerColors.greenBright,glow:dlBrightLight.glow,pop:dlBrightLight.pop,spark:dlBrightLight.spark,blaze:dlBrightLight.blaze,surge:dlBrightLight.surge,flame:dlBrightLight.flame,gold:dlBrightLight.gold,textLight:"#1f2328",textMuted:"#656d76",isLight:!0},dark:{bg:"#0d1117",bgPanel:"#161b22",bgAlt:"#1c2128",primary:datalayerColors.greenAccent,secondary:datalayerColors.greenBrand,accent:datalayerColors.greenBright,glow:dlBrightDark.glow,pop:dlBrightDark.pop,spark:dlBrightDark.spark,blaze:dlBrightDark.blaze,surge:dlBrightDark.surge,flame:dlBrightDark.flame,gold:dlBrightDark.gold,textLight:"#f0f6fc",textMuted:"#8b949e",isLight:!1}},spatial:{light:{bg:"#f0f2ff",bgPanel:"#ffffff",bgAlt:"#eef2ff",primary:spatialColors.indigoBrand,secondary:spatialColors.indigoText,accent:spatialColors.indigoBright,glow:spBrightLight.glow,pop:spBrightLight.pop,spark:spBrightLight.spark,blaze:spBrightLight.blaze,surge:spBrightLight.surge,flame:spBrightLight.flame,gold:spBrightLight.gold,textLight:"#1E1E3F",textMuted:spatialColors.gray,isLight:!0},dark:{bg:spatialColors.black,bgPanel:"#111827",bgAlt:"#1E293B",primary:spatialColors.indigoAccent,secondary:spatialColors.indigoBrand,accent:spatialColors.indigoBright,glow:spBrightDark.glow,pop:spBrightDark.pop,spark:spBrightDark.spark,blaze:spBrightDark.blaze,surge:spBrightDark.surge,flame:spBrightDark.flame,gold:spBrightDark.gold,textLight:"#E0E7FF",textMuted:"#94A3B8",isLight:!1}},lovely:{light:{bg:"#fff5f7",bgPanel:"#ffffff",bgAlt:lovelyColors.roseTint,primary:lovelyColors.roseBrand,secondary:lovelyColors.roseText,accent:lovelyColors.roseBright,glow:lvBrightLight.glow,pop:lvBrightLight.pop,spark:lvBrightLight.spark,blaze:lvBrightLight.blaze,surge:lvBrightLight.surge,flame:lvBrightLight.flame,gold:lvBrightLight.gold,textLight:"#2D1B28",textMuted:lovelyColors.gray,isLight:!0},dark:{bg:lovelyColors.black,bgPanel:"#250E1D",bgAlt:"#3D1530",primary:lovelyColors.roseAccent,secondary:lovelyColors.roseBrand,accent:lovelyColors.roseBright,glow:lvBrightDark.glow,pop:lvBrightDark.pop,spark:lvBrightDark.spark,blaze:lvBrightDark.blaze,surge:lvBrightDark.surge,flame:lvBrightDark.flame,gold:lvBrightDark.gold,textLight:"#FCE7F3",textMuted:"#D4A5BD",isLight:!1}},matrix:{light:{bg:"#f0fff0",bgPanel:"#ffffff",bgAlt:matrixColors.greenTint,primary:matrixColors.greenBrand,secondary:matrixColors.greenText,accent:matrixColors.greenAccent,glow:mxBrightLight.glow,pop:mxBrightLight.pop,spark:mxBrightLight.spark,blaze:mxBrightLight.blaze,surge:mxBrightLight.surge,flame:mxBrightLight.flame,gold:mxBrightLight.gold,textLight:"#0A2E1A",textMuted:matrixColors.gray,isLight:!0},dark:{bg:matrixColors.black,bgPanel:"#0A1F0A",bgAlt:"#122812",primary:matrixColors.greenPhosphor,secondary:matrixColors.greenGlow,accent:matrixColors.greenGlow,glow:mxBrightDark.glow,pop:mxBrightDark.pop,spark:mxBrightDark.spark,blaze:mxBrightDark.blaze,surge:mxBrightDark.surge,flame:mxBrightDark.flame,gold:mxBrightDark.gold,textLight:"#C8E6C9",textMuted:"#66BB6A",isLight:!1}},earth:{light:{bg:"#F0F5FA",bgPanel:"#ffffff",bgAlt:earthColors.oceanTint,primary:earthColors.oceanBrand,secondary:earthColors.oceanText,accent:earthColors.oceanAccent,glow:eaBrightLight.glow,pop:eaBrightLight.pop,spark:eaBrightLight.spark,blaze:eaBrightLight.blaze,surge:eaBrightLight.surge,flame:eaBrightLight.flame,gold:eaBrightLight.gold,textLight:"#1A2332",textMuted:earthColors.gray,isLight:!0},dark:{bg:earthColors.black,bgPanel:"#0E1D30",bgAlt:"#132840",primary:earthColors.oceanAccent,secondary:earthColors.oceanBrand,accent:earthColors.oceanBright,glow:eaBrightDark.glow,pop:eaBrightDark.pop,spark:eaBrightDark.spark,blaze:eaBrightDark.blaze,surge:eaBrightDark.surge,flame:eaBrightDark.flame,gold:eaBrightDark.gold,textLight:"#D4E4DC",textMuted:"#8A9BA8",isLight:!1}},sand:{light:{bg:"#FBF7EF",bgPanel:"#ffffff",bgAlt:sandColors.sandTint,primary:sandColors.sandBrand,secondary:sandColors.sandText,accent:sandColors.sandAccent,glow:saBrightLight.glow,pop:saBrightLight.pop,spark:saBrightLight.spark,blaze:saBrightLight.blaze,surge:saBrightLight.surge,flame:saBrightLight.flame,gold:saBrightLight.gold,textLight:"#2B2118",textMuted:sandColors.gray,isLight:!0},dark:{bg:sandColors.black,bgPanel:"#2A2118",bgAlt:"#33281A",primary:sandColors.sandAccent,secondary:sandColors.sandBrand,accent:sandColors.sandBright,glow:saBrightDark.glow,pop:saBrightDark.pop,spark:saBrightDark.spark,blaze:saBrightDark.blaze,surge:saBrightDark.surge,flame:saBrightDark.flame,gold:saBrightDark.gold,textLight:"#EDE3D3",textMuted:"#B7A793",isLight:!1}},ivory:{light:{bg:"#FBF6EC",bgPanel:"#ffffff",bgAlt:ivoryColors.ivoryTint,primary:ivoryColors.ivoryBrand,secondary:ivoryColors.ivoryText,accent:ivoryColors.ivoryAccent,glow:ivBrightLight.glow,pop:ivBrightLight.pop,spark:ivBrightLight.spark,blaze:ivBrightLight.blaze,surge:ivBrightLight.surge,flame:ivBrightLight.flame,gold:ivBrightLight.gold,textLight:"#2C2318",textMuted:ivoryColors.gray,isLight:!0},dark:{bg:ivoryColors.black,bgPanel:"#2A2219",bgAlt:"#33291B",primary:ivoryColors.ivoryAccent,secondary:ivoryColors.ivoryBrand,accent:ivoryColors.ivoryBright,glow:ivBrightDark.glow,pop:ivBrightDark.pop,spark:ivBrightDark.spark,blaze:ivBrightDark.blaze,surge:ivBrightDark.surge,flame:ivBrightDark.flame,gold:ivBrightDark.gold,textLight:"#EFE6D6",textMuted:"#BBAC97",isLight:!1}},sun:{light:{bg:"#FFF9EC",bgPanel:"#ffffff",bgAlt:sunColors.sunTint,primary:sunColors.sunBrand,secondary:sunColors.sunText,accent:sunColors.sunAccent,glow:suBrightLight.glow,pop:suBrightLight.pop,spark:suBrightLight.spark,blaze:suBrightLight.blaze,surge:suBrightLight.surge,flame:suBrightLight.flame,gold:suBrightLight.gold,textLight:"#2A2210",textMuted:sunColors.gray,isLight:!0},dark:{bg:sunColors.black,bgPanel:"#2A2109",bgAlt:"#33290C",primary:sunColors.sunAccent,secondary:sunColors.sunBrand,accent:sunColors.sunBright,glow:suBrightDark.glow,pop:suBrightDark.pop,spark:suBrightDark.spark,blaze:suBrightDark.blaze,surge:suBrightDark.surge,flame:suBrightDark.flame,gold:suBrightDark.gold,textLight:"#F3E9CF",textMuted:"#BEAC82",isLight:!1}},loop:{light:{bg:loopColors.white,bgPanel:"#ffffff",bgAlt:loopColors.subtle,primary:loopColors.loopBrand,secondary:loopColors.loopText,accent:loopColors.loopAccent,glow:loBrightLight.glow,pop:loBrightLight.pop,spark:loBrightLight.spark,blaze:loBrightLight.blaze,surge:loBrightLight.surge,flame:loBrightLight.flame,gold:loBrightLight.gold,textLight:loopColors.ink,textMuted:loopColors.gray,isLight:!0},dark:{bg:loopColors.black,bgPanel:"#19191B",bgAlt:loopColors.subtleDark,primary:loopColors.loopBrand,secondary:loopColors.loopBright,accent:loopColors.loopAccent,glow:loBrightDark.glow,pop:loBrightDark.pop,spark:loBrightDark.spark,blaze:loBrightDark.blaze,surge:loBrightDark.surge,flame:loBrightDark.flame,gold:loBrightDark.gold,textLight:loopColors.inkDark,textMuted:loopColors.grayDark,isLight:!1}}};function getColorPalette(Au="datalayer",lo="auto"){const $u=lo==="auto"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":lo;return palettes[Au]?.[$u]??palettes.datalayer.dark}function useColorPalette(){const{colorMode:Au,theme:lo}=useThemeStore();return getColorPalette(lo,Au)}const SHEET_SHADOW="0 1px 2px rgba(0,0,0,0.06), 0 24px 48px -28px rgba(0,0,0,0.35)";function Sheet(Au){return jsxRuntimeExports.jsx(Box,{bg:"canvas.default",border:"1px solid",borderColor:"border.default",borderRadius:"card",boxShadow:SHEET_SHADOW,...Au})}const sizeMap$2={small:16,medium:32,large:64};function _DlIconInverseColormode$2({mode:Au,children:lo}){const $u=reactExports.useRef(null),[Ru,Iu]=reactExports.useState({mode:typeof Au=="string"?Au:null,lightTheme:null,darkTheme:null});return reactExports.useLayoutEffect(()=>{if(typeof document>"u")return;let Pu=null,Ou=null,Mu=null,Du=$u.current&&$u.current.parentElement;for(;Du&&(!Pu||!Ou||!Mu);)Du.getAttribute&&(Pu=Pu||Du.getAttribute("data-color-mode"),Ou=Ou||Du.getAttribute("data-light-theme"),Mu=Mu||Du.getAttribute("data-dark-theme")),Du=Du.parentElement;(!Pu||Pu==="auto")&&(Pu=typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),Iu({mode:typeof Au=="string"?Au:Pu==="dark"?"light":"dark",lightTheme:Ou,darkTheme:Mu})},[Au]),reactExports.createElement("span",{ref:$u,"data-color-mode":Ru.mode||"light","data-light-theme":Ru.lightTheme||void 0,"data-dark-theme":Ru.darkTheme||void 0,style:{display:"inline-flex",lineHeight:0,color:"var(--fgColor-default, var(--color-fg-default, currentColor))"}},lo)}function AiAgentIcon({title:Au,titleId:lo,size:$u,colored:Ru,themed:Iu,colormode:Pu,...Ou},Mu){const Du=reactExports.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",fill:Iu?"var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor))":"var(--datalayer-icon-color, currentColor)",width:$u?typeof $u=="string"?sizeMap$2[$u]:$u:"16px","aria-hidden":"true",ref:Mu,"aria-labelledby":lo},Ou,{"data-datalayer-icon":"",style:Ou&&Ou.color!=null?Object.assign({},Ou.style,{"--datalayer-icon-color":Ou.color,color:Ou.color}):Ou&&Ou.style}),reactExports.createElement("style",null,'[data-color-mode="light"]{--datalayer-icon-color-scheme:light}[data-color-mode="dark"]{--datalayer-icon-color-scheme:dark}svg[data-datalayer-icon]{color-scheme:var(--datalayer-icon-color-scheme, light dark)}'),Au?reactExports.createElement("title",{id:lo},Au):null,reactExports.createElement("path",{d:"M5.75 7.5a.75.75 0 01.75.75v1.5a.75.75 0 01-1.5 0v-1.5a.75.75 0 01.75-.75zm5.25.75a.75.75 0 00-1.5 0v1.5a.75.75 0 001.5 0v-1.5z"}),reactExports.createElement("path",{d:"M6.25 0h2A.75.75 0 019 .75V3.5h3.25a2.25 2.25 0 012.25 2.25V8h.75a.75.75 0 010 1.5h-.75v2.75a2.25 2.25 0 01-2.25 2.25h-8.5a2.25 2.25 0 01-2.25-2.25V9.5H.75a.75.75 0 010-1.5h.75V5.75A2.25 2.25 0 013.75 3.5H7.5v-2H6.25a.75.75 0 010-1.5zM3 5.75v6.5c0 .414.336.75.75.75h8.5a.75.75 0 00.75-.75v-6.5a.75.75 0 00-.75-.75h-8.5a.75.75 0 00-.75.75z"}));return Pu?reactExports.createElement(_DlIconInverseColormode$2,{mode:typeof Pu=="string"?Pu:void 0},Du):Du}const ForwardRef$2=reactExports.forwardRef(AiAgentIcon),sizeMap$1={small:16,medium:32,large:64};function _DlIconInverseColormode$1({mode:Au,children:lo}){const $u=reactExports.useRef(null),[Ru,Iu]=reactExports.useState({mode:typeof Au=="string"?Au:null,lightTheme:null,darkTheme:null});return reactExports.useLayoutEffect(()=>{if(typeof document>"u")return;let Pu=null,Ou=null,Mu=null,Du=$u.current&&$u.current.parentElement;for(;Du&&(!Pu||!Ou||!Mu);)Du.getAttribute&&(Pu=Pu||Du.getAttribute("data-color-mode"),Ou=Ou||Du.getAttribute("data-light-theme"),Mu=Mu||Du.getAttribute("data-dark-theme")),Du=Du.parentElement;(!Pu||Pu==="auto")&&(Pu=typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),Iu({mode:typeof Au=="string"?Au:Pu==="dark"?"light":"dark",lightTheme:Ou,darkTheme:Mu})},[Au]),reactExports.createElement("span",{ref:$u,"data-color-mode":Ru.mode||"light","data-light-theme":Ru.lightTheme||void 0,"data-dark-theme":Ru.darkTheme||void 0,style:{display:"inline-flex",lineHeight:0,color:"var(--fgColor-default, var(--color-fg-default, currentColor))"}},lo)}function MicrophoneIcon({title:Au,titleId:lo,size:$u,colored:Ru,themed:Iu,colormode:Pu,...Ou},Mu){const Du=reactExports.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 72 72",fill:Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 72%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 62%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 72%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 62%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 72%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",width:$u?typeof $u=="string"?sizeMap$1[$u]:$u:"16px","aria-hidden":"true",ref:Mu,"aria-labelledby":lo},Ou,{"data-datalayer-icon":"",style:Ou&&Ou.color!=null?Object.assign({},Ou.style,{"--datalayer-icon-color":Ou.color,color:Ou.color}):Ou&&Ou.style}),reactExports.createElement("style",null,'[data-color-mode="light"]{--datalayer-icon-color-scheme:light}[data-color-mode="dark"]{--datalayer-icon-color-scheme:dark}svg[data-datalayer-icon]{color-scheme:var(--datalayer-icon-color-scheme, light dark)}'),Au?reactExports.createElement("title",{id:lo},Au):null,reactExports.createElement("path",{fill:Ru?"#3F3F3F":Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 41%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 93%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 41%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 93%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 41%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",d:"M39.4 29.52c-2.636-2.216-2.553-3.52-2.55-3.523-.109-.127-1.758-1.676-1.777-2.156l-.009-.082-2.556 3.283c.324-.446-6.322 10.406-6.322 10.406L14.393 53.686l3.373 3.372S42.18 35.781 41.828 36.161l3.403-3.356c-.107.004-3.193-1.068-5.83-3.284z"}),reactExports.createElement("path",{fill:Ru?"#D0CFCE":Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 71%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 63%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 71%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 63%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 71%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",d:"M54.62 30.18a.998.998 0 01-1.411.093l-16.62-14.58a1 1 0 01-.099-1.4c-.003.003-.007.004-.01.008l-.654.786a1 1 0 00.11 1.391L52.554 31.06a1 1 0 001.427-.113l.655-.787c.04-.047.055-.105.084-.157-.033.06-.054.123-.1.177z"}),reactExports.createElement("path",{fill:Ru?"#3F3F3F":Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 41%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 93%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 41%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 93%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 41%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",d:"M55.258 25.541c-1.162 3.4-5.283 5.562-5.283 5.562-1.926 1.097-4.032 1.62-6.038 1.52 0 0-.347-.081-.913-.272-1.828-.634-5.85-2.485-7.25-6.88-.377-2.002-.159-4.185.646-6.277 1.023-4.264 4.995-6.256 4.995-6.256 1.41-.956 2.94-1.59 4.479-1.871 2.82-.533 5.66.08 7.775 1.972 3.327 2.947 3.844 8.086 1.59 12.502z"}),reactExports.createElement("path",{fill:Ru?"#9B9B9A":Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 55%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 79%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 55%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 79%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 55%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",d:"M51.475 25.541c-1.172 3.4-5.283 5.562-5.283 5.562a12.08 12.08 0 01-3.168 1.247c-1.828-.633-5.85-2.484-7.25-6.88-.377-2.001-.159-4.184.646-6.276 1.022-4.264 4.995-6.256 4.995-6.256 1.41-.956 2.94-1.59 4.479-1.871 1.46.292 2.83.946 3.992 1.972 3.317 2.947 3.833 8.086 1.589 12.502z"}),reactExports.createElement("path",{d:"M30.75 38.941l4.02-4.619m14.744-3.892c-1.804 1.014-3.774 1.495-5.65 1.404m-2.36-18.184c3.737-2.497 8.405-2.591 11.465.093 3.108 2.727 3.59 7.471 1.489 11.545m-18.223-.065c-.354-1.844-.152-3.862.602-5.789m-3.52 8.196L14.393 53.686l3.373 3.373 23.34-21.572M15.497 56.001l-3.046 3.074m41.417-29.554L37.249 14.94",fill:"none",stroke:Ru?"#000":Ou.color!=null?"color-mix(in srgb, var(--datalayer-icon-color, currentColor) 38%, black)":Iu?"light-dark(color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 96%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor)) 38%, var(--bgColor-default, var(--color-canvas-default, Canvas))))":"light-dark(color-mix(in srgb, var(--datalayer-icon-color, currentColor) 96%, var(--bgColor-default, var(--color-canvas-default, Canvas))), color-mix(in srgb, var(--datalayer-icon-color, currentColor) 38%, var(--bgColor-default, var(--color-canvas-default, Canvas))))",strokeLinecap:"round",strokeLinejoin:"round",strokeMiterlimit:10,strokeWidth:2}));return Pu?reactExports.createElement(_DlIconInverseColormode$1,{mode:typeof Pu=="string"?Pu:void 0},Du):Du}const ForwardRef$1=reactExports.forwardRef(MicrophoneIcon),sizeMap={small:16,medium:32,large:64};function _DlIconInverseColormode({mode:Au,children:lo}){const $u=reactExports.useRef(null),[Ru,Iu]=reactExports.useState({mode:typeof Au=="string"?Au:null,lightTheme:null,darkTheme:null});return reactExports.useLayoutEffect(()=>{if(typeof document>"u")return;let Pu=null,Ou=null,Mu=null,Du=$u.current&&$u.current.parentElement;for(;Du&&(!Pu||!Ou||!Mu);)Du.getAttribute&&(Pu=Pu||Du.getAttribute("data-color-mode"),Ou=Ou||Du.getAttribute("data-light-theme"),Mu=Mu||Du.getAttribute("data-dark-theme")),Du=Du.parentElement;(!Pu||Pu==="auto")&&(Pu=typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),Iu({mode:typeof Au=="string"?Au:Pu==="dark"?"light":"dark",lightTheme:Ou,darkTheme:Mu})},[Au]),reactExports.createElement("span",{ref:$u,"data-color-mode":Ru.mode||"light","data-light-theme":Ru.lightTheme||void 0,"data-dark-theme":Ru.darkTheme||void 0,style:{display:"inline-flex",lineHeight:0,color:"var(--fgColor-default, var(--color-fg-default, currentColor))"}},lo)}function PlusCircleIcon({title:Au,titleId:lo,size:$u,colored:Ru,themed:Iu,colormode:Pu,...Ou},Mu){const Du=reactExports.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fillRule:"evenodd",clipRule:"evenodd",width:$u?typeof $u=="string"?sizeMap[$u]:$u:"16px",viewBox:"0 0 24 24",fill:Iu?"var(--datalayer-icon-color, var(--datalayer-icon-fg, currentColor))":"var(--datalayer-icon-color, currentColor)","aria-hidden":"true",ref:Mu,"aria-labelledby":lo},Ou,{"data-datalayer-icon":"",style:Ou&&Ou.color!=null?Object.assign({},Ou.style,{"--datalayer-icon-color":Ou.color,color:Ou.color}):Ou&&Ou.style}),reactExports.createElement("style",null,'[data-color-mode="light"]{--datalayer-icon-color-scheme:light}[data-color-mode="dark"]{--datalayer-icon-color-scheme:dark}svg[data-datalayer-icon]{color-scheme:var(--datalayer-icon-color-scheme, light dark)}'),Au?reactExports.createElement("title",{id:lo},Au):null,reactExports.createElement("path",{d:"M11.5 0C17.847 0 23 5.153 23 11.5S17.847 23 11.5 23 0 17.847 0 11.5 5.153 0 11.5 0zm0 1C17.295 1 22 5.705 22 11.5S17.295 22 11.5 22 1 17.295 1 11.5 5.705 1 11.5 1zm.5 10h6v1h-6v6h-1v-6H5v-1h6V5h1v6z"}));return Pu?reactExports.createElement(_DlIconInverseColormode,{mode:typeof Pu=="string"?Pu:void 0},Du):Du}const ForwardRef=reactExports.forwardRef(PlusCircleIcon),__vite_import_meta_env__$2={},createStoreImpl$1=Au=>{let lo;const $u=new Set,Ru=(Bu,ju)=>{const Fu=typeof Bu=="function"?Bu(lo):Bu;if(!Object.is(Fu,lo)){const zu=lo;lo=ju??(typeof Fu!="object"||Fu===null)?Fu:Object.assign({},lo,Fu),$u.forEach(Uu=>Uu(lo,zu))}},Iu=()=>lo,Du={setState:Ru,getState:Iu,getInitialState:()=>Lu,subscribe:Bu=>($u.add(Bu),()=>$u.delete(Bu)),destroy:()=>{(__vite_import_meta_env__$2?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),$u.clear()}},Lu=lo=Au(Ru,Iu,Du);return Du},createStore$1=Au=>Au?createStoreImpl$1(Au):createStoreImpl$1;var withSelector={exports:{}},withSelector_production={},shim={exports:{}},useSyncExternalStoreShim_production={};var hasRequiredUseSyncExternalStoreShim_production;function requireUseSyncExternalStoreShim_production(){if(hasRequiredUseSyncExternalStoreShim_production)return useSyncExternalStoreShim_production;hasRequiredUseSyncExternalStoreShim_production=1;var Au=requireReact();function lo(ju,Fu){return ju===Fu&&(ju!==0||1/ju===1/Fu)||ju!==ju&&Fu!==Fu}var $u=typeof Object.is=="function"?Object.is:lo,Ru=Au.useState,Iu=Au.useEffect,Pu=Au.useLayoutEffect,Ou=Au.useDebugValue;function Mu(ju,Fu){var zu=Fu(),Uu=Ru({inst:{value:zu,getSnapshot:Fu}}),Hu=Uu[0].inst,Vu=Uu[1];return Pu(function(){Hu.value=zu,Hu.getSnapshot=Fu,Du(Hu)&&Vu({inst:Hu})},[ju,zu,Fu]),Iu(function(){return Du(Hu)&&Vu({inst:Hu}),ju(function(){Du(Hu)&&Vu({inst:Hu})})},[ju]),Ou(zu),zu}function Du(ju){var Fu=ju.getSnapshot;ju=ju.value;try{var zu=Fu();return!$u(ju,zu)}catch{return!0}}function Lu(ju,Fu){return Fu()}var Bu=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Lu:Mu;return useSyncExternalStoreShim_production.useSyncExternalStore=Au.useSyncExternalStore!==void 0?Au.useSyncExternalStore:Bu,useSyncExternalStoreShim_production}var hasRequiredShim;function requireShim(){return hasRequiredShim||(hasRequiredShim=1,shim.exports=requireUseSyncExternalStoreShim_production()),shim.exports}var hasRequiredWithSelector_production;function requireWithSelector_production(){if(hasRequiredWithSelector_production)return withSelector_production;hasRequiredWithSelector_production=1;var Au=requireReact(),lo=requireShim();function $u(Lu,Bu){return Lu===Bu&&(Lu!==0||1/Lu===1/Bu)||Lu!==Lu&&Bu!==Bu}var Ru=typeof Object.is=="function"?Object.is:$u,Iu=lo.useSyncExternalStore,Pu=Au.useRef,Ou=Au.useEffect,Mu=Au.useMemo,Du=Au.useDebugValue;return withSelector_production.useSyncExternalStoreWithSelector=function(Lu,Bu,ju,Fu,zu){var Uu=Pu(null);if(Uu.current===null){var Hu={hasValue:!1,value:null};Uu.current=Hu}else Hu=Uu.current;Uu=Mu(function(){function Gu(Xu){if(!Wu){if(Wu=!0,Ku=Xu,Xu=Fu(Xu),zu!==void 0&&Hu.hasValue){var ed=Hu.value;if(zu(ed,Xu))return Ju=ed}return Ju=Xu}if(ed=Ju,Ru(Ku,Xu))return ed;var td=Fu(Xu);return zu!==void 0&&zu(ed,td)?(Ku=Xu,ed):(Ku=Xu,Ju=td)}var Wu=!1,Ku,Ju,Yu=ju===void 0?null:ju;return[function(){return Gu(Bu())},Yu===null?void 0:function(){return Gu(Yu())}]},[Bu,ju,Fu,zu]);var Vu=Iu(Lu,Uu[0],Uu[1]);return Ou(function(){Hu.hasValue=!0,Hu.value=Vu},[Vu]),Du(Vu),Vu},withSelector_production}var hasRequiredWithSelector;function requireWithSelector(){return hasRequiredWithSelector||(hasRequiredWithSelector=1,withSelector.exports=requireWithSelector_production()),withSelector.exports}var withSelectorExports=requireWithSelector();const useSyncExternalStoreExports=getDefaultExportFromCjs(withSelectorExports),__vite_import_meta_env__$1={},{useDebugValue}=vM,{useSyncExternalStoreWithSelector}=useSyncExternalStoreExports;let didWarnAboutEqualityFn=!1;const identity$1=Au=>Au;function useStore$1(Au,lo=identity$1,$u){(__vite_import_meta_env__$1?"production":void 0)!=="production"&&$u&&!didWarnAboutEqualityFn&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),didWarnAboutEqualityFn=!0);const Ru=useSyncExternalStoreWithSelector(Au.subscribe,Au.getState,Au.getServerState||Au.getInitialState,lo,$u);return useDebugValue(Ru),Ru}const createImpl$1=Au=>{(__vite_import_meta_env__$1?"production":void 0)!=="production"&&typeof Au!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const lo=typeof Au=="function"?createStore$1(Au):Au,$u=(Ru,Iu)=>useStore$1(lo,Ru,Iu);return Object.assign($u,lo),$u},create$g=Au=>Au?createImpl$1(Au):createImpl$1,CONTROL_PLANE_URL="https://prod1.datalayer.run",RUNTIMES_PLANE_URL="https://r1.datalayer.run",MCP_SERVER_URL="https://mcp.datalayer.run/mcp",DEFAULT_PLANE_URLS={iamUrl:CONTROL_PLANE_URL,managerUrl:CONTROL_PLANE_URL,libraryUrl:CONTROL_PLANE_URL,spacerUrl:CONTROL_PLANE_URL,otelUrl:CONTROL_PLANE_URL,growthUrl:CONTROL_PLANE_URL,inboundsUrl:CONTROL_PLANE_URL,successUrl:CONTROL_PLANE_URL,supportUrl:CONTROL_PLANE_URL,contentsUrl:RUNTIMES_PLANE_URL,runtimesUrl:RUNTIMES_PLANE_URL,schedulerUrl:RUNTIMES_PLANE_URL,aiAgentsUrl:RUNTIMES_PLANE_URL,aiInferenceUrl:RUNTIMES_PLANE_URL,datalayerMcpServerUrl:MCP_SERVER_URL};class Logger{scope;isDevelopment;constructor(lo){this.scope=lo,this.isDevelopment=!1}log(lo,$u,...Ru){if(!this.isDevelopment&&lo==="debug")return;const Pu=`[${new Date().toISOString()}] [${this.scope}] [${lo.toUpperCase()}]`;switch(lo){case"debug":console.debug(Pu,$u,...Ru);break;case"info":console.info(Pu,$u,...Ru);break;case"warn":console.warn(Pu,$u,...Ru);break;case"error":console.error(Pu,$u,...Ru);break}}debug(lo,...$u){this.log("debug",lo,...$u)}info(lo,...$u){this.log("info",lo,...$u)}warn(lo,...$u){this.log("warn",lo,...$u)}error(lo,...$u){this.log("error",lo,...$u)}}function createLogger(Au){return new Logger(Au)}const configLogger=createLogger("config");let loadConfigurationFromServer=!0,initialConfiguration={token:"",credits:0,cpuEnvironment:'ai-agents-env"',gpuEnvironment:"ai-env",useMock:!1,whiteLabel:!0,loadConfigurationFromServer:!0,jupyterServerless:!1,...DEFAULT_PLANE_URLS,launcher:{category:"Datalayer",name:"Datalayer",icon:null,rank:1},brand:{name:"Datalayer",about:"AI Agents for Data Analysis",logoUrl:"https://assets.datalayer.tech/datalayer-25.svg",logoSquareUrl:"https://assets.datalayer.tech/datalayer-square.png",copyright:"© 2025 Datalayer, Inc",docsUrl:"https://datalayer.ai/docs",supportUrl:"https://datalayer.ai/support",termsUrl:"https://datalayer.ai/terms",pricingUrl:"https://datalayer.ai/pricing",privacyUrl:"https://datalayer.ai/privacy"}};const pageConfiguration={};try{if(typeof document<"u"){const Au=document.getElementById("datalayer-config-data");if(Au?.innerText){const lo=JSON.parse(Au?.innerText||"{}");Object.assign(pageConfiguration,lo),lo.loadConfigurationFromServer!=null&&(loadConfigurationFromServer=lo.loadConfigurationFromServer),initialConfiguration={...initialConfiguration,...lo},configLogger.info("Datalayer configuration loaded from HTML page",initialConfiguration),window.document.title=`${initialConfiguration.brand.name} ☰ ${initialConfiguration.brand.about}`}}}catch(Au){configLogger.debug("No valid configuration found in the webpage.",Au)}const coreStore=createStore$1((Au,lo)=>({tab:0,getIntTab:()=>Math.floor(lo().tab),setTab:$u=>Au(Ru=>({tab:$u})),configuration:initialConfiguration,setConfiguration:$u=>{configLogger.debug("Setting Datalayer configuration",$u),Au(Ru=>({configuration:{...Ru.configuration,...$u}}))},version:"",setVersion:$u=>{$u&&!lo().version&&Au(Ru=>({version:$u}))},loadConfigurationFromServer,setLoadConfigurationFromServer:$u=>{Au(Ru=>({loadConfigurationFromServer:$u}))}}));function useCoreStore(Au){return useStore$1(coreStore,Au)}const getOtelConsumeUrl=()=>coreStore.getState().configuration.otelUrl,BACKEND_TOOL_ACTIONS={"create-plan":["read"],"current-time":["read"],decide:["read"],"display-recipe":["read"],"example-create-plan":["read"],"example-current-time":["read"],"example-display-recipe":["read"],"example-generate-haiku":["read"],"example-generate-task-steps":["read"],"example-get-weather":["read"],"example-render-a2ui-surface":["read"],"example-update-plan-step":["read"],"generate-haiku":["read"],"generate-task-steps":["read"],"get-weather":["read"],"runtime-echo":["read"],"runtime-send-mail":["send"],"runtime-sensitive-echo":["read"],"update-plan-step":["read"]},SERVER_ACTIONS={alphavantage:{default:[],tools:{},conditions:{},signs:{}},chart:{checked:"2026-10-02",default:[],tools:{generate_area_chart:["read"],generate_bar_chart:["read"],generate_boxplot_chart:["read"],generate_column_chart:["read"],generate_district_map:["read"],generate_dual_axes_chart:["read"],generate_fishbone_diagram:["read"],generate_flow_diagram:["read"],generate_funnel_chart:["read"],generate_histogram_chart:["read"],generate_line_chart:["read"],generate_liquid_chart:["read"],generate_mind_map:["read"],generate_network_graph:["read"],generate_organization_chart:["read"],generate_path_map:["read"],generate_pie_chart:["read"],generate_pin_map:["read"],generate_radar_chart:["read"],generate_sankey_chart:["read"],generate_scatter_chart:["read"],generate_treemap_chart:["read"],generate_venn_chart:["read"],generate_violin_chart:["read"],generate_waterfall_chart:["read"],generate_word_cloud_chart:["read"],generate_spreadsheet:["read"]},conditions:{},signs:{}},datalayer:{checked:"2026-10-05",default:[],tools:{read_notebook:["read"],read_cell:["read"],download_notebook:["read"],list_notebooks:["read"],list_spaces:["read"],list_space_notebooks:["read"],find_notebook:["read"],list_notebook_versions:["read"],list_kernels:["read"],list_files:["read"],list_sandboxes:["read"],list_toolsets:["read"],search_library:["read"],get_library_artifact:["read"],read_library_artifact:["read"],search_earth_datasets:["read"],search_earth_datagranules:["read"],download_earth_data_granules:["read"],odoo_get_context:["read"],odoo_get_account:["read"],odoo_get_settings:["read"],odoo_list_companies:["read"],odoo_set_company:["write"],odoo_list_models:["read"],odoo_get_fields:["read"],odoo_search_records:["read"],odoo_read_records:["read"],odoo_group_records:["read"],odoo_create_record:["write"],odoo_update_records:["write"],odoo_delete_records:["delete"],odoo_accounting_list_invoices:["read"],odoo_accounting_get_invoice:["read"],odoo_accounting_list_journal_entries:["read"],odoo_accounting_list_open_balances:["read"],odoo_accounting_list_accounts:["read"],odoo_accounting_list_journals:["read"],odoo_accounting_get_journal_entry:["read"],odoo_accounting_trial_balance:["read"],odoo_accounting_general_ledger:["read"],odoo_winauditor_preview_balance:["read"],odoo_winauditor_preview_general_journal:["read"],odoo_winauditor_preview_general_ledger:["read"],odoo_accounting_create_draft_invoice:["write"],odoo_accounting_post_invoice:["write"],odoo_accounting_create_draft_journal_entry:["write"],odoo_accounting_post_journal_entry:["write"],odoo_winauditor_import_balance:["write"],odoo_winauditor_import_general_journal:["write"],odoo_winauditor_import_general_ledger:["write"],odoo_winauditor_preview_import_file:["read"],odoo_winauditor_migration_status:["read"],odoo_winauditor_import_partners:["write"],odoo_winauditor_import_chart_of_accounts:["write"],odoo_winauditor_ensure_journals:["write"],odoo_winauditor_import_journal_items:["write"],odoo_winauditor_post_migration_entries:["write"],odoo_winauditor_reconcile_journal_items:["write"],odoo_winauditor_import_assets:["write"],odoo_winauditor_validate_assets:["write"],odoo_winauditor_rollback_migration:["delete"],odoo_winauditor_attach_document:["write"],odoo_winauditor_list_attachments:["read"],odoo_winauditor_validate_migration:["read"],odoo_accounting_list_partners:["read"],odoo_accounting_partner_ledger:["read"],odoo_accounting_aged_balance:["read"],odoo_accounting_list_taxes:["read"],odoo_accounting_list_assets:["read"],odoo_accounting_get_asset:["read"],odoo_accounting_reconcile_lines:["write"],odoo_accounting_unreconcile_lines:["write"],odoo_accounting_bank_status:["read"],odoo_accounting_list_bank_lines:["read"],odoo_accounting_get_bank_line:["read"],odoo_accounting_suggest_bank_matches:["read"],odoo_accounting_suggest_reconciliations:["read"],odoo_accounting_explain_account_balance:["read"],odoo_accounting_list_bank_feeds:["read"],odoo_accounting_list_currency_rates:["read"],odoo_accounting_get_lock_dates:["read"],odoo_accounting_book_bank_line:["write"],odoo_accounting_match_bank_line:["write"],odoo_accounting_reset_bank_line:["write"],odoo_accounting_remove_duplicate_bank_lines:["delete"],odoo_accounting_link_bank_feed:["write"],odoo_accounting_create_vendor_bill:["write"],odoo_accounting_create_customer_invoice:["write"],odoo_accounting_set_currency_rates:["write"],odoo_accounting_set_lock_date:["write"],odoo_accounting_create_matching_model:["write"],odoo_accounting_get_tax_settings:["read"],odoo_accounting_list_tax_returns:["read"],odoo_accounting_get_tax_return:["read"],odoo_accounting_tax_grids:["read"],odoo_accounting_list_tax_grid_lines:["read"],odoo_accounting_check_tax_period:["read"],odoo_accounting_list_untagged_tax_lines:["read"],odoo_accounting_set_tax_periodicity:["write"],odoo_accounting_set_tax_grids:["write"],read_benchmark:["read"],read_benchmark_task:["read"],read_benchmark_task_trajectory:["read"],list_benchmark_task_files:["read"],list_content_sources:["read"],describe_content_source:["read"],list_content_attachments:["read"],list_dataset_revisions:["read"],query_status:["read"],list_secrets:["read"],use_notebook:["read"],unuse_notebook:["read"],connect_to_jupyter:["read"],insert_cell:["write"],delete_cell:["delete"],move_cell:["write"],edit_cell_source:["write"],snapshot_notebook:["write"],restore_notebook:["write"],overwrite_cell_source:["write"],clear_cell_output:["write"],execute_cell:["write"],execute_code:["write"],restart_notebook:["write"],insert_execute_code_cell:["write"],launch_sandbox:["buy"],use_sandbox:["write"],terminate_sandbox:["delete"],snapshot_sandbox:["write","buy"],share_sandbox:["publish"],unshare_sandbox:["write"],marimo_run_cell:["write"],marimo_run_code:["write"],marimo_remove_cell:["delete"],marimo_plan:["read"],marimo_graph:["read"],enable_toolset:["write"],disable_toolset:["write"],attach_content:["write"],detach_content:["write"],query_source:["read"],cancel_query:["write"],save_query_as_revision:["write"],mount_local_folder:["read"]},conditions:{},signs:{}},earthdata:{checked:"2026-10-07",default:[],tools:{search_earth_datasets:["read"],search_earth_datagranules:["read"],download_earth_data_granules:["write"]},conditions:{},signs:{}},eurus:{default:[],tools:{},conditions:{},signs:{}},filesystem:{checked:"2026-10-02",default:[],tools:{read_file:["read"],read_text_file:["read"],read_media_file:["read"],read_multiple_files:["read"],write_file:["write"],edit_file:["write"],create_directory:["write"],list_directory:["read"],list_directory_with_sizes:["read"],directory_tree:["read"],move_file:["write","delete"],search_files:["read"],get_file_info:["read"],list_allowed_directories:["read"]},conditions:{},signs:{}},github:{default:[],tools:{},conditions:{},signs:{}},"google-workspace":{checked:"2026-10-02",default:[],tools:{start_google_auth:["write"],search_gmail_messages:["read"],get_gmail_message_content:["read"],get_gmail_messages_content_batch:["read"],get_gmail_attachment_content:["read","write"],send_gmail_message:["send"],draft_gmail_message:["write"],get_gmail_thread_content:["read"],get_gmail_threads_content_batch:["read"],list_gmail_labels:["read"],manage_gmail_label:["write"],list_gmail_filters:["read"],manage_gmail_filter:["write","send"],modify_gmail_message_labels:["write"],batch_modify_gmail_message_labels:["write"],search_drive_files:["read"],get_drive_file_content:["read"],get_drive_file_download_url:["read"],list_drive_items:["read"],create_drive_folder:["write"],create_drive_file:["write"],import_to_google_doc:["write"],import_to_google_slides:["write"],import_to_google_sheets:["write"],get_drive_file_permissions:["read"],check_drive_file_public_access:["read"],update_drive_file:["write"],get_drive_shareable_link:["read"],manage_drive_access:["publish","send","delete"],copy_drive_file:["write"],set_drive_file_permissions:["publish","write"],list_calendars:["read"],get_events:["read"],manage_event:["write","send"],manage_out_of_office:["write","send"],manage_focus_time:["write","send"],query_freebusy:["read"],create_calendar:["write"],search_docs:["read"],get_doc_content:["read"],list_docs_in_folder:["read"],create_doc:["write"],modify_doc_text:["write"],find_and_replace_doc:["write"],insert_doc_elements:["write"],insert_doc_image:["write"],update_doc_headers_footers:["write"],batch_update_doc:["write","delete"],inspect_doc_structure:["read"],debug_docs_runtime_info:["read"],create_table_with_data:["write"],debug_table_structure:["read"],export_doc_to_pdf:["write"],update_paragraph_style:["write"],get_doc_as_markdown:["read"],manage_doc_tab:["write"],list_document_comments:["read"],manage_document_comment:["write","send"],list_spreadsheets:["read"],get_spreadsheet_info:["read"],read_sheet_values:["read"],modify_sheet_values:["write"],format_sheet_range:["write"],manage_conditional_formatting:["write"],create_spreadsheet:["write"],create_sheet:["write"],list_sheet_tables:["read"],append_table_rows:["write"],manage_sheet_tab:["write"],resize_sheet_dimensions:["write","delete"],move_sheet_rows:["write","delete"],manage_named_range:["write"],list_spreadsheet_comments:["read"],manage_spreadsheet_comment:["write","send"],list_spaces:["read"],get_messages:["read"],send_message:["send","write"],search_messages:["read"],create_reaction:["send"],download_chat_attachment:["read","write"],create_form:["write"],get_form:["read"],set_publish_settings:["publish"],get_form_response:["read"],list_form_responses:["read"],batch_update_form:["write","delete"],create_presentation:["write"],get_presentation:["read"],batch_update_presentation:["write","delete"],get_page:["read"],get_page_thumbnail:["read"],list_presentation_comments:["read"],manage_presentation_comment:["write","send"],list_task_lists:["read"],get_task_list:["read"],manage_task_list:["write"],list_tasks:["read"],get_task:["read"],manage_task:["write"],list_contacts:["read"],get_contact:["read"],search_contacts:["read"],manage_contact:["write"],list_contact_groups:["read"],get_contact_group:["read"],manage_contacts_batch:["write"],manage_contact_group:["write"],search_custom:["read"],get_search_engine_info:["read"],get_script_project:["read"],manage_script_content:["write","delete"],run_script_function:["write","send","delete","publish"],manage_deployment:["publish"],list_script_deployments:["read"],manage_script_project:["write"],manage_script_version:["write"],get_script_version:["read"],get_script_activity:["read"],generate_trigger_code:["read"],manage_script_trigger:["write"]},conditions:{manage_gmail_label:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_gmail_filter:[{argument:"action",classes:["delete"],equals:["delete","update"]}],modify_gmail_message_labels:[{argument:"add_label_ids",classes:["delete"],includes:["TRASH","SPAM"]}],batch_modify_gmail_message_labels:[{argument:"add_label_ids",classes:["delete"],includes:["TRASH","SPAM"]}],update_drive_file:[{argument:"trashed",classes:["delete"],equals:[!0]}],manage_event:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_out_of_office:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_focus_time:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_doc_tab:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_conditional_formatting:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_sheet_tab:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_named_range:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_task_list:[{argument:"action",classes:["delete"],equals:["delete","clear_completed"]}],manage_task:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_contact:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_contacts_batch:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_contact_group:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_deployment:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_script_project:[{argument:"action",classes:["delete"],equals:["delete"]}],manage_script_trigger:[{argument:"action",classes:["delete"],equals:["delete"]}]},signs:{send_gmail_message:"body",draft_gmail_message:"body",send_message:"message_text"}},huggingface:{default:[],tools:{},conditions:{},signs:{}},kaggle:{default:[],tools:{},conditions:{},signs:{}},odoo:{default:[],tools:{},conditions:{},signs:{}},"odoo-accounting":{checked:"2026-10-05",default:[],tools:{odoo_accounting_list_invoices:["read"],odoo_accounting_get_invoice:["read"],odoo_accounting_list_journal_entries:["read"],odoo_accounting_list_open_balances:["read"],odoo_accounting_list_accounts:["read"],odoo_accounting_list_journals:["read"],odoo_accounting_get_journal_entry:["read"],odoo_accounting_trial_balance:["read"],odoo_accounting_general_ledger:["read"],odoo_accounting_create_draft_invoice:["write"],odoo_accounting_post_invoice:["write"],odoo_accounting_create_draft_journal_entry:["write"],odoo_accounting_post_journal_entry:["write"],odoo_accounting_list_partners:["read"],odoo_accounting_partner_ledger:["read"],odoo_accounting_aged_balance:["read"],odoo_accounting_list_taxes:["read"],odoo_accounting_list_assets:["read"],odoo_accounting_get_asset:["read"],odoo_accounting_reconcile_lines:["write"],odoo_accounting_unreconcile_lines:["write"],odoo_accounting_bank_status:["read"],odoo_accounting_list_bank_lines:["read"],odoo_accounting_get_bank_line:["read"],odoo_accounting_suggest_bank_matches:["read"],odoo_accounting_suggest_reconciliations:["read"],odoo_accounting_explain_account_balance:["read"],odoo_accounting_list_bank_feeds:["read"],odoo_accounting_list_currency_rates:["read"],odoo_accounting_get_lock_dates:["read"],odoo_accounting_book_bank_line:["write"],odoo_accounting_match_bank_line:["write"],odoo_accounting_reset_bank_line:["write"],odoo_accounting_remove_duplicate_bank_lines:["delete"],odoo_accounting_link_bank_feed:["write"],odoo_accounting_create_vendor_bill:["write"],odoo_accounting_create_customer_invoice:["write"],odoo_accounting_set_currency_rates:["write"],odoo_accounting_set_lock_date:["write"],odoo_accounting_create_matching_model:["write"],odoo_accounting_get_tax_settings:["read"],odoo_accounting_list_tax_returns:["read"],odoo_accounting_get_tax_return:["read"],odoo_accounting_tax_grids:["read"],odoo_accounting_list_tax_grid_lines:["read"],odoo_accounting_check_tax_period:["read"],odoo_accounting_list_untagged_tax_lines:["read"],odoo_accounting_set_tax_periodicity:["write"],odoo_accounting_set_tax_grids:["write"]},conditions:{},signs:{}},salesforce:{default:[],tools:{},conditions:{},signs:{}},slack:{checked:"2026-10-02",default:[],tools:{slack_list_channels:["read"],slack_post_message:["send"],slack_reply_to_thread:["send"],slack_add_reaction:["send"],slack_get_channel_history:["read"],slack_get_thread_replies:["read"],slack_get_users:["read"],slack_get_user_profile:["read"]},conditions:{},signs:{slack_post_message:"text",slack_reply_to_thread:"text"}},tavily:{checked:"2026-10-02",default:[],tools:{tavily_search:["read"],tavily_extract:["read"],tavily_crawl:["read"],tavily_map:["read"],tavily_research:["read"]},conditions:{},signs:{}}},BEHAVIOURS=["do_it","if_asked","ask_first","leave_to_me"],DEFAULT_BEHAVIOURS={read:"do_it",write:"ask_first",send:"ask_first",buy:"ask_first",delete:"ask_first",publish:"ask_first"},SERVER_TOOL=/^([A-Za-z0-9_-]+)(?::\d+(?:\.\d+)*)?\.([A-Za-z_][A-Za-z0-9_-]*)$/,own$a=(Au,lo)=>Object.prototype.hasOwnProperty.call(Au,lo)?Au[lo]:void 0,idOf=Au=>{const lo=Au.lastIndexOf(":");return lo>0&&Au.slice(lo+1).includes(".")?Au.slice(0,lo):Au};function splitRef(Au){const lo=SERVER_TOOL.exec(Au);return lo?[lo[1],lo[2]]:[void 0,idOf(Au)]}const isPattern=Au=>/[*?]/.test(Au);function matchesPattern(Au,lo){const $u=Array.from(lo,Ru=>Ru==="*"?"[\\s\\S]*":Ru==="?"?"[\\s\\S]":Ru.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("");return new RegExp(`^${$u}$`).test(Au)}const isComparable=Au=>typeof Au=="string"||typeof Au=="boolean"||typeof Au=="number"&&Number.isFinite(Au)&&(!Number.isInteger(Au)||Number.isSafeInteger(Au)),same=(Au,lo)=>typeof Au=="string"&&typeof lo=="string"?Au.trim().toLowerCase()===lo.trim().toLowerCase():isComparable(Au)&&isComparable(lo)&&Au===lo;function conditionHolds(Au,lo){if(!Object.prototype.hasOwnProperty.call(lo,Au.argument))return!1;const $u=lo[Au.argument];return Au.equals?.some(Ru=>same($u,Ru))?!0:Au.includes?.length?(Array.isArray($u)?$u:[$u]).some(Iu=>Au.includes.some(Pu=>same(Iu,Pu))):!1}function entryOf$1(Au,lo){const $u=own$a(SERVER_ACTIONS,Au);if(!$u)return[[],[]];const Ru=own$a($u.tools,lo);if(Ru)return[[...Ru],own$a($u.conditions,lo)??[]];for(const[Iu,Pu]of Object.entries($u.tools))if(isPattern(Iu)&&matchesPattern(lo,Iu))return[[...Pu],own$a($u.conditions,Iu)??[]];return[[...$u.default],[]]}const FORWARDING={"google-workspace.send_gmail_message":{message:"forward_message_id",mailbox:"user_google_email",recipients:["to","cc","bcc"]}};function addresses(Au){return(Array.isArray(Au)?Au:[Au]).filter($u=>typeof $u=="string").flatMap($u=>$u.split(",")).map($u=>{const Ru=/<([^>]*)>/.exec($u);return(Ru?Ru[1]:$u).trim().toLowerCase()}).filter($u=>$u.includes("@"))}const domainOf=Au=>Au.slice(Au.lastIndexOf("@")+1).trim();function forwardsOutside(Au,lo,$u){const Ru=own$a(FORWARDING,`${Au}.${lo}`),Iu=Ru?$u[Ru.message]:void 0;if(!Ru||typeof Iu!="string"||!Iu.trim())return!1;const[Pu]=addresses($u[Ru.mailbox]);return Pu?Ru.recipients.flatMap(Ou=>addresses($u[Ou])).some(Ou=>domainOf(Ou)!==domainOf(Pu)):!0}function classesOf(Au,lo){const[$u,Ru]=splitRef(Au);if($u===void 0)return[...own$a(BACKEND_TOOL_ACTIONS,Ru)??[]];const[Iu,Pu]=entryOf$1($u,Ru);for(const Ou of Pu)if(lo===void 0||conditionHolds(Ou,lo))for(const Mu of Ou.classes)Iu.includes(Mu)||Iu.push(Mu);return lo!==void 0&&Iu.length>0&&!Iu.includes("publish")&&forwardsOutside($u,Ru,lo)&&Iu.push("publish"),Iu}const strictest=Au=>Au.reduce((lo,$u)=>BEHAVIOURS.indexOf($u)>BEHAVIOURS.indexOf(lo)?$u:lo),connectionTo=(Au,lo)=>Au.connections.find($u=>idOf($u.server)===lo),reaches=(Au,lo)=>Au.only.length===0||Au.only.some($u=>matchesPattern(lo,$u)),isClass$1=Au=>Object.prototype.hasOwnProperty.call(DEFAULT_BEHAVIOURS,Au),normal=Au=>{if(isClass$1(Au))return Au;const[lo,$u]=splitRef(Au);return lo!==void 0?`${lo}.${$u}`:$u},byClasses=(Au,lo)=>{const $u={};for(const Ru of Au.rules)for(const Iu of Ru.appliesTo)isClass$1(Iu)&&($u[Iu]=Ru.behaviour);return lo.map(Ru=>$u[Ru]??DEFAULT_BEHAVIOURS[Ru])};function behaviourFor(Au,lo,$u={}){const[Ru,Iu]=splitRef(lo);let Pu,Ou=[],Mu;if($u.classes?Pu=Mu=[...$u.classes]:(Mu=classesOf(lo),Pu=classesOf(lo,{}),Ou=($u.arguments===void 0?Mu:classesOf(lo,$u.arguments)).filter(Bu=>!Pu.includes(Bu))),Ru!==void 0){const Lu=connectionTo(Au,Ru);if(!Lu||!reaches(Lu,Iu)||Lu.access==="read"&&Mu.some(Bu=>Bu!=="read"))return"leave_to_me"}const Du=Ru!==void 0?`${Ru}.${Iu}`:Iu;for(const Lu of Au.rules)if(Lu.appliesTo.some(Bu=>!isClass$1(Bu)&&normal(Bu)===Du))return strictest([Lu.behaviour,...byClasses(Au,Ou)]);return Pu.length===0&&Ou.length===0?"leave_to_me":strictest(byClasses(Au,[...Pu,...Ou]))}const BEHAVIOUR_WORDS={do_it:{says:"Do it",means:"It does it without asking."},if_asked:{says:"Do it if I asked",means:"Only what you approved in advance."},ask_first:{says:"Ask me first",means:"It waits for your yes."},leave_to_me:{says:"Leave it to me",means:"It never does it, and hands it to you."}},ACTION_WORDS={read:"Read",write:"Create or change",send:"Send",buy:"Buy",delete:"Delete",publish:"Share or publish"};function coverOf(Au){const lo=own$a(ACTION_WORDS,Au);if(lo)return lo;const[$u,Ru]=splitRef(Au);return $u?`${Ru} (${$u})`:Ru}const A2A_PROTOCOL_0_0_1={id:"a2a",version:"0.0.1",name:"Agent2Agent",description:"How agents talk to agents: teams and scenes talk over it, an application's route serves it, and its Agent Card advertises its extensions.",publisher:"Google, now the Linux Foundation",layer:"transport",specUrl:"https://a2a-protocol.org",specVersion:"1.0",status:"shipped",connects:"Other agents, each at its address with its Agent Card",packages:{python:["fasta2a","a2a-sdk"],typescript:["@a2a-js/sdk"]},protocolTools:[],appspecBlock:"a2a"},A2UI_PROTOCOL_0_0_1={id:"a2ui",version:"0.0.1",name:"A2UI",description:"How an agent's answer becomes an interface: components the host renders from a declarative surface.",publisher:"Google",layer:"ui",specUrl:"https://a2ui.org",specVersion:"0.9",status:"shipped",connects:"The person, through components an answer draws",packages:{python:["agent-runtimes"],typescript:["@a2ui/react","@a2ui/web_core"]},protocolTools:[]},ACP_PROTOCOL_0_0_1={id:"acp",version:"0.0.1",name:"Agentic Commerce Protocol",description:"Checkout sessions at a seller, completed with a payment the model never sees. In applications at test merchants only, with no real payment token (decided 2026-10-13): each purchase asked of the person first, made at most once.",publisher:"OpenAI, Stripe",layer:"commerce",specUrl:"https://github.com/agentic-commerce-protocol/agentic-commerce-protocol",specVersion:"2026-04-17",status:"shipped",connects:"Sellers, to check out with a delegated payment",packages:{python:["agent-runtimes"],typescript:["@datalayer/agent-runtimes"]},protocolTools:["agentic-commerce"]},AG_UI_PROTOCOL_0_0_1={id:"ag-ui",version:"0.0.1",name:"AG-UI",description:"How an agent streams its run to a page: messages, tool calls and state as events.",publisher:"CopilotKit",layer:"ui",specUrl:"https://docs.ag-ui.com",specVersion:"0.0.57 (@ag-ui/core)",status:"shipped",connects:"The page a person talks to the agent on",packages:{python:["ag-ui-protocol"],typescript:["@ag-ui/client","@ag-ui/core"]},protocolTools:[]},MCP_PROTOCOL_0_0_1={id:"mcp",version:"0.0.1",name:"Model Context Protocol",description:"How an agent calls tools and reads resources: clients and servers in both languages, and the MCP gateway every connection goes through.",publisher:"Anthropic",layer:"transport",specUrl:"https://modelcontextprotocol.io/specification",specVersion:"2026-07-28 (Python), 2025-11-25 (TypeScript)",status:"shipped",connects:"Tools, resources and prompts served by MCP servers",packages:{python:["mcp"],typescript:["@modelcontextprotocol/sdk","@mcp-ui/client"]},protocolTools:[]},PACT_PROTOCOL_0_0_1={id:"pact",version:"0.0.1",name:"Personal Agent Consent & Trust",description:"A personal agent asking a business's agent over A2A, first as itself, then for a person who delegated some of their permissions.",publisher:"Decagon, Instinct",layer:"consent",specUrl:"https://openpactprotocol.org",specVersion:"1.0",status:"shipped",connects:"Businesses' agents, asked for a person with their delegation",packages:{python:["agent-runtimes"],typescript:["@datalayer/agent-runtimes"]},protocolTools:["pact"],appspecBlock:"pact"},PAP_PROTOCOL_0_0_1={id:"pap",version:"0.0.1",name:"Personal Agent Protocol",description:"A person's agent working with a company for them — signed out, then signed in at the company, its changes confirmed by the person — and an application being a company personal agents reach.",publisher:"Sierra, Meta",layer:"consent",specUrl:"https://personalagentprotocol.org",specVersion:"draft 0.2",status:"shipped",connects:"Companies, as a person's agent there, or being one",packages:{python:["personal-agent-protocol"],typescript:["@datalayer/personal-agent-protocol"]},protocolTools:["pap"],appspecBlock:"pap"},TAP_PROTOCOL_0_0_1={id:"tap",version:"0.0.1",name:"Trusted Agent Protocol",description:"An agent-recognition profile over Web Bot Auth for merchants: a signature tagged agent-browser-auth to browse or agent-payer-auth to pay. Still a draft profile, built from Visa's public Merchant Specifications (2026-10-13) until Visa confirms it. In applications at test merchants only (decided 2026-10-14): the MCP gateway signs each UCP or ACP purchase with agent-payer-auth under the application's own key, and the test merchants verify it; browsing stays Web Bot Auth.",publisher:"Visa",layer:"identity",specUrl:"https://developer.visa.com/capabilities/trusted-agent-protocol/trusted-agent-protocol-specifications",specVersion:"draft (Merchant Specifications, read 2026-10-13)",status:"shipped",connects:"Merchants that recognise an agent by its signature",packages:{python:["agent-runtimes"],typescript:["@datalayer/agent-runtimes","http-message-sig"]},protocolTools:[]},UCP_PROTOCOL_0_0_1={id:"ucp",version:"0.0.1",name:"Universal Commerce Protocol",description:"Shopping at a merchant: catalogue, checkout and orders, every purchase an exact proposal the person approves. In applications at test merchants only, with no real payment (decided 2026-10-13): each purchase asked of the person first, made at most once.",publisher:"Google, with Shopify and retailers",layer:"commerce",specUrl:"https://github.com/Universal-Commerce-Protocol/ucp",specVersion:"2026-08-25",status:"shipped",connects:"Merchants, to search, check out and follow orders",packages:{python:["ucp-sdk","agent-runtimes"],typescript:["@ucp-js/sdk","@datalayer/agent-runtimes"]},protocolTools:["ucp"]},WEB_BOT_AUTH_PROTOCOL_0_0_1={id:"web-bot-auth",version:"0.0.1",name:"Web Bot Auth",description:"Signed outbound requests (RFC 9421) and the key directory a website checks them against. In applications, every request to a company, business or merchant is signed, and a signed fetch reads pages at the sites an application names, GET only (decided 2026-10-13).",publisher:"Cloudflare (IETF draft)",layer:"identity",specUrl:"https://datatracker.ietf.org/doc/draft-ietf-webbotauth-httpsig-protocol/",specVersion:"draft-ietf-webbotauth-httpsig-protocol-00",status:"shipped",connects:"Websites, which can tell the application's requests from someone pretending",packages:{python:["agent-runtimes"],typescript:["@datalayer/agent-runtimes","web-bot-auth"]},protocolTools:["signed-fetch"],appspecBlock:"signed_fetch"},PROTOCOL_CATALOGUE={a2a:A2A_PROTOCOL_0_0_1,a2ui:A2UI_PROTOCOL_0_0_1,acp:ACP_PROTOCOL_0_0_1,"ag-ui":AG_UI_PROTOCOL_0_0_1,mcp:MCP_PROTOCOL_0_0_1,pact:PACT_PROTOCOL_0_0_1,pap:PAP_PROTOCOL_0_0_1,tap:TAP_PROTOCOL_0_0_1,ucp:UCP_PROTOCOL_0_0_1,"web-bot-auth":WEB_BOT_AUTH_PROTOCOL_0_0_1},A2UI_SURFACE_UI_0_0_1={id:"a2ui-surface",version:"0.0.1",name:"Surfaces in the conversation",description:"Forms, tables and cards the agent draws in the conversation; what you fill in goes back to it.",emoji:"🪟",octicon:"browser",plugin:"@datalayer/loop-plugin-a2ui-surface",folder:"a2ui-surface",contributions:{slots:["loop.chatHeader"],points:["reactor.ui.renderer","reactor.ui.toolBinding"],commands:[]},contributionPoints:[],settings:{},renderers:["a2ui"],catalog:"a2ui/v0.9",components:[{id:"Text",name:"Text",category:"text",emoji:"🔤",description:"Words on the page: a heading, a paragraph, the answer — plain or Markdown.",version:"0.9.0",standard:!0,properties:{type:"object",required:["text"],properties:{text:{type:"string",title:"Words",description:"What it says, plain or in simple Markdown."},variant:{type:"string",title:"Style",description:"A heading of a level, a caption, or body text.",enum:["h1","h2","h3","h4","h5","caption","body"],default:"body"}}},events:[]},{id:"Image",name:"Image",category:"media",emoji:"🖼️",description:"A picture: a chart rendered elsewhere, a logo, a photo.",version:"0.9.0",standard:!0,properties:{type:"object",required:["url"],properties:{url:{type:"string",title:"Address",description:"Where the picture is."},description:{type:"string",title:"Description",description:"What it shows, for those who cannot see it."},fit:{type:"string",title:"Fit",description:"How it is resized to its place.",enum:["contain","cover","fill","none","scaleDown"],default:"fill"},variant:{type:"string",title:"Size",description:"An icon, an avatar, a feature or a header.",enum:["icon","avatar","smallFeature","mediumFeature","largeFeature","header"],default:"mediumFeature"}}},events:[]},{id:"Icon",name:"Icon",category:"media",emoji:"🔣",description:"A small drawing that says what something is: a check, a warning, a link.",version:"0.9.0",standard:!0,properties:{type:"object",required:["name"],properties:{name:{type:"string",title:"Icon",description:"Which drawing, by its name.",enum:["accountCircle","add","arrowBack","arrowForward","attachFile","calendarToday","call","camera","check","close","delete","download","edit","event","error","fastForward","favorite","favoriteOff","folder","help","home","info","locationOn","lock","lockOpen","mail","menu","moreVert","moreHoriz","notificationsOff","notifications","pause","payment","person","phone","photo","play","print","refresh","rewind","search","send","settings","share","shoppingCart","skipNext","skipPrevious","star","starHalf","starOff","stop","upload","visibility","visibilityOff","volumeDown","volumeMute","volumeOff","volumeUp","warning"]}}},events:[]},{id:"Video",name:"Video",category:"media",emoji:"🎬",description:"A film played in place.",version:"0.9.0",standard:!0,properties:{type:"object",required:["url"],properties:{url:{type:"string",title:"Address",description:"Where the film is."}}},events:[]},{id:"AudioPlayer",name:"Audio",category:"media",emoji:"🔊",description:"A sound played in place: a recording, a summary read aloud.",version:"0.9.0",standard:!0,properties:{type:"object",required:["url"],properties:{url:{type:"string",title:"Address",description:"Where the sound is."},description:{type:"string",title:"Description",description:"What it is: a title or a summary."}}},events:[]},{id:"Row",name:"Row",category:"layout",emoji:"➡️",description:"Children side by side, left to right.",version:"0.9.0",standard:!0,properties:{type:"object",required:["children"],properties:{children:{type:"array",title:"Blocks",description:"The blocks inside it, by id, left to right.",items:{type:"string"}},justify:{type:"string",title:"Spacing",description:"How the blocks share the width.",enum:["center","end","spaceAround","spaceBetween","spaceEvenly","start","stretch"],default:"start"},align:{type:"string",title:"Alignment",description:"How the blocks line up top to bottom.",enum:["start","center","end","stretch"],default:"stretch"}}},events:[]},{id:"Column",name:"Column",category:"layout",emoji:"⬇️",description:"Children one under the other.",version:"0.9.0",standard:!0,properties:{type:"object",required:["children"],properties:{children:{type:"array",title:"Blocks",description:"The blocks inside it, by id, top to bottom.",items:{type:"string"}},justify:{type:"string",title:"Spacing",description:"How the blocks share the height.",enum:["start","center","end","spaceBetween","spaceAround","spaceEvenly","stretch"],default:"start"},align:{type:"string",title:"Alignment",description:"How the blocks line up left to right.",enum:["center","end","start","stretch"],default:"stretch"}}},events:[]},{id:"List",name:"List",category:"layout",emoji:"📃",description:"Items one after the other, each drawn by the same children: results, alternatives, steps.",version:"0.9.0",standard:!0,properties:{type:"object",required:["children"],properties:{children:{type:"array",title:"Blocks",description:"The blocks inside it, by id, or the template repeated over a list.",items:{type:"string"}},direction:{type:"string",title:"Direction",description:"One under the other, or side by side.",enum:["vertical","horizontal"],default:"vertical"},align:{type:"string",title:"Alignment",description:"How the items line up across.",enum:["start","center","end","stretch"],default:"stretch"}}},events:[]},{id:"Card",name:"Card",category:"layout",emoji:"🗂️",description:"A framed group: what belongs together, set apart.",version:"0.9.0",standard:!0,properties:{type:"object",required:["child"],properties:{child:{type:"string",title:"Block",description:"The one block inside it, by id; a Row or Column for several."}}},events:[]},{id:"Tabs",name:"Tabs",category:"layout",emoji:"📑",description:"Several views of one place, one shown at a time.",version:"0.9.0",standard:!0,properties:{type:"object",required:["tabs"],properties:{tabs:{type:"array",title:"Tabs",description:"Each tab's title and the block it shows, by id.",minItems:1,items:{type:"object",required:["title","child"],properties:{title:{type:"string"},child:{type:"string"}}}}}},events:[]},{id:"Divider",name:"Divider",category:"layout",emoji:"➖",description:"A line between what comes before and after.",version:"0.9.0",standard:!0,properties:{type:"object",properties:{axis:{type:"string",title:"Direction",description:"Across or up and down.",enum:["horizontal","vertical"],default:"horizontal"}}},events:[]},{id:"Modal",name:"Modal",category:"layout",emoji:"🪟",description:"A window over the page, opened by a trigger: details, a confirmation.",version:"0.9.0",standard:!0,properties:{type:"object",required:["trigger","content"],properties:{trigger:{type:"string",title:"Opened by",description:"The block that opens it, by id: a button."},content:{type:"string",title:"Shows",description:"The block shown inside it, by id."}}},events:[]},{id:"Button",name:"Button",category:"action",emoji:"🔘",description:"An action the person takes: send, run, approve. One filled button per screen.",version:"0.9.0",standard:!0,properties:{type:"object",required:["child","action"],properties:{child:{type:"string",title:"Label",description:"The block on it, by id: a Text for its words."},variant:{type:"string",title:"Style",description:"Primary for the one main action, borderless for a link.",enum:["default","primary","borderless"],default:"default"},action:{type:"object",title:"Does",description:"What pressing it sends, by name, with what it reads."}}},events:[]},{id:"TextField",name:"Input",category:"input",emoji:"⌨️",description:"A field the person types in: a word, a sentence, a number, a date.",version:"0.9.0",standard:!0,properties:{type:"object",required:["label"],properties:{label:{type:"string",title:"Label",description:"What the person reads beside it."},value:{type:"string",title:"Value",description:"What is typed in it."},variant:{type:"string",title:"Kind",description:"A short or long text, a number, or hidden as typed.",enum:["longText","number","shortText","obscured"],default:"shortText"},validationRegexp:{type:"string",title:"Pattern",description:"A regular expression what is typed must match."}}},events:[]},{id:"CheckBox",name:"Checkbox",category:"input",emoji:"☑️",description:"Yes or no: an option on or off, a consent given.",version:"0.9.0",standard:!0,properties:{type:"object",required:["label","value"],properties:{label:{type:"string",title:"Label",description:"What the person reads beside it."},value:{type:"boolean",title:"Value",description:"Whether it is ticked."}}},events:[]},{id:"ChoicePicker",name:"Select",category:"input",emoji:"🔽",description:"One choice, or several, among options the builder lists or the data gives.",version:"0.9.0",standard:!0,properties:{type:"object",required:["options","value"],properties:{label:{type:"string",title:"Label",description:"What the person reads above the options."},variant:{type:"string",title:"Choice",description:"One of the options, or several.",enum:["multipleSelection","mutuallyExclusive"],default:"mutuallyExclusive"},options:{type:"array",title:"Options",description:"What may be chosen: the words read and the value sent.",items:{type:"object",required:["label","value"],properties:{label:{type:"string"},value:{type:"string"}}}},value:{type:"array",title:"Value",description:"The values chosen.",items:{type:"string"}},displayStyle:{type:"string",title:"Shown as",description:"Checkboxes or chips.",enum:["checkbox","chips"],default:"checkbox"},filterable:{type:"boolean",title:"Searchable",description:"A search field above the options.",default:!1}}},events:[]},{id:"Slider",name:"Slider",category:"input",emoji:"🎚️",description:"A number chosen along a range: a weight, a budget, a threshold.",version:"0.9.0",standard:!0,properties:{type:"object",required:["value","max"],properties:{label:{type:"string",title:"Label",description:"What the person reads beside it."},min:{type:"number",title:"Least",description:"The smallest value.",default:0},max:{type:"number",title:"Most",description:"The largest value."},value:{type:"number",title:"Value",description:"The value chosen."}}},events:[]},{id:"DateTimeInput",name:"Date and time",category:"input",emoji:"📅",description:"A date, a time, or both, chosen from a calendar.",version:"0.9.0",standard:!0,properties:{type:"object",required:["value"],properties:{value:{type:"string",title:"Value",description:"The date or time chosen, in ISO 8601."},enableDate:{type:"boolean",title:"Date",description:"A date may be chosen.",default:!1},enableTime:{type:"boolean",title:"Time",description:"A time may be chosen.",default:!1},min:{type:"string",title:"Earliest",description:"The earliest that may be chosen, in ISO 8601."},max:{type:"string",title:"Latest",description:"The latest that may be chosen, in ISO 8601."},label:{type:"string",title:"Label",description:"What the person reads beside it."}}},events:[]},{id:"Table",name:"Table",category:"data",emoji:"📋",description:"Rows the application found or keeps, with the columns the builder chooses.",version:"1.0.0",standard:!1,properties:{type:"object",required:["columns"],properties:{title:{type:"string",title:"Title",description:"What the table is, above it."},columns:{type:"array",title:"Columns",description:"The columns, in order.",minItems:1,items:{type:"string"}},page_size:{type:"integer",title:"Rows per page",description:"How many rows show at once.",minimum:1,maximum:500,default:20},selectable:{type:"boolean",title:"Selectable",description:"A row may be chosen, and its choice sent.",default:!1}}},bindings:{shows:["rows"],sends:["selected"]},events:["select"],example:{title:"Runs",columns:["model","pass rate","cost"]}},{id:"Chart",name:"Chart",category:"data",emoji:"📊",description:"Numbers drawn: a bar, a line, a scatter of what the application measured.",version:"1.0.0",standard:!1,properties:{type:"object",required:["kind","x","y"],properties:{title:{type:"string",title:"Title",description:"What the chart shows, above it."},kind:{type:"string",title:"Kind",description:"How the numbers are drawn.",enum:["bar","line","scatter","area"],default:"bar"},x:{type:"string",title:"Across",description:"The field along the bottom."},y:{type:"string",title:"Up",description:"The field measured."},series:{type:"string",title:"Series",description:"A field whose values are drawn apart."}}},bindings:{shows:["points"],sends:[]},events:[],example:{kind:"bar",x:"model",y:"pass rate"}},{id:"FileUpload",name:"File upload",category:"input",emoji:"📎",description:"A file the person gives the application: a document to read, a sheet to check.",version:"1.0.0",standard:!1,properties:{type:"object",required:["label"],properties:{label:{type:"string",title:"Label",description:"What the person reads beside it."},accept:{type:"array",title:"Accepts",description:"The kinds of file it takes, by extension.",items:{type:"string",pattern:"^\\.[a-z0-9]+$"}},multiple:{type:"boolean",title:"Several",description:"More than one file at once.",default:!1},max_mb:{type:"integer",title:"Largest (MB)",description:"The largest file it takes.",minimum:1,maximum:500,default:25}}},bindings:{shows:[],sends:["files"]},events:["upload"],example:{label:"The contract",accept:[".pdf",".docx"]}},{id:"Chat",name:"Chat",category:"conversation",emoji:"💬",description:"The conversation with the application: its welcome, its starters, the composer.",version:"1.0.0",standard:!1,properties:{type:"object",properties:{welcome:{type:"string",title:"Welcome",description:"What it says before anyone writes."},placeholder:{type:"string",title:"Composer hint",description:"Shown in the composer while it is empty.",default:"Ask anything"},starters:{type:"array",title:"Starters",description:"Questions offered before the first message.",maxItems:6,items:{type:"string"}},show_tools:{type:"boolean",title:"Shows its tools",description:"The tool calls are shown as they happen.",default:!0}}},bindings:{shows:["messages"],sends:["message"]},events:["send"],example:{welcome:"Ask me to research anything.",starters:["What changed in Python 3.13?"]}},{id:"Evidence",name:"Evidence",category:"data",emoji:"🔎",description:"What an answer rests on: the sources opened, the passages cited, each with its link.",version:"1.0.0",standard:!1,properties:{type:"object",properties:{title:{type:"string",title:"Title",description:"Above the sources.",default:"Sources"},show_passages:{type:"boolean",title:"Shows passages",description:"Each source with the passage cited from it.",default:!0},max_items:{type:"integer",title:"Most shown",description:"How many sources show before *more*.",minimum:1,maximum:50,default:5}}},bindings:{shows:["sources"],sends:[]},events:["open"],example:{title:"What this rests on"}},{id:"Form",name:"Form",category:"input",emoji:"🧾",description:"Several fields asked at once, from a JSON Schema, checked as they are filled and again when they arrive (drawn with @datalayer/primer-rjsf).",version:"1.1.0",standard:!1,properties:{type:"object",required:["schema"],properties:{title:{type:"string",title:"Title",description:"What the form is for, above it."},schema:{type:"object",title:"Fields",description:"The JSON Schema of what is asked: its fields, their types, what is required."},ui:{type:"object",title:"How its fields are drawn",description:"By field name, the ui: options @datalayer/primer-rjsf reads (a uiSchema): ui:widget one of select, radio, range, updown, switch, checkbox, text, textarea, date, checkboxes, tags; each field's own widget when unsaid."},submit_label:{type:"string",title:"Send button",description:"The words on its button.",default:"Send"}}},bindings:{shows:["values"],sends:["values"]},events:["submit"],example:{title:"The quote",schema:{type:"object",required:["seats"],properties:{seats:{type:"integer",minimum:1,title:"Seats"}}}}},{id:"Download",name:"File to download",category:"data",emoji:"📄",description:"A file the application gives, to save: a report, a sheet, an export — by its link, or the file itself as a data: URL.",version:"1.0.0",standard:!1,properties:{type:"object",required:["name","url"],properties:{name:{type:"string",title:"File name",description:"What the file is saved as, with its extension.",minLength:1},url:{type:"string",title:"Link",description:"Where the file is: an http(s) link, or the file itself as a data: URL.",pattern:"^(https?://|data:)"},media_type:{type:"string",title:"Kind",description:"Its media type (text/csv, application/pdf…), said beside its name."},size:{type:"integer",title:"Size (bytes)",description:"How large it is, said beside its name.",minimum:0},description:{type:"string",title:"Description",description:"A line under its name."}}},bindings:{shows:[],sends:[]},events:["download"],example:{name:"totals.csv",url:"data:text/csv;base64,bW9udGgsdG90YWwKSmFuLDEyMDAK",media_type:"text/csv",size:21,description:"The month's totals."}}]},A2UI_VIEW_UI_0_0_1={id:"a2ui-view",version:"0.0.1",name:"Surface view",description:"The last result of the code, shown as a page you can use rather than as raw output.",emoji:"🖼",octicon:"browser",plugin:"@datalayer/loop-plugin-a2ui",folder:"a2ui",contributions:{slots:[],points:["loop.command","loop.viewType"],commands:["a2ui"]},contributionPoints:[],settings:{},renderers:["a2ui"],catalog:"",components:[]},AGENTSPECS_UI_0_0_1={id:"agentspecs",version:"0.0.1",name:"Agent picker",description:"Choose which agent answers in this conversation.",emoji:"🤖",octicon:"people",plugin:"@datalayer/loop-plugin-agentspecs",folder:"agentspecs",contributions:{slots:["loop.header"],points:["loop.command"],commands:["agents"]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},APP_ACTIVITY_UI_0_0_1={id:"app-activity",version:"0.0.1",name:"Activity",description:"What your application did, is doing, and is about to do, beside its page.",emoji:"🕘",octicon:"pulse",plugin:"@datalayer/loop-plugin-app-activity",folder:"app-activity",per:"application",contributions:{slots:["loop.sidebar"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},APP_COMPONENTS_UI_0_0_1={id:"app-components",version:"0.0.1",name:"Your own components",description:"The components your application's developer wrote, on its page and in its answers.",emoji:"🧩",octicon:"apps",plugin:"@datalayer/loop-plugin-app-components",folder:"app-components",per:"application",contributions:{slots:[],points:["loop.a2ui.component","loop.canvas.block"],commands:[]},contributionPoints:[],settings:{},renderers:["a2ui"],catalog:"",components:[]},APP_COMPUTER_UI_0_0_1={id:"app-computer",version:"0.0.1",name:"Computer",description:"The computer your application works on: what ran there, its files, and taking it over.",emoji:"🖥️",octicon:"device-desktop",plugin:"@datalayer/loop-plugin-app-computer",folder:"app-computer",per:"application",contributions:{slots:["loop.sidebar"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},APP_ELEMENTS_UI_0_0_1={id:"app-elements",version:"0.0.1",name:"Side panel and pages",description:"What your application opens beside the conversation: a side panel, a page of its own, a question for you.",emoji:"🗂️",octicon:"sidebar-expand",plugin:"@datalayer/loop-plugin-app-elements",folder:"app-elements",contributions:{slots:["root"],points:["reactor.ui.renderer"],commands:[]},contributionPoints:[],settings:{},renderers:["a2ui"],catalog:"",components:[]},APP_PAGE_UI_0_0_1={id:"app-page",version:"0.0.1",name:"Application page",description:"Your application's page, drawn beside its conversation.",emoji:"📈",octicon:"browser",plugin:"@datalayer/loop-plugin-app-page",folder:"app-page",per:"application",contributions:{slots:[],points:["loop.chat.surface"],commands:[]},contributionPoints:[],settings:{},renderers:["a2ui","mcp-apps"],catalog:"",components:[]},APP_RULES_UI_0_0_1={id:"app-rules",version:"0.0.1",name:"Rules and approvals",description:"When your application acts alone, when it asks you, and the approvals waiting for your yes.",emoji:"🛡️",octicon:"shield-check",plugin:"@datalayer/loop-plugin-app-rules",folder:"app-rules",per:"application",contributions:{slots:["loop.sidebar"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CANVAS_BLOCKS_UI_0_0_1={id:"canvas-blocks",version:"0.0.1",name:"Blocks",description:"The blocks you place on your application's page in the visual editor, one set for each part that draws them.",emoji:"🧱",octicon:"apps",plugin:"@datalayer/loop-plugin-ui",folder:"canvas-blocks",per:"ui",contributions:{slots:[],points:["loop.canvas.block"],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CANVAS_PARTS_UI_0_0_1={id:"canvas-parts",version:"0.0.1",name:"Parts",description:"What you drop on your agent in the visual editor: connections, skills, models, rules, tests and events.",emoji:"🧰",octicon:"package",plugin:"@datalayer/loop-plugin-parts",folder:"canvas-parts",per:"source",contributions:{slots:[],points:["loop.canvas.part"],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CHAT_EXTRAS_UI_0_0_1={id:"chat-extras",version:"0.0.1",name:"Banner and status",description:"A live banner over the conversation and a status line under it, set by the page around it.",emoji:"📣",octicon:"megaphone",plugin:"@datalayer/loop-plugin-chat-extras",folder:"chat-extras",contributions:{slots:[],points:["loop.chat.extras"],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CHAT_HEADER_UI_0_0_1={id:"chat-header",version:"0.0.1",name:"Chat title bar",description:"The conversation's title bar: who answers, what it runs on, and its actions.",emoji:"🏷️",octicon:"rows",plugin:"@datalayer/loop-plugin-chat-header",folder:"chat-header",contributions:{slots:[],points:["loop.chat.header"],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CHAT_VIEW_UI_0_0_1={id:"chat-view",version:"0.0.1",name:"Chat button",description:"Back to the conversation alone, from under the composer.",emoji:"💬",octicon:"comment-discussion",plugin:"@datalayer/loop-plugin-chat-view",folder:"chat-view",contributions:{slots:["loop.promptAction"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},CHAT_UI_0_0_1={id:"chat",version:"0.0.1",name:"Chat",description:"The conversation: what you ask, what it answers, and the work it opens beside it.",emoji:"💬",octicon:"comment-discussion",plugin:"@datalayer/loop-plugin-chat",folder:"chat",contributions:{slots:[],points:["loop.chat.turn","loop.command","loop.document.toolbar.item","loop.notebook.toolbar.item","loop.viewType"],commands:["chat"]},contributionPoints:["loop.agent.available","loop.chat.composer","loop.chat.extras","loop.chat.header","loop.chat.suggestion","loop.chat.turn","loop.frontendTool"],settings:{type:"object",properties:{placeholder:{type:"string",title:"Composer hint",description:"Shown in the composer while it is empty; the agent's own when unsaid.",default:""},defaultSurface:{type:"string",title:"Opens beside it",description:"What opens beside the conversation: notebook, document, a page, or none.",default:"notebook"},showSurfaceSelector:{type:"boolean",title:"Offers the switcher",description:"The strip that switches what is open beside the conversation.",default:!0},hideHeader:{type:"boolean",title:"Hides its title bar",description:"The conversation without its own title bar.",default:!1},headerButtons:{type:"object",title:"Title bar buttons",description:"Whether the title bar offers a new chat and clearing this one.",properties:{newChat:{type:"boolean",title:"New chat",description:"Start another conversation."},clear:{type:"boolean",title:"Clear",description:"Clear this conversation."}},default:{newChat:!1,clear:!1}},hidePrompt:{type:"boolean",title:"Hides the composer",description:"The conversation read without being written to.",default:!1},promptPlacement:{type:"string",title:"Composer place",description:"Where the composer sits.",enum:["top","bottom","bottom-chat","floating"],default:"bottom"},autoFocusPrompt:{type:"boolean",title:"Composer takes the caret",description:"The composer is ready to type in when the page opens.",default:!0},suggestionLabels:{type:"boolean",title:"Openers by the composer",description:"The openers shown as labels by the composer, not only in its menu.",default:!0},fullScreenTopOffset:{type:["number","string"],title:"Room kept at the top",description:"What full screen leaves at the top for the page's own header.",default:0}}},renderers:[],catalog:"",components:[]},COMMANDS_UI_0_0_1={id:"commands",version:"0.0.1",name:"Command palette",description:"Every command at hand, with Ctrl-K.",emoji:"⌘",octicon:"command-palette",plugin:"@datalayer/loop-plugin-commands",folder:"commands",contributions:{slots:["loop.status"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},DOCUMENT_TOOLBAR_UI_0_0_1={id:"document-toolbar",version:"0.0.1",name:"Document toolbar",description:"Shows what the document's code blocks run on.",emoji:"🔵",octicon:"circle",plugin:"@datalayer/loop-plugin-document-toolbar",folder:"document-toolbar",contributions:{slots:[],points:["loop.document.toolbar"],commands:[]},contributionPoints:["loop.document.toolbar.item"],settings:{},renderers:[],catalog:"",components:[]},DOCUMENT_VIEW_UI_0_0_1={id:"document-view",version:"0.0.1",name:"Document button",description:"The document beside the conversation, from under the composer.",emoji:"📄",octicon:"file",plugin:"@datalayer/loop-plugin-document-view",folder:"document-view",contributions:{slots:["loop.promptAction"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},DOCUMENT_UI_0_0_1={id:"document",version:"0.0.1",name:"Document",description:"A document beside the conversation, written with the agent.",emoji:"📄",octicon:"file",plugin:"@datalayer/loop-plugin-document",folder:"document",contributions:{slots:[],points:["loop.chat.surface","loop.command"],commands:["document"]},contributionPoints:["loop.document.opening","loop.document.toolbar"],settings:{},renderers:[],catalog:"",components:[]},INPUT_PROMPT_UI_0_0_1={id:"input-prompt",version:"0.0.1",name:"Composer",description:"Where you write to the agent, under or over the conversation.",emoji:"✏️",octicon:"pencil",plugin:"@datalayer/loop-plugin-input-prompt",folder:"input-prompt",contributions:{slots:[],points:["loop.chat.composer"],commands:[]},contributionPoints:["loop.prompt.panel"],settings:{},renderers:[],catalog:"",components:[]},MODELS_UI_0_0_1={id:"models",version:"0.0.1",name:"Models",description:"Which model answers, and the models you may choose from.",emoji:"🧠",octicon:"cpu",plugin:"@datalayer/loop-plugin-models",folder:"models",contributions:{slots:[],points:["loop.command"],commands:["models"]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},NOTEBOOK_TOOLBAR_UI_0_0_1={id:"notebook-toolbar",version:"0.0.1",name:"Notebook toolbar",description:"Shows what the notebook is running on.",emoji:"🟢",octicon:"circle",plugin:"@datalayer/loop-plugin-notebook-toolbar",folder:"notebook-toolbar",contributions:{slots:[],points:["loop.notebook.toolbar"],commands:[]},contributionPoints:["loop.notebook.toolbar.item"],settings:{},renderers:[],catalog:"",components:[]},NOTEBOOK_VIEW_UI_0_0_1={id:"notebook-view",version:"0.0.1",name:"Notebook button",description:"The notebook beside the conversation, from under the composer.",emoji:"📓",octicon:"rows",plugin:"@datalayer/loop-plugin-notebook-view",folder:"notebook-view",contributions:{slots:["loop.promptAction"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},NOTEBOOK_UI_0_0_1={id:"notebook",version:"0.0.1",name:"Notebook",description:"A notebook beside the conversation, its code run as you go.",emoji:"📓",octicon:"rows",plugin:"@datalayer/loop-plugin-notebook",folder:"notebook",contributions:{slots:[],points:["loop.chat.surface","loop.command"],commands:["notebook"]},contributionPoints:["loop.notebook.opening","loop.notebook.toolbar"],settings:{},renderers:[],catalog:"",components:[]},PAGE_LAYOUT_UI_0_0_1={id:"page-layout",version:"0.0.1",name:"Page layout",description:"The work on a centred sheet like a document, the composer above it and the conversation in a panel beside it; or the conversation and the work side by side.",emoji:"📄",octicon:"file",plugin:"@datalayer/loop-plugin-page-layout",folder:"page-layout",contributions:{slots:["loop.header"],points:["loop.chat.layout","loop.prompt.panel"],commands:[]},contributionPoints:[],settings:{type:"object",properties:{arrangement:{type:"string",title:"Arrangement",description:"The work on a sheet with the conversation in a panel, or both side by side.",enum:["page","split"],default:"page"},turnPanel:{type:"string",title:"Current turn",description:"Where the current turn hangs on the composer.",enum:["below","above","none"],default:"below"},turnPanelFooter:{type:"string",title:"Under the reply",description:"What is drawn under the reply: everything, its actions, or nothing.",enum:["full","actions","none"],default:"full"},prompt:{type:"string",title:"Composer",description:"Docked above the sheet, or floating over it.",enum:["docked","floating"],default:"docked"},promptAnchor:{type:"string",title:"Floating composer starts",description:"The edge a floating composer starts at.",enum:["top","bottom"],default:"top"},pageSize:{type:"object",title:"Sheet",description:"The sheet: free at its reading width when unsaid, or a paper (letter, a4) whose width it takes, with a width or a height of its own over either.",properties:{format:{type:"string",title:"Paper",description:"The paper the sheet is.",enum:["free","letter","a4"]},width:{type:"number",title:"Width",description:"The sheet's width in pixels; over a paper, it replaces the paper's."},height:{type:"number",title:"Height",description:"The sheet's least height in pixels; what is past it grows the sheet."}}}}},renderers:[],catalog:"",components:[]},PAP_SIGN_IN_UI_0_0_1={id:"pap-sign-in",version:"0.0.1",name:"Sign in at a company",description:"Where your agent asks you to sign in at a company: its page, the code, and until when.",emoji:"🔑",octicon:"sign-in",plugin:"@datalayer/loop-plugin-pap-sign-in",folder:"pap-sign-in",contributions:{slots:["loop.chatHeader"],points:["reactor.ui.renderer","reactor.ui.toolBinding"],commands:[]},contributionPoints:[],settings:{},renderers:["mcp-ui"],catalog:"",components:[]},PROMPT_UI_0_0_1={id:"prompt",version:"0.0.1",name:"Floating composer",description:"The composer in a card you move over the page, and the commands that bring it back or start over.",emoji:"🪶",octicon:"paper-airplane",plugin:"@datalayer/loop-plugin-prompt",folder:"prompt",contributions:{slots:["loop.promptAction"],points:["loop.command"],commands:["new","prompt"]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},SUBAGENT_ACTIVITY_UI_0_0_1={id:"subagent-activity",version:"0.0.1",name:"Delegated work",description:"The face of an agent yours handed work to, pulsing while it works.",emoji:"👥",octicon:"people",plugin:"@datalayer/loop-plugin-subagent-activity",folder:"subagent-activity",contributions:{slots:["loop.inpromptMenu"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},WINDOW_FRAME_UI_0_0_1={id:"window-frame",version:"0.0.1",name:"Window",description:"Draws the editor as a window, with room in its title bar for controls and actions.",emoji:"🪟",octicon:"browser",plugin:"@datalayer/loop-plugin-window-frame",folder:"window-frame",contributions:{slots:["loop.header","loop.window.controls"],points:[],commands:[]},contributionPoints:[],settings:{},renderers:[],catalog:"",components:[]},UI_CATALOGUE={"a2ui-surface":A2UI_SURFACE_UI_0_0_1,"a2ui-view":A2UI_VIEW_UI_0_0_1,agentspecs:AGENTSPECS_UI_0_0_1,"app-activity":APP_ACTIVITY_UI_0_0_1,"app-components":APP_COMPONENTS_UI_0_0_1,"app-computer":APP_COMPUTER_UI_0_0_1,"app-elements":APP_ELEMENTS_UI_0_0_1,"app-page":APP_PAGE_UI_0_0_1,"app-rules":APP_RULES_UI_0_0_1,"canvas-blocks":CANVAS_BLOCKS_UI_0_0_1,"canvas-parts":CANVAS_PARTS_UI_0_0_1,"chat-extras":CHAT_EXTRAS_UI_0_0_1,"chat-header":CHAT_HEADER_UI_0_0_1,"chat-view":CHAT_VIEW_UI_0_0_1,chat:CHAT_UI_0_0_1,commands:COMMANDS_UI_0_0_1,"document-toolbar":DOCUMENT_TOOLBAR_UI_0_0_1,"document-view":DOCUMENT_VIEW_UI_0_0_1,document:DOCUMENT_UI_0_0_1,"input-prompt":INPUT_PROMPT_UI_0_0_1,models:MODELS_UI_0_0_1,"notebook-toolbar":NOTEBOOK_TOOLBAR_UI_0_0_1,"notebook-view":NOTEBOOK_VIEW_UI_0_0_1,notebook:NOTEBOOK_UI_0_0_1,"page-layout":PAGE_LAYOUT_UI_0_0_1,"pap-sign-in":PAP_SIGN_IN_UI_0_0_1,prompt:PROMPT_UI_0_0_1,"subagent-activity":SUBAGENT_ACTIVITY_UI_0_0_1,"window-frame":WINDOW_FRAME_UI_0_0_1};function listUI(){return Object.values(UI_CATALOGUE)}const COMPONENT_CATALOGUE=Object.fromEntries(Object.values(UI_CATALOGUE).flatMap(Au=>Au.components.map(lo=>[lo.id,lo]))),A2UI_UI_RENDERER_0_0_1={id:"a2ui",version:"0.0.1",name:"A2UI",description:"An agent describes an interface — a form, a table, a card — as a tree of components from a catalogue the host allows, and the host renders it; what the user does in it comes back to the agent as an action.",docsUrl:"https://a2ui.org/",enabled:!0},MCP_APPS_UI_RENDERER_0_0_1={id:"mcp-apps",version:"0.0.1",name:"MCP Apps",description:"An MCP server ships an interactive app with a tool: the host renders it in a sandboxed frame beside the conversation, and the app calls the server's tools through the host.",docsUrl:"https://modelcontextprotocol.io/docs/extensions/apps",enabled:!1},MCP_UI_UI_RENDERER_0_0_1={id:"mcp-ui",version:"0.0.1",name:"MCP UI",description:"An MCP tool answers with a UI resource — HTML, a remote page or a component — that the host renders in place of plain text.",docsUrl:"https://mcpui.dev/",enabled:!1},UI_RENDERER_CATALOGUE={a2ui:A2UI_UI_RENDERER_0_0_1,"mcp-apps":MCP_APPS_UI_RENDERER_0_0_1,"mcp-ui":MCP_UI_UI_RENDERER_0_0_1},DEFAULT_UPLOAD_MB=10,DEFAULT_MAX_FILES=5;function kindTakes(Au,lo){const $u=Au.trim().toLowerCase();if($u.startsWith("."))return lo.name.toLowerCase().endsWith($u);const Ru=(lo.type||"").split(";",1)[0].trim().toLowerCase();return $u.endsWith("/*")?Ru.startsWith($u.slice(0,-1)):Ru===$u}const acceptsFile=(Au,lo)=>!Au?.length||Au.some($u=>kindTakes($u,lo)),megabytes=Au=>`${(Au/(1024*1024)).toFixed(1)} MB`,uploadsAccept=Au=>Au.kinds.map(lo=>lo.type).join(",");function uploadsRefusal(Au,lo){if(lo.length===0)return null;const $u=Au.interface.uploads;if(!$u)return`${Au.name} takes no file sent with a message: its Appspec names none it takes (interface.uploads).`;if(lo.length>$u.maxFiles)return`${lo.length} files were sent at once: ${Au.name} takes at most ${$u.maxFiles}.`;for(const Ru of lo){const Iu=$u.kinds.find(Pu=>kindTakes(Pu.type,Ru));if(!Iu){const Pu=$u.kinds.map(Ou=>Ou.type).join(", ");return`${Ru.name} is not a kind of file ${Au.name} takes: it takes ${Pu}.`}if(Ru.size>Iu.maxMb*1024*1024)return`${Ru.name} is ${megabytes(Ru.size)}: ${Au.name} takes ${Iu.type} of at most ${Iu.maxMb} MB.`}return null}function uploadsInWords(Au){return`Takes ${Au.kinds.map($u=>`${$u.type} up to ${$u.maxMb} MB`).join(", ")}; ${Au.maxFiles} at most at once.`}const APP_SCHEMA="loop.app/v1",DEFAULT_LANGUAGE="en",DEFAULT_EMOJI="👀",APP_KINDS=["chat","widget","decision","worker"],APP_ACCENTS=["green","rose","sky","lime","sun","violet"],APP_THEME_VARIANTS=["datalayer","spatial","lovely","matrix","earth","sand","ivory","sun","loop"],APP_THEME_MODES=["light","dark","auto"],APP_EMBED_MODES=["inline","bubble","panel","assistant"],APP_ASSISTANT_CHARACTER_ID=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function isAssistantCharacterId(Au){return typeof Au=="string"&&Au.length<=64&&APP_ASSISTANT_CHARACTER_ID.test(Au)}const ACTION_CLASS_NAMES=["read","write","send","buy","delete","publish"],DEFAULT_LAYOUTS={chat:"chat",widget:"page",decision:"page",worker:"split"},A2UI_OUTPUT="application/json+a2ui";function uiFor(Au,lo={}){if(Au==="decision")return[{plugin:"app-page"}];const $u=[{plugin:"chat"}];return lo.outputs?.includes(A2UI_OUTPUT)&&$u.push({plugin:"a2ui-surface",renderer:"a2ui"}),lo.signsIn&&$u.push({plugin:"pap-sign-in"}),(lo.layout??DEFAULT_LAYOUTS[Au])!=="chat"&&$u.push({plugin:"page-layout"},{plugin:"app-page"},{plugin:"canvas-blocks"}),lo.ownComponents&&$u.push({plugin:"app-components"}),$u}const DEFAULT_RECORD_INCLUDE=["conversations","actions","approvals"],DEFAULT_KEEP_FOR="1_years",DEFAULT_READY_AT=.8,DEFAULT_PROTOCOL="a2ui/v0.9",DEFAULT_ICON="apps",DEFAULT_VERSION="0.0.1",NO_HOST_PARAMETERS={type:"object",properties:{}},isData=Au=>!!Au&&typeof Au=="object"&&!Array.isArray(Au),text$k=(Au,lo="")=>typeof Au=="string"?Au:lo,flag=(Au,lo)=>typeof Au=="boolean"?Au:lo,numberOf=(Au,lo)=>typeof Au=="number"&&Number.isFinite(Au)?Au:lo,texts=Au=>Array.isArray(Au)?Au.filter(lo=>typeof lo=="string"):[],records=Au=>Array.isArray(Au)?Au.filter(isData):[],uiChoices=Au=>Array.isArray(Au)?Au.filter(isData).map(lo=>({plugin:text$k(lo.plugin),...text$k(lo.renderer)?{renderer:text$k(lo.renderer)}:{}})):[],uiShapeProblems=Au=>Array.isArray(Au)?Au.filter(lo=>!isData(lo)).map(lo=>`\`ui\` lists UI plugins, each as \`{plugin, renderer}\`: ${JSON.stringify(lo)} is not one`+(typeof lo=="string"&&UI_RENDERER_CATALOGUE[lo]?` (${JSON.stringify(lo)} is a UI renderer: name the plugin it renders, and say it as its \`renderer\`).`:".")):[];function parseTestTurn(Au){return{...text$k(Au.say)?{say:text$k(Au.say)}:{},...text$k(Au.choose)?{choose:text$k(Au.choose)}:{},...text$k(Au.press)?{press:text$k(Au.press)}:{},...isData(Au.payload)&&Object.keys(Au.payload).length?{payload:{...Au.payload}}:{}}}const oneOf$3=(Au,lo,$u)=>lo.includes(Au)?Au:$u,RETENTION$1=/^([1-9]\d*)_(day|days|month|months|year|years)$/,DAYS={day:1,month:30,year:365};function retentionDays(Au){const lo=RETENTION$1.exec(Au.trim());return lo?Number(lo[1])*DAYS[lo[2].replace(/s$/,"")]:0}function emptyAppspec(Au="chat"){return{schema:APP_SCHEMA,id:"",version:DEFAULT_VERSION,name:"",kind:Au,description:"",owner:"",agent:"",team:"",instructions:"",model:"",skills:[],backendTools:[],context:[],contents:[],connections:[],protocols:[],ui:uiFor(Au),rules:[],permissions:{spaces:[],computer:{browse:!1,files:!1,shell:!1}},interface:{layout:DEFAULT_LAYOUTS[Au],welcome:"",starters:[],commands:[],modes:[],actions:[],profiles:[],language:DEFAULT_LANGUAGE,translations:{},components:[],outputs:[]},tests:{readyAt:DEFAULT_READY_AT,evalset:"",cases:[],verified:{live:[],recorded:[],unverified:[]}},record:{keepFor:DEFAULT_KEEP_FOR,retentionDays:retentionDays(DEFAULT_KEEP_FOR),include:[...DEFAULT_RECORD_INCLUDE],suggestTests:!1},checks:{guards:[],gates:[],track:""},deployment:{},goal:"",triggers:[],memory:"",notifications:[],samples:{documents:[],alternatives:[]},setup:[],enabled:!0,unavailable_because:"",tags:[],icon:DEFAULT_ICON,emoji:DEFAULT_EMOJI,avatar:"",banner:""}}const KNOWN_KEYS=["schema","id","version","name","kind","description","owner","agent","team","instructions","model","skills","backend_tools","tools","context","contents","connections","protocols","ui","pap","pact","commerce","signed_fetch","pair","a2a","rules","permissions","interface","tests","record","checks","deployment","goal","triggers","memory","notifications","decision","samples","enabled","unavailable_because","tags","icon","emoji","avatar","banner"],CHECK_STAGES=["answer","tool_call"];function parseTool(Au){return{name:text$k(Au.name),description:text$k(Au.description),parameters:isData(Au.parameters)?Au.parameters:{...NO_HOST_PARAMETERS},does:texts(Au.does)}}function parseConnection(Au){return{server:text$k(Au.server),access:oneOf$3(Au.access,["read","write"],"read"),as:oneOf$3(Au.as,["owner","user"],"owner"),only:texts(Au.only)}}const PAP_PROFILES=["draft-01"],PAP_PROFILE=PAP_PROFILES[PAP_PROFILES.length-1];function papProfileProblem(Au){if(Au==null||Au==="")return`Its \`pap\` block names no Personal Agent Protocol profile: add \`profile: ${PAP_PROFILE}\`.`;if(!PAP_PROFILES.includes(Au))return`This application asks for Personal Agent Protocol profile “${String(Au)}”; Datalayer speaks ${PAP_PROFILES.join(" or ")}.`}const PAP_INTERFACES=["agent","openapi","mcp","web"],PAP_SIGN_IN=["direct","device","mediated"],PAP_DEFAULT_INTERFACES=["agent"],PAP_DEFAULT_SIGN_IN=["direct","device"],enumsOf=(Au,lo,$u)=>Array.isArray(Au)?Au.filter(Ru=>lo.includes(Ru)):[...$u];function parsePap(Au){const lo=isData(Au.company)?Au.company:{};return{profile:Au.profile,connections:records(Au.connections).map($u=>({id:text$k($u.id),company:text$k($u.company),access:oneOf$3($u.access,["read","write"],"read"),as:oneOf$3($u.as,["owner","user"],"user"),scopes:texts($u.scopes),interfaces:enumsOf($u.interfaces,PAP_INTERFACES,PAP_DEFAULT_INTERFACES),signIn:enumsOf($u.sign_in,PAP_SIGN_IN,PAP_DEFAULT_SIGN_IN),extensions:texts($u.extensions)})),company:{enabled:flag(lo.enabled,!1),signedOut:flag(lo.signed_out,!0),interfaces:enumsOf(lo.interfaces,PAP_INTERFACES,PAP_DEFAULT_INTERFACES),scopes:texts(lo.scopes),extensions:texts(lo.extensions),personalAgents:oneOf$3(lo.personal_agents,["any","registered"],"any"),registeredAgents:texts(lo.registered_agents),operations:records(lo.operations).map($u=>({action:text$k($u.action),tool:text$k($u.tool),...isData($u.allows)?{allows:parsePapStanding($u.allows)}:{},summary:text$k($u.summary),userApprovalRequired:flag($u.user_approval_required,!0)}))}}}function parsePapStanding(Au){return{connection:text$k(Au.connection),action:oneOf$3(Au.action,["write","buy"],"buy"),limits:records(Au.limits).map(lo=>({path:text$k(lo.path),...typeof lo.maximum=="string"?{maximum:text$k(lo.maximum)}:{},...typeof lo.allowed=="string"?{allowed:text$k(lo.allowed)}:{}})),uses:text$k(Au.uses),days:text$k(Au.days)}}function dumpPapStanding(Au){return{connection:Au.connection,action:Au.action,limits:Au.limits.map(lo=>({path:lo.path,...lo.maximum!==void 0?{maximum:lo.maximum}:{},...lo.allowed!==void 0?{allowed:lo.allowed}:{}})),uses:Au.uses,days:Au.days}}function dumpPap(Au){return Au?new Writer().text("profile",Au.profile,"\0").list("connections",Au.connections.map(lo=>new Writer().text("id",lo.id,"\0").text("company",lo.company,"\0").value("access",lo.access,"read").value("as",lo.as,"user").list("scopes",lo.scopes).list("interfaces",lo.interfaces,[...PAP_DEFAULT_INTERFACES]).list("sign_in",lo.signIn,[...PAP_DEFAULT_SIGN_IN]).list("extensions",lo.extensions).data)).part("company",new Writer().value("enabled",Au.company.enabled,!1).value("signed_out",Au.company.signedOut,!0).list("interfaces",Au.company.interfaces,[...PAP_DEFAULT_INTERFACES]).list("scopes",Au.company.scopes).list("extensions",Au.company.extensions).value("personal_agents",Au.company.personalAgents,"any").list("registered_agents",Au.company.registeredAgents).list("operations",Au.company.operations.map(lo=>new Writer().text("action",lo.action,"\0").text("tool",lo.tool,lo.allows?"":"\0").present("allows",lo.allows?dumpPapStanding(lo.allows):void 0).text("summary",lo.summary,"\0").value("user_approval_required",lo.userApprovalRequired,!0).data)).data).data:{}}function parsePact(Au){const lo=isData(Au.business)?Au.business:{},$u={};if(isData(lo.scopes))for(const[Ru,Iu]of Object.entries(lo.scopes))$u[Ru]=text$k(Iu);return{connections:records(Au.connections).map(Ru=>({id:text$k(Ru.id),brand:text$k(Ru.brand),audience:text$k(Ru.audience),access:oneOf$3(Ru.access,["read","write"],"read"),scopes:texts(Ru.scopes)})),business:{enabled:flag(lo.enabled,!1),brand:text$k(lo.brand),scopes:$u,registeredAgents:records(lo.registered_agents).map(Ru=>({issuer:text$k(Ru.issuer),jwksUri:text$k(Ru.jwks_uri)}))}}}function parseCommerce(Au){return{merchants:records(Au.merchants).map(lo=>({id:text$k(lo.id),protocol:oneOf$3(lo.protocol,["ucp","acp"],"ucp"),merchant:text$k(lo.merchant),access:oneOf$3(lo.access,["read","write"],"read"),...isData(lo.limit)?{limit:{amount:text$k(lo.limit.amount),currency:text$k(lo.limit.currency)}}:{}}))}}function dumpCommerce(Au){return Au?new Writer().list("merchants",Au.merchants.map(lo=>new Writer().text("id",lo.id,"\0").text("protocol",lo.protocol,"\0").text("merchant",lo.merchant,"\0").value("access",lo.access,"read").part("limit",lo.limit?{amount:lo.limit.amount,currency:lo.limit.currency}:{}).data)).data:{}}function parseSignedFetch(Au){return{sites:records(Au.sites).map(lo=>({id:text$k(lo.id),site:text$k(lo.site)}))}}function dumpSignedFetch(Au){return Au?new Writer().list("sites",Au.sites.map(lo=>new Writer().text("id",lo.id,"\0").text("site",lo.site,"\0").data)).data:{}}function parsePair(Au){const lo=text$k(Au.id),$u=text$k(Au.role);return/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(lo)?$u!=="business"&&$u!=="personal_agent"?`One of a pair is its business or its personal_agent, not ${JSON.stringify($u)}.`:{id:lo,role:$u}:`A pair's id is lower-case letters, digits and hyphens: ${JSON.stringify(lo)}.`}function dumpPact(Au){if(!Au)return{};const lo=Au.business??{enabled:!1,brand:"",scopes:{},registeredAgents:[]};return new Writer().list("connections",Au.connections.map($u=>new Writer().text("id",$u.id,"\0").text("brand",$u.brand,"\0").text("audience",$u.audience,"\0").value("access",$u.access,"read").list("scopes",$u.scopes).data)).part("business",new Writer().value("enabled",lo.enabled,!1).text("brand",lo.brand).part("scopes",{...lo.scopes}).list("registered_agents",lo.registeredAgents.map($u=>new Writer().text("issuer",$u.issuer,"\0").text("jwks_uri",$u.jwksUri,"\0").data)).data).data}function parseA2A(Au){return{extensions:records(Au.extensions).map(lo=>({uri:text$k(lo.uri),description:text$k(lo.description),required:flag(lo.required,!1),params:isData(lo.params)?{...lo.params}:{}}))}}function dumpA2A(Au){return Au?new Writer().list("extensions",Au.extensions.map(lo=>new Writer().text("uri",lo.uri,"\0").text("description",lo.description).value("required",lo.required,!1).part("params",lo.params).data)).data:{}}function parseRule$1(Au){return{action:text$k(Au.action),appliesTo:typeof Au.applies_to=="string"?[Au.applies_to]:texts(Au.applies_to),behaviour:oneOf$3(Au.behaviour,BEHAVIOURS,"ask_first")}}function parseAction(Au){const lo={name:text$k(Au.name)};return text$k(Au.description)&&(lo.description=text$k(Au.description)),isData(Au.payload)&&(lo.payload=JSON.parse(JSON.stringify(Au.payload))),lo}function parseCommand$1(Au){return{name:text$k(Au.name),description:text$k(Au.description),prompt:text$k(Au.prompt)}}function parseModeOption(Au){const lo={id:text$k(Au.id),label:text$k(Au.label)};for(const $u of["description","instructions","model"])typeof Au[$u]=="string"&&Au[$u]&&(lo[$u]=Au[$u]);return lo}function parseMode(Au){const lo={id:text$k(Au.id),label:text$k(Au.label),options:records(Au.options).map(parseModeOption)};return typeof Au.default=="string"&&Au.default&&(lo.default=Au.default),lo}function parseStarter(Au){const lo={label:text$k(Au.label),message:text$k(Au.message)};return typeof Au.category=="string"&&Au.category&&(lo.category=Au.category),lo}function parseProfile(Au){return{id:text$k(Au.id),label:text$k(Au.label),description:text$k(Au.description),instructions:text$k(Au.instructions),model:typeof Au.model=="string"&&Au.model?Au.model:null,starters:records(Au.starters).map(parseStarter)}}function wordsBy(Au){return Object.fromEntries(Object.entries(isData(Au)?Au:{}).filter(lo=>typeof lo[1]=="string"))}function recordsBy(Au){return Object.fromEntries(Object.entries(isData(Au)?Au:{}).filter(lo=>isData(lo[1])))}const mapValues=(Au,lo)=>Object.fromEntries(Object.entries(Au).map(([$u,Ru])=>[$u,lo(Ru)]));function parseTranslation(Au){return{name:text$k(Au.name),description:text$k(Au.description),welcome:text$k(Au.welcome),starters:mapValues(recordsBy(Au.starters),lo=>({label:text$k(lo.label),message:text$k(lo.message)})),categories:wordsBy(Au.categories),settings:mapValues(recordsBy(Au.settings),lo=>({title:text$k(lo.title),description:text$k(lo.description),options:wordsBy(lo.options)})),commands:wordsBy(Au.commands),modes:mapValues(recordsBy(Au.modes),lo=>({label:text$k(lo.label),options:mapValues(recordsBy(lo.options),$u=>({label:text$k($u.label),description:text$k($u.description)}))})),profiles:mapValues(recordsBy(Au.profiles),lo=>({label:text$k(lo.label),description:text$k(lo.description)}))}}function parseSurface(Au){return{protocol:text$k(Au.protocol,DEFAULT_PROTOCOL),components:records(Au.components).filter(lo=>typeof lo.id=="string"&&typeof lo.component=="string"),composedBy:text$k(Au.composed_by),composedAt:text$k(Au.composed_at)}}const DEFAULT_VOICE={enabled:!1,input:"push_to_talk",output:"on_request",where:"auto"};function parseVoice(Au){const lo=isData(Au)?Au:{};return{enabled:lo.enabled===!0,input:oneOf$3(lo.input,["off","push_to_talk","hands_free"],DEFAULT_VOICE.input),output:oneOf$3(lo.output,["off","on_request","always"],DEFAULT_VOICE.output),voice:text$k(lo.voice),language:text$k(lo.language),where:oneOf$3(lo.where,["auto","device","server"],DEFAULT_VOICE.where)}}function parseUploads(Au){return{kinds:records(Au.kinds).map(lo=>({type:text$k(lo.type),maxMb:numberOf(lo.max_mb,DEFAULT_UPLOAD_MB)})),maxFiles:numberOf(Au.max_files,DEFAULT_MAX_FILES)}}const PAGE_OUTPUT_SHOWS={Text:"text",Image:"url",Table:"rows",Chart:"points"},DEFAULT_CUSTOM_HEIGHT=240;function parseCustomComponent(Au){const lo={name:text$k(Au.name),description:text$k(Au.description),props:isData(Au.props)?JSON.parse(JSON.stringify(Au.props)):{type:"object",properties:{}},shows:texts(Au.shows),sends:texts(Au.sends),source:text$k(Au.source),integrity:text$k(Au.integrity),height:numberOf(Au.height,DEFAULT_CUSTOM_HEIGHT)};return isData(Au.example)&&(lo.example=JSON.parse(JSON.stringify(Au.example))),lo}function dumpCustomComponent(Au){const lo=new Writer().text("name",Au.name,"\0").text("description",Au.description,"\0");return lo.data.props=JSON.parse(JSON.stringify(Au.props)),lo.list("shows",Au.shows).list("sends",Au.sends).text("source",Au.source,"\0").text("integrity",Au.integrity).value("height",Au.height,DEFAULT_CUSTOM_HEIGHT),Au.example&&(lo.data.example=JSON.parse(JSON.stringify(Au.example))),lo.data}function pageOutputShows(Au,lo=[]){return Au in PAGE_OUTPUT_SHOWS?PAGE_OUTPUT_SHOWS[Au]:lo.find($u=>$u.name===Au)?.shows[0]}function parsePage(Au){const lo={function:text$k(Au.function),inputs:isData(Au.inputs)?JSON.parse(JSON.stringify(Au.inputs)):{},outputs:records(Au.outputs).map($u=>({name:text$k($u.name),title:text$k($u.title),component:text$k($u.component,"Text"),props:isData($u.props)?JSON.parse(JSON.stringify($u.props)):{}})),live:Au.live!==!1};return isData(Au.inputs_ui)&&(lo.inputsUi=JSON.parse(JSON.stringify(Au.inputs_ui))),lo}function dumpPage(Au){const lo=new Writer().text("function",Au.function,"\0");return lo.data.inputs=JSON.parse(JSON.stringify(Au.inputs)),Au.inputsUi&&(lo.data.inputs_ui={...Au.inputsUi}),lo.list("outputs",Au.outputs.map($u=>new Writer().text("name",$u.name,"\0").text("title",$u.title).text("component",$u.component,"Text").part("props",{...$u.props}).data)),lo.value("live",Au.live,!0).data}function parseInterface(Au,lo){const $u={layout:oneOf$3(Au.layout,["chat","page","split"],DEFAULT_LAYOUTS[lo]),accent:APP_ACCENTS.includes(Au.accent)?Au.accent:void 0,welcome:text$k(Au.welcome),starters:records(Au.starters).map(parseStarter),commands:records(Au.commands).map(parseCommand$1),modes:records(Au.modes).map(parseMode),actions:records(Au.actions).map(parseAction),profiles:records(Au.profiles).map(parseProfile),language:text$k(Au.language,DEFAULT_LANGUAGE),translations:mapValues(recordsBy(Au.translations),parseTranslation),components:texts(Au.components),voice:parseVoice(Au.voice),outputs:texts(Au.outputs)};return isData(Au.settings)&&($u.settings=JSON.parse(JSON.stringify(Au.settings))),isData(Au.settings_ui)&&($u.settingsUi=JSON.parse(JSON.stringify(Au.settings_ui))),isData(Au.uploads)&&($u.uploads=parseUploads(Au.uploads)),Array.isArray(Au.custom_components)&&($u.customComponents=records(Au.custom_components).map(parseCustomComponent)),isData(Au.surface)&&($u.surface=parseSurface(Au.surface)),isData(Au.page)&&($u.page=parsePage(Au.page)),isAssistantCharacterId(Au.assistant)&&($u.assistant=Au.assistant),(Au.balloon==="history"||Au.balloon==="current")&&($u.balloon=Au.balloon),isData(Au.theme)&&APP_THEME_VARIANTS.includes(Au.theme.variant)&&($u.theme={variant:Au.theme.variant},APP_THEME_MODES.includes(Au.theme.mode)&&($u.theme.mode=Au.theme.mode)),$u}function parseCriterion(Au){return{name:text$k(Au.name),kind:oneOf$3(Au.kind,["metric","noul","choice","score"],"metric"),weight:Math.max(0,numberOf(Au.weight,1)),instructions:text$k(Au.instructions),options:texts(Au.options),direction:Au.direction==="lower"?"lower":"higher",measure:oneOf$3(Au.measure,["","pass_rate","cost_per_task","seconds_per_task"],"")}}function parseDecision(Au){return{question:text$k(Au.question),alternatives:texts(Au.alternatives),criteria:records(Au.criteria).map(parseCriterion),minConfidence:Math.min(1,Math.max(0,numberOf(Au.min_confidence,0))),scenarios:records(Au.scenarios).map(lo=>({name:text$k(lo.name),weights:Object.fromEntries(Object.entries(isData(lo.weights)?lo.weights:{}).filter($u=>typeof $u[1]=="number"))})),decisionModel:text$k(Au.decision_model)}}function parseSamples(Au){return{documents:records(Au.documents).map(lo=>({name:text$k(lo.name),file:text$k(lo.file),text:text$k(lo.text)})),alternatives:records(Au.alternatives).map(lo=>({name:text$k(lo.name),evidence:text$k(lo.evidence),metrics:Object.fromEntries(Object.entries(isData(lo.metrics)?lo.metrics:{}).filter($u=>typeof $u[1]=="number"))}))}}function parseDeployment(Au){const lo={};return isData(Au.hosted)&&(lo.hosted={visibility:oneOf$3(Au.hosted.visibility,["private","invited","organization","link","public"],"private"),slug:text$k(Au.hosted.slug),...Au.hosted.character_alone===!0?{characterAlone:!0}:{}}),isData(Au.embedded)&&(lo.embedded={mode:oneOf$3(Au.embedded.mode,APP_EMBED_MODES,"inline"),origins:texts(Au.embedded.origins),...isData(Au.embedded.host)?{host:{context:texts(Au.embedded.host.context),...Au.embedded.host.user!==void 0?{user:text$k(Au.embedded.host.user)}:{},functions:records(Au.embedded.host.functions).map($u=>({name:text$k($u.name),description:text$k($u.description),parameters:isData($u.parameters)?$u.parameters:{...NO_HOST_PARAMETERS}}))}}:{}}),lo}function parseTrigger(Au){return{type:oneOf$3(Au.type,["schedule","event","once"],"schedule"),cron:text$k(Au.cron),event:text$k(Au.event),at:text$k(Au.at),description:text$k(Au.description),prompt:text$k(Au.prompt)}}function parseAppspec(Au){const lo=[];if(!isData(Au))return{app:emptyAppspec(),problems:["The document is not an application."]};const $u=Au;for(const Uu of Object.keys($u))KNOWN_KEYS.includes(Uu)||lo.push(`\`${Uu}\` is not a field of the spec.`);lo.push(...uiShapeProblems($u.ui));const Ru=text$k($u.schema,APP_SCHEMA);Ru!==APP_SCHEMA&&lo.push(`This reads ${APP_SCHEMA}; the application is written in ${Ru}.`),APP_KINDS.includes($u.kind)||lo.push($u.kind===void 0?"The application does not say its `kind`.":`\`${String($u.kind)}\` is not a kind: chat, widget, decision or worker.`);const Iu=oneOf$3($u.kind,APP_KINDS,"chat"),Pu=emptyAppspec(Iu),Ou=isData($u.permissions)?$u.permissions:{},Mu=isData(Ou.computer)?Ou.computer:{},Du=isData($u.tests)?$u.tests:{},Lu=isData(Du.verified)?Du.verified:{},Bu=isData($u.record)?$u.record:{},ju=isData($u.checks)?$u.checks:{};for(const Uu of records(ju.code))CHECK_STAGES.includes(Uu.on)||lo.push(`The check \`${text$k(Uu.name)}\` of its code runs on answer or tool_call, not \`${String(Uu.on)}\`.`);const Fu=text$k(Bu.keep_for,DEFAULT_KEEP_FOR);retentionDays(Fu)===0&&lo.push(`Cannot read the retention \`${Fu}\`: write 90_days, 18_months or 1_years.`);const zu={...Pu,schema:APP_SCHEMA,id:text$k($u.id),version:text$k($u.version,DEFAULT_VERSION),name:text$k($u.name),kind:Iu,description:text$k($u.description),owner:text$k($u.owner),agent:text$k($u.agent),team:text$k($u.team),instructions:text$k($u.instructions),model:text$k($u.model),skills:texts($u.skills),backendTools:texts($u.backend_tools),tools:records($u.tools).map(parseTool),context:texts($u.context),contents:texts($u.contents),connections:records($u.connections).map(parseConnection),protocols:texts($u.protocols),ui:uiChoices($u.ui),rules:records($u.rules).map(parseRule$1),permissions:{spaces:records(Ou.spaces).map(Uu=>({space:text$k(Uu.space),access:oneOf$3(Uu.access,["read","write"],"read")})),computer:{browse:flag(Mu.browse,!1),files:flag(Mu.files,!1),shell:flag(Mu.shell,!1)}},interface:parseInterface(isData($u.interface)?$u.interface:{},Iu),tests:{readyAt:Math.min(1,Math.max(0,numberOf(Du.ready_at,DEFAULT_READY_AT))),evalset:text$k(Du.evalset),cases:records(Du.cases).map(Uu=>({ask:text$k(Uu.ask),...records(Uu.turns).length?{turns:records(Uu.turns).map(parseTestTurn)}:{},expect:text$k(Uu.expect),...text$k(Uu.code)?{code:text$k(Uu.code)}:{},...records(Uu.files).length?{files:records(Uu.files).map(Hu=>({name:text$k(Hu.name),text:text$k(Hu.text)}))}:{}})),verified:{live:texts(Lu.live),recorded:texts(Lu.recorded),unverified:texts(Lu.unverified)}},record:{keepFor:Fu,retentionDays:retentionDays(Fu),include:Array.isArray(Bu.include)?texts(Bu.include):[...DEFAULT_RECORD_INCLUDE],suggestTests:Bu.suggest_tests===!0},checks:{guards:texts(ju.guards),gates:texts(ju.gates),track:text$k(ju.track),code:records(ju.code).map(Uu=>({name:text$k(Uu.name),on:oneOf$3(Uu.on,CHECK_STAGES,"answer"),description:text$k(Uu.description)}))},deployment:parseDeployment(isData($u.deployment)?$u.deployment:{}),goal:text$k($u.goal),triggers:records($u.triggers).map(parseTrigger),memory:text$k($u.memory),notifications:texts($u.notifications),samples:parseSamples(isData($u.samples)?$u.samples:{}),enabled:flag($u.enabled,!0),unavailable_because:text$k($u.unavailable_because),tags:texts($u.tags),icon:text$k($u.icon,DEFAULT_ICON),emoji:text$k($u.emoji,DEFAULT_EMOJI)||DEFAULT_EMOJI,avatar:text$k($u.avatar).trim(),banner:text$k($u.banner).trim()};if(isData($u.decision)&&(zu.decision=parseDecision($u.decision)),isData($u.pap)&&Object.keys($u.pap).length>0){const Uu=papProfileProblem($u.pap.profile);Uu?lo.push(Uu):zu.pap=parsePap($u.pap)}if(isData($u.pact)&&(zu.pact=parsePact($u.pact)),isData($u.commerce)&&(zu.commerce=parseCommerce($u.commerce)),isData($u.signed_fetch)&&(zu.signed_fetch=parseSignedFetch($u.signed_fetch)),isData($u.pair)){const Uu=parsePair($u.pair);typeof Uu=="string"?lo.push(Uu):zu.pair=Uu}return isData($u.a2a)&&(zu.a2a=parseA2A($u.a2a)),lo.push(...protocolsProblems(zu),...uiProblems(zu)),{app:zu,problems:lo}}function uiProblems(Au){const lo=[],$u=[];for(const Ru of Au.ui){const Iu=Ru.plugin;if($u.includes(Iu)){lo.push(`It lists the UI plugin '${Iu}' twice.`);continue}$u.push(Iu);const Pu=UI_CATALOGUE[Iu];if(!Pu){lo.push(`There is no UI plugin named '${Iu}': one of ${Object.keys(UI_CATALOGUE).sort().join(", ")}.`+(UI_RENDERER_CATALOGUE[Iu]?` '${Iu}' is a UI renderer: say it as a plugin's \`renderer\`.`:""));continue}if(Ru.renderer===void 0)continue;const Ou=UI_RENDERER_CATALOGUE[Ru.renderer];Ou?Pu.renderers.includes(Ou.id)?Au.enabled&&!Ou.enabled&&lo.push(`The UI renderer ${Ou.name} ('${Ou.id}') is not enabled: an application cannot be exposed through it yet.`):lo.push(`The UI plugin ${Pu.name} ('${Iu}') is not exposed through ${Ou.name}: `+(Pu.renderers.length>0?`through ${Pu.renderers.join(", ")} only.`:"through no renderer.")):lo.push(`There is no UI renderer named '${Ru.renderer}': one of ${Object.keys(UI_RENDERER_CATALOGUE).sort().join(", ")}.`)}return lo}function protocolsProblems(Au){const lo=[],$u=[];for(const Iu of Au.protocols){if($u.includes(Iu)){lo.push(`It lists the protocol '${Iu}' twice.`);continue}$u.push(Iu);const Pu=PROTOCOL_CATALOGUE[Iu];Pu?Au.enabled&&Pu.status==="planned"&&lo.push(`${Pu.name} ('${Iu}') is planned, not shipped: an application cannot speak it yet.`):lo.push(`There is no protocol named '${Iu}': one of ${Object.keys(PROTOCOL_CATALOGUE).sort().join(", ")}.`)}const Ru={pap:!!(Au.pap&&(Au.pap.connections.length>0||Au.pap.company.enabled)),pact:!!(Au.pact&&(Au.pact.connections.length>0||Au.pact.business?.enabled)),a2a:!!(Au.a2a&&Au.a2a.extensions.length>0),signed_fetch:!!(Au.signed_fetch&&Au.signed_fetch.sites.length>0)};for(const Iu of Object.values(PROTOCOL_CATALOGUE)){const Pu=Iu.appspecBlock;Pu&&Ru[Pu]&&!Au.protocols.includes(Iu.id)&&lo.push(`Its \`${Pu}\` block configures ${Iu.name}, which it does not list: add '${Iu.id}' to \`protocols\`.`)}for(const Iu of new Set((Au.commerce?.merchants??[]).map(Pu=>Pu.protocol)))Au.protocols.includes(Iu)||lo.push(`Its \`commerce\` block shops over ${Iu.toUpperCase()}, which it does not list: add '${Iu}' to \`protocols\`.`);return lo}const sameList=(Au,lo)=>Au.length===lo.length&&Au.every(($u,Ru)=>$u===lo[Ru]);class Writer{data={};text(lo,$u,Ru=""){return $u!==Ru&&(this.data[lo]=$u),this}value(lo,$u,Ru){return $u!==Ru&&(this.data[lo]=$u),this}list(lo,$u,Ru=[]){return sameList($u,Ru)||(this.data[lo]=$u),this}part(lo,$u){return Object.keys($u).length>0&&(this.data[lo]=$u),this}present(lo,$u){return $u!==void 0&&(this.data[lo]=$u),this}}function sorted(Au){return Array.isArray(Au)?Au.map(sorted):isData(Au)?Object.fromEntries(Object.keys(Au).sort((lo,$u)=>lo<$u?-1:lo>$u?1:0).map(lo=>[lo,sorted(Au[lo])])):Au}function dumpComponent(Au){const{id:lo,component:$u,...Ru}=Au;return{id:lo,component:$u,...sorted(Ru)}}function dumpSurface(Au){return new Writer().text("protocol",Au.protocol,DEFAULT_PROTOCOL).list("components",Au.components.map(dumpComponent)).text("composed_by",Au.composedBy).text("composed_at",Au.composedAt).data}function dumpStarter(Au){return new Writer().text("label",Au.label,"\0").text("message",Au.message,"\0").text("category",Au.category??"").data}const saidWords=Au=>Object.fromEntries(Object.entries(Au).filter(([,lo])=>lo!==""));function dumpTranslation(Au){const lo=($u,Ru)=>Object.fromEntries(Object.entries($u).map(([Iu,Pu])=>[Iu,Ru(Pu)]));return new Writer().text("name",Au.name).text("description",Au.description).text("welcome",Au.welcome).part("starters",lo(Au.starters,$u=>new Writer().text("label",$u.label).text("message",$u.message).data)).part("categories",saidWords(Au.categories)).part("settings",lo(Au.settings,$u=>new Writer().text("title",$u.title).text("description",$u.description).part("options",saidWords($u.options)).data)).part("commands",saidWords(Au.commands)).part("modes",lo(Au.modes,$u=>new Writer().text("label",$u.label).part("options",lo($u.options,Ru=>new Writer().text("label",Ru.label).text("description",Ru.description).data)).data)).part("profiles",lo(Au.profiles,$u=>new Writer().text("label",$u.label).text("description",$u.description).data)).data}function dumpInterface(Au,lo){const $u=new Writer().value("layout",Au.layout,DEFAULT_LAYOUTS[lo]).value("accent",Au.accent,void 0).text("welcome",Au.welcome).list("starters",Au.starters.map(dumpStarter)).list("commands",Au.commands.map(Ru=>({name:Ru.name,description:Ru.description,prompt:Ru.prompt}))).list("modes",Au.modes.map(Ru=>{const Iu=new Writer().text("id",Ru.id,"\0").text("label",Ru.label,"\0").list("options",Ru.options.map(Pu=>new Writer().text("id",Pu.id,"\0").text("label",Pu.label,"\0").text("description",Pu.description??"").text("instructions",Pu.instructions??"").text("model",Pu.model??"").data));return Ru.default&&(Iu.data.default=Ru.default),Iu.data})).list("actions",(Au.actions??[]).map(Ru=>{const Iu=new Writer().text("name",Ru.name,"\0").text("description",Ru.description??"");return Ru.payload&&(Iu.data.payload={...Ru.payload}),Iu.data})).list("profiles",(Au.profiles??[]).map(Ru=>new Writer().text("id",Ru.id,"\0").text("label",Ru.label,"\0").text("description",Ru.description).text("instructions",Ru.instructions).text("model",Ru.model??"").list("starters",Ru.starters.map(dumpStarter)).data)).part("settings",Au.settings?{...Au.settings}:{});return Au.settingsUi&&($u.data.settings_ui={...Au.settingsUi}),$u.text("language",Au.language??DEFAULT_LANGUAGE,DEFAULT_LANGUAGE).part("translations",mapValues(Au.translations??{},dumpTranslation)),Au.uploads&&($u.data.uploads=new Writer().list("kinds",Au.uploads.kinds.map(Ru=>new Writer().text("type",Ru.type,"\0").value("max_mb",Ru.maxMb,DEFAULT_UPLOAD_MB).data)).value("max_files",Au.uploads.maxFiles,DEFAULT_MAX_FILES).data),$u.list("components",Au.components),$u.list("custom_components",(Au.customComponents??[]).map(dumpCustomComponent)),Au.surface&&($u.data.surface=dumpSurface(Au.surface)),Au.page&&($u.data.page=dumpPage(Au.page)),Au.assistant&&($u.data.assistant=Au.assistant),Au.balloon&&($u.data.balloon=Au.balloon),Au.theme&&($u.data.theme=Au.theme.mode?{variant:Au.theme.variant,mode:Au.theme.mode}:{variant:Au.theme.variant}),Au.voice&&$u.part("voice",new Writer().value("enabled",Au.voice.enabled,DEFAULT_VOICE.enabled).value("input",Au.voice.input,DEFAULT_VOICE.input).value("output",Au.voice.output,DEFAULT_VOICE.output).text("voice",Au.voice.voice).text("language",Au.voice.language).value("where",Au.voice.where,DEFAULT_VOICE.where).data),$u.list("outputs",Au.outputs??[]),$u.data}function dumpDecision(Au){return new Writer().text("question",Au.question,"\0").list("alternatives",Au.alternatives).list("criteria",Au.criteria.map(lo=>new Writer().text("name",lo.name,"\0").value("kind",lo.kind,"metric").value("weight",lo.weight,1).text("instructions",lo.instructions).list("options",lo.options).value("direction",lo.direction,"higher").value("measure",lo.measure,"").data)).value("min_confidence",Au.minConfidence,0).list("scenarios",Au.scenarios.map(lo=>new Writer().text("name",lo.name,"\0").part("weights",sorted(lo.weights)).data)).text("decision_model",Au.decisionModel).data}function dumpSamples(Au){return new Writer().list("documents",Au.documents.map(lo=>new Writer().text("name",lo.name,"\0").text("file",lo.file,"\0").text("text",lo.text,"\0").data)).list("alternatives",Au.alternatives.map(lo=>new Writer().text("name",lo.name,"\0").text("evidence",lo.evidence,"\0").part("metrics",{...lo.metrics}).data)).data}function dumpAppspec(Au){const lo=new Writer().value("browse",Au.permissions.computer.browse,!1).value("files",Au.permissions.computer.files,!1).value("shell",Au.permissions.computer.shell,!1).data,$u=new Writer;return $u.data.schema=APP_SCHEMA,$u.text("id",Au.id,"\0").text("version",Au.version,DEFAULT_VERSION).text("name",Au.name,"\0").text("kind",Au.kind,"\0").text("description",Au.description).text("owner",Au.owner).text("agent",Au.agent).text("team",Au.team).text("instructions",Au.instructions).text("model",Au.model).list("skills",Au.skills).list("backend_tools",Au.backendTools).list("tools",(Au.tools??[]).map(Ru=>({name:Ru.name,description:Ru.description,...JSON.stringify(Ru.parameters)===JSON.stringify(NO_HOST_PARAMETERS)?{}:{parameters:Ru.parameters},does:Ru.does}))).list("context",Au.context).list("contents",Au.contents).list("connections",Au.connections.map(Ru=>new Writer().text("server",Ru.server,"\0").value("access",Ru.access,"read").value("as",Ru.as,"owner").list("only",Ru.only).data)).list("protocols",Au.protocols).list("ui",Au.ui.map(Ru=>Ru.renderer?{plugin:Ru.plugin,renderer:Ru.renderer}:{plugin:Ru.plugin})).part("pap",dumpPap(Au.pap)).part("pact",dumpPact(Au.pact)).part("commerce",dumpCommerce(Au.commerce)).part("signed_fetch",dumpSignedFetch(Au.signed_fetch)).part("pair",Au.pair?{id:Au.pair.id,role:Au.pair.role}:{}).part("a2a",dumpA2A(Au.a2a)).list("rules",Au.rules.map(Ru=>({action:Ru.action,applies_to:Ru.appliesTo.length===1&&ACTION_CLASS_NAMES.includes(Ru.appliesTo[0])?Ru.appliesTo[0]:Ru.appliesTo,behaviour:Ru.behaviour}))).part("permissions",new Writer().list("spaces",Au.permissions.spaces.map(Ru=>new Writer().text("space",Ru.space,"\0").value("access",Ru.access,"read").data)).part("computer",lo).data).part("interface",dumpInterface(Au.interface,Au.kind)).part("tests",new Writer().value("ready_at",Au.tests.readyAt,DEFAULT_READY_AT).text("evalset",Au.tests.evalset).list("cases",Au.tests.cases.map(Ru=>({...Ru.turns?.length?{turns:Ru.turns.map(Iu=>parseTestTurn({...Iu}))}:{ask:Ru.ask},expect:Ru.expect,...Ru.code?{code:Ru.code}:{},...Ru.files?.length?{files:Ru.files.map(Iu=>({name:Iu.name,text:Iu.text}))}:{}}))).part("verified",new Writer().list("live",Au.tests.verified.live).list("recorded",Au.tests.verified.recorded).list("unverified",Au.tests.verified.unverified).data).data).part("record",new Writer().text("keep_for",Au.record.keepFor,DEFAULT_KEEP_FOR).list("include",Au.record.include,DEFAULT_RECORD_INCLUDE).value("suggest_tests",Au.record.suggestTests,!1).data).part("checks",new Writer().list("guards",Au.checks.guards).list("gates",Au.checks.gates).text("track",Au.checks.track).list("code",(Au.checks.code??[]).map(Ru=>({name:Ru.name,on:Ru.on,description:Ru.description}))).data).part("deployment",new Writer().present("hosted",Au.deployment.hosted&&new Writer().value("visibility",Au.deployment.hosted.visibility,"private").text("slug",Au.deployment.hosted.slug).value("character_alone",Au.deployment.hosted.characterAlone===!0,!1).data).present("embedded",Au.deployment.embedded&&new Writer().value("mode",Au.deployment.embedded.mode,"inline").list("origins",Au.deployment.embedded.origins).present("host",Au.deployment.embedded.host&&new Writer().list("context",Au.deployment.embedded.host.context).list("functions",Au.deployment.embedded.host.functions.map(Ru=>({name:Ru.name,description:Ru.description,...JSON.stringify(Ru.parameters)===JSON.stringify(NO_HOST_PARAMETERS)?{}:{parameters:Ru.parameters}}))).value("user",Au.deployment.embedded.host.user??"claimed","claimed").data).data).data).text("goal",Au.goal).list("triggers",Au.triggers.map(Ru=>new Writer().text("type",Ru.type,"\0").text("cron",Ru.cron).text("event",Ru.event).text("at",Ru.at).text("description",Ru.description).text("prompt",Ru.prompt).data)).text("memory",Au.memory).list("notifications",Au.notifications),Au.decision&&($u.data.decision=dumpDecision(Au.decision)),$u.part("samples",dumpSamples(Au.samples)).value("enabled",Au.enabled,!0).text("unavailable_because",Au.unavailable_because).list("tags",Au.tags).text("icon",Au.icon??DEFAULT_ICON,DEFAULT_ICON).text("emoji",Au.emoji,DEFAULT_EMOJI).text("avatar",Au.avatar??"","").text("banner",Au.banner??"",""),$u.data}const ALIAS=Symbol.for("yaml.alias"),DOC=Symbol.for("yaml.document"),MAP$1=Symbol.for("yaml.map"),PAIR=Symbol.for("yaml.pair"),SCALAR$1=Symbol.for("yaml.scalar"),SEQ=Symbol.for("yaml.seq"),NODE_TYPE$1=Symbol.for("yaml.node.type"),isAlias=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===ALIAS,isDocument=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===DOC,isMap=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===MAP$1,isPair=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===PAIR,isScalar=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===SCALAR$1,isSeq$1=Au=>!!Au&&typeof Au=="object"&&Au[NODE_TYPE$1]===SEQ;function isCollection(Au){if(Au&&typeof Au=="object")switch(Au[NODE_TYPE$1]){case MAP$1:case SEQ:return!0}return!1}function isNode$1(Au){if(Au&&typeof Au=="object")switch(Au[NODE_TYPE$1]){case ALIAS:case MAP$1:case SCALAR$1:case SEQ:return!0}return!1}const hasAnchor=Au=>(isScalar(Au)||isCollection(Au))&&!!Au.anchor,BREAK=Symbol("break visit"),SKIP$1=Symbol("skip children"),REMOVE=Symbol("remove node");function visit$4(Au,lo){const $u=initVisitor(lo);isDocument(Au)?visit_(null,Au.contents,$u,Object.freeze([Au]))===REMOVE&&(Au.contents=null):visit_(null,Au,$u,Object.freeze([]))}visit$4.BREAK=BREAK;visit$4.SKIP=SKIP$1;visit$4.REMOVE=REMOVE;function visit_(Au,lo,$u,Ru){const Iu=callVisitor(Au,lo,$u,Ru);if(isNode$1(Iu)||isPair(Iu))return replaceNode(Au,Ru,Iu),visit_(Au,Iu,$u,Ru);if(typeof Iu!="symbol"){if(isCollection(lo)){Ru=Object.freeze(Ru.concat(lo));for(let Pu=0;Pu<lo.items.length;++Pu){const Ou=visit_(Pu,lo.items[Pu],$u,Ru);if(typeof Ou=="number")Pu=Ou-1;else{if(Ou===BREAK)return BREAK;Ou===REMOVE&&(lo.items.splice(Pu,1),Pu-=1)}}}else if(isPair(lo)){Ru=Object.freeze(Ru.concat(lo));const Pu=visit_("key",lo.key,$u,Ru);if(Pu===BREAK)return BREAK;Pu===REMOVE&&(lo.key=null);const Ou=visit_("value",lo.value,$u,Ru);if(Ou===BREAK)return BREAK;Ou===REMOVE&&(lo.value=null)}}return Iu}function initVisitor(Au){return typeof Au=="object"&&(Au.Collection||Au.Node||Au.Value)?Object.assign({Alias:Au.Node,Map:Au.Node,Scalar:Au.Node,Seq:Au.Node},Au.Value&&{Map:Au.Value,Scalar:Au.Value,Seq:Au.Value},Au.Collection&&{Map:Au.Collection,Seq:Au.Collection},Au):Au}function callVisitor(Au,lo,$u,Ru){if(typeof $u=="function")return $u(Au,lo,Ru);if(isMap(lo))return $u.Map?.(Au,lo,Ru);if(isSeq$1(lo))return $u.Seq?.(Au,lo,Ru);if(isPair(lo))return $u.Pair?.(Au,lo,Ru);if(isScalar(lo))return $u.Scalar?.(Au,lo,Ru);if(isAlias(lo))return $u.Alias?.(Au,lo,Ru)}function replaceNode(Au,lo,$u){const Ru=lo[lo.length-1];if(isCollection(Ru))Ru.items[Au]=$u;else if(isPair(Ru))Au==="key"?Ru.key=$u:Ru.value=$u;else if(isDocument(Ru))Ru.contents=$u;else{const Iu=isAlias(Ru)?"alias":"scalar";throw new Error(`Cannot replace node with ${Iu} parent`)}}const escapeChars={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},escapeTagName=Au=>Au.replace(/[!,[\]{}]/g,lo=>escapeChars[lo]);class Directives{constructor(lo,$u){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Directives.defaultYaml,lo),this.tags=Object.assign({},Directives.defaultTags,$u)}clone(){const lo=new Directives(this.yaml,this.tags);return lo.docStart=this.docStart,lo}atDocument(){const lo=new Directives(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Directives.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Directives.defaultTags);break}return lo}add(lo,$u){this.atNextDocument&&(this.yaml={explicit:Directives.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Directives.defaultTags),this.atNextDocument=!1);const Ru=lo.trim().split(/[ \t]+/),Iu=Ru.shift();switch(Iu){case"%TAG":{if(Ru.length!==2&&($u(0,"%TAG directive should contain exactly two parts"),Ru.length<2))return!1;const[Pu,Ou]=Ru;return this.tags[Pu]=Ou,!0}case"%YAML":{if(this.yaml.explicit=!0,Ru.length!==1)return $u(0,"%YAML directive should contain exactly one part"),!1;const[Pu]=Ru;if(Pu==="1.1"||Pu==="1.2")return this.yaml.version=Pu,!0;{const Ou=/^\d+\.\d+$/.test(Pu);return $u(6,`Unsupported YAML version ${Pu}`,Ou),!1}}default:return $u(0,`Unknown directive ${Iu}`,!0),!1}}tagName(lo,$u){if(lo==="!")return"!";if(lo[0]!=="!")return $u(`Not a valid tag: ${lo}`),null;if(lo[1]==="<"){const Ou=lo.slice(2,-1);return Ou==="!"||Ou==="!!"?($u(`Verbatim tags aren't resolved, so ${lo} is invalid.`),null):(lo[lo.length-1]!==">"&&$u("Verbatim tags must end with a >"),Ou)}const[,Ru,Iu]=lo.match(/^(.*!)([^!]*)$/s);Iu||$u(`The ${lo} tag has no suffix`);const Pu=this.tags[Ru];if(Pu)try{return Pu+decodeURIComponent(Iu)}catch(Ou){return $u(String(Ou)),null}return Ru==="!"?lo:($u(`Could not resolve tag: ${lo}`),null)}tagString(lo){for(const[$u,Ru]of Object.entries(this.tags))if(lo.startsWith(Ru))return $u+escapeTagName(lo.substring(Ru.length));return lo[0]==="!"?lo:`!<${lo}>`}toString(lo){const $u=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],Ru=Object.entries(this.tags);let Iu;if(lo&&Ru.length>0&&isNode$1(lo.contents)){const Pu={};visit$4(lo.contents,(Ou,Mu)=>{isNode$1(Mu)&&Mu.tag&&(Pu[Mu.tag]=!0)}),Iu=Object.keys(Pu)}else Iu=[];for(const[Pu,Ou]of Ru)Pu==="!!"&&Ou==="tag:yaml.org,2002:"||(!lo||Iu.some(Mu=>Mu.startsWith(Ou)))&&$u.push(`%TAG ${Pu} ${Ou}`);return $u.join(`
|
|
124
124
|
`)}}Directives.defaultYaml={explicit:!1,version:"1.2"};Directives.defaultTags={"!!":"tag:yaml.org,2002:"};function anchorIsValid(Au){if(/[\x00-\x19\s,[\]{}]/.test(Au)){const $u=`Anchor must not contain whitespace or control characters: ${JSON.stringify(Au)}`;throw new Error($u)}return!0}function anchorNames(Au){const lo=new Set;return visit$4(Au,{Value($u,Ru){Ru.anchor&&lo.add(Ru.anchor)}}),lo}function findNewAnchor(Au,lo){for(let $u=1;;++$u){const Ru=`${Au}${$u}`;if(!lo.has(Ru))return Ru}}function createNodeAnchors(Au,lo){const $u=[],Ru=new Map;let Iu=null;return{onAnchor:Pu=>{$u.push(Pu),Iu??(Iu=anchorNames(Au));const Ou=findNewAnchor(lo,Iu);return Iu.add(Ou),Ou},setAnchors:()=>{for(const Pu of $u){const Ou=Ru.get(Pu);if(typeof Ou=="object"&&Ou.anchor&&(isScalar(Ou.node)||isCollection(Ou.node)))Ou.node.anchor=Ou.anchor;else{const Mu=new Error("Failed to resolve repeated object (this should not happen)");throw Mu.source=Pu,Mu}}},sourceObjects:Ru}}function applyReviver(Au,lo,$u,Ru){if(Ru&&typeof Ru=="object")if(Array.isArray(Ru))for(let Iu=0,Pu=Ru.length;Iu<Pu;++Iu){const Ou=Ru[Iu],Mu=applyReviver(Au,Ru,String(Iu),Ou);Mu===void 0?delete Ru[Iu]:Mu!==Ou&&(Ru[Iu]=Mu)}else if(Ru instanceof Map)for(const Iu of Array.from(Ru.keys())){const Pu=Ru.get(Iu),Ou=applyReviver(Au,Ru,Iu,Pu);Ou===void 0?Ru.delete(Iu):Ou!==Pu&&Ru.set(Iu,Ou)}else if(Ru instanceof Set)for(const Iu of Array.from(Ru)){const Pu=applyReviver(Au,Ru,Iu,Iu);Pu===void 0?Ru.delete(Iu):Pu!==Iu&&(Ru.delete(Iu),Ru.add(Pu))}else for(const[Iu,Pu]of Object.entries(Ru)){const Ou=applyReviver(Au,Ru,Iu,Pu);Ou===void 0?delete Ru[Iu]:Ou!==Pu&&(Ru[Iu]=Ou)}return Au.call(lo,$u,Ru)}function toJS(Au,lo,$u){if(Array.isArray(Au))return Au.map((Ru,Iu)=>toJS(Ru,String(Iu),$u));if(Au&&typeof Au.toJSON=="function"){if(!$u||!hasAnchor(Au))return Au.toJSON(lo,$u);const Ru={aliasCount:0,count:1,res:void 0};$u.anchors.set(Au,Ru),$u.onCreate=Pu=>{Ru.res=Pu,delete $u.onCreate};const Iu=Au.toJSON(lo,$u);return $u.onCreate&&$u.onCreate(Iu),Iu}return typeof Au=="bigint"&&!$u?.keep?Number(Au):Au}class NodeBase{constructor(lo){Object.defineProperty(this,NODE_TYPE$1,{value:lo})}clone(){const lo=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(lo.range=this.range.slice()),lo}toJS(lo,{mapAsMap:$u,maxAliasCount:Ru,onAnchor:Iu,reviver:Pu}={}){if(!isDocument(lo))throw new TypeError("A document argument is required");const Ou={anchors:new Map,doc:lo,keep:!0,mapAsMap:$u===!0,mapKeyWarned:!1,maxAliasCount:typeof Ru=="number"?Ru:100},Mu=toJS(this,"",Ou);if(typeof Iu=="function")for(const{count:Du,res:Lu}of Ou.anchors.values())Iu(Lu,Du);return typeof Pu=="function"?applyReviver(Pu,{"":Mu},"",Mu):Mu}}class Alias extends NodeBase{constructor(lo){super(ALIAS),this.source=lo,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(lo,$u){if($u?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let Ru;$u?.aliasResolveCache?Ru=$u.aliasResolveCache:(Ru=[],visit$4(lo,{Node:(Pu,Ou)=>{(isAlias(Ou)||hasAnchor(Ou))&&Ru.push(Ou)}}),$u&&($u.aliasResolveCache=Ru));let Iu;for(const Pu of Ru){if(Pu===this)break;Pu.anchor===this.source&&(Iu=Pu)}if(Iu&&$u){const{anchors:Pu,doc:Ou,maxAliasCount:Mu}=$u;let Du=Pu.get(Iu);if(Du||(toJS(Iu,null,$u),Du=Pu.get(Iu)),Du?.res===void 0){const Lu="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(Lu)}if(Mu>=0&&(Du.count+=1,Du.aliasCount===0&&(Du.aliasCount=getAliasCount(Ou,Iu,Pu)),Du.count*Du.aliasCount>Mu)){const Lu="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(Lu)}}return Iu}toJSON(lo,$u){if(!$u)return{source:this.source};const Ru=this.resolve($u.doc,$u);if(!Ru){const Iu=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(Iu)}return $u.anchors.get(Ru).res}toString(lo,$u,Ru){const Iu=`*${this.source}`;if(lo){if(anchorIsValid(this.source),lo.options.verifyAliasOrder&&!lo.anchors.has(this.source)){const Pu=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(Pu)}if(lo.implicitKey)return`${Iu} `}return Iu}}function getAliasCount(Au,lo,$u){if(isAlias(lo)){const Ru=lo.resolve(Au),Iu=$u&&Ru&&$u.get(Ru);return Iu?Iu.count*Iu.aliasCount:0}else if(isCollection(lo)){let Ru=0;for(const Iu of lo.items){const Pu=getAliasCount(Au,Iu,$u);Pu>Ru&&(Ru=Pu)}return Ru}else if(isPair(lo)){const Ru=getAliasCount(Au,lo.key,$u),Iu=getAliasCount(Au,lo.value,$u);return Math.max(Ru,Iu)}return 1}const isScalarValue=Au=>!Au||typeof Au!="function"&&typeof Au!="object";class Scalar extends NodeBase{constructor(lo){super(SCALAR$1),this.value=lo}toJSON(lo,$u){return $u?.keep?this.value:toJS(this.value,lo,$u)}toString(){return String(this.value)}}Scalar.BLOCK_FOLDED="BLOCK_FOLDED";Scalar.BLOCK_LITERAL="BLOCK_LITERAL";Scalar.PLAIN="PLAIN";Scalar.QUOTE_DOUBLE="QUOTE_DOUBLE";Scalar.QUOTE_SINGLE="QUOTE_SINGLE";const defaultTagPrefix="tag:yaml.org,2002:";function findTagObject(Au,lo,$u){if(lo){const Ru=$u.filter(Pu=>Pu.tag===lo),Iu=Ru.find(Pu=>!Pu.format)??Ru[0];if(!Iu)throw new Error(`Tag ${lo} not found`);return Iu}return $u.find(Ru=>Ru.identify?.(Au)&&!Ru.format)}function createNode(Au,lo,$u){if(isDocument(Au)&&(Au=Au.contents),isNode$1(Au))return Au;if(isPair(Au)){const ju=$u.schema[MAP$1].createNode?.($u.schema,null,$u);return ju.items.push(Au),ju}(Au instanceof String||Au instanceof Number||Au instanceof Boolean||typeof BigInt<"u"&&Au instanceof BigInt)&&(Au=Au.valueOf());const{aliasDuplicateObjects:Ru,onAnchor:Iu,onTagObj:Pu,schema:Ou,sourceObjects:Mu}=$u;let Du;if(Ru&&Au&&typeof Au=="object"){if(Du=Mu.get(Au),Du)return Du.anchor??(Du.anchor=Iu(Au)),new Alias(Du.anchor);Du={anchor:null,node:null},Mu.set(Au,Du)}lo?.startsWith("!!")&&(lo=defaultTagPrefix+lo.slice(2));let Lu=findTagObject(Au,lo,Ou.tags);if(!Lu){if(Au&&typeof Au.toJSON=="function"&&(Au=Au.toJSON()),!Au||typeof Au!="object"){const ju=new Scalar(Au);return Du&&(Du.node=ju),ju}Lu=Au instanceof Map?Ou[MAP$1]:Symbol.iterator in Object(Au)?Ou[SEQ]:Ou[MAP$1]}Pu&&(Pu(Lu),delete $u.onTagObj);const Bu=Lu?.createNode?Lu.createNode($u.schema,Au,$u):typeof Lu?.nodeClass?.from=="function"?Lu.nodeClass.from($u.schema,Au,$u):new Scalar(Au);return lo?Bu.tag=lo:Lu.default||(Bu.tag=Lu.tag),Du&&(Du.node=Bu),Bu}function collectionFromPath(Au,lo,$u){let Ru=$u;for(let Iu=lo.length-1;Iu>=0;--Iu){const Pu=lo[Iu];if(typeof Pu=="number"&&Number.isInteger(Pu)&&Pu>=0){const Ou=[];Ou[Pu]=Ru,Ru=Ou}else Ru=new Map([[Pu,Ru]])}return createNode(Ru,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:Au,sourceObjects:new Map})}const isEmptyPath=Au=>Au==null||typeof Au=="object"&&!!Au[Symbol.iterator]().next().done;class Collection extends NodeBase{constructor(lo,$u){super(lo),Object.defineProperty(this,"schema",{value:$u,configurable:!0,enumerable:!1,writable:!0})}clone(lo){const $u=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return lo&&($u.schema=lo),$u.items=$u.items.map(Ru=>isNode$1(Ru)||isPair(Ru)?Ru.clone(lo):Ru),this.range&&($u.range=this.range.slice()),$u}addIn(lo,$u){if(isEmptyPath(lo))this.add($u);else{const[Ru,...Iu]=lo,Pu=this.get(Ru,!0);if(isCollection(Pu))Pu.addIn(Iu,$u);else if(Pu===void 0&&this.schema)this.set(Ru,collectionFromPath(this.schema,Iu,$u));else throw new Error(`Expected YAML collection at ${Ru}. Remaining path: ${Iu}`)}}deleteIn(lo){const[$u,...Ru]=lo;if(Ru.length===0)return this.delete($u);const Iu=this.get($u,!0);if(isCollection(Iu))return Iu.deleteIn(Ru);throw new Error(`Expected YAML collection at ${$u}. Remaining path: ${Ru}`)}getIn(lo,$u){const[Ru,...Iu]=lo,Pu=this.get(Ru,!0);return Iu.length===0?!$u&&isScalar(Pu)?Pu.value:Pu:isCollection(Pu)?Pu.getIn(Iu,$u):void 0}hasAllNullValues(lo){return this.items.every($u=>{if(!isPair($u))return!1;const Ru=$u.value;return Ru==null||lo&&isScalar(Ru)&&Ru.value==null&&!Ru.commentBefore&&!Ru.comment&&!Ru.tag})}hasIn(lo){const[$u,...Ru]=lo;if(Ru.length===0)return this.has($u);const Iu=this.get($u,!0);return isCollection(Iu)?Iu.hasIn(Ru):!1}setIn(lo,$u){const[Ru,...Iu]=lo;if(Iu.length===0)this.set(Ru,$u);else{const Pu=this.get(Ru,!0);if(isCollection(Pu))Pu.setIn(Iu,$u);else if(Pu===void 0&&this.schema)this.set(Ru,collectionFromPath(this.schema,Iu,$u));else throw new Error(`Expected YAML collection at ${Ru}. Remaining path: ${Iu}`)}}}const stringifyComment=Au=>Au.replace(/^(?!$)(?: $)?/gm,"#");function indentComment(Au,lo){return/^\n+$/.test(Au)?Au.substring(1):lo?Au.replace(/^(?! *$)/gm,lo):Au}const lineComment=(Au,lo,$u)=>Au.endsWith(`
|
|
125
125
|
`)?indentComment($u,lo):$u.includes(`
|
|
126
126
|
`)?`
|
|
@@ -249,7 +249,7 @@ ${$u.comment}`:$u.comment}this.doc.range[2]=$u.offset;break}default:this.errors.
|
|
|
249
249
|
`,$u)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(lo){const $u=lo.items[lo.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,$u.value){const Ru="end"in $u.value?$u.value.end:void 0;(Array.isArray(Ru)?Ru[Ru.length-1]:void 0)?.type==="comment"?Ru?.push(this.sourceToken):lo.items.push({start:[this.sourceToken]})}else $u.sep?$u.sep.push(this.sourceToken):$u.start.push(this.sourceToken);return;case"space":case"comment":if($u.value)lo.items.push({start:[this.sourceToken]});else if($u.sep)$u.sep.push(this.sourceToken);else{if(this.atIndentedComment($u.start,lo.indent)){const Iu=lo.items[lo.items.length-2]?.value?.end;if(Array.isArray(Iu)){arrayPushArray(Iu,$u.start),Iu.push(this.sourceToken),lo.items.pop();return}}$u.start.push(this.sourceToken)}return}if(this.indent>=lo.indent){const Ru=!this.onKeyLine&&this.indent===lo.indent,Iu=Ru&&($u.sep||$u.explicitKey)&&this.type!=="seq-item-ind";let Pu=[];if(Iu&&$u.sep&&!$u.value){const Ou=[];for(let Mu=0;Mu<$u.sep.length;++Mu){const Du=$u.sep[Mu];switch(Du.type){case"newline":Ou.push(Mu);break;case"space":break;case"comment":Du.indent>lo.indent&&(Ou.length=0);break;default:Ou.length=0}}Ou.length>=2&&(Pu=$u.sep.splice(Ou[1]))}switch(this.type){case"anchor":case"tag":Iu||$u.value?(Pu.push(this.sourceToken),lo.items.push({start:Pu}),this.onKeyLine=!0):$u.sep?$u.sep.push(this.sourceToken):$u.start.push(this.sourceToken);return;case"explicit-key-ind":!$u.sep&&!$u.explicitKey?($u.start.push(this.sourceToken),$u.explicitKey=!0):Iu||$u.value?(Pu.push(this.sourceToken),lo.items.push({start:Pu,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if($u.explicitKey)if($u.sep)if($u.value)lo.items.push({start:[],key:null,sep:[this.sourceToken]});else if(includesToken($u.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Pu,key:null,sep:[this.sourceToken]}]});else if(isFlowToken($u.key)&&!includesToken($u.sep,"newline")){const Ou=getFirstKeyStartProps($u.start),Mu=$u.key,Du=$u.sep;Du.push(this.sourceToken),delete $u.key,delete $u.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Ou,key:Mu,sep:Du}]})}else Pu.length>0?$u.sep=$u.sep.concat(Pu,this.sourceToken):$u.sep.push(this.sourceToken);else if(includesToken($u.start,"newline"))Object.assign($u,{key:null,sep:[this.sourceToken]});else{const Ou=getFirstKeyStartProps($u.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Ou,key:null,sep:[this.sourceToken]}]})}else $u.sep?$u.value||Iu?lo.items.push({start:Pu,key:null,sep:[this.sourceToken]}):includesToken($u.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):$u.sep.push(this.sourceToken):Object.assign($u,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const Ou=this.flowScalar(this.type);Iu||$u.value?(lo.items.push({start:Pu,key:Ou,sep:[]}),this.onKeyLine=!0):$u.sep?this.stack.push(Ou):(Object.assign($u,{key:Ou,sep:[]}),this.onKeyLine=!0);return}default:{const Ou=this.startBlockValue(lo);if(Ou){if(Ou.type==="block-seq"){if(!$u.explicitKey&&$u.sep&&!includesToken($u.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else Ru&&lo.items.push({start:Pu});this.stack.push(Ou);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(lo){const $u=lo.items[lo.items.length-1];switch(this.type){case"newline":if($u.value){const Ru="end"in $u.value?$u.value.end:void 0;(Array.isArray(Ru)?Ru[Ru.length-1]:void 0)?.type==="comment"?Ru?.push(this.sourceToken):lo.items.push({start:[this.sourceToken]})}else $u.start.push(this.sourceToken);return;case"space":case"comment":if($u.value)lo.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment($u.start,lo.indent)){const Iu=lo.items[lo.items.length-2]?.value?.end;if(Array.isArray(Iu)){arrayPushArray(Iu,$u.start),Iu.push(this.sourceToken),lo.items.pop();return}}$u.start.push(this.sourceToken)}return;case"anchor":case"tag":if($u.value||this.indent<=lo.indent)break;$u.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==lo.indent)break;$u.value||includesToken($u.start,"seq-item-ind")?lo.items.push({start:[this.sourceToken]}):$u.start.push(this.sourceToken);return}if(this.indent>lo.indent){const Ru=this.startBlockValue(lo);if(Ru){this.stack.push(Ru);return}}yield*this.pop(),yield*this.step()}*flowCollection(lo){const $u=lo.items[lo.items.length-1];if(this.type==="flow-error-end"){let Ru;do yield*this.pop(),Ru=this.peek(1);while(Ru?.type==="flow-collection")}else if(lo.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!$u||$u.sep?lo.items.push({start:[this.sourceToken]}):$u.start.push(this.sourceToken);return;case"map-value-ind":!$u||$u.value?lo.items.push({start:[],key:null,sep:[this.sourceToken]}):$u.sep?$u.sep.push(this.sourceToken):Object.assign($u,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!$u||$u.value?lo.items.push({start:[this.sourceToken]}):$u.sep?$u.sep.push(this.sourceToken):$u.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const Iu=this.flowScalar(this.type);!$u||$u.value?lo.items.push({start:[],key:Iu,sep:[]}):$u.sep?this.stack.push(Iu):Object.assign($u,{key:Iu,sep:[]});return}case"flow-map-end":case"flow-seq-end":lo.end.push(this.sourceToken);return}const Ru=this.startBlockValue(lo);Ru?this.stack.push(Ru):(yield*this.pop(),yield*this.step())}else{const Ru=this.peek(2);if(Ru.type==="block-map"&&(this.type==="map-value-ind"&&Ru.indent===lo.indent||this.type==="newline"&&!Ru.items[Ru.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&Ru.type!=="flow-collection"){const Iu=getPrevProps(Ru),Pu=getFirstKeyStartProps(Iu);fixFlowSeqItems(lo);const Ou=lo.end.splice(1,lo.end.length);Ou.push(this.sourceToken);const Mu={type:"block-map",offset:lo.offset,indent:lo.indent,items:[{start:Pu,key:lo,sep:Ou}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=Mu}else yield*this.lineEnd(lo)}}flowScalar(lo){if(this.onNewLine){let $u=this.source.indexOf(`
|
|
250
250
|
`)+1;for(;$u!==0;)this.onNewLine(this.offset+$u),$u=this.source.indexOf(`
|
|
251
251
|
`,$u)+1}return{type:lo,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(lo){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const $u=getPrevProps(lo),Ru=getFirstKeyStartProps($u);return Ru.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Ru,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const $u=getPrevProps(lo),Ru=getFirstKeyStartProps($u);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Ru,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(lo,$u){return this.type!=="comment"||this.indent<=$u?!1:lo.every(Ru=>Ru.type==="newline"||Ru.type==="space")}*documentEnd(lo){this.type!=="doc-mode"&&(lo.end?lo.end.push(this.sourceToken):lo.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(lo){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:lo.end?lo.end.push(this.sourceToken):lo.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};function parseOptions$1(Au){const lo=Au.prettyErrors!==!1;return{lineCounter:Au.lineCounter||lo&&new LineCounter||null,prettyErrors:lo}}function parseDocument(Au,lo={}){const{lineCounter:$u,prettyErrors:Ru}=parseOptions$1(lo),Iu=new Parser$4($u?.addNewLine),Pu=new Composer(lo);let Ou=null;for(const Mu of Pu.compose(Iu.parse(Au),!0,Au.length))if(!Ou)Ou=Mu;else if(Ou.options.logLevel!=="silent"){Ou.errors.push(new YAMLParseError(Mu.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return Ru&&$u&&(Ou.errors.forEach(prettifyError(Au,$u)),Ou.warnings.forEach(prettifyError(Au,$u))),Ou}function readAppspecYaml(Au){const lo=parseDocument(Au,{prettyErrors:!0});return lo.errors.length>0?{app:parseAppspec({}).app,problems:lo.errors.map(Ru=>{const Iu=Ru.linePos?.[0];return`${Iu?`Line ${Iu.line}: `:""}${Ru.message.split(`
|
|
252
|
-
`)[0]}`})}:parseAppspec(lo.toJS())}function defineContributionPoint(Au){if(!Au)throw new Error("defineContributionPoint: a contribution point needs an id");return{id:Au}}function contribution(Au,lo,$u){return{point:Au,value:lo,options:$u}}class ContributionRegistry{byPoint=new Map;byPlugin=new Map;seq=0;add(lo,$u,Ru,Iu={}){const Pu={plugin:lo,id:Iu.id??lo,order:Iu.order??0,value:Ru,seq:this.seq++},Ou=this.byPoint.get($u.id);Ou?Ou.push(Pu):this.byPoint.set($u.id,[Pu]);let Mu=!1;const Du=()=>{if(Mu)return;Mu=!0;const Bu=this.byPoint.get($u.id);if(Bu){const ju=Bu.indexOf(Pu);ju>=0&&Bu.splice(ju,1),Bu.length===0&&this.byPoint.delete($u.id)}this.byPlugin.get(lo)?.delete(Du)},Lu=this.byPlugin.get(lo);return Lu?Lu.add(Du):this.byPlugin.set(lo,new Set([Du])),Du}get(lo){const $u=this.byPoint.get(lo.id);return!$u||$u.length===0?[]:[...$u].sort((Ru,Iu)=>Ru.order===Iu.order?Ru.seq-Iu.seq:Ru.order-Iu.order).map(({plugin:Ru,id:Iu,order:Pu,value:Ou})=>({plugin:Ru,id:Iu,order:Pu,value:Ou}))}points(){return[...this.byPoint.keys()].sort()}describe(){return this.points().map(lo=>({point:lo,contributions:(this.byPoint.get(lo)??[]).slice().sort(($u,Ru)=>$u.order===Ru.order?$u.seq-Ru.seq:$u.order-Ru.order).map(({plugin:$u,id:Ru,order:Iu,value:Pu})=>({plugin:$u,id:Ru,order:Iu,value:Pu}))}))}disposePlugin(lo){const $u=this.byPlugin.get(lo);if($u){for(const Ru of[...$u])Ru();this.byPlugin.delete(lo)}}}let CommandRegistry$1=class{byId=new Map;byPlugin=new Map;listeners=new Set;seq=0;add(lo,$u){if(!$u.id)throw new Error("CommandRegistry.add: a command needs an id");const Ru=this.byId.get($u.id);if(Ru)throw new Error(`CommandRegistry.add: command '${$u.id}' is already registered by plugin '${Ru.plugin}'. Command ids must be unique; namespace them with the plugin they belong to.`);const Iu={plugin:lo,seq:this.seq++,command:$u};this.byId.set($u.id,Iu);let Pu=!1;const Ou=()=>{Pu||(Pu=!0,this.byId.get($u.id)===Iu&&this.byId.delete($u.id),this.byPlugin.get(lo)?.delete(Ou),this.notify())},Mu=this.byPlugin.get(lo);return Mu?Mu.add(Ou):this.byPlugin.set(lo,new Set([Ou])),this.notify(),Ou}get(lo){const $u=this.byId.get(lo);return $u?{...$u.command,plugin:$u.plugin}:void 0}list(){return[...this.byId.values()].sort((lo,$u)=>{const Ru=lo.command.order??0,Iu=$u.command.order??0;return Ru===Iu?lo.seq-$u.seq:Ru-Iu}).map(lo=>({...lo.command,plugin:lo.plugin}))}async execute(lo,$u){const Ru=this.byId.get(lo);if(!Ru)throw new Error(`CommandRegistry.execute: no command '${lo}' is registered`);if(Ru.command.isEnabled&&!Ru.command.isEnabled())throw new Error(`CommandRegistry.execute: command '${lo}' is not available right now`);return await Ru.command.execute($u)}subscribe(lo){return this.listeners.add(lo),()=>{this.listeners.delete(lo)}}disposePlugin(lo){const $u=this.byPlugin.get(lo);if($u){for(const Ru of[...$u])Ru();this.byPlugin.delete(lo)}}notify(){for(const lo of[...this.listeners])lo()}};const ON_STARTUP="onStartup",ON_ANY="*";function onContributionPoint(Au){return`onContributionPoint:${typeof Au=="string"?Au:Au.id}`}function onView(Au){return`onView:${Au}`}function matchesActivation(Au,lo){return!Au||Au.length===0?lo===ON_STARTUP:Au.some($u=>$u===ON_ANY||$u===lo)}function matchesDeactivation(Au,lo){return!Au||Au.length===0?!1:Au.some($u=>$u===ON_ANY||$u===lo)}function activatesAtStartup(Au){return matchesActivation(Au,ON_STARTUP)}function defineExtension(Au){if(!Au.name)throw new Error("defineExtension: an extension needs a name");if(!Array.isArray(Au.plugins)||Au.plugins.length===0)throw new Error(`defineExtension: ${Au.name} must group at least one plugin`);return Au}function isExtension(Au){return typeof Au=="object"&&Au!==null&&typeof Au.name=="string"&&Array.isArray(Au.plugins)}function defineGate(Au){return defineContributionPoint(Au)}function isRefusal(Au){return Au!==!0}function resolveGate(Au,lo){const $u=[];for(const Iu of Au){let Pu;try{Pu=Iu.value.check(lo)}catch(Ou){Pu=Ou instanceof Error?Ou.message:String(Ou)}isRefusal(Pu)&&$u.push({plugin:Iu.plugin,reason:Pu})}const Ru=$u[0];return{allowed:$u.length===0,reason:Ru?.reason,blockedBy:Ru?.plugin,refusals:$u}}function placeholderFor(Au){return{name:Au.name,version:Au.version,displayName:Au.displayName,description:Au.description,octicon:Au.octicon,emoji:Au.emoji,dependencies:Au.dependencies,activationEvents:Au.activationEvents,deactivationEvents:Au.deactivationEvents,requiredBackendPlugins:Au.requiredBackendPlugins,optionalBackendPlugins:Au.optionalBackendPlugins,contributionPoints:Au.contributionPoints}}function mergeLoaded(Au,lo){return{...lo,displayName:lo.displayName??Au.displayName,description:lo.description??Au.description,octicon:lo.octicon??Au.octicon,emoji:lo.emoji??Au.emoji,version:lo.version??Au.version,activationEvents:lo.activationEvents??Au.activationEvents,deactivationEvents:lo.deactivationEvents??Au.deactivationEvents,requiredBackendPlugins:lo.requiredBackendPlugins??Au.requiredBackendPlugins,optionalBackendPlugins:lo.optionalBackendPlugins??Au.optionalBackendPlugins,contributionPoints:lo.contributionPoints??Au.contributionPoints}}function shallowMergeConfig(Au,lo){return{...Au,...lo}}function normalizePlugins(Au){const lo=new Map,$u=new Map,Ru=new Map,Iu=new Map,Pu=Au.map(Ou=>({ref:Ou}));for(;Pu.length>0;){const Ou=Pu.shift();if(!Ou?.ref)continue;const{ref:Mu,from:Du}=Ou;if(isExtension(Mu)){Iu.set(Mu.name,Mu);for(const ju of Mu.plugins)Pu.push({ref:ju,from:Mu.name});continue}if(isLazyPluginRef(Mu)){if(!lo.has(Mu.name)){$u.set(Mu.name,Mu),lo.set(Mu.name,placeholderFor(Mu)),Du&&Ru.set(Mu.name,Du);for(const ju of Mu.dependencies??[])Pu.push({ref:ju})}continue}const Bu=asConfigured(Mu).plugin;if(!lo.has(Bu.name)){lo.set(Bu.name,Bu),Du&&Ru.set(Bu.name,Du);for(const ju of Bu.dependencies??[])Pu.push({ref:ju})}}return{plugins:Array.from(lo.values()),lazyByName:$u,extensionOf:Ru,extensions:Iu}}function topoSort(Au){const lo=new Map(Au.map(Ou=>[Ou.name,Ou])),$u=new Set,Ru=new Set,Iu=[];function Pu(Ou){if(Ru.has(Ou))return;if($u.has(Ou))throw new Error(`Circular dependency detected at ${Ou}`);$u.add(Ou);const Mu=lo.get(Ou);if(!Mu)throw new Error(`Unknown plugin ${Ou}`);for(const Du of Mu.dependencies??[])Pu(asConfigured(Du).plugin.name);$u.delete(Ou),Ru.add(Ou),Iu.push(Mu)}for(const Ou of Au)Pu(Ou.name);return Iu}function collectOverrides(Au){const lo=new Map,$u=[...Au];for(;$u.length>0;){const Ru=$u.shift();if(!Ru)continue;if(isExtension(Ru)){$u.push(...Ru.plugins);continue}if(isLazyPluginRef(Ru)){for(const Du of Ru.dependencies??[])$u.push(Du);continue}const Iu=asConfigured(Ru),Pu=Iu.plugin.name,Ou=lo.get(Pu)??{},Mu=shallowMergeConfig(Ou,Iu.config);lo.set(Pu,Mu);for(const Du of Iu.plugin.dependencies??[])$u.push(Du)}return lo}function buildReactorFromPlugins(Au,lo={}){const{plugins:$u,lazyByName:Ru,extensionOf:Iu,extensions:Pu}=normalizePlugins(Au),Ou=topoSort($u),Mu=new Map(Ou.map(hd=>[hd.name,hd])),Du=collectOverrides(Au),Lu=new Map,Bu=new Set,ju=new ContributionRegistry,Fu=new CommandRegistry$1;let zu=0,Uu=0,Hu,Vu=!1;const Gu=new Map,Wu=new Set,Ku=new Set;let Ju=new Set;function Yu(){if(!(Uu>0)){zu+=1;for(const hd of Bu)hd()}}function Xu(hd){Uu+=1;try{return hd()}finally{Uu-=1,Uu===0&&Yu()}}for(const hd of Ou){const vd=mergeWithDefaults(hd,Du.get(hd.name)??{});Lu.set(hd.name,{plugin:hd,config:vd,enabled:!0,activated:!1,extension:Iu.get(hd.name),lazy:Ru.get(hd.name),loaded:!Ru.has(hd.name)})}for(const hd of Ou){for(const vd of hd.conflictsWith??[])if(Mu.has(vd))throw new Error(`Plugin ${hd.name} conflicts with ${vd}`);for(const vd of hd.peerDependencies??[])if(!vd.optional&&!Mu.has(vd.name)&&lo.strictPeerDependencies)throw new Error(`Missing required peer dependency ${vd.name} for ${hd.name}`)}function ed(hd){const vd=[];for(const Sd of Ou){const kd=Lu.get(Sd.name);!kd||kd.activated||matchesActivation(kd.plugin.activationEvents,hd)&&vd.push(Sd.name)}return vd}function td(hd){if(!Wu.has(hd.id)){Wu.add(hd.id);const vd=onContributionPoint(hd);ed(vd).length>0&&Promise.resolve().then(()=>_d(vd))}return ju.get(hd)}const nd={hasPlugin(hd){return Lu.has(hd)},getOutput(hd){return Lu.get(hd)?.outputValue},getRequiredBackendPlugins(hd){return Lu.get(hd)?.plugin.requiredBackendPlugins??[]},getOptionalBackendPlugins(hd){return Lu.get(hd)?.plugin.optionalBackendPlugins??[]},getManifest(hd){const vd=Lu.get(hd);if(!vd)return;const{plugin:Sd}=vd;return{name:Sd.name,version:Sd.version,displayName:Sd.displayName??Sd.name,description:Sd.description,octicon:Sd.octicon,emoji:Sd.emoji,extension:vd.extension,requiredBackendPlugins:Sd.requiredBackendPlugins??[],optionalBackendPlugins:Sd.optionalBackendPlugins??[],loaded:vd.loaded,lazy:!!vd.lazy,activated:vd.activated,disabledBy:vd.enabled?void 0:vd.disabledBy??"user",loadError:vd.loadError?.message,activationEvents:Sd.activationEvents??[ON_STARTUP],deactivationEvents:Sd.deactivationEvents??[],contributionPoints:(Sd.contributionPoints??[]).map(kd=>kd.id),contributesTo:[...new Set((Sd.contributes??[]).map(kd=>kd.point.id))]}},isEnabled(hd){return Lu.get(hd)?.enabled??!1},getContributions(hd){return td(hd)},checkGate(hd,vd){return resolveGate(td(hd),vd)}};function od(hd,vd){return{plugin:vd.plugin,config:vd.config,state:{getConfig:()=>vd.config,getInit:()=>vd.initValue,getOutput:()=>vd.outputValue},reactor:nd,contribute(Sd,kd,Rd){const Od=ju.add(hd,Sd,kd,Rd);Yu();let jd=!1;return()=>{jd||(jd=!0,Od(),Yu())}},registerCommand(Sd){const kd=Fu.add(hd,Sd);Yu();let Rd=!1;return()=>{Rd||(Rd=!0,kd(),Yu())}}}}function sd(hd){const vd=Lu.get(hd);if(!vd)throw new Error(`Unknown plugin ${hd}`);if(!vd.loaded)return;const Sd=od(hd,vd);vd.initValue=vd.plugin.init?.(Sd),vd.outputValue=vd.plugin.build?.(Sd)}function ad(hd){const vd=Lu.get(hd);if(!vd||!vd.enabled||!vd.loaded)return;const Sd=od(hd,vd);for(const kd of vd.plugin.contributes??[])ju.add(hd,kd.point,kd.value,kd.options);for(const kd of vd.plugin.commands??[])Fu.add(hd,kd);Yu(),vd.registerDispose=vd.plugin.register?.(Sd)??void 0,vd.afterDispose=vd.plugin.afterRegistration?.(Sd)??void 0}function pd(hd){const vd=Lu.get(hd);!vd||vd.activated||!vd.loaded||(vd.activated=!0,Xu(()=>{vd.enabled&&(vd.plugin.preserveOutput&&vd.outputValue!==void 0||sd(hd),ad(hd))}))}async function gd(hd){const vd=Lu.get(hd);if(!(!vd?.lazy||vd.loaded)){vd.loading??=Promise.resolve().then(()=>vd.lazy.load());try{const Sd=await vd.loading;if(vd.loaded)return;const kd=Sd.default??Sd;if(!kd||typeof kd!="object"||!kd.name)throw new Error(`Lazy plugin ${hd} did not resolve to a plugin`);vd.plugin=mergeLoaded(vd.lazy,kd),vd.config=mergeWithDefaults(vd.plugin,Du.get(hd)??{}),vd.loaded=!0}catch(Sd){vd.loadError=Sd instanceof Error?Sd:new Error(String(Sd)),Yu()}}}function yd(hd){const vd=Lu.get(hd);if(!vd||vd.activated)return Promise.resolve();const Sd=Gu.get(hd);if(Sd)return Sd;const kd=(async()=>{for(const Rd of vd.plugin.dependencies??[])await yd(asConfigured(Rd).plugin.name);vd.lazy&&!vd.loaded&&await gd(hd),pd(hd),Ku.delete(hd)})().finally(()=>{Gu.delete(hd)});return Gu.set(hd,kd),kd}async function _d(hd){const vd=ed(hd);if(vd.length===0)return[];for(const Sd of vd){const kd=Lu.get(Sd);kd?.lazy&&!kd.loaded&&(kd.loading??=Promise.resolve().then(()=>kd.lazy.load()))}for(const Sd of vd)await yd(Sd);return vd.filter(Sd=>Lu.get(Sd)?.activated)}function bd(hd){const vd=new Set([hd]);for(const Sd of Ou)(Sd.dependencies??[]).some(Rd=>vd.has(asConfigured(Rd).plugin.name))&&vd.add(Sd.name);return vd.delete(hd),Ou.map(Sd=>Sd.name).filter(Sd=>vd.has(Sd)).reverse()}function wd(hd){return(Lu.get(hd)?.plugin?.dependencies??[]).every(Sd=>Lu.get(asConfigured(Sd).plugin.name)?.enabled??!0)}function Ed(hd){const vd=Lu.get(hd);if(!vd||vd.enabled||(vd.enabled=!0,vd.disabledBy=void 0,!vd.loaded||!vd.activated))return;vd.plugin.preserveOutput&&vd.outputValue!==void 0||sd(hd),ad(hd)}function cd(hd,vd="other"){const Sd=Lu.get(hd);if(!Sd)throw new Error(`Unknown plugin ${hd}`);if(vd==="other"&&Ku.delete(hd),!Sd.activated)return[];const kd=[];if(Xu(()=>{for(const Rd of bd(hd)){const Od=Lu.get(Rd);Od?.activated&&(ld(Rd),Od.activated=!1,ud(Rd),kd.push(Rd))}ld(hd),Sd.activated=!1,ud(hd),kd.push(hd)}),vd==="other")for(const Rd of kd)Ku.delete(Rd);return kd}function ud(hd){const vd=Lu.get(hd)?.plugin.activationEvents??[];for(const Sd of vd)Sd.startsWith("onContributionPoint:")&&Wu.delete(Sd.slice(20))}function md(hd){const vd=[];for(const Sd of Ou){const kd=Lu.get(Sd.name);kd?.activated&&matchesDeactivation(kd.plugin.deactivationEvents,hd)&&vd.push(...cd(Sd.name))}return vd}function ld(hd){const vd=Lu.get(hd);vd&&(vd.afterDispose?.(),vd.afterDispose=void 0,vd.registerDispose?.(),vd.registerDispose=void 0,ju.disposePlugin(hd),Fu.disposePlugin(hd))}return{...nd,start(){Vu=!0,Xu(()=>{const hd=Ou.filter(vd=>{const Sd=Lu.get(vd.name);return Sd&&Sd.loaded&&!Sd.activated&&activatesAtStartup(Sd.plugin.activationEvents)});for(const vd of hd)Lu.get(vd.name).activated=!0,sd(vd.name);for(const vd of hd)ad(vd.name)}),Hu=_d(ON_STARTUP).then(()=>{})},whenReady(){return Hu??Promise.resolve()},async fire(hd){const vd=md(hd),Sd=await _d(hd);return{deactivated:vd,activated:Sd}},deactivate(hd){cd(hd)},async setBackendPlugins(hd){Ju=new Set(hd);const vd=Rd=>(Lu.get(Rd)?.plugin.requiredBackendPlugins??[]).every(Od=>Ju.has(Od)),Sd=[];for(const Rd of Ou){if(!Lu.get(Rd.name)?.activated||vd(Rd.name))continue;const jd=cd(Rd.name,"backend");for(const Cd of jd)Ku.add(Cd);Sd.push(...jd)}const kd=[];for(const Rd of Ou){const Od=Rd.name;!Ku.has(Od)||!vd(Od)||!Lu.get(Od)?.enabled||(Ku.delete(Od),await yd(Od),Lu.get(Od)?.activated&&kd.push(Od))}return{deactivated:Sd,activated:kd}},async install(hd){const vd=normalizePlugins([hd]),Sd=vd.plugins.filter(jd=>!Lu.has(jd.name));if(Sd.length===0)return[];for(const jd of Sd)for(const Cd of jd.conflictsWith??[])if(Mu.has(Cd)||Sd.some(Ad=>Ad.name===Cd))throw new Error(`Plugin ${jd.name} conflicts with ${Cd}`);for(const[jd,Cd]of vd.lazyByName)Ru.set(jd,Cd);for(const[jd,Cd]of vd.extensionOf)Iu.set(jd,Cd);for(const[jd,Cd]of vd.extensions)Pu.set(jd,Cd);const kd=collectOverrides([hd]);for(const jd of Sd)Mu.set(jd.name,jd),Lu.set(jd.name,{plugin:jd,config:mergeWithDefaults(jd,kd.get(jd.name)??{}),enabled:!0,activated:!1,extension:Iu.get(jd.name),lazy:Ru.get(jd.name),loaded:!Ru.has(jd.name)});const Rd=topoSort([...Ou,...Sd]);if(Ou.splice(0,Ou.length,...Rd),Yu(),!Vu)return Sd.map(jd=>jd.name);const Od=[];for(const jd of Rd)Sd.some(Cd=>Cd.name===jd.name)&&(Od.push(jd.name),activatesAtStartup(jd.activationEvents)&&await yd(jd.name));return Od},stop(){Vu=!1,Xu(()=>{for(const hd of[...Ou].reverse()){ld(hd.name);const vd=Lu.get(hd.name);vd&&(vd.activated=!1)}Wu.clear()})},enable(hd){const vd=Lu.get(hd);if(!vd)throw new Error(`Unknown plugin ${hd}`);vd.enabled||Xu(()=>{Ed(hd);for(const Sd of[...bd(hd)].reverse()){const kd=Lu.get(Sd);!kd||kd.enabled||kd.disabledBy==="dependency"&&wd(Sd)&&Ed(Sd)}})},disable(hd){const vd=Lu.get(hd);if(!vd)throw new Error(`Unknown plugin ${hd}`);vd.enabled&&Xu(()=>{for(const Sd of bd(hd)){const kd=Lu.get(Sd);kd?.enabled&&(kd.enabled=!1,kd.disabledBy="dependency",ld(Sd))}vd.enabled=!1,vd.disabledBy="user",ld(hd)})},subscribe(hd){return Bu.add(hd),()=>{Bu.delete(hd)}},listPlugins(){return Ou.map(hd=>hd.name)},listExtensions(){return[...Pu.keys()]},getExtensionManifest(hd){const vd=Pu.get(hd);if(vd)return{name:vd.name,version:vd.version,displayName:vd.displayName??vd.name,description:vd.description,octicon:vd.octicon,emoji:vd.emoji,plugins:Ou.filter(Sd=>Iu.get(Sd.name)===hd).map(Sd=>Sd.name)}},getConfig(hd){return Lu.get(hd)?.config},describeContributions(){return ju.describe()},listCommands(){return Fu.list()},getCommand(hd){return Fu.get(hd)},executeCommand(hd,vd){return Fu.execute(hd,vd)},getDependencies(hd){return(Lu.get(hd)?.plugin.dependencies??[]).map(vd=>asConfigured(vd).plugin.name)},getRevision(){return zu}}}function definePlugin(Au){return Au}function defineLazyPlugin(Au){if(!Au.name)throw new Error("defineLazyPlugin: a lazy plugin needs a name");if(typeof Au.load!="function")throw new Error(`defineLazyPlugin: ${Au.name} needs a load function`);return Au}function isLazyPluginRef(Au){return typeof Au=="object"&&Au!==null&&typeof Au.load=="function"&&typeof Au.name=="string"&&!("plugin"in Au)}function configurePlugin(Au,lo){return{plugin:Au,config:lo}}function asConfigured(Au){return"plugin"in Au?Au:{plugin:Au,config:{}}}function mergeWithDefaults(Au,lo){const $u=Au.config??{};return Au.mergeConfig?Au.mergeConfig($u,lo):shallowMergeConfig($u,lo)}let activeEffect=null;class ReactiveEffect{runFn;dependencies=new Set;runner;constructor(lo){this.runFn=lo,this.runner=this.run.bind(this)}run(){for(const $u of this.dependencies)$u.subscribers.delete(this.runner);this.dependencies.clear();const lo=activeEffect;activeEffect=this;try{this.runFn()}finally{activeEffect=lo}}}class SignalImpl{_value;subscribers=new Set;constructor(lo){this._value=lo}get value(){return activeEffect&&(this.subscribers.add(activeEffect.runner),activeEffect.dependencies.add(this)),this._value}set value(lo){if(Object.is(this._value,lo))return;this._value=lo;const $u=Array.from(this.subscribers);for(const Ru of $u)queueSubscriber(Ru)}peek(){return this._value}}function queueSubscriber(Au){Au()}function signal$2(Au){return new SignalImpl(Au)}function effect$1(Au){const lo=new ReactiveEffect(Au);return lo.runner(),()=>{for(const $u of lo.dependencies)$u.subscribers.delete(lo.runner);lo.dependencies.clear()}}function computed$1(Au){const lo=signal$2(Au());return effect$1(()=>{lo.value=Au()}),{get value(){return lo.value},peek:()=>lo.peek()}}function isApplePlatform(){if(typeof navigator>"u")return!1;const lo=navigator.userAgentData?.platform??navigator.platform??"",$u=navigator.userAgent??"";return/mac|iphone|ipad|ipod/i.test(`${lo} ${$u}`)}const MODIFIERS={mod:"mod",cmdorctrl:"mod",commandorcontrol:"mod",ctrl:"ctrl",control:"ctrl",meta:"meta",cmd:"meta",command:"meta",super:"meta",win:"meta",alt:"alt",option:"alt",opt:"alt",shift:"shift"},KEY_ALIASES={esc:"escape",del:"delete",ins:"insert",space:" ",spacebar:" ",up:"arrowup",down:"arrowdown",left:"arrowleft",right:"arrowright",plus:"+",return:"enter"};function parseKeybinding(Au){if(!Au)return null;const lo={key:"",mod:!1,ctrl:!1,meta:!1,alt:!1,shift:!1},$u=Au.split("+").map(Ru=>Ru.trim()).filter((Ru,Iu,Pu)=>Ru!==""||Iu===Pu.length-1);for(const[Ru,Iu]of $u.entries()){const Pu=Iu.toLowerCase(),Ou=MODIFIERS[Pu];if(Ou&&Ru<$u.length-1){lo[Ou]=!0;continue}const Mu=Iu===""?"+":KEY_ALIASES[Pu]??Pu;lo.key=Mu}return lo.key?lo:null}function matchesKeybinding(Au,lo,$u=isApplePlatform()){if((Au.key?.toLowerCase()??"")!==lo.key)return!1;const Iu=lo.ctrl||lo.mod&&!$u,Pu=lo.meta||lo.mod&&$u;return Au.ctrlKey===Iu&&Au.metaKey===Pu&&Au.altKey===lo.alt&&Au.shiftKey===lo.shift}const APPLE_SYMBOLS={ctrl:"⌃",meta:"⌘",alt:"⌥",shift:"⇧"},OTHER_LABELS={ctrl:"Ctrl",meta:"Meta",alt:"Alt",shift:"Shift"},KEY_LABELS={arrowup:"↑",arrowdown:"↓",arrowleft:"←",arrowright:"→",enter:"↵",escape:"Esc"," ":"Space",backspace:"⌫",delete:"Del",tab:"⇥"};function formatKeybinding(Au,lo=isApplePlatform()){const $u=parseKeybinding(Au);if(!$u)return Au;const Ru=$u.ctrl||$u.mod&&!lo,Iu=$u.meta||$u.mod&&lo,Pu=KEY_LABELS[$u.key]??($u.key.length===1?$u.key.toUpperCase():titleCase($u.key));return lo?[$u.ctrl?APPLE_SYMBOLS.ctrl:"",$u.alt?APPLE_SYMBOLS.alt:"",$u.shift?APPLE_SYMBOLS.shift:"",Iu?APPLE_SYMBOLS.meta:"",Pu].join(""):[Ru?OTHER_LABELS.ctrl:"",Iu&&!Ru?OTHER_LABELS.meta:"",$u.alt?OTHER_LABELS.alt:"",$u.shift?OTHER_LABELS.shift:"",Pu].filter(Boolean).join("+")}function titleCase(Au){return Au.charAt(0).toUpperCase()+Au.slice(1)}const ANY_ORIGIN="*";class OriginNotAllowedError extends Error{url;origin;constructor(lo,$u,Ru="a remote"){super(`Refusing to load ${Ru} from ${$u}: not an allowed origin. Pass allowedOrigins, or call setAllowedOrigins() from the host, to accept it.`),this.name="OriginNotAllowedError",this.url=lo,this.origin=$u}}const LEFTMOST_WILDCARD=/^[a-z][a-z0-9+.-]*:\/\/\*\./i;function parseOriginRule(Au){const lo=Au.trim();if(lo===ANY_ORIGIN)return{kind:"any"};try{if(LEFTMOST_WILDCARD.test(lo)){const $u=new URL(lo.replace("*.",""));return{kind:"suffix",protocol:$u.protocol,suffix:`.${$u.hostname}`,port:$u.port}}return{kind:"exact",origin:new URL(lo).origin}}catch{console.warn(`[reactor] ignoring an unreadable allowed origin: ${JSON.stringify(Au)}. Write it with a scheme, e.g. https://cdn.example.com or https://*.example.com.`);return}}function matches$1(Au,lo){if(Au.kind==="any")return!0;if(Au.kind==="exact")return Au.origin===lo;let $u;try{$u=new URL(lo)}catch{return!1}return $u.protocol===Au.protocol&&$u.port===Au.port&&$u.hostname.endsWith(Au.suffix)}let policy=[];function resolveOrigin(Au){const lo=typeof location<"u"&&location?.href?location.href:void 0;return lo?new URL(Au,lo).origin:/^[a-z]+:\/\//i.test(Au)?new URL(Au).origin:void 0}function pageOrigin(){const Au=typeof location<"u"&&location?.href?location.href:void 0;return Au?new URL(Au).origin:void 0}function isOriginAllowed(Au,lo=[]){let $u;try{$u=resolveOrigin(Au)}catch{return!1}if($u===void 0||$u===pageOrigin())return!0;if($u==="null")return!1;for(const Ru of[...policy,...lo]){const Iu=parseOriginRule(Ru);if(Iu&&matches$1(Iu,$u))return!0}return!1}function assertOriginAllowed(Au,lo=[],$u="a remote"){if(isOriginAllowed(Au,lo))return;let Ru;try{Ru=resolveOrigin(Au)??Au}catch{throw new OriginNotAllowedError(Au,Au,$u)}throw new OriginNotAllowedError(Au,Ru,$u)}let runtimeLoad;async function federationRuntime(){return runtimeLoad||(runtimeLoad=import("@module-federation/runtime").then(lo=>lo.default??lo).catch(lo=>{throw runtimeLoad=void 0,new Error(`Loading a Module Federation container needs @module-federation/runtime, which is an optional peer dependency of @datalayer/reactor. Install it, or pass a loader of your own. (${String(lo)})`)})),runtimeLoad}const HOST_NAME="datalayer_reactor_host";function sharedFromHost(Au={},lo={}){const $u=getReactorSharedModules(),Ru={};for(const[Iu,Pu]of Object.entries($u)){const{shareConfig:Ou,...Mu}=lo[Iu]??{};Ru[Iu]={lib:()=>Pu,version:Au[Iu],...Mu,shareConfig:{singleton:!0,requiredVersion:!1,...Ou}}}return Ru}let initialised;async function initReactorFederation(Au={}){if(initialised)return initialised;const lo=(async()=>{const $u=await federationRuntime();return $u.init({name:Au.name??HOST_NAME,remotes:Au.remotes??[],shared:Au.shared??sharedFromHost(Au.versions)}),$u})();return initialised=lo,lo.catch(()=>{initialised===lo&&(initialised=void 0)}),lo}async function registerFederatedRemote(Au,lo={}){assertOriginAllowed(Au.entry,lo.allowedOrigins,`the container ${Au.name}`),(await initReactorFederation()).registerRemotes([Au],{force:lo.force??!1})}function createFederationLoader(){return async(Au,lo)=>{const $u=lo?.scope;if(!$u)throw new Error(`${lo?.name??Au}: the federation loader needs a container name — pass \`scope\` on the remote reference.`);await registerFederatedRemote({name:$u,entry:Au,type:lo?.type},{allowedOrigins:lo?.allowedOrigins});const Ru=await initReactorFederation(),Iu=`${$u}/${(lo?.module??"./plugin").replace(/^\.\//,"")}`,Pu=await Ru.loadRemote(Iu);if(!Pu)throw new Error(`${lo?.name??$u}: the container at ${Au} exposes no ${Iu}.`);return Pu}}const federationLoader=createFederationLoader();function defineFederatedPlugin(Au,lo={}){return defineRemotePlugin(Au,{loader:federationLoader,...lo})}const SHARED_GLOBAL="__DATALAYER_REACTOR__",REACTOR_API_VERSION="v1",REACTOR_SHARED_MODULES=["react","react-dom","@datalayer/reactor","@datalayer/reactor/react"];function getReactorSharedModules(){return globalThis[SHARED_GLOBAL]?.shared??{}}function missingSharedModules(Au=REACTOR_SHARED_MODULES){const lo=getReactorSharedModules();return Au.filter($u=>!($u in lo))}const importRemoteModule=Au=>import(Au);class RemoteRefused extends Error{}function defineRemotePlugin(Au,lo={}){const{loader:$u=importRemoteModule,apiVersion:Ru=REACTOR_API_VERSION,allowedOrigins:Iu}=lo;return defineLazyPlugin({name:Au.name,version:Au.version,displayName:Au.displayName,description:Au.description,octicon:Au.octicon,emoji:Au.emoji,dependencies:Au.dependencies,activationEvents:Au.activationEvents,deactivationEvents:Au.deactivationEvents,requiredBackendPlugins:Au.requiredBackendPlugins,optionalBackendPlugins:Au.optionalBackendPlugins,load:async()=>{if(Au.apiVersion&&Au.apiVersion!==Ru)throw new RemoteRefused(`${Au.name} declares API version ${Au.apiVersion}; this host speaks ${Ru}.`);assertOriginAllowed(Au.entry,Iu,Au.name);const Pu=missingSharedModules();Pu.length>0&&console.warn(`[reactor] loading ${Au.name} from ${Au.entry} with these modules unpublished: ${Pu.join(", ")}. If it reaches for one it will get its own copy — call setReactorSharedModules() from the host before loading remotes.`);const Ou=await $u(Au.entry,{name:Au.name,scope:Au.scope,module:Au.module,type:Au.type,allowedOrigins:Iu}),Mu=Au.export?Ou[Au.export]:Ou.default??Ou;if(!Mu)throw new Error(`${Au.name}: ${Au.entry} has no ${Au.export?`export "${Au.export}"`:"default export"}.`);return Mu}})}async function bootstrapExtensions(Au,lo={}){const{fetchJson:$u,allowedOrigins:Ru,...Iu}=lo,Pu=Au.replace(/\/+$/,""),Ou=`${Pu}/plugins/frontend-extensions`,Mu={...Iu,allowedOrigins:/^[a-z]+:\/\//i.test(Pu)?[...Ru??[],Pu]:Ru};let Du;try{Du=($u?await $u(Ou):await fetch(Ou).then(Bu=>{if(!Bu.ok)throw new Error(`HTTP ${Bu.status}`);return Bu.json()}))??[]}catch(Lu){return console.warn(`[reactor] could not read ${Ou}:`,Lu),[]}return Du.map(Lu=>{const Bu=/^[a-z]+:\/\//i.test(Lu.entry)?Lu.entry:`${Pu}${Lu.entry}`,ju=Lu.kind==="federated",Fu=(Lu.plugins??[]).map(zu=>{const Uu=zu.scope??Lu.remoteName,Hu=zu.module??Lu.module,Vu={...zu,entry:Bu,apiVersion:Lu.apiVersion,scope:Uu,module:Hu,type:zu.type||Lu.remoteType||void 0};return(ju||zu.scope)&&Uu?defineFederatedPlugin({...Vu,scope:Uu},Mu):defineRemotePlugin(Vu,Mu)});return defineExtension({name:Lu.name,version:Lu.version,displayName:Lu.displayName,description:Lu.description,octicon:Lu.octicon,emoji:Lu.emoji,plugins:Fu})})}const AgentTools=defineContributionPoint("reactor.agentTools");function defineAgentTools(Au){const lo=new Set;for(const $u of Au.commands){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test($u.name))throw new Error(`${Au.id}: tool name '${$u.name}' must be letters, digits and underscores.`);if(lo.has($u.name))throw new Error(`${Au.id}: tool name '${$u.name}' is declared twice.`);lo.add($u.name)}return{...Au,toolset:Au.toolset??Au.commands.map($u=>$u.name)}}var ArrayExt;(function(Au){function lo(ed,td,nd=0,od=-1){let sd=ed.length;if(sd===0)return-1;nd<0?nd=Math.max(0,nd+sd):nd=Math.min(nd,sd-1),od<0?od=Math.max(0,od+sd):od=Math.min(od,sd-1);let ad;od<nd?ad=od+1+(sd-nd):ad=od-nd+1;for(let pd=0;pd<ad;++pd){let gd=(nd+pd)%sd;if(ed[gd]===td)return gd}return-1}Au.firstIndexOf=lo;function $u(ed,td,nd=-1,od=0){let sd=ed.length;if(sd===0)return-1;nd<0?nd=Math.max(0,nd+sd):nd=Math.min(nd,sd-1),od<0?od=Math.max(0,od+sd):od=Math.min(od,sd-1);let ad;nd<od?ad=nd+1+(sd-od):ad=nd-od+1;for(let pd=0;pd<ad;++pd){let gd=(nd-pd+sd)%sd;if(ed[gd]===td)return gd}return-1}Au.lastIndexOf=$u;function Ru(ed,td,nd=0,od=-1){let sd=ed.length;if(sd===0)return-1;nd<0?nd=Math.max(0,nd+sd):nd=Math.min(nd,sd-1),od<0?od=Math.max(0,od+sd):od=Math.min(od,sd-1);let ad;od<nd?ad=od+1+(sd-nd):ad=od-nd+1;for(let pd=0;pd<ad;++pd){let gd=(nd+pd)%sd;if(td(ed[gd],gd))return gd}return-1}Au.findFirstIndex=Ru;function Iu(ed,td,nd=-1,od=0){let sd=ed.length;if(sd===0)return-1;nd<0?nd=Math.max(0,nd+sd):nd=Math.min(nd,sd-1),od<0?od=Math.max(0,od+sd):od=Math.min(od,sd-1);let ad;nd<od?ad=nd+1+(sd-od):ad=nd-od+1;for(let pd=0;pd<ad;++pd){let gd=(nd-pd+sd)%sd;if(td(ed[gd],gd))return gd}return-1}Au.findLastIndex=Iu;function Pu(ed,td,nd=0,od=-1){let sd=Ru(ed,td,nd,od);return sd!==-1?ed[sd]:void 0}Au.findFirstValue=Pu;function Ou(ed,td,nd=-1,od=0){let sd=Iu(ed,td,nd,od);return sd!==-1?ed[sd]:void 0}Au.findLastValue=Ou;function Mu(ed,td,nd,od=0,sd=-1){let ad=ed.length;if(ad===0)return 0;od<0?od=Math.max(0,od+ad):od=Math.min(od,ad-1),sd<0?sd=Math.max(0,sd+ad):sd=Math.min(sd,ad-1);let pd=od,gd=sd-od+1;for(;gd>0;){let yd=gd>>1,_d=pd+yd;nd(ed[_d],td)<0?(pd=_d+1,gd-=yd+1):gd=yd}return pd}Au.lowerBound=Mu;function Du(ed,td,nd,od=0,sd=-1){let ad=ed.length;if(ad===0)return 0;od<0?od=Math.max(0,od+ad):od=Math.min(od,ad-1),sd<0?sd=Math.max(0,sd+ad):sd=Math.min(sd,ad-1);let pd=od,gd=sd-od+1;for(;gd>0;){let yd=gd>>1,_d=pd+yd;nd(ed[_d],td)>0?gd=yd:(pd=_d+1,gd-=yd+1)}return pd}Au.upperBound=Du;function Lu(ed,td,nd){if(ed===td)return!0;if(ed.length!==td.length)return!1;for(let od=0,sd=ed.length;od<sd;++od)if(nd?!nd(ed[od],td[od]):ed[od]!==td[od])return!1;return!0}Au.shallowEqual=Lu;function Bu(ed,td={}){let{start:nd,stop:od,step:sd}=td;if(sd===void 0&&(sd=1),sd===0)throw new Error("Slice `step` cannot be zero.");let ad=ed.length;nd===void 0?nd=sd<0?ad-1:0:nd<0?nd=Math.max(nd+ad,sd<0?-1:0):nd>=ad&&(nd=sd<0?ad-1:ad),od===void 0?od=sd<0?-1:ad:od<0?od=Math.max(od+ad,sd<0?-1:0):od>=ad&&(od=sd<0?ad-1:ad);let pd;sd<0&&od>=nd||sd>0&&nd>=od?pd=0:sd<0?pd=Math.floor((od-nd+1)/sd+1):pd=Math.floor((od-nd-1)/sd+1);let gd=[];for(let yd=0;yd<pd;++yd)gd[yd]=ed[nd+yd*sd];return gd}Au.slice=Bu;function ju(ed,td,nd){let od=ed.length;if(od<=1||(td<0?td=Math.max(0,td+od):td=Math.min(td,od-1),nd<0?nd=Math.max(0,nd+od):nd=Math.min(nd,od-1),td===nd))return;let sd=ed[td],ad=td<nd?1:-1;for(let pd=td;pd!==nd;pd+=ad)ed[pd]=ed[pd+ad];ed[nd]=sd}Au.move=ju;function Fu(ed,td=0,nd=-1){let od=ed.length;if(!(od<=1))for(td<0?td=Math.max(0,td+od):td=Math.min(td,od-1),nd<0?nd=Math.max(0,nd+od):nd=Math.min(nd,od-1);td<nd;){let sd=ed[td],ad=ed[nd];ed[td++]=ad,ed[nd--]=sd}}Au.reverse=Fu;function zu(ed,td,nd=0,od=-1){let sd=ed.length;if(sd<=1||(nd<0?nd=Math.max(0,nd+sd):nd=Math.min(nd,sd-1),od<0?od=Math.max(0,od+sd):od=Math.min(od,sd-1),nd>=od))return;let ad=od-nd+1;if(td>0?td=td%ad:td<0&&(td=(td%ad+ad)%ad),td===0)return;let pd=nd+td;Fu(ed,nd,pd-1),Fu(ed,pd,od),Fu(ed,nd,od)}Au.rotate=zu;function Uu(ed,td,nd=0,od=-1){let sd=ed.length;if(sd===0)return;nd<0?nd=Math.max(0,nd+sd):nd=Math.min(nd,sd-1),od<0?od=Math.max(0,od+sd):od=Math.min(od,sd-1);let ad;od<nd?ad=od+1+(sd-nd):ad=od-nd+1;for(let pd=0;pd<ad;++pd)ed[(nd+pd)%sd]=td}Au.fill=Uu;function Hu(ed,td,nd){let od=ed.length;td<0?td=Math.max(0,td+od):td=Math.min(td,od);for(let sd=od;sd>td;--sd)ed[sd]=ed[sd-1];ed[td]=nd}Au.insert=Hu;function Vu(ed,td){let nd=ed.length;if(td<0&&(td+=nd),td<0||td>=nd)return;let od=ed[td];for(let sd=td+1;sd<nd;++sd)ed[sd-1]=ed[sd];return ed.length=nd-1,od}Au.removeAt=Vu;function Gu(ed,td,nd=0,od=-1){let sd=lo(ed,td,nd,od);return sd!==-1&&Vu(ed,sd),sd}Au.removeFirstOf=Gu;function Wu(ed,td,nd=-1,od=0){let sd=$u(ed,td,nd,od);return sd!==-1&&Vu(ed,sd),sd}Au.removeLastOf=Wu;function Ku(ed,td,nd=0,od=-1){let sd=ed.length;if(sd===0)return 0;nd<0?nd=Math.max(0,nd+sd):nd=Math.min(nd,sd-1),od<0?od=Math.max(0,od+sd):od=Math.min(od,sd-1);let ad=0;for(let pd=0;pd<sd;++pd)nd<=od&&pd>=nd&&pd<=od&&ed[pd]===td||od<nd&&(pd<=od||pd>=nd)&&ed[pd]===td?ad++:ad>0&&(ed[pd-ad]=ed[pd]);return ad>0&&(ed.length=sd-ad),ad}Au.removeAllOf=Ku;function Ju(ed,td,nd=0,od=-1){let sd,ad=Ru(ed,td,nd,od);return ad!==-1&&(sd=Vu(ed,ad)),{index:ad,value:sd}}Au.removeFirstWhere=Ju;function Yu(ed,td,nd=-1,od=0){let sd,ad=Iu(ed,td,nd,od);return ad!==-1&&(sd=Vu(ed,ad)),{index:ad,value:sd}}Au.removeLastWhere=Yu;function Xu(ed,td,nd=0,od=-1){let sd=ed.length;if(sd===0)return 0;nd<0?nd=Math.max(0,nd+sd):nd=Math.min(nd,sd-1),od<0?od=Math.max(0,od+sd):od=Math.min(od,sd-1);let ad=0;for(let pd=0;pd<sd;++pd)nd<=od&&pd>=nd&&pd<=od&&td(ed[pd],pd)||od<nd&&(pd<=od||pd>=nd)&&td(ed[pd],pd)?ad++:ad>0&&(ed[pd-ad]=ed[pd]);return ad>0&&(ed.length=sd-ad),ad}Au.removeAllWhere=Xu})(ArrayExt||(ArrayExt={}));function*chain(...Au){for(const lo of Au)yield*lo}function*empty$3(){}function*enumerate(Au,lo=0){for(const $u of Au)yield[lo++,$u]}function*filter$3(Au,lo){let $u=0;for(const Ru of Au)lo(Ru,$u++)&&(yield Ru)}function find$3(Au,lo){let $u=0;for(const Ru of Au)if(lo(Ru,$u++))return Ru}function findIndex(Au,lo){let $u=0;for(const Ru of Au)if(lo(Ru,$u++))return $u-1;return-1}function min$1(Au,lo){let $u;for(const Ru of Au){if($u===void 0){$u=Ru;continue}lo(Ru,$u)<0&&($u=Ru)}return $u}function max$1(Au,lo){let $u;for(const Ru of Au){if($u===void 0){$u=Ru;continue}lo(Ru,$u)>0&&($u=Ru)}return $u}function minmax(Au,lo){let $u=!0,Ru,Iu;for(const Pu of Au)$u?(Ru=Pu,Iu=Pu,$u=!1):lo(Pu,Ru)<0?Ru=Pu:lo(Pu,Iu)>0&&(Iu=Pu);return $u?void 0:[Ru,Iu]}function toArray$1(Au){return Array.from(Au)}function toObject(Au){const lo={};for(const[$u,Ru]of Au)lo[$u]=Ru;return lo}function each(Au,lo){let $u=0;for(const Ru of Au)if(lo(Ru,$u++)===!1)return}function every$2(Au,lo){let $u=0;for(const Ru of Au)if(lo(Ru,$u++)===!1)return!1;return!0}function some$1(Au,lo){let $u=0;for(const Ru of Au)if(lo(Ru,$u++))return!0;return!1}function*map$5(Au,lo){let $u=0;for(const Ru of Au)yield lo(Ru,$u++)}function*range$1(Au,lo,$u){lo===void 0?(lo=Au,Au=0,$u=1):$u===void 0&&($u=1);const Ru=Private$w.rangeLength(Au,lo,$u);for(let Iu=0;Iu<Ru;Iu++)yield Au+$u*Iu}var Private$w;(function(Au){function lo($u,Ru,Iu){return Iu===0?1/0:$u>Ru&&Iu>0||$u<Ru&&Iu<0?0:Math.ceil((Ru-$u)/Iu)}Au.rangeLength=lo})(Private$w||(Private$w={}));function reduce(Au,lo,$u){const Ru=Au[Symbol.iterator]();let Iu=0,Pu=Ru.next();if(Pu.done&&$u===void 0)throw new TypeError("Reduce of empty iterable with no initial value.");if(Pu.done)return $u;let Ou=Ru.next();if(Ou.done&&$u===void 0)return Pu.value;if(Ou.done)return lo($u,Pu.value,Iu++);let Mu;$u===void 0?Mu=lo(Pu.value,Ou.value,Iu++):Mu=lo(lo($u,Pu.value,Iu++),Ou.value,Iu++);let Du;for(;!(Du=Ru.next()).done;)Mu=lo(Mu,Du.value,Iu++);return Mu}function*repeat$1(Au,lo){for(;0<lo--;)yield Au}function*once(Au){yield Au}function*retro(Au){if(typeof Au.retro=="function")yield*Au.retro();else for(let lo=Au.length-1;lo>-1;lo--)yield Au[lo]}function topologicSort(Au){let lo=[],$u=new Set,Ru=new Map;for(const Ou of Au)Iu(Ou);for(const[Ou]of Ru)Pu(Ou);return lo;function Iu(Ou){let[Mu,Du]=Ou,Lu=Ru.get(Du);Lu?Lu.push(Mu):Ru.set(Du,[Mu])}function Pu(Ou){if($u.has(Ou))return;$u.add(Ou);let Mu=Ru.get(Ou);if(Mu)for(const Du of Mu)Pu(Du);lo.push(Ou)}}function*stride(Au,lo){let $u=0;for(const Ru of Au)$u++%lo===0&&(yield Ru)}var StringExt;(function(Au){function lo(Ou,Mu,Du=0){let Lu=new Array(Mu.length);for(let Bu=0,ju=Du,Fu=Mu.length;Bu<Fu;++Bu,++ju){if(ju=Ou.indexOf(Mu[Bu],ju),ju===-1)return null;Lu[Bu]=ju}return Lu}Au.findIndices=lo;function $u(Ou,Mu,Du=0){let Lu=lo(Ou,Mu,Du);if(!Lu)return null;let Bu=0;for(let ju=0,Fu=Lu.length;ju<Fu;++ju){let zu=Lu[ju]-Du;Bu+=zu*zu}return{score:Bu,indices:Lu}}Au.matchSumOfSquares=$u;function Ru(Ou,Mu,Du=0){let Lu=lo(Ou,Mu,Du);if(!Lu)return null;let Bu=0,ju=Du-1;for(let Fu=0,zu=Lu.length;Fu<zu;++Fu){let Uu=Lu[Fu];Bu+=Uu-ju-1,ju=Uu}return{score:Bu,indices:Lu}}Au.matchSumOfDeltas=Ru;function Iu(Ou,Mu,Du){let Lu=[],Bu=0,ju=0,Fu=Mu.length;for(;Bu<Fu;){let zu=Mu[Bu],Uu=Mu[Bu];for(;++Bu<Fu&&Mu[Bu]===Uu+1;)Uu++;ju<zu&&Lu.push(Ou.slice(ju,zu)),zu<Uu+1&&Lu.push(Du(Ou.slice(zu,Uu+1))),ju=Uu+1}return ju<Ou.length&&Lu.push(Ou.slice(ju)),Lu}Au.highlight=Iu;function Pu(Ou,Mu){return Ou<Mu?-1:Ou>Mu?1:0}Au.cmp=Pu})(StringExt||(StringExt={}));function*take(Au,lo){if(lo<1)return;const $u=Au[Symbol.iterator]();let Ru;for(;0<lo--&&!(Ru=$u.next()).done;)yield Ru.value}function*zip(...Au){const lo=Au.map(Ru=>Ru[Symbol.iterator]());let $u=lo.map(Ru=>Ru.next());for(;every$2($u,Ru=>!Ru.done);$u=lo.map(Ru=>Ru.next()))yield $u.map(Ru=>Ru.value)}const index_es6$4=Object.freeze(Object.defineProperty({__proto__:null,get ArrayExt(){return ArrayExt},get StringExt(){return StringExt},chain,each,empty:empty$3,enumerate,every:every$2,filter:filter$3,find:find$3,findIndex,map:map$5,max:max$1,min:min$1,minmax,once,range:range$1,reduce,repeat:repeat$1,retro,some:some$1,stride,take,toArray:toArray$1,toObject,topologicSort,zip},Symbol.toStringTag,{value:"Module"}));var JSONExt;(function(Au){Au.emptyObject=Object.freeze({}),Au.emptyArray=Object.freeze([]);function lo(Bu){return Bu===null||typeof Bu=="boolean"||typeof Bu=="number"||typeof Bu=="string"}Au.isPrimitive=lo;function $u(Bu){return Array.isArray(Bu)}Au.isArray=$u;function Ru(Bu){return!lo(Bu)&&!$u(Bu)}Au.isObject=Ru;function Iu(Bu,ju){if(Bu===ju)return!0;if(lo(Bu)||lo(ju))return!1;let Fu=$u(Bu),zu=$u(ju);return Fu!==zu?!1:Fu&&zu?Ou(Bu,ju):Mu(Bu,ju)}Au.deepEqual=Iu;function Pu(Bu){return lo(Bu)?Bu:$u(Bu)?Du(Bu):Lu(Bu)}Au.deepCopy=Pu;function Ou(Bu,ju){if(Bu===ju)return!0;if(Bu.length!==ju.length)return!1;for(let Fu=0,zu=Bu.length;Fu<zu;++Fu)if(!Iu(Bu[Fu],ju[Fu]))return!1;return!0}function Mu(Bu,ju){if(Bu===ju)return!0;for(let Fu in Bu)if(Bu[Fu]!==void 0&&!(Fu in ju))return!1;for(let Fu in ju)if(ju[Fu]!==void 0&&!(Fu in Bu))return!1;for(let Fu in Bu){let zu=Bu[Fu],Uu=ju[Fu];if(!(zu===void 0&&Uu===void 0)&&(zu===void 0||Uu===void 0||!Iu(zu,Uu)))return!1}return!0}function Du(Bu){let ju=new Array(Bu.length);for(let Fu=0,zu=Bu.length;Fu<zu;++Fu)ju[Fu]=Pu(Bu[Fu]);return ju}function Lu(Bu){let ju={};for(let Fu in Bu){let zu=Bu[Fu];zu!==void 0&&(ju[Fu]=Pu(zu))}return ju}})(JSONExt||(JSONExt={}));class MimeData{constructor(){this._types=[],this._values=[]}types(){return this._types.slice()}hasData(lo){return this._types.indexOf(lo)!==-1}getData(lo){let $u=this._types.indexOf(lo);return $u!==-1?this._values[$u]:void 0}setData(lo,$u){this.clearData(lo),this._types.push(lo),this._values.push($u)}clearData(lo){let $u=this._types.indexOf(lo);$u!==-1&&(this._types.splice($u,1),this._values.splice($u,1))}clear(){this._types.length=0,this._values.length=0}}class PluginRegistry{constructor(lo={}){this._application=null,this._validatePlugin=()=>!0,this._plugins=new Map,this._services=new Map,lo.validatePlugin&&(console.info("Plugins may be rejected by the custom validation plugin method."),this._validatePlugin=lo.validatePlugin)}get application(){return this._application}set application(lo){if(this._application!==null)throw Error("PluginRegistry.application is already set. It cannot be overridden.");this._application=lo}get deferredPlugins(){return Array.from(this._plugins).filter(([lo,$u])=>$u.autoStart==="defer").map(([lo,$u])=>lo)}getPluginDescription(lo){var $u,Ru;return(Ru=($u=this._plugins.get(lo))===null||$u===void 0?void 0:$u.description)!==null&&Ru!==void 0?Ru:""}hasPlugin(lo){return this._plugins.has(lo)}isPluginActivated(lo){var $u,Ru;return(Ru=($u=this._plugins.get(lo))===null||$u===void 0?void 0:$u.activated)!==null&&Ru!==void 0?Ru:!1}listPlugins(){return Array.from(this._plugins.keys())}registerPlugin(lo){if(this._plugins.has(lo.id))throw new TypeError(`Plugin '${lo.id}' is already registered.`);if(!this._validatePlugin(lo))throw new Error(`Plugin '${lo.id}' is not valid.`);const $u=Private$v.createPluginData(lo);Private$v.ensureNoCycle($u,this._plugins,this._services),$u.provides&&this._services.set($u.provides,$u.id),this._plugins.set($u.id,$u)}registerPlugins(lo){for(const $u of lo)this.registerPlugin($u)}deregisterPlugin(lo,$u){const Ru=this._plugins.get(lo);if(Ru){if(Ru.activated&&!$u)throw new Error(`Plugin '${lo}' is still active.`);this._plugins.delete(lo)}}async activatePlugin(lo){const $u=this._plugins.get(lo);if(!$u)throw new ReferenceError(`Plugin '${lo}' is not registered.`);if($u.activated)return;if($u.promise)return $u.promise;const Ru=$u.requires.map(Pu=>this.resolveRequiredService(Pu)),Iu=$u.optional.map(Pu=>this.resolveOptionalService(Pu));return $u.promise=Promise.all([...Ru,...Iu]).then(Pu=>$u.activate.apply(void 0,[this.application,...Pu])).then(Pu=>{$u.service=Pu,$u.activated=!0,$u.promise=null}).catch(Pu=>{throw $u.promise=null,Pu}),$u.promise}async activatePlugins(lo,$u={}){switch(lo){case"defer":{const Ru=this.deferredPlugins.filter(Iu=>this._plugins.get(Iu).autoStart).map(Iu=>this.activatePlugin(Iu));await Promise.all(Ru);break}case"startUp":{const Iu=Private$v.collectStartupPlugins(this._plugins,$u).map(async Pu=>{try{return await this.activatePlugin(Pu)}catch(Ou){console.error(`Plugin '${Pu}' failed to activate.`,Ou)}});await Promise.all(Iu);break}}}async deactivatePlugin(lo){const $u=this._plugins.get(lo);if(!$u)throw new ReferenceError(`Plugin '${lo}' is not registered.`);if(!$u.activated)return[];if(!$u.deactivate)throw new TypeError(`Plugin '${lo}'#deactivate() method missing`);const Ru=Private$v.findDependents(lo,this._plugins,this._services),Iu=Ru.map(Pu=>this._plugins.get(Pu));for(const Pu of Iu)if(!Pu.deactivate)throw new TypeError(`Plugin ${Pu.id}#deactivate() method missing (depends on ${lo})`);for(const Pu of Iu){const Ou=[...Pu.requires,...Pu.optional].map(Mu=>{const Du=this._services.get(Mu);return Du?this._plugins.get(Du).service:null});await Pu.deactivate(this.application,...Ou),Pu.service=null,Pu.activated=!1}return Ru.pop(),Ru}async resolveRequiredService(lo){const $u=this._services.get(lo);if(!$u)throw new TypeError(`No provider for: ${lo.name}.`);const Ru=this._plugins.get($u);return Ru.activated||await this.activatePlugin($u),Ru.service}async resolveOptionalService(lo){const $u=this._services.get(lo);if(!$u)return null;const Ru=this._plugins.get($u);if(!Ru.activated)try{await this.activatePlugin($u)}catch(Iu){return console.error(Iu),null}return Ru.service}}var Private$v;(function(Au){class lo{constructor(Mu){var Du,Lu,Bu,ju;this._activated=!1,this._promise=null,this._service=null,this.id=Mu.id,this.description=(Du=Mu.description)!==null&&Du!==void 0?Du:"",this.activate=Mu.activate,this.deactivate=(Lu=Mu.deactivate)!==null&&Lu!==void 0?Lu:null,this.provides=(Bu=Mu.provides)!==null&&Bu!==void 0?Bu:null,this.autoStart=(ju=Mu.autoStart)!==null&&ju!==void 0?ju:!1,this.requires=Mu.requires?Mu.requires.slice():[],this.optional=Mu.optional?Mu.optional.slice():[]}get activated(){return this._activated}set activated(Mu){this._activated=Mu}get service(){return this._service}set service(Mu){this._service=Mu}get promise(){return this._promise}set promise(Mu){this._promise=Mu}}function $u(Ou){return new lo(Ou)}Au.createPluginData=$u;function Ru(Ou,Mu,Du){const Lu=[...Ou.requires,...Ou.optional],Bu=Fu=>{if(Fu===Ou.provides)return!0;const zu=Du.get(Fu);if(!zu)return!1;const Uu=Mu.get(zu),Hu=[...Uu.requires,...Uu.optional];return Hu.length===0?!1:(ju.push(zu),Hu.some(Bu)?!0:(ju.pop(),!1))};if(!Ou.provides||Lu.length===0)return;const ju=[Ou.id];if(Lu.some(Bu))throw new ReferenceError(`Cycle detected: ${ju.join(" -> ")}.`)}Au.ensureNoCycle=Ru;function Iu(Ou,Mu,Du){const Lu=new Array,Bu=Hu=>{const Vu=Mu.get(Hu),Gu=[...Vu.requires,...Vu.optional];Lu.push(...Gu.reduce((Wu,Ku)=>{const Ju=Du.get(Ku);return Ju&&Wu.push([Hu,Ju]),Wu},[]))};for(const Hu of Mu.keys())Bu(Hu);const ju=Lu.filter(Hu=>Hu[1]===Ou);let Fu=0;for(;ju.length>Fu;){const Hu=ju.length,Vu=new Set(ju.map(Gu=>Gu[0]));for(const Gu of Vu)Lu.filter(Wu=>Wu[1]===Gu).forEach(Wu=>{ju.includes(Wu)||ju.push(Wu)});Fu=Hu}const zu=topologicSort(ju),Uu=zu.findIndex(Hu=>Hu===Ou);return Uu===-1?[Ou]:zu.slice(0,Uu+1)}Au.findDependents=Iu;function Pu(Ou,Mu){const Du=new Set;for(const Lu of Ou.keys())Ou.get(Lu).autoStart===!0&&Du.add(Lu);if(Mu.startPlugins)for(const Lu of Mu.startPlugins)Du.add(Lu);if(Mu.ignorePlugins)for(const Lu of Mu.ignorePlugins)Du.delete(Lu);return Array.from(Du)}Au.collectStartupPlugins=Pu})(Private$v||(Private$v={}));class PromiseDelegate{constructor(){this.promise=new Promise((lo,$u)=>{this._resolve=lo,this._reject=$u})}resolve(lo){let $u=this._resolve;$u(lo)}reject(lo){let $u=this._reject;$u(lo)}}let Token$2=class{constructor(lo,$u){this.name=lo,this.description=$u??"",this._tokenStructuralPropertyT=null}};function fallbackRandomValues(Au){let lo=0;for(let $u=0,Ru=Au.length;$u<Ru;++$u)$u%4===0&&(lo=Math.random()*4294967295>>>0),Au[$u]=lo&255,lo>>>=8}var Random;(function(Au){Au.getRandomValues=(()=>{const lo=typeof window<"u"&&(window.crypto||window.msCrypto)||null;return lo&&typeof lo.getRandomValues=="function"?function(Ru){return lo.getRandomValues(Ru)}:fallbackRandomValues})()})(Random||(Random={}));function uuid4Factory(Au){const lo=new Uint8Array(16),$u=new Array(256);for(let Ru=0;Ru<16;++Ru)$u[Ru]="0"+Ru.toString(16);for(let Ru=16;Ru<256;++Ru)$u[Ru]=Ru.toString(16);return function(){return Au(lo),lo[6]=64|lo[6]&15,lo[8]=128|lo[8]&63,$u[lo[0]]+$u[lo[1]]+$u[lo[2]]+$u[lo[3]]+"-"+$u[lo[4]]+$u[lo[5]]+"-"+$u[lo[6]]+$u[lo[7]]+"-"+$u[lo[8]]+$u[lo[9]]+"-"+$u[lo[10]]+$u[lo[11]]+$u[lo[12]]+$u[lo[13]]+$u[lo[14]]+$u[lo[15]]}}var UUID;(function(Au){Au.uuid4=uuid4Factory(Random.getRandomValues)})(UUID||(UUID={}));class Signal{constructor(lo){this.sender=lo}connect(lo,$u){return Private$u.connect(this,lo,$u)}disconnect(lo,$u){return Private$u.disconnect(this,lo,$u)}emit(lo){Private$u.emit(this,lo)}}(function(Au){function lo(Du,Lu){Private$u.disconnectBetween(Du,Lu)}Au.disconnectBetween=lo;function $u(Du){Private$u.disconnectSender(Du)}Au.disconnectSender=$u;function Ru(Du){Private$u.disconnectReceiver(Du)}Au.disconnectReceiver=Ru;function Iu(Du){Private$u.disconnectAll(Du)}Au.disconnectAll=Iu;function Pu(Du){Private$u.disconnectAll(Du)}Au.clearData=Pu;function Ou(){return Private$u.exceptionHandler}Au.getExceptionHandler=Ou;function Mu(Du){let Lu=Private$u.exceptionHandler;return Private$u.exceptionHandler=Du,Lu}Au.setExceptionHandler=Mu})(Signal||(Signal={}));class Stream extends Signal{constructor(){super(...arguments),this._pending=new PromiseDelegate}async*[Symbol.asyncIterator](){let lo=this._pending;for(;;)try{const{args:$u,next:Ru}=await lo.promise;lo=Ru,yield $u}catch{return}}emit(lo){const $u=this._pending,Ru=this._pending=new PromiseDelegate;$u.resolve({args:lo,next:Ru}),super.emit(lo)}stop(){this._pending.promise.catch(()=>{}),this._pending.reject("stop"),this._pending=new PromiseDelegate}}var Private$u;(function(Au){Au.exceptionHandler=Wu=>{console.error(Wu)};function lo(Wu,Ku,Ju){Ju=Ju||void 0;let Yu=Du.get(Wu.sender);if(Yu||(Yu=[],Du.set(Wu.sender,Yu)),Fu(Yu,Wu,Ku,Ju))return!1;let Xu=Ju||Ku,ed=Lu.get(Xu);ed||(ed=[],Lu.set(Xu,ed));let td={signal:Wu,slot:Ku,thisArg:Ju};return Yu.push(td),ed.push(td),!0}Au.connect=lo;function $u(Wu,Ku,Ju){Ju=Ju||void 0;let Yu=Du.get(Wu.sender);if(!Yu||Yu.length===0)return!1;let Xu=Fu(Yu,Wu,Ku,Ju);if(!Xu)return!1;let ed=Ju||Ku,td=Lu.get(ed);return Xu.signal=null,Uu(Yu),Uu(td),!0}Au.disconnect=$u;function Ru(Wu,Ku){let Ju=Du.get(Wu);if(!Ju||Ju.length===0)return;let Yu=Lu.get(Ku);if(!(!Yu||Yu.length===0)){for(const Xu of Yu)Xu.signal&&Xu.signal.sender===Wu&&(Xu.signal=null);Uu(Ju),Uu(Yu)}}Au.disconnectBetween=Ru;function Iu(Wu){let Ku=Du.get(Wu);if(!(!Ku||Ku.length===0)){for(const Ju of Ku){if(!Ju.signal)continue;let Yu=Ju.thisArg||Ju.slot;Ju.signal=null,Uu(Lu.get(Yu))}Uu(Ku)}}Au.disconnectSender=Iu;function Pu(Wu){let Ku=Lu.get(Wu);if(!(!Ku||Ku.length===0)){for(const Ju of Ku){if(!Ju.signal)continue;let Yu=Ju.signal.sender;Ju.signal=null,Uu(Du.get(Yu))}Uu(Ku)}}Au.disconnectReceiver=Pu;function Ou(Wu){Iu(Wu),Pu(Wu)}Au.disconnectAll=Ou;function Mu(Wu,Ku){let Ju=Du.get(Wu.sender);if(!(!Ju||Ju.length===0))for(let Yu=0,Xu=Ju.length;Yu<Xu;++Yu){let ed=Ju[Yu];ed.signal===Wu&&zu(ed,Ku)}}Au.emit=Mu;const Du=new WeakMap,Lu=new WeakMap,Bu=new Set,ju=typeof requestAnimationFrame=="function"?requestAnimationFrame:setImmediate;function Fu(Wu,Ku,Ju,Yu){return find$3(Wu,Xu=>Xu.signal===Ku&&Xu.slot===Ju&&Xu.thisArg===Yu)}function zu(Wu,Ku){let{signal:Ju,slot:Yu,thisArg:Xu}=Wu;try{Yu.call(Xu,Ju.sender,Ku)}catch(ed){Au.exceptionHandler(ed)}}function Uu(Wu){Bu.size===0&&ju(Hu),Bu.add(Wu)}function Hu(){Bu.forEach(Vu),Bu.clear()}function Vu(Wu){ArrayExt.removeAllWhere(Wu,Gu)}function Gu(Wu){return Wu.signal===null}})(Private$u||(Private$u={}));const index_es6$3=Object.freeze(Object.defineProperty({__proto__:null,get Signal(){return Signal},Stream},Symbol.toStringTag,{value:"Module"}));class Poll{constructor(lo){var $u;this._disposed=new Signal(this),this._lingered=0,this._tick=new PromiseDelegate,this._ticked=new Signal(this),this._factory=lo.factory,this._linger=($u=lo.linger)!==null&&$u!==void 0?$u:Private$t.DEFAULT_LINGER,this._standby=lo.standby||Private$t.DEFAULT_STANDBY,this._state={...Private$t.DEFAULT_STATE,timestamp:new Date().getTime()};const Ru=lo.frequency||{},Iu=Math.max(Ru.interval||0,Ru.max||0,Private$t.DEFAULT_FREQUENCY.max);this.frequency={...Private$t.DEFAULT_FREQUENCY,...Ru,max:Iu},this.name=lo.name||Private$t.DEFAULT_NAME,(!("auto"in lo)||lo.auto)&&setTimeout(()=>this.start())}get disposed(){return this._disposed}get frequency(){return this._frequency}set frequency(lo){if(this.isDisposed||JSONExt.deepEqual(lo,this.frequency||{}))return;let{backoff:$u,interval:Ru,max:Iu}=lo;if(Ru=Math.round(Ru),Iu=Math.round(Iu),typeof $u=="number"&&$u<1)throw new Error("Poll backoff growth factor must be at least 1");if((Ru<0||Ru>Iu)&&Ru!==Poll.NEVER)throw new Error("Poll interval must be between 0 and max");if(Iu>Poll.MAX_INTERVAL&&Iu!==Poll.NEVER)throw new Error(`Max interval must be less than ${Poll.MAX_INTERVAL}`);this._frequency={backoff:$u,interval:Ru,max:Iu}}get isDisposed(){return this.state.phase==="disposed"}get standby(){return this._standby}set standby(lo){this.isDisposed||this.standby===lo||(this._standby=lo)}get state(){return this._state}get tick(){return this._tick.promise}get ticked(){return this._ticked}async*[Symbol.asyncIterator](){for(;!this.isDisposed;)yield this.state,await this.tick.catch(()=>{})}dispose(){this.isDisposed||(this._state={...Private$t.DISPOSED_STATE,timestamp:new Date().getTime()},this._tick.promise.catch(lo=>{}),this._tick.reject(new Error(`Poll (${this.name}) is disposed.`)),this._disposed.emit(void 0),Signal.clearData(this))}refresh(){return this.schedule({cancel:({phase:lo})=>lo==="refreshed",interval:Poll.IMMEDIATE,phase:"refreshed"})}async schedule(lo={}){if(this.isDisposed||lo.cancel&&lo.cancel(this.state))return;const $u=this._tick,Ru=new PromiseDelegate,Iu={interval:this.frequency.interval,payload:null,phase:"standby",timestamp:new Date().getTime(),...lo};if(this._state=Iu,this._tick=Ru,clearTimeout(this._timeout),this._ticked.emit(this.state),$u.resolve(this),await $u.promise,Iu.interval===Poll.NEVER){this._timeout=void 0;return}const Pu=()=>{this.isDisposed||this.tick!==Ru.promise||this._execute()};this._timeout=setTimeout(Pu,Iu.interval)}start(){return this.schedule({cancel:({phase:lo})=>lo!=="constructed"&&lo!=="standby"&&lo!=="stopped",interval:Poll.IMMEDIATE,phase:"started"})}stop(){return this.schedule({cancel:({phase:lo})=>lo==="stopped",interval:Poll.NEVER,phase:"stopped"})}get hidden(){return Private$t.hidden}_execute(){let lo=typeof this.standby=="function"?this.standby():this.standby;if(lo==="never"?lo=!1:lo==="when-hidden"&&(this.hidden?lo=++this._lingered>this._linger:(this._lingered=0,lo=!1)),lo){this.schedule();return}const $u=this.tick;this._factory(this.state).then(Ru=>{this.isDisposed||this.tick!==$u||this.schedule({payload:Ru,phase:this.state.phase==="rejected"?"reconnected":"resolved"})}).catch(Ru=>{this.isDisposed||this.tick!==$u||this.schedule({interval:Private$t.sleep(this.frequency,this.state),payload:Ru,phase:"rejected"})})}}(function(Au){Au.IMMEDIATE=0,Au.MAX_INTERVAL=2147483647,Au.NEVER=1/0})(Poll||(Poll={}));var Private$t;(function(Au){Au.DEFAULT_BACKOFF=3,Au.DEFAULT_FREQUENCY={backoff:!0,interval:1e3,max:30*1e3},Au.DEFAULT_LINGER=1,Au.DEFAULT_NAME="unknown",Au.DEFAULT_STANDBY="when-hidden",Au.DEFAULT_STATE={interval:Poll.NEVER,payload:null,phase:"constructed",timestamp:new Date(0).getTime()},Au.DISPOSED_STATE={interval:Poll.NEVER,payload:null,phase:"disposed",timestamp:new Date(0).getTime()};function lo(Ru,Iu){const{backoff:Pu,interval:Ou,max:Mu}=Ru;if(Ou===Poll.NEVER)return Ou;const Du=Pu===!0?Au.DEFAULT_BACKOFF:Pu===!1?1:Pu,Lu=$u(Ou,Iu.interval*Du);return Math.min(Mu,Lu)}Au.sleep=lo,Au.hidden=typeof document>"u"?!1:(document.addEventListener("visibilitychange",()=>{Au.hidden=document.visibilityState==="hidden"}),document.addEventListener("pagehide",()=>{Au.hidden=document.visibilityState==="hidden"}),document.visibilityState==="hidden");function $u(Ru,Iu){return Ru=Math.ceil(Ru),Iu=Math.floor(Iu),Math.floor(Math.random()*(Iu-Ru+1))+Ru}})(Private$t||(Private$t={}));class RateLimiter{constructor(lo,$u=500){this.args=void 0,this.payload=null,this.limit=$u,this.poll=new Poll({auto:!1,factory:async()=>{const{args:Ru}=this;return this.args=void 0,lo(...Ru)},frequency:{backoff:!1,interval:Poll.NEVER,max:Poll.NEVER},standby:"never"}),this.payload=new PromiseDelegate,this.poll.ticked.connect((Ru,Iu)=>{const{payload:Pu}=this;if(Iu.phase==="resolved"){this.payload=new PromiseDelegate,Pu.resolve(Iu.payload);return}if(Iu.phase==="rejected"||Iu.phase==="stopped"){this.payload=new PromiseDelegate,Pu.promise.catch(Ou=>{}),Pu.reject(Iu.payload);return}},this)}get isDisposed(){return this.payload===null}dispose(){this.isDisposed||(this.args=void 0,this.payload=null,this.poll.dispose())}async stop(){return this.poll.stop()}}class Debouncer extends RateLimiter{invoke(...lo){return this.args=lo,this.poll.schedule({interval:this.limit,phase:"invoked"}),this.payload.promise}}class Throttler extends RateLimiter{constructor(lo,$u){super(lo,typeof $u=="number"?$u:$u&&$u.limit),this._trailing=!1,typeof $u!="number"&&$u&&$u.edge==="trailing"&&(this._trailing=!0),this._interval=this._trailing?this.limit:Poll.IMMEDIATE}invoke(...lo){const $u=this.poll.state.phase!=="invoked";return($u||this._trailing)&&(this.args=lo),$u&&this.poll.schedule({interval:this._interval,phase:"invoked"}),this.payload.promise}}const index_es6$2=Object.freeze(Object.defineProperty({__proto__:null,Debouncer,get Poll(){return Poll},RateLimiter,Throttler},Symbol.toStringTag,{value:"Module"})),QueryClientContext=reactExports.createContext(void 0),useQueryClient=Au=>{const lo=reactExports.useContext(QueryClientContext);if(!lo)throw new Error("No QueryClient set, use QueryClientProvider to set one");return lo},QueryClientProvider=({client:Au,children:lo})=>(reactExports.useEffect(()=>(Au.mount(),()=>{Au.unmount()}),[Au]),jsxRuntimeExports.jsx(QueryClientContext.Provider,{value:Au,children:lo})),defaultTimeoutProvider={setTimeout:(Au,lo)=>setTimeout(Au,lo),clearTimeout:Au=>clearTimeout(Au),setInterval:(Au,lo)=>setInterval(Au,lo),clearInterval:Au=>clearInterval(Au)};var TimeoutManager=class{#e=defaultTimeoutProvider;#t=!1;setTimeoutProvider(Au){this.#e=Au}setTimeout(Au,lo){return this.#e.setTimeout(Au,lo)}clearTimeout(Au){this.#e.clearTimeout(Au)}setInterval(Au,lo){return this.#e.setInterval(Au,lo)}clearInterval(Au){this.#e.clearInterval(Au)}};const timeoutManager=new TimeoutManager;function systemSetTimeoutZero(Au){setTimeout(Au,0)}const isServer$1=typeof window>"u"||"Deno"in globalThis;function noop$2(){}function functionalUpdate(Au,lo){return typeof Au=="function"?Au(lo):Au}function isValidTimeout(Au){return typeof Au=="number"&&Au>=0&&Au!==1/0}function timeUntilStale(Au,lo){return Math.max(Au+(lo||0)-Date.now(),0)}function resolveQueryValue(Au,lo){return typeof Au=="function"?Au(lo):Au}function matchQuery(Au,lo){const{type:$u="all",exact:Ru,fetchStatus:Iu,predicate:Pu,queryKey:Ou,stale:Mu}=Au;if(Ou){if(Ru){if(lo.queryHash!==hashQueryKeyByOptions(Ou,lo.options))return!1}else if(!partialMatchKey(lo.queryKey,Ou))return!1}if($u!=="all"){const Du=lo.isActive();if($u==="active"&&!Du||$u==="inactive"&&Du)return!1}return!(typeof Mu=="boolean"&&lo.isStale()!==Mu||Iu&&Iu!==lo.state.fetchStatus||Pu&&!Pu(lo))}function matchMutation(Au,lo){const{exact:$u,status:Ru,predicate:Iu,mutationKey:Pu}=Au;if(Pu){if(!lo.options.mutationKey)return!1;if($u){if(hashKey(lo.options.mutationKey)!==hashKey(Pu))return!1}else if(!partialMatchKey(lo.options.mutationKey,Pu))return!1}return!(Ru&&lo.state.status!==Ru||Iu&&!Iu(lo))}function hashQueryKeyByOptions(Au,lo){return(lo?.queryKeyHashFn||hashKey)(Au)}function hashKey(Au){return JSON.stringify(Au,(lo,$u)=>isPlainObject$8($u)?Object.keys($u).sort().reduce((Ru,Iu)=>(Ru[Iu]=$u[Iu],Ru),{}):$u)}function partialMatchKey(Au,lo){if(Au===lo)return!0;if(typeof Au!=typeof lo)return!1;if(Au&&lo&&typeof Au=="object"&&typeof lo=="object"){if(Array.isArray(Au)&&Array.isArray(lo)){if(lo.length>Au.length)return!1;for(let Ru=0;Ru<lo.length;Ru++)if(!partialMatchKey(Au[Ru],lo[Ru]))return!1;return!0}const $u=Object.keys(lo);for(const Ru of $u)if(!partialMatchKey(Au[Ru],lo[Ru]))return!1;return!0}return!1}const hasOwn$1=Object.prototype.hasOwnProperty;function replaceEqualDeep(Au,lo,$u=0){if(Au===lo)return Au;if($u>500)return lo;const Ru=isPlainArray(Au)&&isPlainArray(lo);if(!Ru&&!(isPlainObject$8(Au)&&isPlainObject$8(lo)))return lo;const Iu=(Ru?Au:Object.keys(Au)).length,Pu=Ru?lo:Object.keys(lo),Ou=Pu.length,Mu=Ru?new Array(Ou):{};let Du=0;for(let Lu=0;Lu<Ou;Lu++){const Bu=Ru?Lu:Pu[Lu],ju=Au[Bu],Fu=lo[Bu];if(ju===Fu){Mu[Bu]=ju,(Ru?Lu<Iu:hasOwn$1.call(Au,Bu))&&Du++;continue}if(ju===null||Fu===null||typeof ju!="object"||typeof Fu!="object"){Mu[Bu]=Fu;continue}const zu=replaceEqualDeep(ju,Fu,$u+1);Mu[Bu]=zu,zu===ju&&Du++}return Iu===Ou&&Du===Iu?Au:Mu}function shallowEqualObjects(Au,lo){if(!lo||Object.keys(Au).length!==Object.keys(lo).length)return!1;for(const $u in Au)if(Au[$u]!==lo[$u])return!1;return!0}function isPlainArray(Au){return Array.isArray(Au)&&Au.length===Object.keys(Au).length}function isPlainObject$8(Au){if(!hasObjectPrototype(Au))return!1;const lo=Object.getPrototypeOf(Au),$u=lo?.constructor;if($u===void 0)return!0;if(typeof $u!="function")return!1;const Ru=$u.prototype;return!(!hasObjectPrototype(Ru)||!Ru.hasOwnProperty("isPrototypeOf")||lo!==Object.prototype)}function hasObjectPrototype(Au){return Object.prototype.toString.call(Au)==="[object Object]"}function sleep$2(Au){return new Promise(lo=>{timeoutManager.setTimeout(lo,Au)})}function replaceData(Au,lo,$u){return typeof $u.structuralSharing=="function"?$u.structuralSharing(Au,lo):$u.structuralSharing!==!1?replaceEqualDeep(Au,lo):lo}function addToEnd(Au,lo,$u=0){const Ru=[...Au,lo];return $u&&Ru.length>$u?Ru.slice(1):Ru}function addToStart(Au,lo,$u=0){const Ru=[lo,...Au];return $u&&Ru.length>$u?Ru.slice(0,-1):Ru}const skipToken=Symbol();function ensureQueryFn(Au,lo){return!Au.queryFn&&lo?.initialPromise?()=>lo.initialPromise:!Au.queryFn||Au.queryFn===skipToken?()=>Promise.reject(new Error(`Missing queryFn: '${Au.queryHash}'`)):Au.queryFn}function shouldThrowError(Au,lo){return typeof Au=="function"?Au(...lo):!!Au}function addConsumeAwareSignal(Au,lo,$u){let Ru=!1,Iu;return Object.defineProperty(Au,"signal",{enumerable:!0,get:()=>(Iu??=lo(),Ru||(Ru=!0,Iu.aborted?$u():Iu.addEventListener("abort",$u,{once:!0})),Iu)}),Au}let isServerFn=()=>isServer$1;const isServer=()=>isServerFn();var Subscribable=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(Au){return this.listeners.add(Au),this.onSubscribe(),()=>{this.listeners.delete(Au),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},FocusManager=class extends Subscribable{#e;#t;#r;constructor(){super(),this.#r=Au=>{if(typeof window<"u"&&window.addEventListener){const lo=()=>Au();return window.addEventListener("visibilitychange",lo,!1),()=>{window.removeEventListener("visibilitychange",lo)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(Au){this.#r=Au,this.#t?.(),this.#t=Au(lo=>{typeof lo=="boolean"?this.setFocused(lo):this.onFocus()})}setFocused(Au){this.#e!==Au&&(this.#e=Au,this.onFocus())}onFocus(){const Au=this.isFocused();this.listeners.forEach(lo=>{lo(Au)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}};const focusManager=new FocusManager,defaultScheduler=systemSetTimeoutZero;function createNotifyManager(){let Au=[],lo=0,$u=Mu=>{Mu()},Ru=Mu=>{Mu()},Iu=defaultScheduler;const Pu=Mu=>{lo?Au.push(Mu):Iu(()=>{$u(Mu)})},Ou=()=>{const Mu=Au;Au=[],Mu.length&&Iu(()=>{Ru(()=>{Mu.forEach(Du=>{$u(Du)})})})};return{batch:Mu=>{let Du;lo++;try{Du=Mu()}finally{lo--,lo||Ou()}return Du},batchCalls:Mu=>(...Du)=>{Pu(()=>{Mu(...Du)})},schedule:Pu,setNotifyFunction:Mu=>{$u=Mu},setBatchNotifyFunction:Mu=>{Ru=Mu},setScheduler:Mu=>{Iu=Mu}}}const notifyManager=createNotifyManager();var OnlineManager=class extends Subscribable{#e=!0;#t;#r;constructor(){super(),this.#r=Au=>{if(typeof window<"u"&&window.addEventListener){const lo=()=>Au(!0),$u=()=>Au(!1);return window.addEventListener("online",lo,!1),window.addEventListener("offline",$u,!1),()=>{window.removeEventListener("online",lo),window.removeEventListener("offline",$u)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(Au){this.#r=Au,this.#t?.(),this.#t=Au(this.setOnline.bind(this))}setOnline(Au){this.#e!==Au&&(this.#e=Au,this.listeners.forEach(lo=>{lo(Au)}))}isOnline(){return this.#e}};const onlineManager=new OnlineManager;function defaultRetryDelay(Au){return Math.min(1e3*2**Au,3e4)}function canFetch(Au){return(Au??"online")==="online"?onlineManager.isOnline():!0}var CancelledError=class extends Error{constructor(Au){super("CancelledError"),this.revert=Au?.revert,this.silent=Au?.silent}};function createRetryer(Au){let lo=!1,$u=0,Ru,Iu="pending",Pu,Ou;const Mu=new Promise((Wu,Ku)=>{Pu=Wu,Ou=Ku});Mu.catch(noop$2);const Du=()=>Iu!=="pending",Lu=Wu=>{if(!Du()){const Ku=new CancelledError(Wu);Hu(Ku),Au.onCancel?.(Ku)}},Bu=()=>{lo=!0},ju=()=>{lo=!1},Fu=()=>focusManager.isFocused()&&(Au.networkMode==="always"||onlineManager.isOnline())&&Au.canRun(),zu=()=>canFetch(Au.networkMode)&&Au.canRun(),Uu=Wu=>{Du()||(Ru?.(),Iu="resolved",Pu(Wu))},Hu=Wu=>{Du()||(Ru?.(),Iu="rejected",Ou(Wu))},Vu=Wu=>new Promise(Ku=>{Ru=Ju=>{(Du()||Wu())&&Ku(Ju)},Au.onPause?.()}).then(()=>{Ru=void 0,Du()||Au.onContinue?.()}),Gu=()=>{if(Du())return;let Wu;const Ku=$u===0?Au.initialPromise:void 0;try{Wu=Ku??Au.fn()}catch(Ju){Wu=Promise.reject(Ju)}Promise.resolve(Wu).then(Uu).catch(Ju=>{if(Du())return;const Yu=Au.retry??(isServer()?0:3),Xu=Au.retryDelay??defaultRetryDelay,ed=typeof Xu=="function"?Xu($u,Ju):Xu,td=Yu===!0||typeof Yu=="number"&&$u<Yu||typeof Yu=="function"&&Yu($u,Ju);if(lo||!td){Hu(Ju);return}$u++,Au.onFail?.($u,Ju),sleep$2(ed).then(()=>Fu()?void 0:Vu(Fu)).then(()=>{lo?Hu(Ju):Gu()})})};return{promise:Mu,status:()=>Iu,cancel:Lu,continue:()=>(Ru?.(),Mu),cancelRetry:Bu,continueRetry:ju,canStart:zu,start:()=>(zu()?Gu():Vu(zu).then(Gu),Mu)}}var Removable=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),isValidTimeout(this.gcTime)&&(this.#e=timeoutManager.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(Au){this.gcTime=Math.max(this.gcTime||0,Au??(isServer()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(timeoutManager.clearTimeout(this.#e),this.#e=void 0)}};function infiniteQueryBehavior(Au){return{onFetch:(lo,$u)=>{const Ru=lo.options,Iu=lo.fetchOptions?.meta?.fetchMore?.direction,Pu=lo.state.data?.pages||[],Ou=lo.state.data?.pageParams||[];let Mu={pages:[],pageParams:[]},Du=0;const Lu=async()=>{let Bu=!1;const ju=Uu=>{addConsumeAwareSignal(Uu,()=>lo.signal,()=>Bu=!0)},Fu=ensureQueryFn(lo.options,lo.fetchOptions),zu=async(Uu,Hu,Vu)=>{if(Bu)return Promise.reject(lo.signal.reason);if(Hu==null&&Uu.pages.length)return Promise.resolve(Uu);const Wu=(()=>{const Xu={client:lo.client,queryKey:lo.queryKey,pageParam:Hu,direction:Vu?"backward":"forward",meta:lo.options.meta};return ju(Xu),Xu})(),Ku=await Fu(Wu),{maxPages:Ju}=lo.options,Yu=Vu?addToStart:addToEnd;return{pages:Yu(Uu.pages,Ku,Ju),pageParams:Yu(Uu.pageParams,Hu,Ju)}};if(Iu&&Pu.length){const Uu=Iu==="backward",Hu=Uu?getPreviousPageParam:getNextPageParam,Vu={pages:Pu,pageParams:Ou};Mu=await zu(Vu,Hu(Ru,Vu),Uu)}else{const Uu=Au??Pu.length;do{const Hu=Du===0?Ou[0]===void 0?Ru.initialPageParam:Ou[0]:getNextPageParam(Ru,Mu);if(Du>0&&Hu==null)break;Mu=await zu(Mu,Hu),Du++}while(Du<Uu)}return Mu};lo.options.persister?lo.fetchFn=()=>lo.options.persister?.(Lu,{client:lo.client,queryKey:lo.queryKey,meta:lo.options.meta,signal:lo.signal},$u):lo.fetchFn=Lu}}}function getNextPageParam(Au,{pages:lo,pageParams:$u}){const Ru=lo.length-1;return lo.length>0?Au.getNextPageParam(lo[Ru],lo,$u[Ru],$u):void 0}function getPreviousPageParam(Au,{pages:lo,pageParams:$u}){return lo.length>0?Au.getPreviousPageParam?.(lo[0],lo,$u[0],$u):void 0}var Query=class extends Removable{#e;#t;#r;#n;#i;#o;#s;#l;constructor(Au){super(),this.#l=!1,this.#s=Au.defaultOptions,this.setOptions(Au.options),this.observers=[],this.#i=Au.client,this.#n=this.#i.getQueryCache(),this.queryKey=Au.queryKey,this.queryHash=Au.queryHash,this.#t=getDefaultState$1(this.options),this.state=Au.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#o?.promise}setOptions(Au){if(this.options={...this.#s,...Au},Au?._type&&(this.#e=Au._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const lo=getDefaultState$1(this.options);lo.data!==void 0&&(this.setState(successState(lo.data,lo.dataUpdatedAt)),this.#t=lo)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(Au,lo){const $u=replaceData(this.state.data,Au,this.options);return this.#a({data:$u,type:"success",dataUpdatedAt:lo?.updatedAt,manual:lo?.manual}),$u}setState(Au){this.#a({type:"setState",state:Au})}cancel(Au){const lo=this.#o?.promise;return this.#o?.cancel(Au),lo?lo.then(noop$2).catch(noop$2):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(Au=>resolveQueryValue(Au.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===skipToken||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(Au=>resolveQueryValue(Au.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(Au=>Au.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(Au=0){return this.state.data===void 0?!0:Au==="static"?!1:this.state.isInvalidated?!0:!timeUntilStale(this.state.dataUpdatedAt,Au)}onFocus(){this.observers.find(Au=>Au.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#o?.continue()}onOnline(){this.observers.find(Au=>Au.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#o?.continue()}addObserver(Au){this.observers.includes(Au)||(this.observers.push(Au),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",query:this,observer:Au}))}removeObserver(Au){const lo=this.observers.indexOf(Au);lo!==-1&&(this.observers.splice(lo,1),this.observers.length||(this.#o&&(this.#l||this.state.fetchStatus==="paused"&&this.state.status==="pending"?this.#o.cancel({revert:!0}):this.#o.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:Au}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#a({type:"invalidate"})}async fetch(Au,lo){if(this.state.fetchStatus!=="idle"&&this.#o?.status()!=="rejected"){if(this.state.data!==void 0&&lo?.cancelRefetch)this.cancel({silent:!0});else if(this.#o)return this.#o.continueRetry(),this.#o.promise}if(Au&&this.setOptions(Au),!this.options.queryFn){const Du=this.observers.find(Lu=>Lu.options.queryFn);Du&&this.setOptions(Du.options)}const $u=new AbortController,Ru=Du=>{Object.defineProperty(Du,"signal",{enumerable:!0,get:()=>(this.#l=!0,$u.signal)})},Iu=()=>{const Du=ensureQueryFn(this.options,lo),Bu=(()=>{const ju={client:this.#i,queryKey:this.queryKey,meta:this.meta};return Ru(ju),ju})();return this.#l=!1,this.options.persister?this.options.persister(Du,Bu,this):Du(Bu)},Ou=(()=>{const Du={fetchOptions:lo,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:Iu};return Ru(Du),Du})();(this.#e==="infinite"?infiniteQueryBehavior(this.options.pages):this.options.behavior)?.onFetch(Ou,this),this.#r=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==Ou.fetchOptions?.meta)&&this.#a({type:"fetch",meta:Ou.fetchOptions?.meta});const Mu=this.#o=createRetryer({initialPromise:lo?.initialPromise,fn:Ou.fetchFn,onCancel:Du=>{Du instanceof CancelledError&&Du.revert&&this.setState({...this.#r,fetchStatus:"idle"}),$u.abort()},onFail:(Du,Lu)=>{this.#a({type:"failed",failureCount:Du,error:Lu})},onPause:()=>{this.#a({type:"pause"})},onContinue:()=>{this.#a({type:"continue"})},retry:Ou.options.retry,retryDelay:Ou.options.retryDelay,networkMode:Ou.options.networkMode,canRun:()=>!0});try{const Du=await Mu.start();if(Du===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(Du),this.#n.config.onSuccess?.(Du,this),this.#n.config.onSettled?.(Du,this.state.error,this),Du}catch(Du){if(Du instanceof CancelledError){if(Du.silent)return this.#o.promise;if(Du.revert){if(this.state.data===void 0)throw Du;return this.state.data}}throw this.#a({type:"error",error:Du}),this.#n.config.onError?.(Du,this),this.#n.config.onSettled?.(this.state.data,Du,this),Du}finally{this.#o===Mu&&(this.#o=void 0),this.scheduleGc()}}#a(Au){const lo=$u=>{switch(Au.type){case"failed":return{...$u,fetchFailureCount:Au.failureCount,fetchFailureReason:Au.error};case"pause":return{...$u,fetchStatus:"paused"};case"continue":return{...$u,fetchStatus:"fetching"};case"fetch":return{...$u,...fetchState($u.data,this.options),fetchMeta:Au.meta??null};case"success":const Ru={...$u,...successState(Au.data,Au.dataUpdatedAt),dataUpdateCount:$u.dataUpdateCount+1,...!Au.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#r=Au.manual?Ru:void 0,Ru;case"error":const Iu=Au.error;return{...$u,error:Iu,errorUpdateCount:$u.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:$u.fetchFailureCount+1,fetchFailureReason:Iu,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...$u,isInvalidated:!0};case"setState":return{...$u,...Au.state}}};this.state=lo(this.state),notifyManager.batch(()=>{this.observers.slice().forEach($u=>{$u.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:Au})})}};function fetchState(Au,lo){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:canFetch(lo.networkMode)?"fetching":"paused",...Au===void 0&&{error:null,status:"pending"}}}function successState(Au,lo){return{data:Au,dataUpdatedAt:lo??Date.now(),error:null,isInvalidated:!1,status:"success"}}function getDefaultState$1(Au){const lo=typeof Au.initialData=="function"?Au.initialData():Au.initialData,$u=lo!==void 0,Ru=$u?typeof Au.initialDataUpdatedAt=="function"?Au.initialDataUpdatedAt():Au.initialDataUpdatedAt:0;return{data:lo,dataUpdateCount:0,dataUpdatedAt:$u?Ru??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:$u?"success":"pending",fetchStatus:"idle"}}var QueryObserver=class extends Subscribable{#e;#t=void 0;#r=void 0;#n=void 0;#i;#o;#s;#l;#a;#p;#u;#d;#c;#f=new Set;constructor(Au,lo){super(),this.options=lo,this.#e=Au,this.#s=null,this.bindMethods(),this.setOptions(lo)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),shouldFetchOnMount(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return shouldFetchOn(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return shouldFetchOn(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#_(),this.#x(),this.#t.removeObserver(this)}setOptions(Au){const lo=this.options,$u=this.#t;if(this.options=this.#e.defaultQueryOptions(Au),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof resolveQueryValue(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#t.setOptions(this.options),lo._defaulted&&!shallowEqualObjects(this.options,lo)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const Ru=this.hasListeners();Ru&&shouldFetchOptionally(this.#t,$u,this.options,lo)&&this.#h(),this.updateResult(),Ru&&(this.#t!==$u||resolveQueryValue(this.options.enabled,this.#t)!==resolveQueryValue(lo.enabled,this.#t)||resolveQueryValue(this.options.staleTime,this.#t)!==resolveQueryValue(lo.staleTime,this.#t))&&this.#g();const Iu=this.#v();Ru&&(this.#t!==$u||resolveQueryValue(this.options.enabled,this.#t)!==resolveQueryValue(lo.enabled,this.#t)||Iu!==this.#c)&&this.#b(Iu)}getOptimisticResult(Au){const lo=this.#e.getQueryCache().build(this.#e,Au),$u=this.createResult(lo,Au);return shallowEqualObjects(this.getCurrentResult(),$u)||(this.#n=$u,this.#o=this.options,this.#i=this.#t.state),$u}getCurrentResult(){return this.#n}trackResult(Au,lo){return new Proxy(Au,{get:($u,Ru)=>(this.trackProp(Ru),lo?.(Ru),Reflect.get($u,Ru))})}trackProp(Au){this.#f.add(Au)}getCurrentQuery(){return this.#t}refetch({...Au}={}){return this.fetch({...Au})}fetchOptimistic(Au){const lo=this.#e.defaultQueryOptions(Au),$u=this.#e.getQueryCache().build(this.#e,lo);let Ru=()=>{},Iu;const Pu=new Promise(Ou=>{Iu=Ou,Ru=this.#e.getQueryCache().subscribe(Mu=>{Mu.type==="updated"&&Mu.query.queryHash===$u.queryHash&&$u.state.data!==void 0&&(Ru(),Ou(this.createResult($u,lo)))})});return Promise.race([$u.fetch().then(()=>{const Ou=this.createResult($u,lo);return Iu?.(Ou),Ou}).finally(()=>{Ru()}),Pu])}fetch(Au){return this.#h({...Au,cancelRefetch:Au.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#n))}#h(Au){this.#S();let lo=this.#t.fetch(this.options,Au);return Au?.throwOnError||(lo=lo.catch(noop$2)),lo}#m(Au){return!isServer()&&resolveQueryValue(this.options.enabled,this.#t)!==!1&&isValidTimeout(Au)}#g(){this.#_();const Au=resolveQueryValue(this.options.staleTime,this.#t);if(this.#n.isStale||!this.#m(Au))return;const lo=timeUntilStale(this.#n.dataUpdatedAt,Au)+1;this.#u=timeoutManager.setTimeout(()=>{this.#n.isStale||this.updateResult()},lo)}#v(){return resolveQueryValue(this.options.refetchInterval,this.#t)??!1}#b(Au){this.#x(),this.#c=Au,!(this.#c===0||!this.#m(this.#c))&&(this.#d=timeoutManager.setInterval(()=>{(this.options.refetchIntervalInBackground||focusManager.isFocused())&&this.#h()},this.#c))}#y(){this.#g(),this.#b(this.#v())}#_(){this.#u!==void 0&&(timeoutManager.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(timeoutManager.clearInterval(this.#d),this.#d=void 0)}createResult(Au,lo){const $u=this.#t,Ru=this.options,Iu=this.#n,Pu=this.#i,Ou=this.#o,Mu=Au!==$u?Au.state:this.#r,{state:Du}=Au;let Lu={...Du},Bu=!1,ju;if(lo._optimisticResults){const Yu=this.hasListeners(),Xu=!Yu&&shouldFetchOnMount(Au,lo),ed=Yu&&shouldFetchOptionally(Au,$u,lo,Ru);(Xu||ed)&&(Lu={...Lu,...fetchState(Du.data,Au.options)}),lo._optimisticResults==="isRestoring"&&(Lu.fetchStatus="idle")}let{error:Fu,errorUpdatedAt:zu,status:Uu}=Lu;ju=Lu.data;let Hu=!1;if(lo.placeholderData!==void 0&&ju===void 0&&Uu==="pending"){let Yu;Iu?.isPlaceholderData&&lo.placeholderData===Ou?.placeholderData?(Yu=Iu.data,Hu=!0):Yu=typeof lo.placeholderData=="function"?lo.placeholderData(this.#p?.state.data,this.#p):lo.placeholderData,Yu!==void 0&&(Uu="success",ju=replaceData(Iu?.data,Yu,lo),Bu=!0)}if(lo.select&&ju!==void 0&&!Hu)if(Iu&&ju===Pu?.data&&lo.select===this.#l)ju=this.#a;else try{this.#l=lo.select,ju=lo.select(ju),ju=replaceData(Iu?.data,ju,lo),this.#a=ju,this.#s=null}catch(Yu){this.#s=Yu}else ju===void 0&&(this.#s=null);this.#s&&(Fu=this.#s,ju=this.#a,zu=Date.now(),Uu="error",Bu=!1);const Vu=Lu.fetchStatus==="fetching",Gu=Uu==="pending",Wu=Uu==="error",Ku=Gu&&Vu,Ju=ju!==void 0;return{status:Uu,fetchStatus:Lu.fetchStatus,isPending:Gu,isSuccess:Uu==="success",isError:Wu,isInitialLoading:Ku,isLoading:Ku,data:ju,dataUpdatedAt:Lu.dataUpdatedAt,error:Fu,errorUpdatedAt:zu,failureCount:Lu.fetchFailureCount,failureReason:Lu.fetchFailureReason,errorUpdateCount:Lu.errorUpdateCount,isFetched:Au.isFetched(),isFetchedAfterMount:Lu.dataUpdateCount>Mu.dataUpdateCount||Lu.errorUpdateCount>Mu.errorUpdateCount,isFetching:Vu,isRefetching:Vu&&!Gu,isLoadingError:Wu&&!Ju,isPaused:Lu.fetchStatus==="paused",isPlaceholderData:Bu,isRefetchError:Wu&&Ju,isStale:isStale(Au,lo),refetch:this.refetch,isEnabled:resolveQueryValue(lo.enabled,Au)!==!1}}updateResult(){const Au=this.#n,lo=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#o=this.options,this.#i.data!==void 0&&(this.#p=this.#t),shallowEqualObjects(lo,Au))return;this.#n=lo;const Ru=(()=>{if(!Au)return!0;const{notifyOnChangeProps:Iu}=this.options,Pu=typeof Iu=="function"?Iu():Iu;if(Pu==="all"||!Pu&&!this.#f.size)return!0;const Ou=new Set(Pu??this.#f);return this.options.throwOnError&&Ou.add("error"),Object.keys(this.#n).some(Mu=>{const Du=Mu;return this.#n[Du]!==Au[Du]&&Ou.has(Du)})})();notifyManager.batch(()=>{Ru&&this.listeners.forEach(Iu=>{Iu(this.#n)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}#S(){const Au=this.#e.getQueryCache().build(this.#e,this.options);if(Au===this.#t)return;const lo=this.#t;this.#t=Au,this.#r=Au.state,this.hasListeners()&&(lo?.removeObserver(this),Au.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function shouldLoadOnMount(Au,lo){return resolveQueryValue(lo.enabled,Au)!==!1&&Au.state.data===void 0&&!(Au.state.status==="error"&&resolveQueryValue(lo.retryOnMount,Au)===!1)}function shouldFetchOnMount(Au,lo){return shouldLoadOnMount(Au,lo)||Au.state.data!==void 0&&shouldFetchOn(Au,lo,lo.refetchOnMount)}function shouldFetchOn(Au,lo,$u){if(resolveQueryValue(lo.enabled,Au)!==!1&&resolveQueryValue(lo.staleTime,Au)!=="static"){const Ru=resolveQueryValue($u,Au);return Ru==="always"||Ru!==!1&&isStale(Au,lo)}return!1}function shouldFetchOptionally(Au,lo,$u,Ru){return(Au!==lo||resolveQueryValue(Ru.enabled,Au)===!1)&&(!$u.suspense||Au.state.status!=="error")&&isStale(Au,$u)}function isStale(Au,lo){return resolveQueryValue(lo.enabled,Au)!==!1&&Au.isStaleByTime(resolveQueryValue(lo.staleTime,Au))}var Mutation=class extends Removable{#e;#t;#r;#n;constructor(Au){super(),this.#e=Au.client,this.mutationId=Au.mutationId,this.#r=Au.mutationCache,this.#t=[],this.state=Au.state||getDefaultState(),this.setOptions(Au.options),this.scheduleGc()}setOptions(Au){this.options=Au,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(Au){this.#t.includes(Au)||(this.#t.push(Au),this.clearGcTimeout(),this.#r.notify({type:"observerAdded",mutation:this,observer:Au}))}removeObserver(Au){this.#t=this.#t.filter(lo=>lo!==Au),this.scheduleGc(),this.#r.notify({type:"observerRemoved",mutation:this,observer:Au})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#r.remove(this))}continue(){return this.#n?.continue()??(this.state.status==="pending"?this.execute(this.state.variables):Promise.resolve())}async execute(Au){const lo=()=>{this.#i({type:"continue"})},$u={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},Ru=this.#n=createRetryer({fn:()=>this.options.mutationFn?this.options.mutationFn(Au,$u):Promise.reject(new Error("No mutationFn found")),onFail:(Ou,Mu)=>{this.#i({type:"failed",failureCount:Ou,error:Mu})},onPause:()=>{this.#i({type:"pause"})},onContinue:lo,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#r.canRun(this)}),Iu=this.state.status==="pending",Pu=!Ru.canStart();try{if(Iu)lo();else{this.#i({type:"pending",variables:Au,isPaused:Pu}),this.#r.config.onMutate&&await this.#r.config.onMutate(Au,this,$u);const Mu=await this.options.onMutate?.(Au,$u);Mu!==this.state.context&&this.#i({type:"pending",context:Mu,variables:Au,isPaused:Pu})}const Ou=await Ru.start();return await this.#r.config.onSuccess?.(Ou,Au,this.state.context,this,$u),await this.options.onSuccess?.(Ou,Au,this.state.context,$u),await this.#r.config.onSettled?.(Ou,null,this.state.variables,this.state.context,this,$u),await this.options.onSettled?.(Ou,null,Au,this.state.context,$u),this.#i({type:"success",data:Ou}),Ou}catch(Ou){try{await this.#r.config.onError?.(Ou,Au,this.state.context,this,$u)}catch(Mu){Promise.reject(Mu)}try{await this.options.onError?.(Ou,Au,this.state.context,$u)}catch(Mu){Promise.reject(Mu)}try{await this.#r.config.onSettled?.(void 0,Ou,this.state.variables,this.state.context,this,$u)}catch(Mu){Promise.reject(Mu)}try{await this.options.onSettled?.(void 0,Ou,Au,this.state.context,$u)}catch(Mu){Promise.reject(Mu)}throw this.#i({type:"error",error:Ou}),Ou}finally{this.#n===Ru&&(this.#n=void 0),this.#r.runNext(this)}}#i(Au){const lo=$u=>{switch(Au.type){case"failed":return{...$u,failureCount:Au.failureCount,failureReason:Au.error};case"pause":return{...$u,isPaused:!0};case"continue":return{...$u,isPaused:!1};case"pending":return{...$u,context:Au.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:Au.isPaused,status:"pending",variables:Au.variables,submittedAt:Date.now()};case"success":return{...$u,data:Au.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...$u,data:void 0,error:Au.error,failureCount:$u.failureCount+1,failureReason:Au.error,isPaused:!1,status:"error"}}};this.state=lo(this.state),notifyManager.batch(()=>{this.#t.forEach($u=>{$u.onMutationUpdate(Au)}),this.#r.notify({mutation:this,type:"updated",action:Au})})}};function getDefaultState(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var MutationCache=class extends Subscribable{#e;#t;#r;constructor(Au={}){super(),this.config=Au,this.#e=new Set,this.#t=new Map,this.#r=0}build(Au,lo,$u){const Ru=new Mutation({client:Au,mutationCache:this,mutationId:++this.#r,options:Au.defaultMutationOptions(lo),state:$u});return this.add(Ru),Ru}add(Au){this.#e.add(Au);const lo=scopeFor(Au);if(typeof lo=="string"){const $u=this.#t.get(lo);$u?$u.push(Au):this.#t.set(lo,[Au])}this.notify({type:"added",mutation:Au})}remove(Au){if(this.#e.delete(Au)){const lo=scopeFor(Au);if(typeof lo=="string"){const $u=this.#t.get(lo);if($u)if($u.length>1){const Ru=$u.indexOf(Au);Ru!==-1&&$u.splice(Ru,1)}else $u[0]===Au&&this.#t.delete(lo)}}this.notify({type:"removed",mutation:Au})}canRun(Au){const lo=scopeFor(Au);if(typeof lo=="string"){const $u=this.#t.get(lo)?.find(Ru=>Ru.state.status==="pending");return!$u||$u===Au}else return!0}runNext(Au){const lo=scopeFor(Au);return typeof lo=="string"?this.#t.get(lo)?.find($u=>$u!==Au&&$u.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){notifyManager.batch(()=>{const Au=this.getAll();this.#e.clear(),this.#t.clear(),Au.forEach(lo=>{this.notify({type:"removed",mutation:lo})})})}getAll(){return Array.from(this.#e)}find(Au){const lo={exact:!0,...Au};return this.getAll().find($u=>matchMutation(lo,$u))}findAll(Au={}){return this.getAll().filter(lo=>matchMutation(Au,lo))}notify(Au){notifyManager.batch(()=>{this.listeners.forEach(lo=>{lo(Au)})})}resumePausedMutations(){const Au=this.getAll().filter(lo=>lo.state.isPaused);return notifyManager.batch(()=>Promise.all(Au.map(lo=>lo.continue().catch(noop$2))))}};function scopeFor(Au){return Au.options.scope?.id}var MutationObserver$1=class extends Subscribable{#e;#t=void 0;#r;#n;constructor(lo,$u){super(),this.#e=lo,this.setOptions($u),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(lo){const $u=this.options;this.options=this.#e.defaultMutationOptions(lo),shallowEqualObjects(this.options,$u)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#r,observer:this}),$u?.mutationKey&&this.options.mutationKey&&hashKey($u.mutationKey)!==hashKey(this.options.mutationKey)?this.reset():this.#r?.state.status==="pending"&&this.#r.setOptions(this.options)}onSubscribe(){this.listeners.size===1&&this.#r&&(this.#r.addObserver(this),this.#i())}onUnsubscribe(){this.hasListeners()||this.#r?.removeObserver(this)}onMutationUpdate(lo){this.#i(),this.#o(lo)}getCurrentResult(){return this.#t}reset(){this.#r?.removeObserver(this),this.#r=void 0,this.#i(),this.#o()}mutate(lo,$u){return this.#n=$u,this.#r?.removeObserver(this),this.#r=this.#e.getMutationCache().build(this.#e,this.options),this.#r.addObserver(this),this.#r.execute(lo)}#i(){const lo=this.#r?.state??getDefaultState();this.#t={...lo,isPending:lo.status==="pending",isSuccess:lo.status==="success",isError:lo.status==="error",isIdle:lo.status==="idle",mutate:this.mutate,reset:this.reset}}#o(lo){notifyManager.batch(()=>{const $u=this.#n;if($u&&this.hasListeners()){const Ru=this.#t.variables,Iu=this.#t.context,Pu={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(lo?.type==="success"){try{$u.onSuccess?.(lo.data,Ru,Iu,Pu)}catch(Ou){Promise.reject(Ou)}try{$u.onSettled?.(lo.data,null,Ru,Iu,Pu)}catch(Ou){Promise.reject(Ou)}}else if(lo?.type==="error"){try{$u.onError?.(lo.error,Ru,Iu,Pu)}catch(Ou){Promise.reject(Ou)}try{$u.onSettled?.(void 0,lo.error,Ru,Iu,Pu)}catch(Ou){Promise.reject(Ou)}}}this.listeners.forEach(Ru=>{Ru(this.#t)})})}},QueryCache=class extends Subscribable{#e;constructor(Au={}){super(),this.config=Au,this.#e=new Map}build(Au,lo,$u){const Ru=lo.queryKey,Iu=lo.queryHash??hashQueryKeyByOptions(Ru,lo);let Pu=this.get(Iu);return Pu||(Pu=new Query({client:Au,queryKey:Ru,queryHash:Iu,options:Au.defaultQueryOptions(lo),state:$u,defaultOptions:Au.getQueryDefaults(Ru)}),this.add(Pu)),Pu}add(Au){this.#e.has(Au.queryHash)||(this.#e.set(Au.queryHash,Au),this.notify({type:"added",query:Au}))}remove(Au){this.#e.get(Au.queryHash)===Au&&(Au.destroy(),this.#e.delete(Au.queryHash),this.notify({type:"removed",query:Au}))}clear(){notifyManager.batch(()=>{this.getAll().forEach(Au=>{this.remove(Au)})})}get(Au){return this.#e.get(Au)}getAll(){return[...this.#e.values()]}find(Au){const lo={exact:!0,...Au};return this.getAll().find($u=>matchQuery(lo,$u))}findAll(Au={}){const lo=this.getAll();return Object.keys(Au).length>0?lo.filter($u=>matchQuery(Au,$u)):lo}notify(Au){notifyManager.batch(()=>{this.listeners.forEach(lo=>{lo(Au)})})}onFocus(){notifyManager.batch(()=>{this.getAll().forEach(Au=>{Au.onFocus()})})}onOnline(){notifyManager.batch(()=>{this.getAll().forEach(Au=>{Au.onOnline()})})}},QueryClient=class{#e;#t;#r;#n;#i;#o;#s;#l;constructor(Au={}){this.#e=Au.queryCache||new QueryCache,this.#t=Au.mutationCache||new MutationCache,this.#r=Au.defaultOptions||{},this.#n=new Map,this.#i=new Map,this.#o=0}mount(){this.#o++,this.#o===1&&(this.#s=focusManager.subscribe(async Au=>{Au&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#l=onlineManager.subscribe(async Au=>{Au&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#o--,this.#o===0&&(this.#s?.(),this.#s=void 0,this.#l?.(),this.#l=void 0)}isFetching(Au){return this.#e.findAll({...Au,fetchStatus:"fetching"}).length}isMutating(Au){return this.#t.findAll({...Au,status:"pending"}).length}getQueryData(Au){const lo=this.defaultQueryOptions({queryKey:Au});return this.#e.get(lo.queryHash)?.state.data}ensureQueryData(Au){const lo=this.defaultQueryOptions(Au),$u=this.#e.build(this,lo),Ru=$u.state.data;return Ru===void 0?this.fetchQuery(Au):(Au.revalidateIfStale&&$u.isStaleByTime(resolveQueryValue(lo.staleTime,$u))&&this.prefetchQuery(lo),Promise.resolve(Ru))}getQueriesData(Au){return this.#e.findAll(Au).map(({queryKey:lo,state:$u})=>[lo,$u.data])}setQueryData(Au,lo,$u){const Ru=this.defaultQueryOptions({queryKey:Au}),Iu=this.#e.get(Ru.queryHash)?.state.data,Pu=functionalUpdate(lo,Iu);if(Pu!==void 0)return this.#e.build(this,Ru).setData(Pu,{...$u,manual:!0})}setQueriesData(Au,lo,$u){return notifyManager.batch(()=>this.#e.findAll(Au).map(({queryKey:Ru})=>[Ru,this.setQueryData(Ru,lo,$u)]))}getQueryState(Au){const lo=this.defaultQueryOptions({queryKey:Au});return this.#e.get(lo.queryHash)?.state}removeQueries(Au){const lo=this.#e;notifyManager.batch(()=>{lo.findAll(Au).forEach($u=>{lo.remove($u)})})}resetQueries(Au,lo){const $u=this.#e;return notifyManager.batch(()=>{const Ru=$u.findAll(Au),Iu=new Set(Ru);return Ru.forEach(Pu=>{Pu.reset()}),this.refetchQueries({type:"active",predicate:Pu=>Iu.has(Pu)},lo)})}cancelQueries(Au,lo={}){const $u={revert:!0,...lo},Ru=notifyManager.batch(()=>this.#e.findAll(Au).map(Iu=>Iu.cancel($u)));return Promise.all(Ru).then(noop$2).catch(noop$2)}invalidateQueries(Au,lo={}){return notifyManager.batch(()=>(this.#e.findAll(Au).forEach($u=>{$u.invalidate()}),Au?.refetchType==="none"?Promise.resolve():this.refetchQueries({...Au,type:Au?.refetchType??Au?.type??"active"},lo)))}refetchQueries(Au,lo={}){const $u={...lo,cancelRefetch:lo.cancelRefetch??!0},Ru=notifyManager.batch(()=>this.#e.findAll(Au).filter(Iu=>!Iu.isDisabled()&&!Iu.isStatic()).map(Iu=>{let Pu=Iu.fetch(void 0,$u);return $u.throwOnError||(Pu=Pu.catch(noop$2)),Iu.state.fetchStatus==="paused"?Promise.resolve():Pu}));return Promise.all(Ru).then(noop$2)}async query(Au){const lo=this.defaultQueryOptions(Au);lo.retry===void 0&&(lo.retry=!1);const $u=this.#e.build(this,lo),Ru=$u.isStaleByTime(resolveQueryValue(lo.staleTime,$u))?await $u.fetch(lo):$u.state.data,Iu=lo.select;return Iu?Iu(Ru):Ru}fetchQuery(Au){const lo=this.defaultQueryOptions(Au);lo.retry===void 0&&(lo.retry=!1);const $u=this.#e.build(this,lo);return $u.isStaleByTime(resolveQueryValue(lo.staleTime,$u))?$u.fetch(lo):Promise.resolve($u.state.data)}prefetchQuery(Au){return this.fetchQuery(Au).then(noop$2).catch(noop$2)}infiniteQuery(Au){return Au._type="infinite",this.query(Au)}fetchInfiniteQuery(Au){return Au._type="infinite",this.fetchQuery(Au)}prefetchInfiniteQuery(Au){return this.fetchInfiniteQuery(Au).then(noop$2).catch(noop$2)}ensureInfiniteQueryData(Au){return Au._type="infinite",this.ensureQueryData(Au)}resumePausedMutations(){return onlineManager.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#r}setDefaultOptions(Au){this.#r=Au}setQueryDefaults(Au,lo){this.#n.set(hashKey(Au),{queryKey:Au,defaultOptions:lo})}getQueryDefaults(Au){const lo=[...this.#n.values()],$u={};return lo.forEach(Ru=>{partialMatchKey(Au,Ru.queryKey)&&Object.assign($u,Ru.defaultOptions)}),$u}setMutationDefaults(Au,lo){this.#i.set(hashKey(Au),{mutationKey:Au,defaultOptions:lo})}getMutationDefaults(Au){const lo=[...this.#i.values()],$u={};return lo.forEach(Ru=>{partialMatchKey(Au,Ru.mutationKey)&&Object.assign($u,Ru.defaultOptions)}),$u}defaultQueryOptions(Au){if(Au._defaulted)return Au;const lo={...this.#r.queries,...this.getQueryDefaults(Au.queryKey),...Au,_defaulted:!0};return lo.queryHash||(lo.queryHash=hashQueryKeyByOptions(lo.queryKey,lo)),lo.refetchOnReconnect===void 0&&(lo.refetchOnReconnect=lo.networkMode!=="always"),lo.throwOnError===void 0&&(lo.throwOnError=!!lo.suspense),!lo.networkMode&&lo.persister&&(lo.networkMode="offlineFirst"),lo.queryFn===skipToken&&(lo.enabled=!1),lo}defaultMutationOptions(Au){return Au?._defaulted?Au:{...this.#r.mutations,...Au?.mutationKey&&this.getMutationDefaults(Au.mutationKey),...Au,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};const IsRestoringContext=reactExports.createContext(!1),useIsRestoring=()=>reactExports.useContext(IsRestoringContext);IsRestoringContext.Provider;function createValue(){let Au=!1;return{clearReset:()=>{Au=!1},reset:()=>{Au=!0},isReset:()=>Au}}const QueryErrorResetBoundaryContext=reactExports.createContext(createValue()),useQueryErrorResetBoundary=()=>reactExports.useContext(QueryErrorResetBoundaryContext),ensurePreventErrorBoundaryRetry=(Au,lo,$u)=>{const Ru=$u?.state.status==="error"&&typeof Au.throwOnError=="function"?shouldThrowError(Au.throwOnError,[$u.state.error,$u]):Au.throwOnError;(Au.suspense||Ru)&&(lo.isReset()||(Au.retryOnMount=!1))},useClearResetErrorBoundary=Au=>{reactExports.useEffect(()=>{Au.clearReset()},[Au])},getHasError=({result:Au,errorResetBoundary:lo,throwOnError:$u,query:Ru,suspense:Iu})=>Au.isError&&!lo.isReset()&&!Au.isFetching&&Ru&&(Iu&&Au.data===void 0||shouldThrowError($u,[Au.error,Ru])),ensureSuspenseTimers=Au=>{if(Au.suspense){const $u=Iu=>Iu==="static"?Iu:Math.max(Iu??1e3,1e3),Ru=Au.staleTime;Au.staleTime=typeof Ru=="function"?(...Iu)=>$u(Ru(...Iu)):$u(Ru),typeof Au.gcTime=="number"&&(Au.gcTime=Math.max(Au.gcTime,1e3))}},shouldSuspend=(Au,lo)=>Au?.suspense&&lo.isPending,fetchOptimistic=(Au,lo,$u)=>lo.fetchOptimistic(Au).catch(()=>{$u.clearReset()});function useBaseQuery(Au,lo,$u){const Ru=useIsRestoring(),Iu=useQueryErrorResetBoundary(),Pu=useQueryClient(),Ou=Pu.defaultQueryOptions(Au),Mu=Pu.getQueryCache().get(Ou.queryHash),Du=Au.subscribed!==!1;Ou._optimisticResults=Ru?"isRestoring":Du?"optimistic":void 0,ensureSuspenseTimers(Ou),ensurePreventErrorBoundaryRetry(Ou,Iu,Mu),useClearResetErrorBoundary(Iu);const[Lu]=reactExports.useState(()=>new lo(Pu,Ou)),Bu=Lu.getOptimisticResult(Ou),ju=!Ru&&Du;if(reactExports.useSyncExternalStore(reactExports.useCallback(Fu=>{const zu=ju?Lu.subscribe(notifyManager.batchCalls(Fu)):noop$2;return Lu.updateResult(),zu},[Lu,ju]),()=>Lu.getCurrentResult(),()=>Lu.getCurrentResult()),reactExports.useEffect(()=>{Lu.setOptions(Ou)},[Ou,Lu]),shouldSuspend(Ou,Bu))throw fetchOptimistic(Ou,Lu,Iu);if(getHasError({result:Bu,errorResetBoundary:Iu,throwOnError:Ou.throwOnError,query:Mu,suspense:Ou.suspense}))throw Bu.error;return Ou.notifyOnChangeProps?Bu:Lu.trackResult(Bu)}function useQuery(Au,lo){return useBaseQuery(Au,QueryObserver)}function useMutation(Au,lo){const $u=useQueryClient(),[Ru]=reactExports.useState(()=>new MutationObserver$1($u,Au));reactExports.useEffect(()=>{Ru.setOptions(Au)},[Ru,Au]);const Iu=reactExports.useSyncExternalStore(reactExports.useCallback(Ou=>Ru.subscribe(notifyManager.batchCalls(Ou)),[Ru]),()=>Ru.getCurrentResult(),()=>Ru.getCurrentResult()),Pu=reactExports.useCallback((...Ou)=>{Ru.mutate(Ou[0],Ou[1]).catch(noop$2)},[Ru]);if(Iu.error&&shouldThrowError(Ru.options.throwOnError,[Iu.error]))throw Iu.error;return{...Iu,mutate:Pu,mutateAsync:Iu.mutate}}function getCookie$1(Au){let lo;try{lo=document.cookie}catch{return lo}const $u=Au+"=",Iu=decodeURIComponent(document.cookie).split(";");for(let Pu=0;Pu<Iu.length;Pu++){let Ou=Iu[Pu];for(;Ou.charAt(0)===" ";)Ou=Ou.substring(1);if(Ou.indexOf($u)===0)return Ou.substring($u.length,Ou.length)}}function setCookie(Au,lo,$u="/"){const Ru=new Date,Pu=Ru.getTime()+1e3*36e3;Ru.setTime(Pu),document.cookie=`${Au}=${lo}; expires=${Ru.toUTCString()}; SameSite=Lax; path=${$u}`}function deleteCookie$1(Au){document.cookie=`${Au}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`}function createError(Au){const lo=new Error(Au);return lo.source="ulid",lo}const ENCODING="0123456789ABCDEFGHJKMNPQRSTVWXYZ",ENCODING_LEN=ENCODING.length,TIME_MAX=Math.pow(2,48)-1,TIME_LEN=10,RANDOM_LEN=16;function randomChar(Au){let lo=Math.floor(Au()*ENCODING_LEN);return lo===ENCODING_LEN&&(lo=ENCODING_LEN-1),ENCODING.charAt(lo)}function encodeTime(Au,lo){if(isNaN(Au))throw new Error(Au+" must be a number");if(Au>TIME_MAX)throw createError("cannot encode time greater than "+TIME_MAX);if(Au<0)throw createError("time must be positive");if(Number.isInteger(Number(Au))===!1)throw createError("time must be an integer");let $u,Ru="";for(;lo>0;lo--)$u=Au%ENCODING_LEN,Ru=ENCODING.charAt($u)+Ru,Au=(Au-$u)/ENCODING_LEN;return Ru}function encodeRandom(Au,lo){let $u="";for(;Au>0;Au--)$u=randomChar(lo)+$u;return $u}function detectPrng(Au=!1,lo){lo||(lo=typeof window<"u"?window:null);const $u=lo&&(lo.crypto||lo.msCrypto);if($u)return()=>{const Ru=new Uint8Array(1);return $u.getRandomValues(Ru),Ru[0]/255};try{const Ru=require("crypto");return()=>Ru.randomBytes(1).readUInt8()/255}catch{}if(Au){try{console.error("secure crypto unusable, falling back to insecure Math.random()!")}catch{}return()=>Math.random()}throw createError("secure crypto unusable, insecure Math.random not allowed")}function factory$1(Au){return Au||(Au=detectPrng()),function($u){return isNaN($u)&&($u=Date.now()),encodeTime($u,TIME_LEN)+encodeRandom(RANDOM_LEN,Au)}}const ulid$1=factory$1(),asDisplayName=(Au,lo)=>Au?lo?Au+" "+lo:Au:lo??"",namesAsInitials=(Au,lo)=>((Au||" ").charAt(0)+(lo||" ").charAt(0)).toLocaleUpperCase().trim(),toFriendlyName=(Au,lo)=>Au||lo||"";function parseJwtPayload(Au){try{const lo=Au.split(".");if(lo.length<2)return null;const $u=lo[1].replace(/-/g,"+").replace(/_/g,"/"),Ru=$u.padEnd($u.length+(4-$u.length%4)%4,"="),Iu=atob(Ru);return JSON.parse(Iu)}catch{return null}}function getJwtExpiryMs(Au){if(!Au)return null;const $u=parseJwtPayload(Au)?.exp;return typeof $u=="number"&&Number.isFinite($u)?$u*1e3:null}function isJwtExpired(Au,lo=0){const $u=getJwtExpiryMs(Au);return $u===null?!1:$u-lo*1e3<=Date.now()}var lib$d={},activitymonitor={};const require$$0$3=getAugmentedNamespace(index_es6$3);var hasRequiredActivitymonitor;function requireActivitymonitor(){if(hasRequiredActivitymonitor)return activitymonitor;hasRequiredActivitymonitor=1,Object.defineProperty(activitymonitor,"__esModule",{value:!0}),activitymonitor.ActivityMonitor=void 0;const Au=require$$0$3;class lo{constructor(Ru){this._timer=-1,this._timeout=-1,this._isDisposed=!1,this._activityStopped=new Au.Signal(this),Ru.signal.connect(this._onSignalFired,this),this._timeout=Ru.timeout||1e3}get activityStopped(){return this._activityStopped}get timeout(){return this._timeout}set timeout(Ru){this._timeout=Ru}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,Au.Signal.clearData(this))}_onSignalFired(Ru,Iu){clearTimeout(this._timer),this._sender=Ru,this._args=Iu,this._timer=setTimeout(()=>{this._activityStopped.emit({sender:this._sender,args:this._args})},this._timeout)}}return activitymonitor.ActivityMonitor=lo,activitymonitor}var interfaces$1={},hasRequiredInterfaces$1;function requireInterfaces$1(){return hasRequiredInterfaces$1||(hasRequiredInterfaces$1=1,Object.defineProperty(interfaces$1,"__esModule",{value:!0})),interfaces$1}var lru={},hasRequiredLru;function requireLru(){if(hasRequiredLru)return lru;hasRequiredLru=1,Object.defineProperty(lru,"__esModule",{value:!0}),lru.LruCache=void 0;const Au=128;class lo{constructor(Ru={}){if(this._map=new Map,this._maxSize=Ru?.maxSize||Au,this._maxSize<1)throw new Error("maxSize must be at least 1")}get size(){return this._map.size}clear(){this._map.clear()}get(Ru){const Iu=this._map.get(Ru)||null;return Iu!=null&&(this._map.delete(Ru),this._map.set(Ru,Iu)),Iu}set(Ru,Iu){!this._map.delete(Ru)&&this._map.size>=this._maxSize&&this._map.delete(this._map.keys().next().value),this._map.set(Ru,Iu)}}return lru.LruCache=lo,lru}var markdowncodeblocks={},hasRequiredMarkdowncodeblocks;function requireMarkdowncodeblocks(){if(hasRequiredMarkdowncodeblocks)return markdowncodeblocks;hasRequiredMarkdowncodeblocks=1,Object.defineProperty(markdowncodeblocks,"__esModule",{value:!0}),markdowncodeblocks.MarkdownCodeBlocks=void 0;var Au;return(function(lo){lo.CODE_BLOCK_MARKER="```";const $u=[".markdown",".mdown",".mkdn",".md",".mkd",".mdwn",".mdtxt",".mdtext",".text",".txt",".Rmd"];class Ru{constructor(Mu){this.startLine=Mu,this.code="",this.endLine=-1}}lo.MarkdownCodeBlock=Ru;function Iu(Ou){return $u.indexOf(Ou)>-1}lo.isMarkdown=Iu;function Pu(Ou){if(!Ou||Ou==="")return[];const Mu=Ou.split(`
|
|
252
|
+
`)[0]}`})}:parseAppspec(lo.toJS())}function defineContributionPoint(Au){if(!Au)throw new Error("defineContributionPoint: a contribution point needs an id");return{id:Au}}function contribution(Au,lo,$u){return{point:Au,value:lo,options:$u}}class ContributionRegistry{byPoint=new Map;byPlugin=new Map;seq=0;add(lo,$u,Ru,Iu={}){const Pu={plugin:lo,id:Iu.id??lo,order:Iu.order??0,value:Ru,seq:this.seq++},Ou=this.byPoint.get($u.id);Ou?Ou.push(Pu):this.byPoint.set($u.id,[Pu]);let Mu=!1;const Du=()=>{if(Mu)return;Mu=!0;const Bu=this.byPoint.get($u.id);if(Bu){const ju=Bu.indexOf(Pu);ju>=0&&Bu.splice(ju,1),Bu.length===0&&this.byPoint.delete($u.id)}this.byPlugin.get(lo)?.delete(Du)},Lu=this.byPlugin.get(lo);return Lu?Lu.add(Du):this.byPlugin.set(lo,new Set([Du])),Du}get(lo){const $u=this.byPoint.get(lo.id);return!$u||$u.length===0?[]:[...$u].sort((Ru,Iu)=>Ru.order===Iu.order?Ru.seq-Iu.seq:Ru.order-Iu.order).map(({plugin:Ru,id:Iu,order:Pu,value:Ou})=>({plugin:Ru,id:Iu,order:Pu,value:Ou}))}points(){return[...this.byPoint.keys()].sort()}describe(){return this.points().map(lo=>({point:lo,contributions:(this.byPoint.get(lo)??[]).slice().sort(($u,Ru)=>$u.order===Ru.order?$u.seq-Ru.seq:$u.order-Ru.order).map(({plugin:$u,id:Ru,order:Iu,value:Pu})=>({plugin:$u,id:Ru,order:Iu,value:Pu}))}))}disposePlugin(lo){const $u=this.byPlugin.get(lo);if($u){for(const Ru of[...$u])Ru();this.byPlugin.delete(lo)}}}let CommandRegistry$1=class{byId=new Map;byPlugin=new Map;listeners=new Set;seq=0;add(lo,$u){if(!$u.id)throw new Error("CommandRegistry.add: a command needs an id");const Ru=this.byId.get($u.id);if(Ru)throw new Error(`CommandRegistry.add: command '${$u.id}' is already registered by plugin '${Ru.plugin}'. Command ids must be unique; namespace them with the plugin they belong to.`);const Iu={plugin:lo,seq:this.seq++,command:$u};this.byId.set($u.id,Iu);let Pu=!1;const Ou=()=>{Pu||(Pu=!0,this.byId.get($u.id)===Iu&&this.byId.delete($u.id),this.byPlugin.get(lo)?.delete(Ou),this.notify())},Mu=this.byPlugin.get(lo);return Mu?Mu.add(Ou):this.byPlugin.set(lo,new Set([Ou])),this.notify(),Ou}get(lo){const $u=this.byId.get(lo);return $u?{...$u.command,plugin:$u.plugin}:void 0}list(){return[...this.byId.values()].sort((lo,$u)=>{const Ru=lo.command.order??0,Iu=$u.command.order??0;return Ru===Iu?lo.seq-$u.seq:Ru-Iu}).map(lo=>({...lo.command,plugin:lo.plugin}))}async execute(lo,$u){const Ru=this.byId.get(lo);if(!Ru)throw new Error(`CommandRegistry.execute: no command '${lo}' is registered`);if(Ru.command.isEnabled&&!Ru.command.isEnabled())throw new Error(`CommandRegistry.execute: command '${lo}' is not available right now`);return await Ru.command.execute($u)}subscribe(lo){return this.listeners.add(lo),()=>{this.listeners.delete(lo)}}disposePlugin(lo){const $u=this.byPlugin.get(lo);if($u){for(const Ru of[...$u])Ru();this.byPlugin.delete(lo)}}notify(){for(const lo of[...this.listeners])lo()}};const ON_STARTUP="onStartup",ON_ANY="*";function onContributionPoint(Au){return`onContributionPoint:${typeof Au=="string"?Au:Au.id}`}function onView(Au){return`onView:${Au}`}function matchesActivation(Au,lo){return!Au||Au.length===0?lo===ON_STARTUP:Au.some($u=>$u===ON_ANY||$u===lo)}function matchesDeactivation(Au,lo){return!Au||Au.length===0?!1:Au.some($u=>$u===ON_ANY||$u===lo)}function activatesAtStartup(Au){return matchesActivation(Au,ON_STARTUP)}function defineExtension(Au){if(!Au.name)throw new Error("defineExtension: an extension needs a name");if(!Array.isArray(Au.plugins)||Au.plugins.length===0)throw new Error(`defineExtension: ${Au.name} must group at least one plugin`);return Au}function isExtension(Au){return typeof Au=="object"&&Au!==null&&typeof Au.name=="string"&&Array.isArray(Au.plugins)}function defineGate(Au){return defineContributionPoint(Au)}function isRefusal(Au){return Au!==!0}function resolveGate(Au,lo){const $u=[];for(const Iu of Au){let Pu;try{Pu=Iu.value.check(lo)}catch(Ou){Pu=Ou instanceof Error?Ou.message:String(Ou)}isRefusal(Pu)&&$u.push({plugin:Iu.plugin,reason:Pu})}const Ru=$u[0];return{allowed:$u.length===0,reason:Ru?.reason,blockedBy:Ru?.plugin,refusals:$u}}function placeholderFor(Au){return{name:Au.name,version:Au.version,displayName:Au.displayName,description:Au.description,octicon:Au.octicon,emoji:Au.emoji,dependencies:Au.dependencies,activationEvents:Au.activationEvents,deactivationEvents:Au.deactivationEvents,requiredBackendPlugins:Au.requiredBackendPlugins,optionalBackendPlugins:Au.optionalBackendPlugins,contributionPoints:Au.contributionPoints}}function mergeLoaded(Au,lo){return{...lo,displayName:lo.displayName??Au.displayName,description:lo.description??Au.description,octicon:lo.octicon??Au.octicon,emoji:lo.emoji??Au.emoji,version:lo.version??Au.version,activationEvents:lo.activationEvents??Au.activationEvents,deactivationEvents:lo.deactivationEvents??Au.deactivationEvents,requiredBackendPlugins:lo.requiredBackendPlugins??Au.requiredBackendPlugins,optionalBackendPlugins:lo.optionalBackendPlugins??Au.optionalBackendPlugins,contributionPoints:lo.contributionPoints??Au.contributionPoints}}function shallowMergeConfig(Au,lo){return{...Au,...lo}}function normalizePlugins(Au){const lo=new Map,$u=new Map,Ru=new Map,Iu=new Map,Pu=Au.map(Ou=>({ref:Ou}));for(;Pu.length>0;){const Ou=Pu.shift();if(!Ou?.ref)continue;const{ref:Mu,from:Du}=Ou;if(isExtension(Mu)){Iu.set(Mu.name,Mu);for(const ju of Mu.plugins)Pu.push({ref:ju,from:Mu.name});continue}if(isLazyPluginRef(Mu)){if(!lo.has(Mu.name)){$u.set(Mu.name,Mu),lo.set(Mu.name,placeholderFor(Mu)),Du&&Ru.set(Mu.name,Du);for(const ju of Mu.dependencies??[])Pu.push({ref:ju})}continue}const Bu=asConfigured(Mu).plugin;if(!lo.has(Bu.name)){lo.set(Bu.name,Bu),Du&&Ru.set(Bu.name,Du);for(const ju of Bu.dependencies??[])Pu.push({ref:ju})}}return{plugins:Array.from(lo.values()),lazyByName:$u,extensionOf:Ru,extensions:Iu}}function topoSort(Au){const lo=new Map(Au.map(Ou=>[Ou.name,Ou])),$u=new Set,Ru=new Set,Iu=[];function Pu(Ou){if(Ru.has(Ou))return;if($u.has(Ou))throw new Error(`Circular dependency detected at ${Ou}`);$u.add(Ou);const Mu=lo.get(Ou);if(!Mu)throw new Error(`Unknown plugin ${Ou}`);for(const Du of Mu.dependencies??[])Pu(asConfigured(Du).plugin.name);$u.delete(Ou),Ru.add(Ou),Iu.push(Mu)}for(const Ou of Au)Pu(Ou.name);return Iu}function collectOverrides(Au){const lo=new Map,$u=[...Au];for(;$u.length>0;){const Ru=$u.shift();if(!Ru)continue;if(isExtension(Ru)){$u.push(...Ru.plugins);continue}if(isLazyPluginRef(Ru)){for(const Du of Ru.dependencies??[])$u.push(Du);continue}const Iu=asConfigured(Ru),Pu=Iu.plugin.name,Ou=lo.get(Pu)??{},Mu=shallowMergeConfig(Ou,Iu.config);lo.set(Pu,Mu);for(const Du of Iu.plugin.dependencies??[])$u.push(Du)}return lo}function buildReactorFromPlugins(Au,lo={}){const{plugins:$u,lazyByName:Ru,extensionOf:Iu,extensions:Pu}=normalizePlugins(Au),Ou=topoSort($u),Mu=new Map(Ou.map(hd=>[hd.name,hd])),Du=collectOverrides(Au),Lu=new Map,Bu=new Set,ju=new ContributionRegistry,Fu=new CommandRegistry$1;let zu=0,Uu=0,Hu,Vu=!1;const Gu=new Map,Wu=new Set,Ku=new Set;let Ju=new Set;function Yu(){if(!(Uu>0)){zu+=1;for(const hd of Bu)hd()}}function Xu(hd){Uu+=1;try{return hd()}finally{Uu-=1,Uu===0&&Yu()}}for(const hd of Ou){const vd=mergeWithDefaults(hd,Du.get(hd.name)??{});Lu.set(hd.name,{plugin:hd,config:vd,enabled:!0,activated:!1,extension:Iu.get(hd.name),lazy:Ru.get(hd.name),loaded:!Ru.has(hd.name)})}for(const hd of Ou){for(const vd of hd.conflictsWith??[])if(Mu.has(vd))throw new Error(`Plugin ${hd.name} conflicts with ${vd}`);for(const vd of hd.peerDependencies??[])if(!vd.optional&&!Mu.has(vd.name)&&lo.strictPeerDependencies)throw new Error(`Missing required peer dependency ${vd.name} for ${hd.name}`)}function ed(hd){const vd=[];for(const Sd of Ou){const kd=Lu.get(Sd.name);!kd||kd.activated||matchesActivation(kd.plugin.activationEvents,hd)&&vd.push(Sd.name)}return vd}function td(hd){if(!Wu.has(hd.id)){Wu.add(hd.id);const vd=onContributionPoint(hd);ed(vd).length>0&&Promise.resolve().then(()=>_d(vd))}return ju.get(hd)}const nd={hasPlugin(hd){return Lu.has(hd)},getOutput(hd){return Lu.get(hd)?.outputValue},getRequiredBackendPlugins(hd){return Lu.get(hd)?.plugin.requiredBackendPlugins??[]},getOptionalBackendPlugins(hd){return Lu.get(hd)?.plugin.optionalBackendPlugins??[]},getManifest(hd){const vd=Lu.get(hd);if(!vd)return;const{plugin:Sd}=vd;return{name:Sd.name,version:Sd.version,displayName:Sd.displayName??Sd.name,description:Sd.description,octicon:Sd.octicon,emoji:Sd.emoji,extension:vd.extension,requiredBackendPlugins:Sd.requiredBackendPlugins??[],optionalBackendPlugins:Sd.optionalBackendPlugins??[],loaded:vd.loaded,lazy:!!vd.lazy,activated:vd.activated,disabledBy:vd.enabled?void 0:vd.disabledBy??"user",loadError:vd.loadError?.message,activationEvents:Sd.activationEvents??[ON_STARTUP],deactivationEvents:Sd.deactivationEvents??[],contributionPoints:(Sd.contributionPoints??[]).map(kd=>kd.id),contributesTo:[...new Set((Sd.contributes??[]).map(kd=>kd.point.id))]}},isEnabled(hd){return Lu.get(hd)?.enabled??!1},getContributions(hd){return td(hd)},checkGate(hd,vd){return resolveGate(td(hd),vd)}};function od(hd,vd){return{plugin:vd.plugin,config:vd.config,state:{getConfig:()=>vd.config,getInit:()=>vd.initValue,getOutput:()=>vd.outputValue},reactor:nd,contribute(Sd,kd,Rd){const Od=ju.add(hd,Sd,kd,Rd);Yu();let jd=!1;return()=>{jd||(jd=!0,Od(),Yu())}},registerCommand(Sd){const kd=Fu.add(hd,Sd);Yu();let Rd=!1;return()=>{Rd||(Rd=!0,kd(),Yu())}}}}function sd(hd){const vd=Lu.get(hd);if(!vd)throw new Error(`Unknown plugin ${hd}`);if(!vd.loaded)return;const Sd=od(hd,vd);vd.initValue=vd.plugin.init?.(Sd),vd.outputValue=vd.plugin.build?.(Sd)}function ad(hd){const vd=Lu.get(hd);if(!vd||!vd.enabled||!vd.loaded)return;const Sd=od(hd,vd);for(const kd of vd.plugin.contributes??[])ju.add(hd,kd.point,kd.value,kd.options);for(const kd of vd.plugin.commands??[])Fu.add(hd,kd);Yu(),vd.registerDispose=vd.plugin.register?.(Sd)??void 0,vd.afterDispose=vd.plugin.afterRegistration?.(Sd)??void 0}function pd(hd){const vd=Lu.get(hd);!vd||vd.activated||!vd.loaded||(vd.activated=!0,Xu(()=>{vd.enabled&&(vd.plugin.preserveOutput&&vd.outputValue!==void 0||sd(hd),ad(hd))}))}async function gd(hd){const vd=Lu.get(hd);if(!(!vd?.lazy||vd.loaded)){vd.loading??=Promise.resolve().then(()=>vd.lazy.load());try{const Sd=await vd.loading;if(vd.loaded)return;const kd=Sd.default??Sd;if(!kd||typeof kd!="object"||!kd.name)throw new Error(`Lazy plugin ${hd} did not resolve to a plugin`);vd.plugin=mergeLoaded(vd.lazy,kd),vd.config=mergeWithDefaults(vd.plugin,Du.get(hd)??{}),vd.loaded=!0}catch(Sd){vd.loadError=Sd instanceof Error?Sd:new Error(String(Sd)),Yu()}}}function yd(hd){const vd=Lu.get(hd);if(!vd||vd.activated)return Promise.resolve();const Sd=Gu.get(hd);if(Sd)return Sd;const kd=(async()=>{for(const Rd of vd.plugin.dependencies??[])await yd(asConfigured(Rd).plugin.name);vd.lazy&&!vd.loaded&&await gd(hd),pd(hd),Ku.delete(hd)})().finally(()=>{Gu.delete(hd)});return Gu.set(hd,kd),kd}async function _d(hd){const vd=ed(hd);if(vd.length===0)return[];for(const Sd of vd){const kd=Lu.get(Sd);kd?.lazy&&!kd.loaded&&(kd.loading??=Promise.resolve().then(()=>kd.lazy.load()))}for(const Sd of vd)await yd(Sd);return vd.filter(Sd=>Lu.get(Sd)?.activated)}function bd(hd){const vd=new Set([hd]);for(const Sd of Ou)(Sd.dependencies??[]).some(Rd=>vd.has(asConfigured(Rd).plugin.name))&&vd.add(Sd.name);return vd.delete(hd),Ou.map(Sd=>Sd.name).filter(Sd=>vd.has(Sd)).reverse()}function wd(hd){return(Lu.get(hd)?.plugin?.dependencies??[]).every(Sd=>Lu.get(asConfigured(Sd).plugin.name)?.enabled??!0)}function Ed(hd){const vd=Lu.get(hd);if(!vd||vd.enabled||(vd.enabled=!0,vd.disabledBy=void 0,!vd.loaded||!vd.activated))return;vd.plugin.preserveOutput&&vd.outputValue!==void 0||sd(hd),ad(hd)}function cd(hd,vd="other"){const Sd=Lu.get(hd);if(!Sd)throw new Error(`Unknown plugin ${hd}`);if(vd==="other"&&Ku.delete(hd),!Sd.activated)return[];const kd=[];if(Xu(()=>{for(const Rd of bd(hd)){const Od=Lu.get(Rd);Od?.activated&&(ld(Rd),Od.activated=!1,ud(Rd),kd.push(Rd))}ld(hd),Sd.activated=!1,ud(hd),kd.push(hd)}),vd==="other")for(const Rd of kd)Ku.delete(Rd);return kd}function ud(hd){const vd=Lu.get(hd)?.plugin.activationEvents??[];for(const Sd of vd)Sd.startsWith("onContributionPoint:")&&Wu.delete(Sd.slice(20))}function md(hd){const vd=[];for(const Sd of Ou){const kd=Lu.get(Sd.name);kd?.activated&&matchesDeactivation(kd.plugin.deactivationEvents,hd)&&vd.push(...cd(Sd.name))}return vd}function ld(hd){const vd=Lu.get(hd);vd&&(vd.afterDispose?.(),vd.afterDispose=void 0,vd.registerDispose?.(),vd.registerDispose=void 0,ju.disposePlugin(hd),Fu.disposePlugin(hd))}return{...nd,start(){Vu=!0,Xu(()=>{const hd=Ou.filter(vd=>{const Sd=Lu.get(vd.name);return Sd&&Sd.loaded&&!Sd.activated&&activatesAtStartup(Sd.plugin.activationEvents)});for(const vd of hd)Lu.get(vd.name).activated=!0,sd(vd.name);for(const vd of hd)ad(vd.name)}),Hu=_d(ON_STARTUP).then(()=>{})},whenReady(){return Hu??Promise.resolve()},async fire(hd){const vd=md(hd),Sd=await _d(hd);return{deactivated:vd,activated:Sd}},deactivate(hd){cd(hd)},async setBackendPlugins(hd){Ju=new Set(hd);const vd=Rd=>(Lu.get(Rd)?.plugin.requiredBackendPlugins??[]).every(Od=>Ju.has(Od)),Sd=[];for(const Rd of Ou){if(!Lu.get(Rd.name)?.activated||vd(Rd.name))continue;const jd=cd(Rd.name,"backend");for(const Cd of jd)Ku.add(Cd);Sd.push(...jd)}const kd=[];for(const Rd of Ou){const Od=Rd.name;!Ku.has(Od)||!vd(Od)||!Lu.get(Od)?.enabled||(Ku.delete(Od),await yd(Od),Lu.get(Od)?.activated&&kd.push(Od))}return{deactivated:Sd,activated:kd}},async install(hd){const vd=normalizePlugins([hd]),Sd=vd.plugins.filter(jd=>!Lu.has(jd.name));if(Sd.length===0)return[];for(const jd of Sd)for(const Cd of jd.conflictsWith??[])if(Mu.has(Cd)||Sd.some(Ad=>Ad.name===Cd))throw new Error(`Plugin ${jd.name} conflicts with ${Cd}`);for(const[jd,Cd]of vd.lazyByName)Ru.set(jd,Cd);for(const[jd,Cd]of vd.extensionOf)Iu.set(jd,Cd);for(const[jd,Cd]of vd.extensions)Pu.set(jd,Cd);const kd=collectOverrides([hd]);for(const jd of Sd)Mu.set(jd.name,jd),Lu.set(jd.name,{plugin:jd,config:mergeWithDefaults(jd,kd.get(jd.name)??{}),enabled:!0,activated:!1,extension:Iu.get(jd.name),lazy:Ru.get(jd.name),loaded:!Ru.has(jd.name)});const Rd=topoSort([...Ou,...Sd]);if(Ou.splice(0,Ou.length,...Rd),Yu(),!Vu)return Sd.map(jd=>jd.name);const Od=[];for(const jd of Rd)Sd.some(Cd=>Cd.name===jd.name)&&(Od.push(jd.name),activatesAtStartup(jd.activationEvents)&&await yd(jd.name));return Od},stop(){Vu=!1,Xu(()=>{for(const hd of[...Ou].reverse()){ld(hd.name);const vd=Lu.get(hd.name);vd&&(vd.activated=!1)}Wu.clear()})},enable(hd){const vd=Lu.get(hd);if(!vd)throw new Error(`Unknown plugin ${hd}`);vd.enabled||Xu(()=>{Ed(hd);for(const Sd of[...bd(hd)].reverse()){const kd=Lu.get(Sd);!kd||kd.enabled||kd.disabledBy==="dependency"&&wd(Sd)&&Ed(Sd)}})},disable(hd){const vd=Lu.get(hd);if(!vd)throw new Error(`Unknown plugin ${hd}`);vd.enabled&&Xu(()=>{for(const Sd of bd(hd)){const kd=Lu.get(Sd);kd?.enabled&&(kd.enabled=!1,kd.disabledBy="dependency",ld(Sd))}vd.enabled=!1,vd.disabledBy="user",ld(hd)})},subscribe(hd){return Bu.add(hd),()=>{Bu.delete(hd)}},listPlugins(){return Ou.map(hd=>hd.name)},listExtensions(){return[...Pu.keys()]},getExtensionManifest(hd){const vd=Pu.get(hd);if(vd)return{name:vd.name,version:vd.version,displayName:vd.displayName??vd.name,description:vd.description,octicon:vd.octicon,emoji:vd.emoji,plugins:Ou.filter(Sd=>Iu.get(Sd.name)===hd).map(Sd=>Sd.name)}},getConfig(hd){return Lu.get(hd)?.config},describeContributions(){return ju.describe()},listCommands(){return Fu.list()},getCommand(hd){return Fu.get(hd)},executeCommand(hd,vd){return Fu.execute(hd,vd)},getDependencies(hd){return(Lu.get(hd)?.plugin.dependencies??[]).map(vd=>asConfigured(vd).plugin.name)},getRevision(){return zu}}}function definePlugin(Au){return Au}function defineLazyPlugin(Au){if(!Au.name)throw new Error("defineLazyPlugin: a lazy plugin needs a name");if(typeof Au.load!="function")throw new Error(`defineLazyPlugin: ${Au.name} needs a load function`);return Au}function isLazyPluginRef(Au){return typeof Au=="object"&&Au!==null&&typeof Au.load=="function"&&typeof Au.name=="string"&&!("plugin"in Au)}function configurePlugin(Au,lo){return{plugin:Au,config:lo}}function asConfigured(Au){return"plugin"in Au?Au:{plugin:Au,config:{}}}function mergeWithDefaults(Au,lo){const $u=Au.config??{};return Au.mergeConfig?Au.mergeConfig($u,lo):shallowMergeConfig($u,lo)}let activeEffect=null;class ReactiveEffect{runFn;dependencies=new Set;runner;constructor(lo){this.runFn=lo,this.runner=this.run.bind(this)}run(){for(const $u of this.dependencies)$u.subscribers.delete(this.runner);this.dependencies.clear();const lo=activeEffect;activeEffect=this;try{this.runFn()}finally{activeEffect=lo}}}class SignalImpl{_value;subscribers=new Set;constructor(lo){this._value=lo}get value(){return activeEffect&&(this.subscribers.add(activeEffect.runner),activeEffect.dependencies.add(this)),this._value}set value(lo){if(Object.is(this._value,lo))return;this._value=lo;const $u=Array.from(this.subscribers);for(const Ru of $u)queueSubscriber(Ru)}peek(){return this._value}}function queueSubscriber(Au){Au()}function signal$2(Au){return new SignalImpl(Au)}function effect$1(Au){const lo=new ReactiveEffect(Au);return lo.runner(),()=>{for(const $u of lo.dependencies)$u.subscribers.delete(lo.runner);lo.dependencies.clear()}}function computed$1(Au){const lo=signal$2(Au());return effect$1(()=>{lo.value=Au()}),{get value(){return lo.value},peek:()=>lo.peek()}}function isApplePlatform(){if(typeof navigator>"u")return!1;const lo=navigator.userAgentData?.platform??navigator.platform??"",$u=navigator.userAgent??"";return/mac|iphone|ipad|ipod/i.test(`${lo} ${$u}`)}const MODIFIERS={mod:"mod",cmdorctrl:"mod",commandorcontrol:"mod",ctrl:"ctrl",control:"ctrl",meta:"meta",cmd:"meta",command:"meta",super:"meta",win:"meta",alt:"alt",option:"alt",opt:"alt",shift:"shift"},KEY_ALIASES={esc:"escape",del:"delete",ins:"insert",space:" ",spacebar:" ",up:"arrowup",down:"arrowdown",left:"arrowleft",right:"arrowright",plus:"+",return:"enter"};function parseKeybinding(Au){if(!Au)return null;const lo={key:"",mod:!1,ctrl:!1,meta:!1,alt:!1,shift:!1},$u=Au.split("+").map(Ru=>Ru.trim()).filter((Ru,Iu,Pu)=>Ru!==""||Iu===Pu.length-1);for(const[Ru,Iu]of $u.entries()){const Pu=Iu.toLowerCase(),Ou=MODIFIERS[Pu];if(Ou&&Ru<$u.length-1){lo[Ou]=!0;continue}const Mu=Iu===""?"+":KEY_ALIASES[Pu]??Pu;lo.key=Mu}return lo.key?lo:null}function matchesKeybinding(Au,lo,$u=isApplePlatform()){if((Au.key?.toLowerCase()??"")!==lo.key)return!1;const Iu=lo.ctrl||lo.mod&&!$u,Pu=lo.meta||lo.mod&&$u;return Au.ctrlKey===Iu&&Au.metaKey===Pu&&Au.altKey===lo.alt&&Au.shiftKey===lo.shift}const APPLE_SYMBOLS={ctrl:"⌃",meta:"⌘",alt:"⌥",shift:"⇧"},OTHER_LABELS={ctrl:"Ctrl",meta:"Meta",alt:"Alt",shift:"Shift"},KEY_LABELS={arrowup:"↑",arrowdown:"↓",arrowleft:"←",arrowright:"→",enter:"↵",escape:"Esc"," ":"Space",backspace:"⌫",delete:"Del",tab:"⇥"};function formatKeybinding(Au,lo=isApplePlatform()){const $u=parseKeybinding(Au);if(!$u)return Au;const Ru=$u.ctrl||$u.mod&&!lo,Iu=$u.meta||$u.mod&&lo,Pu=KEY_LABELS[$u.key]??($u.key.length===1?$u.key.toUpperCase():titleCase($u.key));return lo?[$u.ctrl?APPLE_SYMBOLS.ctrl:"",$u.alt?APPLE_SYMBOLS.alt:"",$u.shift?APPLE_SYMBOLS.shift:"",Iu?APPLE_SYMBOLS.meta:"",Pu].join(""):[Ru?OTHER_LABELS.ctrl:"",Iu&&!Ru?OTHER_LABELS.meta:"",$u.alt?OTHER_LABELS.alt:"",$u.shift?OTHER_LABELS.shift:"",Pu].filter(Boolean).join("+")}function titleCase(Au){return Au.charAt(0).toUpperCase()+Au.slice(1)}const ANY_ORIGIN="*";class OriginNotAllowedError extends Error{url;origin;constructor(lo,$u,Ru="a remote"){super(`Refusing to load ${Ru} from ${$u}: not an allowed origin. Pass allowedOrigins, or call setAllowedOrigins() from the host, to accept it.`),this.name="OriginNotAllowedError",this.url=lo,this.origin=$u}}const LEFTMOST_WILDCARD=/^[a-z][a-z0-9+.-]*:\/\/\*\./i;function parseOriginRule(Au){const lo=Au.trim();if(lo===ANY_ORIGIN)return{kind:"any"};try{if(LEFTMOST_WILDCARD.test(lo)){const $u=new URL(lo.replace("*.",""));return{kind:"suffix",protocol:$u.protocol,suffix:`.${$u.hostname}`,port:$u.port}}return{kind:"exact",origin:new URL(lo).origin}}catch{console.warn(`[reactor] ignoring an unreadable allowed origin: ${JSON.stringify(Au)}. Write it with a scheme, e.g. https://cdn.example.com or https://*.example.com.`);return}}function matches$1(Au,lo){if(Au.kind==="any")return!0;if(Au.kind==="exact")return Au.origin===lo;let $u;try{$u=new URL(lo)}catch{return!1}return $u.protocol===Au.protocol&&$u.port===Au.port&&$u.hostname.endsWith(Au.suffix)}let policy=[];function resolveOrigin(Au){const lo=typeof location<"u"&&location?.href?location.href:void 0;return lo?new URL(Au,lo).origin:/^[a-z]+:\/\//i.test(Au)?new URL(Au).origin:void 0}function pageOrigin(){const Au=typeof location<"u"&&location?.href?location.href:void 0;return Au?new URL(Au).origin:void 0}function isOriginAllowed(Au,lo=[]){let $u;try{$u=resolveOrigin(Au)}catch{return!1}if($u===void 0||$u===pageOrigin())return!0;if($u==="null")return!1;for(const Ru of[...policy,...lo]){const Iu=parseOriginRule(Ru);if(Iu&&matches$1(Iu,$u))return!0}return!1}function assertOriginAllowed(Au,lo=[],$u="a remote"){if(isOriginAllowed(Au,lo))return;let Ru;try{Ru=resolveOrigin(Au)??Au}catch{throw new OriginNotAllowedError(Au,Au,$u)}throw new OriginNotAllowedError(Au,Ru,$u)}let runtimeLoad;async function federationRuntime(){return runtimeLoad||(runtimeLoad=import("@module-federation/runtime").then(lo=>lo.default??lo).catch(lo=>{throw runtimeLoad=void 0,new Error(`Loading a Module Federation container needs @module-federation/runtime, which is an optional peer dependency of @datalayer/reactor. Install it, or pass a loader of your own. (${String(lo)})`)})),runtimeLoad}const HOST_NAME="datalayer_reactor_host";function sharedFromHost(Au={},lo={}){const $u=getReactorSharedModules(),Ru={};for(const[Iu,Pu]of Object.entries($u)){const{shareConfig:Ou,...Mu}=lo[Iu]??{};Ru[Iu]={lib:()=>Pu,version:Au[Iu],...Mu,shareConfig:{singleton:!0,requiredVersion:!1,...Ou}}}return Ru}let initialised;async function initReactorFederation(Au={}){if(initialised)return initialised;const lo=(async()=>{const $u=await federationRuntime();return $u.init({name:Au.name??HOST_NAME,remotes:Au.remotes??[],shared:Au.shared??sharedFromHost(Au.versions)}),$u})();return initialised=lo,lo.catch(()=>{initialised===lo&&(initialised=void 0)}),lo}async function registerFederatedRemote(Au,lo={}){assertOriginAllowed(Au.entry,lo.allowedOrigins,`the container ${Au.name}`),(await initReactorFederation()).registerRemotes([Au],{force:lo.force??!1})}function createFederationLoader(){return async(Au,lo)=>{const $u=lo?.scope;if(!$u)throw new Error(`${lo?.name??Au}: the federation loader needs a container name — pass \`scope\` on the remote reference.`);await registerFederatedRemote({name:$u,entry:Au,type:lo?.type},{allowedOrigins:lo?.allowedOrigins});const Ru=await initReactorFederation(),Iu=`${$u}/${(lo?.module??"./plugin").replace(/^\.\//,"")}`,Pu=await Ru.loadRemote(Iu);if(!Pu)throw new Error(`${lo?.name??$u}: the container at ${Au} exposes no ${Iu}.`);return Pu}}const federationLoader=createFederationLoader();function defineFederatedPlugin(Au,lo={}){return defineRemotePlugin(Au,{loader:federationLoader,...lo})}const SHARED_GLOBAL="__DATALAYER_REACTOR__",REACTOR_API_VERSION="v1",REACTOR_SHARED_MODULES=["react","react-dom","@datalayer/reactor","@datalayer/reactor/react"];function getReactorSharedModules(){return globalThis[SHARED_GLOBAL]?.shared??{}}function missingSharedModules(Au=REACTOR_SHARED_MODULES){const lo=getReactorSharedModules();return Au.filter($u=>!($u in lo))}const importRemoteModule=Au=>import(Au);class RemoteRefused extends Error{}function defineRemotePlugin(Au,lo={}){const{loader:$u=importRemoteModule,apiVersion:Ru=REACTOR_API_VERSION,allowedOrigins:Iu}=lo;return defineLazyPlugin({name:Au.name,version:Au.version,displayName:Au.displayName,description:Au.description,octicon:Au.octicon,emoji:Au.emoji,dependencies:Au.dependencies,activationEvents:Au.activationEvents,deactivationEvents:Au.deactivationEvents,requiredBackendPlugins:Au.requiredBackendPlugins,optionalBackendPlugins:Au.optionalBackendPlugins,load:async()=>{if(Au.apiVersion&&Au.apiVersion!==Ru)throw new RemoteRefused(`${Au.name} declares API version ${Au.apiVersion}; this host speaks ${Ru}.`);assertOriginAllowed(Au.entry,Iu,Au.name);const Pu=missingSharedModules();Pu.length>0&&console.warn(`[reactor] loading ${Au.name} from ${Au.entry} with these modules unpublished: ${Pu.join(", ")}. If it reaches for one it will get its own copy — call setReactorSharedModules() from the host before loading remotes.`);const Ou=await $u(Au.entry,{name:Au.name,scope:Au.scope,module:Au.module,type:Au.type,allowedOrigins:Iu}),Mu=Au.export?Ou[Au.export]:Ou.default??Ou;if(!Mu)throw new Error(`${Au.name}: ${Au.entry} has no ${Au.export?`export "${Au.export}"`:"default export"}.`);return Mu}})}async function bootstrapExtensions(Au,lo={}){const{fetchJson:$u,allowedOrigins:Ru,...Iu}=lo,Pu=Au.replace(/\/+$/,""),Ou=`${Pu}/plugins/frontend-extensions`,Mu={...Iu,allowedOrigins:/^[a-z]+:\/\//i.test(Pu)?[...Ru??[],Pu]:Ru};let Du;try{Du=($u?await $u(Ou):await fetch(Ou).then(Bu=>{if(!Bu.ok)throw new Error(`HTTP ${Bu.status}`);return Bu.json()}))??[]}catch(Lu){return console.warn(`[reactor] could not read ${Ou}:`,Lu),[]}return Du.map(Lu=>{const Bu=/^[a-z]+:\/\//i.test(Lu.entry)?Lu.entry:`${Pu}${Lu.entry}`,ju=Lu.kind==="federated",Fu=(Lu.plugins??[]).map(zu=>{const Uu=zu.scope??Lu.remoteName,Hu=zu.module??Lu.module,Vu={...zu,entry:Bu,apiVersion:Lu.apiVersion,scope:Uu,module:Hu,type:zu.type||Lu.remoteType||void 0};return(ju||zu.scope)&&Uu?defineFederatedPlugin({...Vu,scope:Uu},Mu):defineRemotePlugin(Vu,Mu)});return defineExtension({name:Lu.name,version:Lu.version,displayName:Lu.displayName,description:Lu.description,octicon:Lu.octicon,emoji:Lu.emoji,plugins:Fu})})}const AgentTools=defineContributionPoint("reactor.agentTools");function defineAgentTools(Au){const lo=new Set;for(const $u of Au.commands){if(!/^[A-Za-z][A-Za-z0-9_]*$/.test($u.name))throw new Error(`${Au.id}: tool name '${$u.name}' must be letters, digits and underscores.`);if(lo.has($u.name))throw new Error(`${Au.id}: tool name '${$u.name}' is declared twice.`);lo.add($u.name)}return{...Au,toolset:Au.toolset??Au.commands.map($u=>$u.name)}}var ArrayExt;(function(Au){function lo(ed,td,nd=0,od=-1){let sd=ed.length;if(sd===0)return-1;nd<0?nd=Math.max(0,nd+sd):nd=Math.min(nd,sd-1),od<0?od=Math.max(0,od+sd):od=Math.min(od,sd-1);let ad;od<nd?ad=od+1+(sd-nd):ad=od-nd+1;for(let pd=0;pd<ad;++pd){let gd=(nd+pd)%sd;if(ed[gd]===td)return gd}return-1}Au.firstIndexOf=lo;function $u(ed,td,nd=-1,od=0){let sd=ed.length;if(sd===0)return-1;nd<0?nd=Math.max(0,nd+sd):nd=Math.min(nd,sd-1),od<0?od=Math.max(0,od+sd):od=Math.min(od,sd-1);let ad;nd<od?ad=nd+1+(sd-od):ad=nd-od+1;for(let pd=0;pd<ad;++pd){let gd=(nd-pd+sd)%sd;if(ed[gd]===td)return gd}return-1}Au.lastIndexOf=$u;function Ru(ed,td,nd=0,od=-1){let sd=ed.length;if(sd===0)return-1;nd<0?nd=Math.max(0,nd+sd):nd=Math.min(nd,sd-1),od<0?od=Math.max(0,od+sd):od=Math.min(od,sd-1);let ad;od<nd?ad=od+1+(sd-nd):ad=od-nd+1;for(let pd=0;pd<ad;++pd){let gd=(nd+pd)%sd;if(td(ed[gd],gd))return gd}return-1}Au.findFirstIndex=Ru;function Iu(ed,td,nd=-1,od=0){let sd=ed.length;if(sd===0)return-1;nd<0?nd=Math.max(0,nd+sd):nd=Math.min(nd,sd-1),od<0?od=Math.max(0,od+sd):od=Math.min(od,sd-1);let ad;nd<od?ad=nd+1+(sd-od):ad=nd-od+1;for(let pd=0;pd<ad;++pd){let gd=(nd-pd+sd)%sd;if(td(ed[gd],gd))return gd}return-1}Au.findLastIndex=Iu;function Pu(ed,td,nd=0,od=-1){let sd=Ru(ed,td,nd,od);return sd!==-1?ed[sd]:void 0}Au.findFirstValue=Pu;function Ou(ed,td,nd=-1,od=0){let sd=Iu(ed,td,nd,od);return sd!==-1?ed[sd]:void 0}Au.findLastValue=Ou;function Mu(ed,td,nd,od=0,sd=-1){let ad=ed.length;if(ad===0)return 0;od<0?od=Math.max(0,od+ad):od=Math.min(od,ad-1),sd<0?sd=Math.max(0,sd+ad):sd=Math.min(sd,ad-1);let pd=od,gd=sd-od+1;for(;gd>0;){let yd=gd>>1,_d=pd+yd;nd(ed[_d],td)<0?(pd=_d+1,gd-=yd+1):gd=yd}return pd}Au.lowerBound=Mu;function Du(ed,td,nd,od=0,sd=-1){let ad=ed.length;if(ad===0)return 0;od<0?od=Math.max(0,od+ad):od=Math.min(od,ad-1),sd<0?sd=Math.max(0,sd+ad):sd=Math.min(sd,ad-1);let pd=od,gd=sd-od+1;for(;gd>0;){let yd=gd>>1,_d=pd+yd;nd(ed[_d],td)>0?gd=yd:(pd=_d+1,gd-=yd+1)}return pd}Au.upperBound=Du;function Lu(ed,td,nd){if(ed===td)return!0;if(ed.length!==td.length)return!1;for(let od=0,sd=ed.length;od<sd;++od)if(nd?!nd(ed[od],td[od]):ed[od]!==td[od])return!1;return!0}Au.shallowEqual=Lu;function Bu(ed,td={}){let{start:nd,stop:od,step:sd}=td;if(sd===void 0&&(sd=1),sd===0)throw new Error("Slice `step` cannot be zero.");let ad=ed.length;nd===void 0?nd=sd<0?ad-1:0:nd<0?nd=Math.max(nd+ad,sd<0?-1:0):nd>=ad&&(nd=sd<0?ad-1:ad),od===void 0?od=sd<0?-1:ad:od<0?od=Math.max(od+ad,sd<0?-1:0):od>=ad&&(od=sd<0?ad-1:ad);let pd;sd<0&&od>=nd||sd>0&&nd>=od?pd=0:sd<0?pd=Math.floor((od-nd+1)/sd+1):pd=Math.floor((od-nd-1)/sd+1);let gd=[];for(let yd=0;yd<pd;++yd)gd[yd]=ed[nd+yd*sd];return gd}Au.slice=Bu;function ju(ed,td,nd){let od=ed.length;if(od<=1||(td<0?td=Math.max(0,td+od):td=Math.min(td,od-1),nd<0?nd=Math.max(0,nd+od):nd=Math.min(nd,od-1),td===nd))return;let sd=ed[td],ad=td<nd?1:-1;for(let pd=td;pd!==nd;pd+=ad)ed[pd]=ed[pd+ad];ed[nd]=sd}Au.move=ju;function Fu(ed,td=0,nd=-1){let od=ed.length;if(!(od<=1))for(td<0?td=Math.max(0,td+od):td=Math.min(td,od-1),nd<0?nd=Math.max(0,nd+od):nd=Math.min(nd,od-1);td<nd;){let sd=ed[td],ad=ed[nd];ed[td++]=ad,ed[nd--]=sd}}Au.reverse=Fu;function zu(ed,td,nd=0,od=-1){let sd=ed.length;if(sd<=1||(nd<0?nd=Math.max(0,nd+sd):nd=Math.min(nd,sd-1),od<0?od=Math.max(0,od+sd):od=Math.min(od,sd-1),nd>=od))return;let ad=od-nd+1;if(td>0?td=td%ad:td<0&&(td=(td%ad+ad)%ad),td===0)return;let pd=nd+td;Fu(ed,nd,pd-1),Fu(ed,pd,od),Fu(ed,nd,od)}Au.rotate=zu;function Uu(ed,td,nd=0,od=-1){let sd=ed.length;if(sd===0)return;nd<0?nd=Math.max(0,nd+sd):nd=Math.min(nd,sd-1),od<0?od=Math.max(0,od+sd):od=Math.min(od,sd-1);let ad;od<nd?ad=od+1+(sd-nd):ad=od-nd+1;for(let pd=0;pd<ad;++pd)ed[(nd+pd)%sd]=td}Au.fill=Uu;function Hu(ed,td,nd){let od=ed.length;td<0?td=Math.max(0,td+od):td=Math.min(td,od);for(let sd=od;sd>td;--sd)ed[sd]=ed[sd-1];ed[td]=nd}Au.insert=Hu;function Vu(ed,td){let nd=ed.length;if(td<0&&(td+=nd),td<0||td>=nd)return;let od=ed[td];for(let sd=td+1;sd<nd;++sd)ed[sd-1]=ed[sd];return ed.length=nd-1,od}Au.removeAt=Vu;function Gu(ed,td,nd=0,od=-1){let sd=lo(ed,td,nd,od);return sd!==-1&&Vu(ed,sd),sd}Au.removeFirstOf=Gu;function Wu(ed,td,nd=-1,od=0){let sd=$u(ed,td,nd,od);return sd!==-1&&Vu(ed,sd),sd}Au.removeLastOf=Wu;function Ku(ed,td,nd=0,od=-1){let sd=ed.length;if(sd===0)return 0;nd<0?nd=Math.max(0,nd+sd):nd=Math.min(nd,sd-1),od<0?od=Math.max(0,od+sd):od=Math.min(od,sd-1);let ad=0;for(let pd=0;pd<sd;++pd)nd<=od&&pd>=nd&&pd<=od&&ed[pd]===td||od<nd&&(pd<=od||pd>=nd)&&ed[pd]===td?ad++:ad>0&&(ed[pd-ad]=ed[pd]);return ad>0&&(ed.length=sd-ad),ad}Au.removeAllOf=Ku;function Ju(ed,td,nd=0,od=-1){let sd,ad=Ru(ed,td,nd,od);return ad!==-1&&(sd=Vu(ed,ad)),{index:ad,value:sd}}Au.removeFirstWhere=Ju;function Yu(ed,td,nd=-1,od=0){let sd,ad=Iu(ed,td,nd,od);return ad!==-1&&(sd=Vu(ed,ad)),{index:ad,value:sd}}Au.removeLastWhere=Yu;function Xu(ed,td,nd=0,od=-1){let sd=ed.length;if(sd===0)return 0;nd<0?nd=Math.max(0,nd+sd):nd=Math.min(nd,sd-1),od<0?od=Math.max(0,od+sd):od=Math.min(od,sd-1);let ad=0;for(let pd=0;pd<sd;++pd)nd<=od&&pd>=nd&&pd<=od&&td(ed[pd],pd)||od<nd&&(pd<=od||pd>=nd)&&td(ed[pd],pd)?ad++:ad>0&&(ed[pd-ad]=ed[pd]);return ad>0&&(ed.length=sd-ad),ad}Au.removeAllWhere=Xu})(ArrayExt||(ArrayExt={}));function*chain(...Au){for(const lo of Au)yield*lo}function*empty$3(){}function*enumerate(Au,lo=0){for(const $u of Au)yield[lo++,$u]}function*filter$3(Au,lo){let $u=0;for(const Ru of Au)lo(Ru,$u++)&&(yield Ru)}function find$3(Au,lo){let $u=0;for(const Ru of Au)if(lo(Ru,$u++))return Ru}function findIndex(Au,lo){let $u=0;for(const Ru of Au)if(lo(Ru,$u++))return $u-1;return-1}function min$1(Au,lo){let $u;for(const Ru of Au){if($u===void 0){$u=Ru;continue}lo(Ru,$u)<0&&($u=Ru)}return $u}function max$1(Au,lo){let $u;for(const Ru of Au){if($u===void 0){$u=Ru;continue}lo(Ru,$u)>0&&($u=Ru)}return $u}function minmax(Au,lo){let $u=!0,Ru,Iu;for(const Pu of Au)$u?(Ru=Pu,Iu=Pu,$u=!1):lo(Pu,Ru)<0?Ru=Pu:lo(Pu,Iu)>0&&(Iu=Pu);return $u?void 0:[Ru,Iu]}function toArray$1(Au){return Array.from(Au)}function toObject(Au){const lo={};for(const[$u,Ru]of Au)lo[$u]=Ru;return lo}function each(Au,lo){let $u=0;for(const Ru of Au)if(lo(Ru,$u++)===!1)return}function every$2(Au,lo){let $u=0;for(const Ru of Au)if(lo(Ru,$u++)===!1)return!1;return!0}function some$1(Au,lo){let $u=0;for(const Ru of Au)if(lo(Ru,$u++))return!0;return!1}function*map$5(Au,lo){let $u=0;for(const Ru of Au)yield lo(Ru,$u++)}function*range$1(Au,lo,$u){lo===void 0?(lo=Au,Au=0,$u=1):$u===void 0&&($u=1);const Ru=Private$w.rangeLength(Au,lo,$u);for(let Iu=0;Iu<Ru;Iu++)yield Au+$u*Iu}var Private$w;(function(Au){function lo($u,Ru,Iu){return Iu===0?1/0:$u>Ru&&Iu>0||$u<Ru&&Iu<0?0:Math.ceil((Ru-$u)/Iu)}Au.rangeLength=lo})(Private$w||(Private$w={}));function reduce(Au,lo,$u){const Ru=Au[Symbol.iterator]();let Iu=0,Pu=Ru.next();if(Pu.done&&$u===void 0)throw new TypeError("Reduce of empty iterable with no initial value.");if(Pu.done)return $u;let Ou=Ru.next();if(Ou.done&&$u===void 0)return Pu.value;if(Ou.done)return lo($u,Pu.value,Iu++);let Mu;$u===void 0?Mu=lo(Pu.value,Ou.value,Iu++):Mu=lo(lo($u,Pu.value,Iu++),Ou.value,Iu++);let Du;for(;!(Du=Ru.next()).done;)Mu=lo(Mu,Du.value,Iu++);return Mu}function*repeat$1(Au,lo){for(;0<lo--;)yield Au}function*once(Au){yield Au}function*retro(Au){if(typeof Au.retro=="function")yield*Au.retro();else for(let lo=Au.length-1;lo>-1;lo--)yield Au[lo]}function topologicSort(Au){let lo=[],$u=new Set,Ru=new Map;for(const Ou of Au)Iu(Ou);for(const[Ou]of Ru)Pu(Ou);return lo;function Iu(Ou){let[Mu,Du]=Ou,Lu=Ru.get(Du);Lu?Lu.push(Mu):Ru.set(Du,[Mu])}function Pu(Ou){if($u.has(Ou))return;$u.add(Ou);let Mu=Ru.get(Ou);if(Mu)for(const Du of Mu)Pu(Du);lo.push(Ou)}}function*stride(Au,lo){let $u=0;for(const Ru of Au)$u++%lo===0&&(yield Ru)}var StringExt;(function(Au){function lo(Ou,Mu,Du=0){let Lu=new Array(Mu.length);for(let Bu=0,ju=Du,Fu=Mu.length;Bu<Fu;++Bu,++ju){if(ju=Ou.indexOf(Mu[Bu],ju),ju===-1)return null;Lu[Bu]=ju}return Lu}Au.findIndices=lo;function $u(Ou,Mu,Du=0){let Lu=lo(Ou,Mu,Du);if(!Lu)return null;let Bu=0;for(let ju=0,Fu=Lu.length;ju<Fu;++ju){let zu=Lu[ju]-Du;Bu+=zu*zu}return{score:Bu,indices:Lu}}Au.matchSumOfSquares=$u;function Ru(Ou,Mu,Du=0){let Lu=lo(Ou,Mu,Du);if(!Lu)return null;let Bu=0,ju=Du-1;for(let Fu=0,zu=Lu.length;Fu<zu;++Fu){let Uu=Lu[Fu];Bu+=Uu-ju-1,ju=Uu}return{score:Bu,indices:Lu}}Au.matchSumOfDeltas=Ru;function Iu(Ou,Mu,Du){let Lu=[],Bu=0,ju=0,Fu=Mu.length;for(;Bu<Fu;){let zu=Mu[Bu],Uu=Mu[Bu];for(;++Bu<Fu&&Mu[Bu]===Uu+1;)Uu++;ju<zu&&Lu.push(Ou.slice(ju,zu)),zu<Uu+1&&Lu.push(Du(Ou.slice(zu,Uu+1))),ju=Uu+1}return ju<Ou.length&&Lu.push(Ou.slice(ju)),Lu}Au.highlight=Iu;function Pu(Ou,Mu){return Ou<Mu?-1:Ou>Mu?1:0}Au.cmp=Pu})(StringExt||(StringExt={}));function*take(Au,lo){if(lo<1)return;const $u=Au[Symbol.iterator]();let Ru;for(;0<lo--&&!(Ru=$u.next()).done;)yield Ru.value}function*zip(...Au){const lo=Au.map(Ru=>Ru[Symbol.iterator]());let $u=lo.map(Ru=>Ru.next());for(;every$2($u,Ru=>!Ru.done);$u=lo.map(Ru=>Ru.next()))yield $u.map(Ru=>Ru.value)}const index_es6$4=Object.freeze(Object.defineProperty({__proto__:null,get ArrayExt(){return ArrayExt},get StringExt(){return StringExt},chain,each,empty:empty$3,enumerate,every:every$2,filter:filter$3,find:find$3,findIndex,map:map$5,max:max$1,min:min$1,minmax,once,range:range$1,reduce,repeat:repeat$1,retro,some:some$1,stride,take,toArray:toArray$1,toObject,topologicSort,zip},Symbol.toStringTag,{value:"Module"}));var JSONExt;(function(Au){Au.emptyObject=Object.freeze({}),Au.emptyArray=Object.freeze([]);function lo(Bu){return Bu===null||typeof Bu=="boolean"||typeof Bu=="number"||typeof Bu=="string"}Au.isPrimitive=lo;function $u(Bu){return Array.isArray(Bu)}Au.isArray=$u;function Ru(Bu){return!lo(Bu)&&!$u(Bu)}Au.isObject=Ru;function Iu(Bu,ju){if(Bu===ju)return!0;if(lo(Bu)||lo(ju))return!1;let Fu=$u(Bu),zu=$u(ju);return Fu!==zu?!1:Fu&&zu?Ou(Bu,ju):Mu(Bu,ju)}Au.deepEqual=Iu;function Pu(Bu){return lo(Bu)?Bu:$u(Bu)?Du(Bu):Lu(Bu)}Au.deepCopy=Pu;function Ou(Bu,ju){if(Bu===ju)return!0;if(Bu.length!==ju.length)return!1;for(let Fu=0,zu=Bu.length;Fu<zu;++Fu)if(!Iu(Bu[Fu],ju[Fu]))return!1;return!0}function Mu(Bu,ju){if(Bu===ju)return!0;for(let Fu in Bu)if(Bu[Fu]!==void 0&&!(Fu in ju))return!1;for(let Fu in ju)if(ju[Fu]!==void 0&&!(Fu in Bu))return!1;for(let Fu in Bu){let zu=Bu[Fu],Uu=ju[Fu];if(!(zu===void 0&&Uu===void 0)&&(zu===void 0||Uu===void 0||!Iu(zu,Uu)))return!1}return!0}function Du(Bu){let ju=new Array(Bu.length);for(let Fu=0,zu=Bu.length;Fu<zu;++Fu)ju[Fu]=Pu(Bu[Fu]);return ju}function Lu(Bu){let ju={};for(let Fu in Bu){let zu=Bu[Fu];zu!==void 0&&(ju[Fu]=Pu(zu))}return ju}})(JSONExt||(JSONExt={}));class MimeData{constructor(){this._types=[],this._values=[]}types(){return this._types.slice()}hasData(lo){return this._types.indexOf(lo)!==-1}getData(lo){let $u=this._types.indexOf(lo);return $u!==-1?this._values[$u]:void 0}setData(lo,$u){this.clearData(lo),this._types.push(lo),this._values.push($u)}clearData(lo){let $u=this._types.indexOf(lo);$u!==-1&&(this._types.splice($u,1),this._values.splice($u,1))}clear(){this._types.length=0,this._values.length=0}}class PluginRegistry{constructor(lo={}){this._application=null,this._validatePlugin=()=>!0,this._plugins=new Map,this._services=new Map,lo.validatePlugin&&(console.info("Plugins may be rejected by the custom validation plugin method."),this._validatePlugin=lo.validatePlugin)}get application(){return this._application}set application(lo){if(this._application!==null)throw Error("PluginRegistry.application is already set. It cannot be overridden.");this._application=lo}get deferredPlugins(){return Array.from(this._plugins).filter(([lo,$u])=>$u.autoStart==="defer").map(([lo,$u])=>lo)}getPluginDescription(lo){var $u,Ru;return(Ru=($u=this._plugins.get(lo))===null||$u===void 0?void 0:$u.description)!==null&&Ru!==void 0?Ru:""}hasPlugin(lo){return this._plugins.has(lo)}isPluginActivated(lo){var $u,Ru;return(Ru=($u=this._plugins.get(lo))===null||$u===void 0?void 0:$u.activated)!==null&&Ru!==void 0?Ru:!1}listPlugins(){return Array.from(this._plugins.keys())}registerPlugin(lo){if(this._plugins.has(lo.id))throw new TypeError(`Plugin '${lo.id}' is already registered.`);if(!this._validatePlugin(lo))throw new Error(`Plugin '${lo.id}' is not valid.`);const $u=Private$v.createPluginData(lo);Private$v.ensureNoCycle($u,this._plugins,this._services),$u.provides&&this._services.set($u.provides,$u.id),this._plugins.set($u.id,$u)}registerPlugins(lo){for(const $u of lo)this.registerPlugin($u)}deregisterPlugin(lo,$u){const Ru=this._plugins.get(lo);if(Ru){if(Ru.activated&&!$u)throw new Error(`Plugin '${lo}' is still active.`);this._plugins.delete(lo)}}async activatePlugin(lo){const $u=this._plugins.get(lo);if(!$u)throw new ReferenceError(`Plugin '${lo}' is not registered.`);if($u.activated)return;if($u.promise)return $u.promise;const Ru=$u.requires.map(Pu=>this.resolveRequiredService(Pu)),Iu=$u.optional.map(Pu=>this.resolveOptionalService(Pu));return $u.promise=Promise.all([...Ru,...Iu]).then(Pu=>$u.activate.apply(void 0,[this.application,...Pu])).then(Pu=>{$u.service=Pu,$u.activated=!0,$u.promise=null}).catch(Pu=>{throw $u.promise=null,Pu}),$u.promise}async activatePlugins(lo,$u={}){switch(lo){case"defer":{const Ru=this.deferredPlugins.filter(Iu=>this._plugins.get(Iu).autoStart).map(Iu=>this.activatePlugin(Iu));await Promise.all(Ru);break}case"startUp":{const Iu=Private$v.collectStartupPlugins(this._plugins,$u).map(async Pu=>{try{return await this.activatePlugin(Pu)}catch(Ou){console.error(`Plugin '${Pu}' failed to activate.`,Ou)}});await Promise.all(Iu);break}}}async deactivatePlugin(lo){const $u=this._plugins.get(lo);if(!$u)throw new ReferenceError(`Plugin '${lo}' is not registered.`);if(!$u.activated)return[];if(!$u.deactivate)throw new TypeError(`Plugin '${lo}'#deactivate() method missing`);const Ru=Private$v.findDependents(lo,this._plugins,this._services),Iu=Ru.map(Pu=>this._plugins.get(Pu));for(const Pu of Iu)if(!Pu.deactivate)throw new TypeError(`Plugin ${Pu.id}#deactivate() method missing (depends on ${lo})`);for(const Pu of Iu){const Ou=[...Pu.requires,...Pu.optional].map(Mu=>{const Du=this._services.get(Mu);return Du?this._plugins.get(Du).service:null});await Pu.deactivate(this.application,...Ou),Pu.service=null,Pu.activated=!1}return Ru.pop(),Ru}async resolveRequiredService(lo){const $u=this._services.get(lo);if(!$u)throw new TypeError(`No provider for: ${lo.name}.`);const Ru=this._plugins.get($u);return Ru.activated||await this.activatePlugin($u),Ru.service}async resolveOptionalService(lo){const $u=this._services.get(lo);if(!$u)return null;const Ru=this._plugins.get($u);if(!Ru.activated)try{await this.activatePlugin($u)}catch(Iu){return console.error(Iu),null}return Ru.service}}var Private$v;(function(Au){class lo{constructor(Mu){var Du,Lu,Bu,ju;this._activated=!1,this._promise=null,this._service=null,this.id=Mu.id,this.description=(Du=Mu.description)!==null&&Du!==void 0?Du:"",this.activate=Mu.activate,this.deactivate=(Lu=Mu.deactivate)!==null&&Lu!==void 0?Lu:null,this.provides=(Bu=Mu.provides)!==null&&Bu!==void 0?Bu:null,this.autoStart=(ju=Mu.autoStart)!==null&&ju!==void 0?ju:!1,this.requires=Mu.requires?Mu.requires.slice():[],this.optional=Mu.optional?Mu.optional.slice():[]}get activated(){return this._activated}set activated(Mu){this._activated=Mu}get service(){return this._service}set service(Mu){this._service=Mu}get promise(){return this._promise}set promise(Mu){this._promise=Mu}}function $u(Ou){return new lo(Ou)}Au.createPluginData=$u;function Ru(Ou,Mu,Du){const Lu=[...Ou.requires,...Ou.optional],Bu=Fu=>{if(Fu===Ou.provides)return!0;const zu=Du.get(Fu);if(!zu)return!1;const Uu=Mu.get(zu),Hu=[...Uu.requires,...Uu.optional];return Hu.length===0?!1:(ju.push(zu),Hu.some(Bu)?!0:(ju.pop(),!1))};if(!Ou.provides||Lu.length===0)return;const ju=[Ou.id];if(Lu.some(Bu))throw new ReferenceError(`Cycle detected: ${ju.join(" -> ")}.`)}Au.ensureNoCycle=Ru;function Iu(Ou,Mu,Du){const Lu=new Array,Bu=Hu=>{const Vu=Mu.get(Hu),Gu=[...Vu.requires,...Vu.optional];Lu.push(...Gu.reduce((Wu,Ku)=>{const Ju=Du.get(Ku);return Ju&&Wu.push([Hu,Ju]),Wu},[]))};for(const Hu of Mu.keys())Bu(Hu);const ju=Lu.filter(Hu=>Hu[1]===Ou);let Fu=0;for(;ju.length>Fu;){const Hu=ju.length,Vu=new Set(ju.map(Gu=>Gu[0]));for(const Gu of Vu)Lu.filter(Wu=>Wu[1]===Gu).forEach(Wu=>{ju.includes(Wu)||ju.push(Wu)});Fu=Hu}const zu=topologicSort(ju),Uu=zu.findIndex(Hu=>Hu===Ou);return Uu===-1?[Ou]:zu.slice(0,Uu+1)}Au.findDependents=Iu;function Pu(Ou,Mu){const Du=new Set;for(const Lu of Ou.keys())Ou.get(Lu).autoStart===!0&&Du.add(Lu);if(Mu.startPlugins)for(const Lu of Mu.startPlugins)Du.add(Lu);if(Mu.ignorePlugins)for(const Lu of Mu.ignorePlugins)Du.delete(Lu);return Array.from(Du)}Au.collectStartupPlugins=Pu})(Private$v||(Private$v={}));class PromiseDelegate{constructor(){this.promise=new Promise((lo,$u)=>{this._resolve=lo,this._reject=$u})}resolve(lo){let $u=this._resolve;$u(lo)}reject(lo){let $u=this._reject;$u(lo)}}let Token$2=class{constructor(lo,$u){this.name=lo,this.description=$u??"",this._tokenStructuralPropertyT=null}};function fallbackRandomValues(Au){let lo=0;for(let $u=0,Ru=Au.length;$u<Ru;++$u)$u%4===0&&(lo=Math.random()*4294967295>>>0),Au[$u]=lo&255,lo>>>=8}var Random;(function(Au){Au.getRandomValues=(()=>{const lo=typeof window<"u"&&(window.crypto||window.msCrypto)||null;return lo&&typeof lo.getRandomValues=="function"?function(Ru){return lo.getRandomValues(Ru)}:fallbackRandomValues})()})(Random||(Random={}));function uuid4Factory(Au){const lo=new Uint8Array(16),$u=new Array(256);for(let Ru=0;Ru<16;++Ru)$u[Ru]="0"+Ru.toString(16);for(let Ru=16;Ru<256;++Ru)$u[Ru]=Ru.toString(16);return function(){return Au(lo),lo[6]=64|lo[6]&15,lo[8]=128|lo[8]&63,$u[lo[0]]+$u[lo[1]]+$u[lo[2]]+$u[lo[3]]+"-"+$u[lo[4]]+$u[lo[5]]+"-"+$u[lo[6]]+$u[lo[7]]+"-"+$u[lo[8]]+$u[lo[9]]+"-"+$u[lo[10]]+$u[lo[11]]+$u[lo[12]]+$u[lo[13]]+$u[lo[14]]+$u[lo[15]]}}var UUID;(function(Au){Au.uuid4=uuid4Factory(Random.getRandomValues)})(UUID||(UUID={}));class Signal{constructor(lo){this.sender=lo}connect(lo,$u){return Private$u.connect(this,lo,$u)}disconnect(lo,$u){return Private$u.disconnect(this,lo,$u)}emit(lo){Private$u.emit(this,lo)}}(function(Au){function lo(Du,Lu){Private$u.disconnectBetween(Du,Lu)}Au.disconnectBetween=lo;function $u(Du){Private$u.disconnectSender(Du)}Au.disconnectSender=$u;function Ru(Du){Private$u.disconnectReceiver(Du)}Au.disconnectReceiver=Ru;function Iu(Du){Private$u.disconnectAll(Du)}Au.disconnectAll=Iu;function Pu(Du){Private$u.disconnectAll(Du)}Au.clearData=Pu;function Ou(){return Private$u.exceptionHandler}Au.getExceptionHandler=Ou;function Mu(Du){let Lu=Private$u.exceptionHandler;return Private$u.exceptionHandler=Du,Lu}Au.setExceptionHandler=Mu})(Signal||(Signal={}));class Stream extends Signal{constructor(){super(...arguments),this._pending=new PromiseDelegate}async*[Symbol.asyncIterator](){let lo=this._pending;for(;;)try{const{args:$u,next:Ru}=await lo.promise;lo=Ru,yield $u}catch{return}}emit(lo){const $u=this._pending,Ru=this._pending=new PromiseDelegate;$u.resolve({args:lo,next:Ru}),super.emit(lo)}stop(){this._pending.promise.catch(()=>{}),this._pending.reject("stop"),this._pending=new PromiseDelegate}}var Private$u;(function(Au){Au.exceptionHandler=Wu=>{console.error(Wu)};function lo(Wu,Ku,Ju){Ju=Ju||void 0;let Yu=Du.get(Wu.sender);if(Yu||(Yu=[],Du.set(Wu.sender,Yu)),Fu(Yu,Wu,Ku,Ju))return!1;let Xu=Ju||Ku,ed=Lu.get(Xu);ed||(ed=[],Lu.set(Xu,ed));let td={signal:Wu,slot:Ku,thisArg:Ju};return Yu.push(td),ed.push(td),!0}Au.connect=lo;function $u(Wu,Ku,Ju){Ju=Ju||void 0;let Yu=Du.get(Wu.sender);if(!Yu||Yu.length===0)return!1;let Xu=Fu(Yu,Wu,Ku,Ju);if(!Xu)return!1;let ed=Ju||Ku,td=Lu.get(ed);return Xu.signal=null,Uu(Yu),Uu(td),!0}Au.disconnect=$u;function Ru(Wu,Ku){let Ju=Du.get(Wu);if(!Ju||Ju.length===0)return;let Yu=Lu.get(Ku);if(!(!Yu||Yu.length===0)){for(const Xu of Yu)Xu.signal&&Xu.signal.sender===Wu&&(Xu.signal=null);Uu(Ju),Uu(Yu)}}Au.disconnectBetween=Ru;function Iu(Wu){let Ku=Du.get(Wu);if(!(!Ku||Ku.length===0)){for(const Ju of Ku){if(!Ju.signal)continue;let Yu=Ju.thisArg||Ju.slot;Ju.signal=null,Uu(Lu.get(Yu))}Uu(Ku)}}Au.disconnectSender=Iu;function Pu(Wu){let Ku=Lu.get(Wu);if(!(!Ku||Ku.length===0)){for(const Ju of Ku){if(!Ju.signal)continue;let Yu=Ju.signal.sender;Ju.signal=null,Uu(Du.get(Yu))}Uu(Ku)}}Au.disconnectReceiver=Pu;function Ou(Wu){Iu(Wu),Pu(Wu)}Au.disconnectAll=Ou;function Mu(Wu,Ku){let Ju=Du.get(Wu.sender);if(!(!Ju||Ju.length===0))for(let Yu=0,Xu=Ju.length;Yu<Xu;++Yu){let ed=Ju[Yu];ed.signal===Wu&&zu(ed,Ku)}}Au.emit=Mu;const Du=new WeakMap,Lu=new WeakMap,Bu=new Set,ju=typeof requestAnimationFrame=="function"?requestAnimationFrame:setImmediate;function Fu(Wu,Ku,Ju,Yu){return find$3(Wu,Xu=>Xu.signal===Ku&&Xu.slot===Ju&&Xu.thisArg===Yu)}function zu(Wu,Ku){let{signal:Ju,slot:Yu,thisArg:Xu}=Wu;try{Yu.call(Xu,Ju.sender,Ku)}catch(ed){Au.exceptionHandler(ed)}}function Uu(Wu){Bu.size===0&&ju(Hu),Bu.add(Wu)}function Hu(){Bu.forEach(Vu),Bu.clear()}function Vu(Wu){ArrayExt.removeAllWhere(Wu,Gu)}function Gu(Wu){return Wu.signal===null}})(Private$u||(Private$u={}));const index_es6$3=Object.freeze(Object.defineProperty({__proto__:null,get Signal(){return Signal},Stream},Symbol.toStringTag,{value:"Module"}));class Poll{constructor(lo){var $u;this._disposed=new Signal(this),this._lingered=0,this._tick=new PromiseDelegate,this._ticked=new Signal(this),this._factory=lo.factory,this._linger=($u=lo.linger)!==null&&$u!==void 0?$u:Private$t.DEFAULT_LINGER,this._standby=lo.standby||Private$t.DEFAULT_STANDBY,this._state={...Private$t.DEFAULT_STATE,timestamp:new Date().getTime()};const Ru=lo.frequency||{},Iu=Math.max(Ru.interval||0,Ru.max||0,Private$t.DEFAULT_FREQUENCY.max);this.frequency={...Private$t.DEFAULT_FREQUENCY,...Ru,max:Iu},this.name=lo.name||Private$t.DEFAULT_NAME,(!("auto"in lo)||lo.auto)&&setTimeout(()=>this.start())}get disposed(){return this._disposed}get frequency(){return this._frequency}set frequency(lo){if(this.isDisposed||JSONExt.deepEqual(lo,this.frequency||{}))return;let{backoff:$u,interval:Ru,max:Iu}=lo;if(Ru=Math.round(Ru),Iu=Math.round(Iu),typeof $u=="number"&&$u<1)throw new Error("Poll backoff growth factor must be at least 1");if((Ru<0||Ru>Iu)&&Ru!==Poll.NEVER)throw new Error("Poll interval must be between 0 and max");if(Iu>Poll.MAX_INTERVAL&&Iu!==Poll.NEVER)throw new Error(`Max interval must be less than ${Poll.MAX_INTERVAL}`);this._frequency={backoff:$u,interval:Ru,max:Iu}}get isDisposed(){return this.state.phase==="disposed"}get standby(){return this._standby}set standby(lo){this.isDisposed||this.standby===lo||(this._standby=lo)}get state(){return this._state}get tick(){return this._tick.promise}get ticked(){return this._ticked}async*[Symbol.asyncIterator](){for(;!this.isDisposed;)yield this.state,await this.tick.catch(()=>{})}dispose(){this.isDisposed||(this._state={...Private$t.DISPOSED_STATE,timestamp:new Date().getTime()},this._tick.promise.catch(lo=>{}),this._tick.reject(new Error(`Poll (${this.name}) is disposed.`)),this._disposed.emit(void 0),Signal.clearData(this))}refresh(){return this.schedule({cancel:({phase:lo})=>lo==="refreshed",interval:Poll.IMMEDIATE,phase:"refreshed"})}async schedule(lo={}){if(this.isDisposed||lo.cancel&&lo.cancel(this.state))return;const $u=this._tick,Ru=new PromiseDelegate,Iu={interval:this.frequency.interval,payload:null,phase:"standby",timestamp:new Date().getTime(),...lo};if(this._state=Iu,this._tick=Ru,clearTimeout(this._timeout),this._ticked.emit(this.state),$u.resolve(this),await $u.promise,Iu.interval===Poll.NEVER){this._timeout=void 0;return}const Pu=()=>{this.isDisposed||this.tick!==Ru.promise||this._execute()};this._timeout=setTimeout(Pu,Iu.interval)}start(){return this.schedule({cancel:({phase:lo})=>lo!=="constructed"&&lo!=="standby"&&lo!=="stopped",interval:Poll.IMMEDIATE,phase:"started"})}stop(){return this.schedule({cancel:({phase:lo})=>lo==="stopped",interval:Poll.NEVER,phase:"stopped"})}get hidden(){return Private$t.hidden}_execute(){let lo=typeof this.standby=="function"?this.standby():this.standby;if(lo==="never"?lo=!1:lo==="when-hidden"&&(this.hidden?lo=++this._lingered>this._linger:(this._lingered=0,lo=!1)),lo){this.schedule();return}const $u=this.tick;this._factory(this.state).then(Ru=>{this.isDisposed||this.tick!==$u||this.schedule({payload:Ru,phase:this.state.phase==="rejected"?"reconnected":"resolved"})}).catch(Ru=>{this.isDisposed||this.tick!==$u||this.schedule({interval:Private$t.sleep(this.frequency,this.state),payload:Ru,phase:"rejected"})})}}(function(Au){Au.IMMEDIATE=0,Au.MAX_INTERVAL=2147483647,Au.NEVER=1/0})(Poll||(Poll={}));var Private$t;(function(Au){Au.DEFAULT_BACKOFF=3,Au.DEFAULT_FREQUENCY={backoff:!0,interval:1e3,max:30*1e3},Au.DEFAULT_LINGER=1,Au.DEFAULT_NAME="unknown",Au.DEFAULT_STANDBY="when-hidden",Au.DEFAULT_STATE={interval:Poll.NEVER,payload:null,phase:"constructed",timestamp:new Date(0).getTime()},Au.DISPOSED_STATE={interval:Poll.NEVER,payload:null,phase:"disposed",timestamp:new Date(0).getTime()};function lo(Ru,Iu){const{backoff:Pu,interval:Ou,max:Mu}=Ru;if(Ou===Poll.NEVER)return Ou;const Du=Pu===!0?Au.DEFAULT_BACKOFF:Pu===!1?1:Pu,Lu=$u(Ou,Iu.interval*Du);return Math.min(Mu,Lu)}Au.sleep=lo,Au.hidden=typeof document>"u"?!1:(document.addEventListener("visibilitychange",()=>{Au.hidden=document.visibilityState==="hidden"}),document.addEventListener("pagehide",()=>{Au.hidden=document.visibilityState==="hidden"}),document.visibilityState==="hidden");function $u(Ru,Iu){return Ru=Math.ceil(Ru),Iu=Math.floor(Iu),Math.floor(Math.random()*(Iu-Ru+1))+Ru}})(Private$t||(Private$t={}));class RateLimiter{constructor(lo,$u=500){this.args=void 0,this.payload=null,this.limit=$u,this.poll=new Poll({auto:!1,factory:async()=>{const{args:Ru}=this;return this.args=void 0,lo(...Ru)},frequency:{backoff:!1,interval:Poll.NEVER,max:Poll.NEVER},standby:"never"}),this.payload=new PromiseDelegate,this.poll.ticked.connect((Ru,Iu)=>{const{payload:Pu}=this;if(Iu.phase==="resolved"){this.payload=new PromiseDelegate,Pu.resolve(Iu.payload);return}if(Iu.phase==="rejected"||Iu.phase==="stopped"){this.payload=new PromiseDelegate,Pu.promise.catch(Ou=>{}),Pu.reject(Iu.payload);return}},this)}get isDisposed(){return this.payload===null}dispose(){this.isDisposed||(this.args=void 0,this.payload=null,this.poll.dispose())}async stop(){return this.poll.stop()}}class Debouncer extends RateLimiter{invoke(...lo){return this.args=lo,this.poll.schedule({interval:this.limit,phase:"invoked"}),this.payload.promise}}class Throttler extends RateLimiter{constructor(lo,$u){super(lo,typeof $u=="number"?$u:$u&&$u.limit),this._trailing=!1,typeof $u!="number"&&$u&&$u.edge==="trailing"&&(this._trailing=!0),this._interval=this._trailing?this.limit:Poll.IMMEDIATE}invoke(...lo){const $u=this.poll.state.phase!=="invoked";return($u||this._trailing)&&(this.args=lo),$u&&this.poll.schedule({interval:this._interval,phase:"invoked"}),this.payload.promise}}const index_es6$2=Object.freeze(Object.defineProperty({__proto__:null,Debouncer,get Poll(){return Poll},RateLimiter,Throttler},Symbol.toStringTag,{value:"Module"})),QueryClientContext=reactExports.createContext(void 0),useQueryClient=Au=>{const lo=reactExports.useContext(QueryClientContext);if(!lo)throw new Error("No QueryClient set, use QueryClientProvider to set one");return lo},QueryClientProvider=({client:Au,children:lo})=>(reactExports.useEffect(()=>(Au.mount(),()=>{Au.unmount()}),[Au]),jsxRuntimeExports.jsx(QueryClientContext.Provider,{value:Au,children:lo})),defaultTimeoutProvider={setTimeout:(Au,lo)=>setTimeout(Au,lo),clearTimeout:Au=>clearTimeout(Au),setInterval:(Au,lo)=>setInterval(Au,lo),clearInterval:Au=>clearInterval(Au)};var TimeoutManager=class{#e=defaultTimeoutProvider;#t=!1;setTimeoutProvider(Au){this.#e=Au}setTimeout(Au,lo){return this.#e.setTimeout(Au,lo)}clearTimeout(Au){this.#e.clearTimeout(Au)}setInterval(Au,lo){return this.#e.setInterval(Au,lo)}clearInterval(Au){this.#e.clearInterval(Au)}};const timeoutManager=new TimeoutManager;function systemSetTimeoutZero(Au){setTimeout(Au,0)}const isServer$1=typeof window>"u"||"Deno"in globalThis;function noop$2(){}function functionalUpdate(Au,lo){return typeof Au=="function"?Au(lo):Au}function isValidTimeout(Au){return typeof Au=="number"&&Au>=0&&Au!==1/0}function timeUntilStale(Au,lo){return Math.max(Au+(lo||0)-Date.now(),0)}function resolveQueryValue(Au,lo){return typeof Au=="function"?Au(lo):Au}function matchQuery(Au,lo){const{type:$u="all",exact:Ru,fetchStatus:Iu,predicate:Pu,queryKey:Ou,stale:Mu}=Au;if(Ou){if(Ru){if(lo.queryHash!==hashQueryKeyByOptions(Ou,lo.options))return!1}else if(!partialMatchKey(lo.queryKey,Ou))return!1}if($u!=="all"){const Du=lo.isActive();if($u==="active"&&!Du||$u==="inactive"&&Du)return!1}return!(typeof Mu=="boolean"&&lo.isStale()!==Mu||Iu&&Iu!==lo.state.fetchStatus||Pu&&!Pu(lo))}function matchMutation(Au,lo){const{exact:$u,status:Ru,predicate:Iu,mutationKey:Pu}=Au;if(Pu){if(!lo.options.mutationKey)return!1;if($u){if(hashKey(lo.options.mutationKey)!==hashKey(Pu))return!1}else if(!partialMatchKey(lo.options.mutationKey,Pu))return!1}return!(Ru&&lo.state.status!==Ru||Iu&&!Iu(lo))}function hashQueryKeyByOptions(Au,lo){return(lo?.queryKeyHashFn||hashKey)(Au)}function hashKey(Au){return JSON.stringify(Au,(lo,$u)=>isPlainObject$8($u)?Object.keys($u).sort().reduce((Ru,Iu)=>(Ru[Iu]=$u[Iu],Ru),{}):$u)}function partialMatchKey(Au,lo){if(Au===lo)return!0;if(typeof Au!=typeof lo)return!1;if(Au&&lo&&typeof Au=="object"&&typeof lo=="object"){if(Array.isArray(Au)&&Array.isArray(lo)){if(lo.length>Au.length)return!1;for(let Ru=0;Ru<lo.length;Ru++)if(!partialMatchKey(Au[Ru],lo[Ru]))return!1;return!0}const $u=Object.keys(lo);for(const Ru of $u)if(!partialMatchKey(Au[Ru],lo[Ru]))return!1;return!0}return!1}const hasOwn$1=Object.prototype.hasOwnProperty;function replaceEqualDeep(Au,lo,$u=0){if(Au===lo)return Au;if($u>500)return lo;const Ru=isPlainArray(Au)&&isPlainArray(lo);if(!Ru&&!(isPlainObject$8(Au)&&isPlainObject$8(lo)))return lo;const Iu=(Ru?Au:Object.keys(Au)).length,Pu=Ru?lo:Object.keys(lo),Ou=Pu.length,Mu=Ru?new Array(Ou):{};let Du=0;for(let Lu=0;Lu<Ou;Lu++){const Bu=Ru?Lu:Pu[Lu],ju=Au[Bu],Fu=lo[Bu];if(ju===Fu){Mu[Bu]=ju,(Ru?Lu<Iu:hasOwn$1.call(Au,Bu))&&Du++;continue}if(ju===null||Fu===null||typeof ju!="object"||typeof Fu!="object"){Mu[Bu]=Fu;continue}const zu=replaceEqualDeep(ju,Fu,$u+1);Mu[Bu]=zu,zu===ju&&Du++}return Iu===Ou&&Du===Iu?Au:Mu}function shallowEqualObjects(Au,lo){if(!lo||Object.keys(Au).length!==Object.keys(lo).length)return!1;for(const $u in Au)if(Au[$u]!==lo[$u])return!1;return!0}function isPlainArray(Au){return Array.isArray(Au)&&Au.length===Object.keys(Au).length}function isPlainObject$8(Au){if(!hasObjectPrototype(Au))return!1;const lo=Object.getPrototypeOf(Au),$u=lo?.constructor;if($u===void 0)return!0;if(typeof $u!="function")return!1;const Ru=$u.prototype;return!(!hasObjectPrototype(Ru)||!Ru.hasOwnProperty("isPrototypeOf")||lo!==Object.prototype)}function hasObjectPrototype(Au){return Object.prototype.toString.call(Au)==="[object Object]"}function sleep$2(Au){return new Promise(lo=>{timeoutManager.setTimeout(lo,Au)})}function replaceData(Au,lo,$u){return typeof $u.structuralSharing=="function"?$u.structuralSharing(Au,lo):$u.structuralSharing!==!1?replaceEqualDeep(Au,lo):lo}function addToEnd(Au,lo,$u=0){const Ru=[...Au,lo];return $u&&Ru.length>$u?Ru.slice(1):Ru}function addToStart(Au,lo,$u=0){const Ru=[lo,...Au];return $u&&Ru.length>$u?Ru.slice(0,-1):Ru}const skipToken=Symbol();function ensureQueryFn(Au,lo){return!Au.queryFn&&lo?.initialPromise?()=>lo.initialPromise:!Au.queryFn||Au.queryFn===skipToken?()=>Promise.reject(new Error(`Missing queryFn: '${Au.queryHash}'`)):Au.queryFn}function shouldThrowError(Au,lo){return typeof Au=="function"?Au(...lo):!!Au}function addConsumeAwareSignal(Au,lo,$u){let Ru=!1,Iu;return Object.defineProperty(Au,"signal",{enumerable:!0,get:()=>(Iu??=lo(),Ru||(Ru=!0,Iu.aborted?$u():Iu.addEventListener("abort",$u,{once:!0})),Iu)}),Au}let isServerFn=()=>isServer$1;const isServer=()=>isServerFn();var Subscribable=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(Au){return this.listeners.add(Au),this.onSubscribe(),()=>{this.listeners.delete(Au),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},FocusManager=class extends Subscribable{#e;#t;#r;constructor(){super(),this.#r=Au=>{if(typeof window<"u"&&window.addEventListener){const lo=()=>Au();return window.addEventListener("visibilitychange",lo,!1),()=>{window.removeEventListener("visibilitychange",lo)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(Au){this.#r=Au,this.#t?.(),this.#t=Au(lo=>{typeof lo=="boolean"?this.setFocused(lo):this.onFocus()})}setFocused(Au){this.#e!==Au&&(this.#e=Au,this.onFocus())}onFocus(){const Au=this.isFocused();this.listeners.forEach(lo=>{lo(Au)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}};const focusManager=new FocusManager,defaultScheduler=systemSetTimeoutZero;function createNotifyManager(){let Au=[],lo=0,$u=Mu=>{Mu()},Ru=Mu=>{Mu()},Iu=defaultScheduler;const Pu=Mu=>{lo?Au.push(Mu):Iu(()=>{$u(Mu)})},Ou=()=>{const Mu=Au;Au=[],Mu.length&&Iu(()=>{Ru(()=>{Mu.forEach(Du=>{$u(Du)})})})};return{batch:Mu=>{let Du;lo++;try{Du=Mu()}finally{lo--,lo||Ou()}return Du},batchCalls:Mu=>(...Du)=>{Pu(()=>{Mu(...Du)})},schedule:Pu,setNotifyFunction:Mu=>{$u=Mu},setBatchNotifyFunction:Mu=>{Ru=Mu},setScheduler:Mu=>{Iu=Mu}}}const notifyManager=createNotifyManager();var OnlineManager=class extends Subscribable{#e=!0;#t;#r;constructor(){super(),this.#r=Au=>{if(typeof window<"u"&&window.addEventListener){const lo=()=>Au(!0),$u=()=>Au(!1);return window.addEventListener("online",lo,!1),window.addEventListener("offline",$u,!1),()=>{window.removeEventListener("online",lo),window.removeEventListener("offline",$u)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(Au){this.#r=Au,this.#t?.(),this.#t=Au(this.setOnline.bind(this))}setOnline(Au){this.#e!==Au&&(this.#e=Au,this.listeners.forEach(lo=>{lo(Au)}))}isOnline(){return this.#e}};const onlineManager=new OnlineManager;function defaultRetryDelay(Au){return Math.min(1e3*2**Au,3e4)}function canFetch(Au){return(Au??"online")==="online"?onlineManager.isOnline():!0}var CancelledError=class extends Error{constructor(Au){super("CancelledError"),this.revert=Au?.revert,this.silent=Au?.silent}};function createRetryer(Au){let lo=!1,$u=0,Ru,Iu="pending",Pu,Ou;const Mu=new Promise((Wu,Ku)=>{Pu=Wu,Ou=Ku});Mu.catch(noop$2);const Du=()=>Iu!=="pending",Lu=Wu=>{if(!Du()){const Ku=new CancelledError(Wu);Hu(Ku),Au.onCancel?.(Ku)}},Bu=()=>{lo=!0},ju=()=>{lo=!1},Fu=()=>focusManager.isFocused()&&(Au.networkMode==="always"||onlineManager.isOnline())&&Au.canRun(),zu=()=>canFetch(Au.networkMode)&&Au.canRun(),Uu=Wu=>{Du()||(Ru?.(),Iu="resolved",Pu(Wu))},Hu=Wu=>{Du()||(Ru?.(),Iu="rejected",Ou(Wu))},Vu=Wu=>new Promise(Ku=>{Ru=Ju=>{(Du()||Wu())&&Ku(Ju)},Au.onPause?.()}).then(()=>{Ru=void 0,Du()||Au.onContinue?.()}),Gu=()=>{if(Du())return;let Wu;const Ku=$u===0?Au.initialPromise:void 0;try{Wu=Ku??Au.fn()}catch(Ju){Wu=Promise.reject(Ju)}Promise.resolve(Wu).then(Uu).catch(Ju=>{if(Du())return;const Yu=Au.retry??(isServer()?0:3),Xu=Au.retryDelay??defaultRetryDelay,ed=typeof Xu=="function"?Xu($u,Ju):Xu,td=Yu===!0||typeof Yu=="number"&&$u<Yu||typeof Yu=="function"&&Yu($u,Ju);if(lo||!td){Hu(Ju);return}$u++,Au.onFail?.($u,Ju),sleep$2(ed).then(()=>Fu()?void 0:Vu(Fu)).then(()=>{lo?Hu(Ju):Gu()})})};return{promise:Mu,status:()=>Iu,cancel:Lu,continue:()=>(Ru?.(),Mu),cancelRetry:Bu,continueRetry:ju,canStart:zu,start:()=>(zu()?Gu():Vu(zu).then(Gu),Mu)}}var Removable=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),isValidTimeout(this.gcTime)&&(this.#e=timeoutManager.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(Au){this.gcTime=Math.max(this.gcTime||0,Au??(isServer()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(timeoutManager.clearTimeout(this.#e),this.#e=void 0)}};function infiniteQueryBehavior(Au){return{onFetch:(lo,$u)=>{const Ru=lo.options,Iu=lo.fetchOptions?.meta?.fetchMore?.direction,Pu=lo.state.data?.pages||[],Ou=lo.state.data?.pageParams||[];let Mu={pages:[],pageParams:[]},Du=0;const Lu=async()=>{let Bu=!1;const ju=Uu=>{addConsumeAwareSignal(Uu,()=>lo.signal,()=>Bu=!0)},Fu=ensureQueryFn(lo.options,lo.fetchOptions),zu=async(Uu,Hu,Vu)=>{if(Bu)return Promise.reject(lo.signal.reason);if(Hu==null&&Uu.pages.length)return Promise.resolve(Uu);const Wu=(()=>{const Xu={client:lo.client,queryKey:lo.queryKey,pageParam:Hu,direction:Vu?"backward":"forward",meta:lo.options.meta};return ju(Xu),Xu})(),Ku=await Fu(Wu),{maxPages:Ju}=lo.options,Yu=Vu?addToStart:addToEnd;return{pages:Yu(Uu.pages,Ku,Ju),pageParams:Yu(Uu.pageParams,Hu,Ju)}};if(Iu&&Pu.length){const Uu=Iu==="backward",Hu=Uu?getPreviousPageParam:getNextPageParam,Vu={pages:Pu,pageParams:Ou};Mu=await zu(Vu,Hu(Ru,Vu),Uu)}else{const Uu=Au??Pu.length;do{const Hu=Du===0?Ou[0]===void 0?Ru.initialPageParam:Ou[0]:getNextPageParam(Ru,Mu);if(Du>0&&Hu==null)break;Mu=await zu(Mu,Hu),Du++}while(Du<Uu)}return Mu};lo.options.persister?lo.fetchFn=()=>lo.options.persister?.(Lu,{client:lo.client,queryKey:lo.queryKey,meta:lo.options.meta,signal:lo.signal},$u):lo.fetchFn=Lu}}}function getNextPageParam(Au,{pages:lo,pageParams:$u}){const Ru=lo.length-1;return lo.length>0?Au.getNextPageParam(lo[Ru],lo,$u[Ru],$u):void 0}function getPreviousPageParam(Au,{pages:lo,pageParams:$u}){return lo.length>0?Au.getPreviousPageParam?.(lo[0],lo,$u[0],$u):void 0}var Query=class extends Removable{#e;#t;#r;#n;#i;#o;#s;#l;constructor(Au){super(),this.#l=!1,this.#s=Au.defaultOptions,this.setOptions(Au.options),this.observers=[],this.#i=Au.client,this.#n=this.#i.getQueryCache(),this.queryKey=Au.queryKey,this.queryHash=Au.queryHash,this.#t=getDefaultState$1(this.options),this.state=Au.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#o?.promise}setOptions(Au){if(this.options={...this.#s,...Au},Au?._type&&(this.#e=Au._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const lo=getDefaultState$1(this.options);lo.data!==void 0&&(this.setState(successState(lo.data,lo.dataUpdatedAt)),this.#t=lo)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(Au,lo){const $u=replaceData(this.state.data,Au,this.options);return this.#a({data:$u,type:"success",dataUpdatedAt:lo?.updatedAt,manual:lo?.manual}),$u}setState(Au){this.#a({type:"setState",state:Au})}cancel(Au){const lo=this.#o?.promise;return this.#o?.cancel(Au),lo?lo.then(noop$2).catch(noop$2):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(Au=>resolveQueryValue(Au.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===skipToken||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(Au=>resolveQueryValue(Au.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(Au=>Au.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(Au=0){return this.state.data===void 0?!0:Au==="static"?!1:this.state.isInvalidated?!0:!timeUntilStale(this.state.dataUpdatedAt,Au)}onFocus(){this.observers.find(Au=>Au.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#o?.continue()}onOnline(){this.observers.find(Au=>Au.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#o?.continue()}addObserver(Au){this.observers.includes(Au)||(this.observers.push(Au),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",query:this,observer:Au}))}removeObserver(Au){const lo=this.observers.indexOf(Au);lo!==-1&&(this.observers.splice(lo,1),this.observers.length||(this.#o&&(this.#l||this.state.fetchStatus==="paused"&&this.state.status==="pending"?this.#o.cancel({revert:!0}):this.#o.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:Au}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#a({type:"invalidate"})}async fetch(Au,lo){if(this.state.fetchStatus!=="idle"&&this.#o?.status()!=="rejected"){if(this.state.data!==void 0&&lo?.cancelRefetch)this.cancel({silent:!0});else if(this.#o)return this.#o.continueRetry(),this.#o.promise}if(Au&&this.setOptions(Au),!this.options.queryFn){const Du=this.observers.find(Lu=>Lu.options.queryFn);Du&&this.setOptions(Du.options)}const $u=new AbortController,Ru=Du=>{Object.defineProperty(Du,"signal",{enumerable:!0,get:()=>(this.#l=!0,$u.signal)})},Iu=()=>{const Du=ensureQueryFn(this.options,lo),Bu=(()=>{const ju={client:this.#i,queryKey:this.queryKey,meta:this.meta};return Ru(ju),ju})();return this.#l=!1,this.options.persister?this.options.persister(Du,Bu,this):Du(Bu)},Ou=(()=>{const Du={fetchOptions:lo,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:Iu};return Ru(Du),Du})();(this.#e==="infinite"?infiniteQueryBehavior(this.options.pages):this.options.behavior)?.onFetch(Ou,this),this.#r=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==Ou.fetchOptions?.meta)&&this.#a({type:"fetch",meta:Ou.fetchOptions?.meta});const Mu=this.#o=createRetryer({initialPromise:lo?.initialPromise,fn:Ou.fetchFn,onCancel:Du=>{Du instanceof CancelledError&&Du.revert&&this.setState({...this.#r,fetchStatus:"idle"}),$u.abort()},onFail:(Du,Lu)=>{this.#a({type:"failed",failureCount:Du,error:Lu})},onPause:()=>{this.#a({type:"pause"})},onContinue:()=>{this.#a({type:"continue"})},retry:Ou.options.retry,retryDelay:Ou.options.retryDelay,networkMode:Ou.options.networkMode,canRun:()=>!0});try{const Du=await Mu.start();if(Du===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(Du),this.#n.config.onSuccess?.(Du,this),this.#n.config.onSettled?.(Du,this.state.error,this),Du}catch(Du){if(Du instanceof CancelledError){if(Du.silent)return this.#o.promise;if(Du.revert){if(this.state.data===void 0)throw Du;return this.state.data}}throw this.#a({type:"error",error:Du}),this.#n.config.onError?.(Du,this),this.#n.config.onSettled?.(this.state.data,Du,this),Du}finally{this.#o===Mu&&(this.#o=void 0),this.scheduleGc()}}#a(Au){const lo=$u=>{switch(Au.type){case"failed":return{...$u,fetchFailureCount:Au.failureCount,fetchFailureReason:Au.error};case"pause":return{...$u,fetchStatus:"paused"};case"continue":return{...$u,fetchStatus:"fetching"};case"fetch":return{...$u,...fetchState($u.data,this.options),fetchMeta:Au.meta??null};case"success":const Ru={...$u,...successState(Au.data,Au.dataUpdatedAt),dataUpdateCount:$u.dataUpdateCount+1,...!Au.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#r=Au.manual?Ru:void 0,Ru;case"error":const Iu=Au.error;return{...$u,error:Iu,errorUpdateCount:$u.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:$u.fetchFailureCount+1,fetchFailureReason:Iu,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...$u,isInvalidated:!0};case"setState":return{...$u,...Au.state}}};this.state=lo(this.state),notifyManager.batch(()=>{this.observers.slice().forEach($u=>{$u.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:Au})})}};function fetchState(Au,lo){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:canFetch(lo.networkMode)?"fetching":"paused",...Au===void 0&&{error:null,status:"pending"}}}function successState(Au,lo){return{data:Au,dataUpdatedAt:lo??Date.now(),error:null,isInvalidated:!1,status:"success"}}function getDefaultState$1(Au){const lo=typeof Au.initialData=="function"?Au.initialData():Au.initialData,$u=lo!==void 0,Ru=$u?typeof Au.initialDataUpdatedAt=="function"?Au.initialDataUpdatedAt():Au.initialDataUpdatedAt:0;return{data:lo,dataUpdateCount:0,dataUpdatedAt:$u?Ru??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:$u?"success":"pending",fetchStatus:"idle"}}var QueryObserver=class extends Subscribable{#e;#t=void 0;#r=void 0;#n=void 0;#i;#o;#s;#l;#a;#p;#u;#d;#c;#f=new Set;constructor(Au,lo){super(),this.options=lo,this.#e=Au,this.#s=null,this.bindMethods(),this.setOptions(lo)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),shouldFetchOnMount(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return shouldFetchOn(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return shouldFetchOn(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#_(),this.#x(),this.#t.removeObserver(this)}setOptions(Au){const lo=this.options,$u=this.#t;if(this.options=this.#e.defaultQueryOptions(Au),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof resolveQueryValue(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#t.setOptions(this.options),lo._defaulted&&!shallowEqualObjects(this.options,lo)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const Ru=this.hasListeners();Ru&&shouldFetchOptionally(this.#t,$u,this.options,lo)&&this.#h(),this.updateResult(),Ru&&(this.#t!==$u||resolveQueryValue(this.options.enabled,this.#t)!==resolveQueryValue(lo.enabled,this.#t)||resolveQueryValue(this.options.staleTime,this.#t)!==resolveQueryValue(lo.staleTime,this.#t))&&this.#g();const Iu=this.#v();Ru&&(this.#t!==$u||resolveQueryValue(this.options.enabled,this.#t)!==resolveQueryValue(lo.enabled,this.#t)||Iu!==this.#c)&&this.#b(Iu)}getOptimisticResult(Au){const lo=this.#e.getQueryCache().build(this.#e,Au),$u=this.createResult(lo,Au);return shallowEqualObjects(this.getCurrentResult(),$u)||(this.#n=$u,this.#o=this.options,this.#i=this.#t.state),$u}getCurrentResult(){return this.#n}trackResult(Au,lo){return new Proxy(Au,{get:($u,Ru)=>(this.trackProp(Ru),lo?.(Ru),Reflect.get($u,Ru))})}trackProp(Au){this.#f.add(Au)}getCurrentQuery(){return this.#t}refetch({...Au}={}){return this.fetch({...Au})}fetchOptimistic(Au){const lo=this.#e.defaultQueryOptions(Au),$u=this.#e.getQueryCache().build(this.#e,lo);let Ru=()=>{},Iu;const Pu=new Promise(Ou=>{Iu=Ou,Ru=this.#e.getQueryCache().subscribe(Mu=>{Mu.type==="updated"&&Mu.query.queryHash===$u.queryHash&&$u.state.data!==void 0&&(Ru(),Ou(this.createResult($u,lo)))})});return Promise.race([$u.fetch(lo).then(()=>{const Ou=this.createResult($u,lo);return Iu?.(Ou),Ou}).finally(()=>{Ru()}),Pu])}fetch(Au){return this.#h({...Au,cancelRefetch:Au.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#n))}#h(Au){this.#S();let lo=this.#t.fetch(this.options,Au);return Au?.throwOnError||(lo=lo.catch(noop$2)),lo}#m(Au){return!isServer()&&resolveQueryValue(this.options.enabled,this.#t)!==!1&&isValidTimeout(Au)}#g(){this.#_();const Au=resolveQueryValue(this.options.staleTime,this.#t);if(this.#n.isStale||!this.#m(Au))return;const lo=timeUntilStale(this.#n.dataUpdatedAt,Au)+1;this.#u=timeoutManager.setTimeout(()=>{this.#n.isStale||this.updateResult()},lo)}#v(){return resolveQueryValue(this.options.refetchInterval,this.#t)??!1}#b(Au){this.#x(),this.#c=Au,!(this.#c===0||!this.#m(this.#c))&&(this.#d=timeoutManager.setInterval(()=>{(this.options.refetchIntervalInBackground||focusManager.isFocused())&&this.#h()},this.#c))}#y(){this.#g(),this.#b(this.#v())}#_(){this.#u!==void 0&&(timeoutManager.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(timeoutManager.clearInterval(this.#d),this.#d=void 0)}createResult(Au,lo){const $u=this.#t,Ru=this.options,Iu=this.#n,Pu=this.#i,Ou=this.#o,Mu=Au!==$u?Au.state:this.#r,{state:Du}=Au;let Lu={...Du},Bu=!1,ju;if(lo._optimisticResults){const Yu=this.hasListeners(),Xu=!Yu&&shouldFetchOnMount(Au,lo),ed=Yu&&shouldFetchOptionally(Au,$u,lo,Ru);(Xu||ed)&&(Lu={...Lu,...fetchState(Du.data,Au.options)}),lo._optimisticResults==="isRestoring"&&(Lu.fetchStatus="idle")}let{error:Fu,errorUpdatedAt:zu,status:Uu}=Lu;ju=Lu.data;let Hu=!1;if(lo.placeholderData!==void 0&&ju===void 0&&Uu==="pending"){let Yu;Iu?.isPlaceholderData&&lo.placeholderData===Ou?.placeholderData?(Yu=Iu.data,Hu=!0):Yu=typeof lo.placeholderData=="function"?lo.placeholderData(this.#p?.state.data,this.#p):lo.placeholderData,Yu!==void 0&&(Uu="success",ju=replaceData(Iu?.data,Yu,lo),Bu=!0)}if(lo.select&&ju!==void 0&&!Hu)if(Iu&&ju===Pu?.data&&lo.select===this.#l)ju=this.#a;else try{this.#l=lo.select,ju=lo.select(ju),ju=replaceData(Iu?.data,ju,lo),this.#a=ju,this.#s=null}catch(Yu){this.#s=Yu}else ju===void 0&&(this.#s=null);this.#s&&(Fu=this.#s,ju=this.#a,zu=Date.now(),Uu="error",Bu=!1);const Vu=Lu.fetchStatus==="fetching",Gu=Uu==="pending",Wu=Uu==="error",Ku=Gu&&Vu,Ju=ju!==void 0;return{status:Uu,fetchStatus:Lu.fetchStatus,isPending:Gu,isSuccess:Uu==="success",isError:Wu,isInitialLoading:Ku,isLoading:Ku,data:ju,dataUpdatedAt:Lu.dataUpdatedAt,error:Fu,errorUpdatedAt:zu,failureCount:Lu.fetchFailureCount,failureReason:Lu.fetchFailureReason,errorUpdateCount:Lu.errorUpdateCount,isFetched:Au.isFetched(),isFetchedAfterMount:Lu.dataUpdateCount>Mu.dataUpdateCount||Lu.errorUpdateCount>Mu.errorUpdateCount,isFetching:Vu,isRefetching:Vu&&!Gu,isLoadingError:Wu&&!Ju,isPaused:Lu.fetchStatus==="paused",isPlaceholderData:Bu,isRefetchError:Wu&&Ju,isStale:isStale(Au,lo),refetch:this.refetch,isEnabled:resolveQueryValue(lo.enabled,Au)!==!1}}updateResult(){const Au=this.#n,lo=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#o=this.options,this.#i.data!==void 0&&(this.#p=this.#t),shallowEqualObjects(lo,Au))return;this.#n=lo;const Ru=(()=>{if(!Au)return!0;const{notifyOnChangeProps:Iu}=this.options,Pu=typeof Iu=="function"?Iu():Iu;if(Pu==="all"||!Pu&&!this.#f.size)return!0;const Ou=new Set(Pu??this.#f);return this.options.throwOnError&&Ou.add("error"),Object.keys(this.#n).some(Mu=>{const Du=Mu;return this.#n[Du]!==Au[Du]&&Ou.has(Du)})})();notifyManager.batch(()=>{Ru&&this.listeners.forEach(Iu=>{Iu(this.#n)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}#S(){const Au=this.#e.getQueryCache().build(this.#e,this.options);if(Au===this.#t)return;const lo=this.#t;this.#t=Au,this.#r=Au.state,this.hasListeners()&&(lo?.removeObserver(this),Au.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function shouldLoadOnMount(Au,lo){return resolveQueryValue(lo.enabled,Au)!==!1&&Au.state.data===void 0&&!(Au.state.status==="error"&&resolveQueryValue(lo.retryOnMount,Au)===!1)}function shouldFetchOnMount(Au,lo){return shouldLoadOnMount(Au,lo)||Au.state.data!==void 0&&shouldFetchOn(Au,lo,lo.refetchOnMount)}function shouldFetchOn(Au,lo,$u){if(resolveQueryValue(lo.enabled,Au)!==!1&&resolveQueryValue(lo.staleTime,Au)!=="static"){const Ru=resolveQueryValue($u,Au);return Ru==="always"||Ru!==!1&&isStale(Au,lo)}return!1}function shouldFetchOptionally(Au,lo,$u,Ru){return(Au!==lo||resolveQueryValue(Ru.enabled,Au)===!1)&&(!$u.suspense||Au.state.status!=="error")&&isStale(Au,$u)}function isStale(Au,lo){return resolveQueryValue(lo.enabled,Au)!==!1&&Au.isStaleByTime(resolveQueryValue(lo.staleTime,Au))}var Mutation=class extends Removable{#e;#t;#r;#n;constructor(Au){super(),this.#e=Au.client,this.mutationId=Au.mutationId,this.#r=Au.mutationCache,this.#t=[],this.state=Au.state||getDefaultState(),this.setOptions(Au.options),this.scheduleGc()}setOptions(Au){this.options=Au,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(Au){this.#t.includes(Au)||(this.#t.push(Au),this.clearGcTimeout(),this.#r.notify({type:"observerAdded",mutation:this,observer:Au}))}removeObserver(Au){this.#t=this.#t.filter(lo=>lo!==Au),this.scheduleGc(),this.#r.notify({type:"observerRemoved",mutation:this,observer:Au})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#r.remove(this))}continue(){return this.#n?.continue()??(this.state.status==="pending"?this.execute(this.state.variables):Promise.resolve())}async execute(Au){const lo=()=>{this.#i({type:"continue"})},$u={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},Ru=this.#n=createRetryer({fn:()=>this.options.mutationFn?this.options.mutationFn(Au,$u):Promise.reject(new Error("No mutationFn found")),onFail:(Ou,Mu)=>{this.#i({type:"failed",failureCount:Ou,error:Mu})},onPause:()=>{this.#i({type:"pause"})},onContinue:lo,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#r.canRun(this)}),Iu=this.state.status==="pending",Pu=!Ru.canStart();try{if(Iu)lo();else{this.#i({type:"pending",variables:Au,isPaused:Pu}),this.#r.config.onMutate&&await this.#r.config.onMutate(Au,this,$u);const Mu=await this.options.onMutate?.(Au,$u);Mu!==this.state.context&&this.#i({type:"pending",context:Mu,variables:Au,isPaused:Pu})}const Ou=await Ru.start();return await this.#r.config.onSuccess?.(Ou,Au,this.state.context,this,$u),await this.options.onSuccess?.(Ou,Au,this.state.context,$u),await this.#r.config.onSettled?.(Ou,null,this.state.variables,this.state.context,this,$u),await this.options.onSettled?.(Ou,null,Au,this.state.context,$u),this.#i({type:"success",data:Ou}),Ou}catch(Ou){try{await this.#r.config.onError?.(Ou,Au,this.state.context,this,$u)}catch(Mu){Promise.reject(Mu)}try{await this.options.onError?.(Ou,Au,this.state.context,$u)}catch(Mu){Promise.reject(Mu)}try{await this.#r.config.onSettled?.(void 0,Ou,this.state.variables,this.state.context,this,$u)}catch(Mu){Promise.reject(Mu)}try{await this.options.onSettled?.(void 0,Ou,Au,this.state.context,$u)}catch(Mu){Promise.reject(Mu)}throw this.#i({type:"error",error:Ou}),Ou}finally{this.#n===Ru&&(this.#n=void 0),this.#r.runNext(this)}}#i(Au){const lo=$u=>{switch(Au.type){case"failed":return{...$u,failureCount:Au.failureCount,failureReason:Au.error};case"pause":return{...$u,isPaused:!0};case"continue":return{...$u,isPaused:!1};case"pending":return{...$u,context:Au.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:Au.isPaused,status:"pending",variables:Au.variables,submittedAt:Date.now()};case"success":return{...$u,data:Au.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...$u,data:void 0,error:Au.error,failureCount:$u.failureCount+1,failureReason:Au.error,isPaused:!1,status:"error"}}};this.state=lo(this.state),notifyManager.batch(()=>{this.#t.forEach($u=>{$u.onMutationUpdate(Au)}),this.#r.notify({mutation:this,type:"updated",action:Au})})}};function getDefaultState(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var MutationCache=class extends Subscribable{#e;#t;#r;constructor(Au={}){super(),this.config=Au,this.#e=new Set,this.#t=new Map,this.#r=0}build(Au,lo,$u){const Ru=new Mutation({client:Au,mutationCache:this,mutationId:++this.#r,options:Au.defaultMutationOptions(lo),state:$u});return this.add(Ru),Ru}add(Au){this.#e.add(Au);const lo=scopeFor(Au);if(typeof lo=="string"){const $u=this.#t.get(lo);$u?$u.push(Au):this.#t.set(lo,[Au])}this.notify({type:"added",mutation:Au})}remove(Au){if(this.#e.delete(Au)){const lo=scopeFor(Au);if(typeof lo=="string"){const $u=this.#t.get(lo);if($u)if($u.length>1){const Ru=$u.indexOf(Au);Ru!==-1&&$u.splice(Ru,1)}else $u[0]===Au&&this.#t.delete(lo)}}this.notify({type:"removed",mutation:Au})}canRun(Au){const lo=scopeFor(Au);if(typeof lo=="string"){const $u=this.#t.get(lo)?.find(Ru=>Ru.state.status==="pending");return!$u||$u===Au}else return!0}runNext(Au){const lo=scopeFor(Au);return typeof lo=="string"?this.#t.get(lo)?.find($u=>$u!==Au&&$u.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){notifyManager.batch(()=>{const Au=this.getAll();this.#e.clear(),this.#t.clear(),Au.forEach(lo=>{this.notify({type:"removed",mutation:lo})})})}getAll(){return Array.from(this.#e)}find(Au){const lo={exact:!0,...Au};return this.getAll().find($u=>matchMutation(lo,$u))}findAll(Au={}){return this.getAll().filter(lo=>matchMutation(Au,lo))}notify(Au){notifyManager.batch(()=>{this.listeners.forEach(lo=>{lo(Au)})})}resumePausedMutations(){const Au=this.getAll().filter(lo=>lo.state.isPaused);return notifyManager.batch(()=>Promise.all(Au.map(lo=>lo.continue().catch(noop$2))))}};function scopeFor(Au){return Au.options.scope?.id}var MutationObserver$1=class extends Subscribable{#e;#t=void 0;#r;#n;constructor(lo,$u){super(),this.#e=lo,this.setOptions($u),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(lo){const $u=this.options;this.options=this.#e.defaultMutationOptions(lo),shallowEqualObjects(this.options,$u)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#r,observer:this}),$u?.mutationKey&&this.options.mutationKey&&hashKey($u.mutationKey)!==hashKey(this.options.mutationKey)?this.reset():this.#r?.state.status==="pending"&&this.#r.setOptions(this.options)}onSubscribe(){this.listeners.size===1&&this.#r&&(this.#r.addObserver(this),this.#i())}onUnsubscribe(){this.hasListeners()||this.#r?.removeObserver(this)}onMutationUpdate(lo){this.#i(),this.#o(lo)}getCurrentResult(){return this.#t}reset(){this.#r?.removeObserver(this),this.#r=void 0,this.#i(),this.#o()}mutate(lo,$u){return this.#n=$u,this.#r?.removeObserver(this),this.#r=this.#e.getMutationCache().build(this.#e,this.options),this.#r.addObserver(this),this.#r.execute(lo)}#i(){const lo=this.#r?.state??getDefaultState();this.#t={...lo,isPending:lo.status==="pending",isSuccess:lo.status==="success",isError:lo.status==="error",isIdle:lo.status==="idle",mutate:this.mutate,reset:this.reset}}#o(lo){notifyManager.batch(()=>{const $u=this.#n;if($u&&this.hasListeners()){const Ru=this.#t.variables,Iu=this.#t.context,Pu={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(lo?.type==="success"){try{$u.onSuccess?.(lo.data,Ru,Iu,Pu)}catch(Ou){Promise.reject(Ou)}try{$u.onSettled?.(lo.data,null,Ru,Iu,Pu)}catch(Ou){Promise.reject(Ou)}}else if(lo?.type==="error"){try{$u.onError?.(lo.error,Ru,Iu,Pu)}catch(Ou){Promise.reject(Ou)}try{$u.onSettled?.(void 0,lo.error,Ru,Iu,Pu)}catch(Ou){Promise.reject(Ou)}}}this.listeners.forEach(Ru=>{Ru(this.#t)})})}},QueryCache=class extends Subscribable{#e;constructor(Au={}){super(),this.config=Au,this.#e=new Map}build(Au,lo,$u){const Ru=lo.queryKey,Iu=lo.queryHash??hashQueryKeyByOptions(Ru,lo);let Pu=this.get(Iu);return Pu||(Pu=new Query({client:Au,queryKey:Ru,queryHash:Iu,options:Au.defaultQueryOptions(lo),state:$u,defaultOptions:Au.getQueryDefaults(Ru)}),this.add(Pu)),Pu}add(Au){this.#e.has(Au.queryHash)||(this.#e.set(Au.queryHash,Au),this.notify({type:"added",query:Au}))}remove(Au){this.#e.get(Au.queryHash)===Au&&(Au.destroy(),this.#e.delete(Au.queryHash),this.notify({type:"removed",query:Au}))}clear(){notifyManager.batch(()=>{this.getAll().forEach(Au=>{this.remove(Au)})})}get(Au){return this.#e.get(Au)}getAll(){return[...this.#e.values()]}find(Au){const lo={exact:!0,...Au};return this.getAll().find($u=>matchQuery(lo,$u))}findAll(Au={}){const lo=this.getAll();return Object.keys(Au).length>0?lo.filter($u=>matchQuery(Au,$u)):lo}notify(Au){notifyManager.batch(()=>{this.listeners.forEach(lo=>{lo(Au)})})}onFocus(){notifyManager.batch(()=>{this.getAll().forEach(Au=>{Au.onFocus()})})}onOnline(){notifyManager.batch(()=>{this.getAll().forEach(Au=>{Au.onOnline()})})}},QueryClient=class{#e;#t;#r;#n;#i;#o;#s;#l;constructor(Au={}){this.#e=Au.queryCache||new QueryCache,this.#t=Au.mutationCache||new MutationCache,this.#r=Au.defaultOptions||{},this.#n=new Map,this.#i=new Map,this.#o=0}mount(){this.#o++,this.#o===1&&(this.#s=focusManager.subscribe(async Au=>{Au&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#l=onlineManager.subscribe(async Au=>{Au&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#o--,this.#o===0&&(this.#s?.(),this.#s=void 0,this.#l?.(),this.#l=void 0)}isFetching(Au){return this.#e.findAll({...Au,fetchStatus:"fetching"}).length}isMutating(Au){return this.#t.findAll({...Au,status:"pending"}).length}getQueryData(Au){const lo=this.defaultQueryOptions({queryKey:Au});return this.#e.get(lo.queryHash)?.state.data}ensureQueryData(Au){const lo=this.defaultQueryOptions(Au),$u=this.#e.build(this,lo),Ru=$u.state.data;return Ru===void 0?this.fetchQuery(Au):(Au.revalidateIfStale&&$u.isStaleByTime(resolveQueryValue(lo.staleTime,$u))&&this.prefetchQuery(lo),Promise.resolve(Ru))}getQueriesData(Au){return this.#e.findAll(Au).map(({queryKey:lo,state:$u})=>[lo,$u.data])}setQueryData(Au,lo,$u){const Ru=this.defaultQueryOptions({queryKey:Au}),Iu=this.#e.get(Ru.queryHash)?.state.data,Pu=functionalUpdate(lo,Iu);if(Pu!==void 0)return this.#e.build(this,Ru).setData(Pu,{...$u,manual:!0})}setQueriesData(Au,lo,$u){return notifyManager.batch(()=>this.#e.findAll(Au).map(({queryKey:Ru})=>[Ru,this.setQueryData(Ru,lo,$u)]))}getQueryState(Au){const lo=this.defaultQueryOptions({queryKey:Au});return this.#e.get(lo.queryHash)?.state}removeQueries(Au){const lo=this.#e;notifyManager.batch(()=>{lo.findAll(Au).forEach($u=>{lo.remove($u)})})}resetQueries(Au,lo){const $u=this.#e;return notifyManager.batch(()=>{const Ru=$u.findAll(Au),Iu=new Set(Ru);return Ru.forEach(Pu=>{Pu.reset()}),this.refetchQueries({type:"active",predicate:Pu=>Iu.has(Pu)},lo)})}cancelQueries(Au,lo={}){const $u={revert:!0,...lo},Ru=notifyManager.batch(()=>this.#e.findAll(Au).map(Iu=>Iu.cancel($u)));return Promise.all(Ru).then(noop$2).catch(noop$2)}invalidateQueries(Au,lo={}){return notifyManager.batch(()=>(this.#e.findAll(Au).forEach($u=>{$u.invalidate()}),Au?.refetchType==="none"?Promise.resolve():this.refetchQueries({...Au,type:Au?.refetchType??Au?.type??"active"},lo)))}refetchQueries(Au,lo={}){const $u={...lo,cancelRefetch:lo.cancelRefetch??!0},Ru=notifyManager.batch(()=>this.#e.findAll(Au).filter(Iu=>!Iu.isDisabled()&&!Iu.isStatic()).map(Iu=>{let Pu=Iu.fetch(void 0,$u);return $u.throwOnError||(Pu=Pu.catch(noop$2)),Iu.state.fetchStatus==="paused"?Promise.resolve():Pu}));return Promise.all(Ru).then(noop$2)}async query(Au){const lo=this.defaultQueryOptions(Au);lo.retry===void 0&&(lo.retry=!1);const $u=this.#e.build(this,lo),Ru=$u.isStaleByTime(resolveQueryValue(lo.staleTime,$u))?await $u.fetch(lo):$u.state.data,Iu=lo.select;return Iu?Iu(Ru):Ru}fetchQuery(Au){const lo=this.defaultQueryOptions(Au);lo.retry===void 0&&(lo.retry=!1);const $u=this.#e.build(this,lo);return $u.isStaleByTime(resolveQueryValue(lo.staleTime,$u))?$u.fetch(lo):Promise.resolve($u.state.data)}prefetchQuery(Au){return this.fetchQuery(Au).then(noop$2).catch(noop$2)}infiniteQuery(Au){return Au._type="infinite",this.query(Au)}fetchInfiniteQuery(Au){return Au._type="infinite",this.fetchQuery(Au)}prefetchInfiniteQuery(Au){return this.fetchInfiniteQuery(Au).then(noop$2).catch(noop$2)}ensureInfiniteQueryData(Au){return Au._type="infinite",this.ensureQueryData(Au)}resumePausedMutations(){return onlineManager.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#r}setDefaultOptions(Au){this.#r=Au}setQueryDefaults(Au,lo){this.#n.set(hashKey(Au),{queryKey:Au,defaultOptions:lo})}getQueryDefaults(Au){const lo=[...this.#n.values()],$u={};return lo.forEach(Ru=>{partialMatchKey(Au,Ru.queryKey)&&Object.assign($u,Ru.defaultOptions)}),$u}setMutationDefaults(Au,lo){this.#i.set(hashKey(Au),{mutationKey:Au,defaultOptions:lo})}getMutationDefaults(Au){const lo=[...this.#i.values()],$u={};return lo.forEach(Ru=>{partialMatchKey(Au,Ru.mutationKey)&&Object.assign($u,Ru.defaultOptions)}),$u}defaultQueryOptions(Au){if(Au._defaulted)return Au;const lo={...this.#r.queries,...this.getQueryDefaults(Au.queryKey),...Au,_defaulted:!0};return lo.queryHash||(lo.queryHash=hashQueryKeyByOptions(lo.queryKey,lo)),lo.refetchOnReconnect===void 0&&(lo.refetchOnReconnect=lo.networkMode!=="always"),lo.throwOnError===void 0&&(lo.throwOnError=!!lo.suspense),!lo.networkMode&&lo.persister&&(lo.networkMode="offlineFirst"),lo.queryFn===skipToken&&(lo.enabled=!1),lo}defaultMutationOptions(Au){return Au?._defaulted?Au:{...this.#r.mutations,...Au?.mutationKey&&this.getMutationDefaults(Au.mutationKey),...Au,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};const IsRestoringContext=reactExports.createContext(!1),useIsRestoring=()=>reactExports.useContext(IsRestoringContext);IsRestoringContext.Provider;function createValue(){let Au=!1;return{clearReset:()=>{Au=!1},reset:()=>{Au=!0},isReset:()=>Au}}const QueryErrorResetBoundaryContext=reactExports.createContext(createValue()),useQueryErrorResetBoundary=()=>reactExports.useContext(QueryErrorResetBoundaryContext),ensurePreventErrorBoundaryRetry=(Au,lo,$u)=>{const Ru=$u?.state.status==="error"&&typeof Au.throwOnError=="function"?shouldThrowError(Au.throwOnError,[$u.state.error,$u]):Au.throwOnError;(Au.suspense||Ru)&&(lo.isReset()||(Au.retryOnMount=!1))},useClearResetErrorBoundary=Au=>{reactExports.useEffect(()=>{Au.clearReset()},[Au])},getHasError=({result:Au,errorResetBoundary:lo,throwOnError:$u,query:Ru,suspense:Iu})=>Au.isError&&!lo.isReset()&&!Au.isFetching&&Ru&&(Iu&&Au.data===void 0||shouldThrowError($u,[Au.error,Ru])),ensureSuspenseTimers=Au=>{if(Au.suspense){const $u=Iu=>Iu==="static"?Iu:Math.max(Iu??1e3,1e3),Ru=Au.staleTime;Au.staleTime=typeof Ru=="function"?(...Iu)=>$u(Ru(...Iu)):$u(Ru),typeof Au.gcTime=="number"&&(Au.gcTime=Math.max(Au.gcTime,1e3))}},shouldSuspend=(Au,lo)=>Au?.suspense&&lo.isPending,fetchOptimistic=(Au,lo,$u)=>lo.fetchOptimistic(Au).catch(()=>{$u.clearReset()});function useBaseQuery(Au,lo,$u){const Ru=useIsRestoring(),Iu=useQueryErrorResetBoundary(),Pu=useQueryClient(),Ou=Pu.defaultQueryOptions(Au),Mu=Pu.getQueryCache().get(Ou.queryHash),Du=Au.subscribed!==!1;Ou._optimisticResults=Ru?"isRestoring":Du?"optimistic":void 0,ensureSuspenseTimers(Ou),ensurePreventErrorBoundaryRetry(Ou,Iu,Mu),useClearResetErrorBoundary(Iu);const[Lu]=reactExports.useState(()=>new lo(Pu,Ou)),Bu=Lu.getOptimisticResult(Ou),ju=!Ru&&Du;if(reactExports.useSyncExternalStore(reactExports.useCallback(Fu=>{const zu=ju?Lu.subscribe(notifyManager.batchCalls(Fu)):noop$2;return Lu.updateResult(),zu},[Lu,ju]),()=>Lu.getCurrentResult(),()=>Lu.getCurrentResult()),reactExports.useEffect(()=>{Lu.setOptions(Ou)},[Ou,Lu]),shouldSuspend(Ou,Bu))throw fetchOptimistic(Ou,Lu,Iu);if(getHasError({result:Bu,errorResetBoundary:Iu,throwOnError:Ou.throwOnError,query:Mu,suspense:Ou.suspense}))throw Bu.error;return Ou.notifyOnChangeProps?Bu:Lu.trackResult(Bu)}function useQuery(Au,lo){return useBaseQuery(Au,QueryObserver)}function useMutation(Au,lo){const $u=useQueryClient(),[Ru]=reactExports.useState(()=>new MutationObserver$1($u,Au));reactExports.useEffect(()=>{Ru.setOptions(Au)},[Ru,Au]);const Iu=reactExports.useSyncExternalStore(reactExports.useCallback(Ou=>Ru.subscribe(notifyManager.batchCalls(Ou)),[Ru]),()=>Ru.getCurrentResult(),()=>Ru.getCurrentResult()),Pu=reactExports.useCallback((...Ou)=>{Ru.mutate(Ou[0],Ou[1]).catch(noop$2)},[Ru]);if(Iu.error&&shouldThrowError(Ru.options.throwOnError,[Iu.error]))throw Iu.error;return{...Iu,mutate:Pu,mutateAsync:Iu.mutate}}function getCookie$1(Au){let lo;try{lo=document.cookie}catch{return lo}const $u=Au+"=",Iu=decodeURIComponent(document.cookie).split(";");for(let Pu=0;Pu<Iu.length;Pu++){let Ou=Iu[Pu];for(;Ou.charAt(0)===" ";)Ou=Ou.substring(1);if(Ou.indexOf($u)===0)return Ou.substring($u.length,Ou.length)}}function setCookie(Au,lo,$u="/"){const Ru=new Date,Pu=Ru.getTime()+1e3*36e3;Ru.setTime(Pu),document.cookie=`${Au}=${lo}; expires=${Ru.toUTCString()}; SameSite=Lax; path=${$u}`}function deleteCookie$1(Au){document.cookie=`${Au}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`}function createError(Au){const lo=new Error(Au);return lo.source="ulid",lo}const ENCODING="0123456789ABCDEFGHJKMNPQRSTVWXYZ",ENCODING_LEN=ENCODING.length,TIME_MAX=Math.pow(2,48)-1,TIME_LEN=10,RANDOM_LEN=16;function randomChar(Au){let lo=Math.floor(Au()*ENCODING_LEN);return lo===ENCODING_LEN&&(lo=ENCODING_LEN-1),ENCODING.charAt(lo)}function encodeTime(Au,lo){if(isNaN(Au))throw new Error(Au+" must be a number");if(Au>TIME_MAX)throw createError("cannot encode time greater than "+TIME_MAX);if(Au<0)throw createError("time must be positive");if(Number.isInteger(Number(Au))===!1)throw createError("time must be an integer");let $u,Ru="";for(;lo>0;lo--)$u=Au%ENCODING_LEN,Ru=ENCODING.charAt($u)+Ru,Au=(Au-$u)/ENCODING_LEN;return Ru}function encodeRandom(Au,lo){let $u="";for(;Au>0;Au--)$u=randomChar(lo)+$u;return $u}function detectPrng(Au=!1,lo){lo||(lo=typeof window<"u"?window:null);const $u=lo&&(lo.crypto||lo.msCrypto);if($u)return()=>{const Ru=new Uint8Array(1);return $u.getRandomValues(Ru),Ru[0]/255};try{const Ru=require("crypto");return()=>Ru.randomBytes(1).readUInt8()/255}catch{}if(Au){try{console.error("secure crypto unusable, falling back to insecure Math.random()!")}catch{}return()=>Math.random()}throw createError("secure crypto unusable, insecure Math.random not allowed")}function factory$1(Au){return Au||(Au=detectPrng()),function($u){return isNaN($u)&&($u=Date.now()),encodeTime($u,TIME_LEN)+encodeRandom(RANDOM_LEN,Au)}}const ulid$1=factory$1(),asDisplayName=(Au,lo)=>Au?lo?Au+" "+lo:Au:lo??"",namesAsInitials=(Au,lo)=>((Au||" ").charAt(0)+(lo||" ").charAt(0)).toLocaleUpperCase().trim(),toFriendlyName=(Au,lo)=>Au||lo||"";function parseJwtPayload(Au){try{const lo=Au.split(".");if(lo.length<2)return null;const $u=lo[1].replace(/-/g,"+").replace(/_/g,"/"),Ru=$u.padEnd($u.length+(4-$u.length%4)%4,"="),Iu=atob(Ru);return JSON.parse(Iu)}catch{return null}}function getJwtExpiryMs(Au){if(!Au)return null;const $u=parseJwtPayload(Au)?.exp;return typeof $u=="number"&&Number.isFinite($u)?$u*1e3:null}function isJwtExpired(Au,lo=0){const $u=getJwtExpiryMs(Au);return $u===null?!1:$u-lo*1e3<=Date.now()}var lib$d={},activitymonitor={};const require$$0$3=getAugmentedNamespace(index_es6$3);var hasRequiredActivitymonitor;function requireActivitymonitor(){if(hasRequiredActivitymonitor)return activitymonitor;hasRequiredActivitymonitor=1,Object.defineProperty(activitymonitor,"__esModule",{value:!0}),activitymonitor.ActivityMonitor=void 0;const Au=require$$0$3;class lo{constructor(Ru){this._timer=-1,this._timeout=-1,this._isDisposed=!1,this._activityStopped=new Au.Signal(this),Ru.signal.connect(this._onSignalFired,this),this._timeout=Ru.timeout||1e3}get activityStopped(){return this._activityStopped}get timeout(){return this._timeout}set timeout(Ru){this._timeout=Ru}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,Au.Signal.clearData(this))}_onSignalFired(Ru,Iu){clearTimeout(this._timer),this._sender=Ru,this._args=Iu,this._timer=setTimeout(()=>{this._activityStopped.emit({sender:this._sender,args:this._args})},this._timeout)}}return activitymonitor.ActivityMonitor=lo,activitymonitor}var interfaces$1={},hasRequiredInterfaces$1;function requireInterfaces$1(){return hasRequiredInterfaces$1||(hasRequiredInterfaces$1=1,Object.defineProperty(interfaces$1,"__esModule",{value:!0})),interfaces$1}var lru={},hasRequiredLru;function requireLru(){if(hasRequiredLru)return lru;hasRequiredLru=1,Object.defineProperty(lru,"__esModule",{value:!0}),lru.LruCache=void 0;const Au=128;class lo{constructor(Ru={}){if(this._map=new Map,this._maxSize=Ru?.maxSize||Au,this._maxSize<1)throw new Error("maxSize must be at least 1")}get size(){return this._map.size}clear(){this._map.clear()}get(Ru){const Iu=this._map.get(Ru)||null;return Iu!=null&&(this._map.delete(Ru),this._map.set(Ru,Iu)),Iu}set(Ru,Iu){!this._map.delete(Ru)&&this._map.size>=this._maxSize&&this._map.delete(this._map.keys().next().value),this._map.set(Ru,Iu)}}return lru.LruCache=lo,lru}var markdowncodeblocks={},hasRequiredMarkdowncodeblocks;function requireMarkdowncodeblocks(){if(hasRequiredMarkdowncodeblocks)return markdowncodeblocks;hasRequiredMarkdowncodeblocks=1,Object.defineProperty(markdowncodeblocks,"__esModule",{value:!0}),markdowncodeblocks.MarkdownCodeBlocks=void 0;var Au;return(function(lo){lo.CODE_BLOCK_MARKER="```";const $u=[".markdown",".mdown",".mkdn",".md",".mkd",".mdwn",".mdtxt",".mdtext",".text",".txt",".Rmd"];class Ru{constructor(Mu){this.startLine=Mu,this.code="",this.endLine=-1}}lo.MarkdownCodeBlock=Ru;function Iu(Ou){return $u.indexOf(Ou)>-1}lo.isMarkdown=Iu;function Pu(Ou){if(!Ou||Ou==="")return[];const Mu=Ou.split(`
|
|
253
253
|
`),Du=[];let Lu=null;for(let Bu=0;Bu<Mu.length;Bu++){const ju=Mu[Bu],Fu=ju.indexOf(lo.CODE_BLOCK_MARKER)===0,zu=Lu!=null;if(!(!Fu&&!zu))if(zu)Lu&&(Fu?(Lu.endLine=Bu-1,Du.push(Lu),Lu=null):Lu.code+=ju+`
|
|
254
254
|
`);else{Lu=new Ru(Bu);const Uu=ju.indexOf(lo.CODE_BLOCK_MARKER),Hu=ju.lastIndexOf(lo.CODE_BLOCK_MARKER);Uu!==Hu&&(Lu.code=ju.substring(Uu+lo.CODE_BLOCK_MARKER.length,Hu),Lu.endLine=Bu,Du.push(Lu),Lu=null)}}return Du}lo.findMarkdownCodeBlocks=Pu})(Au||(markdowncodeblocks.MarkdownCodeBlocks=Au={})),markdowncodeblocks}var pageconfig={},dist$2={exports:{}};const require$$0$2=getAugmentedNamespace(index_es6$4);var dist$1=dist$2.exports,hasRequiredDist;function requireDist(){return hasRequiredDist||(hasRequiredDist=1,(function(Au,lo){(function($u,Ru){Ru(lo,require$$0$2)})(dist$1,(function($u,Ru){$u.JSONExt=void 0,(function(ju){ju.emptyObject=Object.freeze({}),ju.emptyArray=Object.freeze([]);function Fu(Yu){return Yu===null||typeof Yu=="boolean"||typeof Yu=="number"||typeof Yu=="string"}ju.isPrimitive=Fu;function zu(Yu){return Array.isArray(Yu)}ju.isArray=zu;function Uu(Yu){return!Fu(Yu)&&!zu(Yu)}ju.isObject=Uu;function Hu(Yu,Xu){if(Yu===Xu)return!0;if(Fu(Yu)||Fu(Xu))return!1;let ed=zu(Yu),td=zu(Xu);return ed!==td?!1:ed&&td?Gu(Yu,Xu):Wu(Yu,Xu)}ju.deepEqual=Hu;function Vu(Yu){return Fu(Yu)?Yu:zu(Yu)?Ku(Yu):Ju(Yu)}ju.deepCopy=Vu;function Gu(Yu,Xu){if(Yu===Xu)return!0;if(Yu.length!==Xu.length)return!1;for(let ed=0,td=Yu.length;ed<td;++ed)if(!Hu(Yu[ed],Xu[ed]))return!1;return!0}function Wu(Yu,Xu){if(Yu===Xu)return!0;for(let ed in Yu)if(Yu[ed]!==void 0&&!(ed in Xu))return!1;for(let ed in Xu)if(Xu[ed]!==void 0&&!(ed in Yu))return!1;for(let ed in Yu){let td=Yu[ed],nd=Xu[ed];if(!(td===void 0&&nd===void 0)&&(td===void 0||nd===void 0||!Hu(td,nd)))return!1}return!0}function Ku(Yu){let Xu=new Array(Yu.length);for(let ed=0,td=Yu.length;ed<td;++ed)Xu[ed]=Vu(Yu[ed]);return Xu}function Ju(Yu){let Xu={};for(let ed in Yu){let td=Yu[ed];td!==void 0&&(Xu[ed]=Vu(td))}return Xu}})($u.JSONExt||($u.JSONExt={}));class Iu{constructor(){this._types=[],this._values=[]}types(){return this._types.slice()}hasData(Fu){return this._types.indexOf(Fu)!==-1}getData(Fu){let zu=this._types.indexOf(Fu);return zu!==-1?this._values[zu]:void 0}setData(Fu,zu){this.clearData(Fu),this._types.push(Fu),this._values.push(zu)}clearData(Fu){let zu=this._types.indexOf(Fu);zu!==-1&&(this._types.splice(zu,1),this._values.splice(zu,1))}clear(){this._types.length=0,this._values.length=0}}class Pu{constructor(Fu={}){this._application=null,this._validatePlugin=()=>!0,this._plugins=new Map,this._services=new Map,Fu.validatePlugin&&(console.info("Plugins may be rejected by the custom validation plugin method."),this._validatePlugin=Fu.validatePlugin)}get application(){return this._application}set application(Fu){if(this._application!==null)throw Error("PluginRegistry.application is already set. It cannot be overridden.");this._application=Fu}get deferredPlugins(){return Array.from(this._plugins).filter(([Fu,zu])=>zu.autoStart==="defer").map(([Fu,zu])=>Fu)}getPluginDescription(Fu){var zu,Uu;return(Uu=(zu=this._plugins.get(Fu))===null||zu===void 0?void 0:zu.description)!==null&&Uu!==void 0?Uu:""}hasPlugin(Fu){return this._plugins.has(Fu)}isPluginActivated(Fu){var zu,Uu;return(Uu=(zu=this._plugins.get(Fu))===null||zu===void 0?void 0:zu.activated)!==null&&Uu!==void 0?Uu:!1}listPlugins(){return Array.from(this._plugins.keys())}registerPlugin(Fu){if(this._plugins.has(Fu.id))throw new TypeError(`Plugin '${Fu.id}' is already registered.`);if(!this._validatePlugin(Fu))throw new Error(`Plugin '${Fu.id}' is not valid.`);const zu=Ou.createPluginData(Fu);Ou.ensureNoCycle(zu,this._plugins,this._services),zu.provides&&this._services.set(zu.provides,zu.id),this._plugins.set(zu.id,zu)}registerPlugins(Fu){for(const zu of Fu)this.registerPlugin(zu)}deregisterPlugin(Fu,zu){const Uu=this._plugins.get(Fu);if(Uu){if(Uu.activated&&!zu)throw new Error(`Plugin '${Fu}' is still active.`);this._plugins.delete(Fu)}}async activatePlugin(Fu){const zu=this._plugins.get(Fu);if(!zu)throw new ReferenceError(`Plugin '${Fu}' is not registered.`);if(zu.activated)return;if(zu.promise)return zu.promise;const Uu=zu.requires.map(Vu=>this.resolveRequiredService(Vu)),Hu=zu.optional.map(Vu=>this.resolveOptionalService(Vu));return zu.promise=Promise.all([...Uu,...Hu]).then(Vu=>zu.activate.apply(void 0,[this.application,...Vu])).then(Vu=>{zu.service=Vu,zu.activated=!0,zu.promise=null}).catch(Vu=>{throw zu.promise=null,Vu}),zu.promise}async activatePlugins(Fu,zu={}){switch(Fu){case"defer":{const Uu=this.deferredPlugins.filter(Hu=>this._plugins.get(Hu).autoStart).map(Hu=>this.activatePlugin(Hu));await Promise.all(Uu);break}case"startUp":{const Hu=Ou.collectStartupPlugins(this._plugins,zu).map(async Vu=>{try{return await this.activatePlugin(Vu)}catch(Gu){console.error(`Plugin '${Vu}' failed to activate.`,Gu)}});await Promise.all(Hu);break}}}async deactivatePlugin(Fu){const zu=this._plugins.get(Fu);if(!zu)throw new ReferenceError(`Plugin '${Fu}' is not registered.`);if(!zu.activated)return[];if(!zu.deactivate)throw new TypeError(`Plugin '${Fu}'#deactivate() method missing`);const Uu=Ou.findDependents(Fu,this._plugins,this._services),Hu=Uu.map(Vu=>this._plugins.get(Vu));for(const Vu of Hu)if(!Vu.deactivate)throw new TypeError(`Plugin ${Vu.id}#deactivate() method missing (depends on ${Fu})`);for(const Vu of Hu){const Gu=[...Vu.requires,...Vu.optional].map(Wu=>{const Ku=this._services.get(Wu);return Ku?this._plugins.get(Ku).service:null});await Vu.deactivate(this.application,...Gu),Vu.service=null,Vu.activated=!1}return Uu.pop(),Uu}async resolveRequiredService(Fu){const zu=this._services.get(Fu);if(!zu)throw new TypeError(`No provider for: ${Fu.name}.`);const Uu=this._plugins.get(zu);return Uu.activated||await this.activatePlugin(zu),Uu.service}async resolveOptionalService(Fu){const zu=this._services.get(Fu);if(!zu)return null;const Uu=this._plugins.get(zu);if(!Uu.activated)try{await this.activatePlugin(zu)}catch(Hu){return console.error(Hu),null}return Uu.service}}var Ou;(function(ju){class Fu{constructor(Wu){var Ku,Ju,Yu,Xu;this._activated=!1,this._promise=null,this._service=null,this.id=Wu.id,this.description=(Ku=Wu.description)!==null&&Ku!==void 0?Ku:"",this.activate=Wu.activate,this.deactivate=(Ju=Wu.deactivate)!==null&&Ju!==void 0?Ju:null,this.provides=(Yu=Wu.provides)!==null&&Yu!==void 0?Yu:null,this.autoStart=(Xu=Wu.autoStart)!==null&&Xu!==void 0?Xu:!1,this.requires=Wu.requires?Wu.requires.slice():[],this.optional=Wu.optional?Wu.optional.slice():[]}get activated(){return this._activated}set activated(Wu){this._activated=Wu}get service(){return this._service}set service(Wu){this._service=Wu}get promise(){return this._promise}set promise(Wu){this._promise=Wu}}function zu(Gu){return new Fu(Gu)}ju.createPluginData=zu;function Uu(Gu,Wu,Ku){const Ju=[...Gu.requires,...Gu.optional],Yu=ed=>{if(ed===Gu.provides)return!0;const td=Ku.get(ed);if(!td)return!1;const nd=Wu.get(td),od=[...nd.requires,...nd.optional];return od.length===0?!1:(Xu.push(td),od.some(Yu)?!0:(Xu.pop(),!1))};if(!Gu.provides||Ju.length===0)return;const Xu=[Gu.id];if(Ju.some(Yu))throw new ReferenceError(`Cycle detected: ${Xu.join(" -> ")}.`)}ju.ensureNoCycle=Uu;function Hu(Gu,Wu,Ku){const Ju=new Array,Yu=od=>{const sd=Wu.get(od),ad=[...sd.requires,...sd.optional];Ju.push(...ad.reduce((pd,gd)=>{const yd=Ku.get(gd);return yd&&pd.push([od,yd]),pd},[]))};for(const od of Wu.keys())Yu(od);const Xu=Ju.filter(od=>od[1]===Gu);let ed=0;for(;Xu.length>ed;){const od=Xu.length,sd=new Set(Xu.map(ad=>ad[0]));for(const ad of sd)Ju.filter(pd=>pd[1]===ad).forEach(pd=>{Xu.includes(pd)||Xu.push(pd)});ed=od}const td=Ru.topologicSort(Xu),nd=td.findIndex(od=>od===Gu);return nd===-1?[Gu]:td.slice(0,nd+1)}ju.findDependents=Hu;function Vu(Gu,Wu){const Ku=new Set;for(const Ju of Gu.keys())Gu.get(Ju).autoStart===!0&&Ku.add(Ju);if(Wu.startPlugins)for(const Ju of Wu.startPlugins)Ku.add(Ju);if(Wu.ignorePlugins)for(const Ju of Wu.ignorePlugins)Ku.delete(Ju);return Array.from(Ku)}ju.collectStartupPlugins=Vu})(Ou||(Ou={}));class Mu{constructor(){this.promise=new Promise((Fu,zu)=>{this._resolve=Fu,this._reject=zu})}resolve(Fu){let zu=this._resolve;zu(Fu)}reject(Fu){let zu=this._reject;zu(Fu)}}class Du{constructor(Fu,zu){this.name=Fu,this.description=zu??"",this._tokenStructuralPropertyT=null}}function Lu(ju){let Fu=0;for(let zu=0,Uu=ju.length;zu<Uu;++zu)zu%4===0&&(Fu=Math.random()*4294967295>>>0),ju[zu]=Fu&255,Fu>>>=8}$u.Random=void 0,(function(ju){ju.getRandomValues=(()=>{const Fu=typeof window<"u"&&(window.crypto||window.msCrypto)||null;return Fu&&typeof Fu.getRandomValues=="function"?function(Uu){return Fu.getRandomValues(Uu)}:Lu})()})($u.Random||($u.Random={}));function Bu(ju){const Fu=new Uint8Array(16),zu=new Array(256);for(let Uu=0;Uu<16;++Uu)zu[Uu]="0"+Uu.toString(16);for(let Uu=16;Uu<256;++Uu)zu[Uu]=Uu.toString(16);return function(){return ju(Fu),Fu[6]=64|Fu[6]&15,Fu[8]=128|Fu[8]&63,zu[Fu[0]]+zu[Fu[1]]+zu[Fu[2]]+zu[Fu[3]]+"-"+zu[Fu[4]]+zu[Fu[5]]+"-"+zu[Fu[6]]+zu[Fu[7]]+"-"+zu[Fu[8]]+zu[Fu[9]]+"-"+zu[Fu[10]]+zu[Fu[11]]+zu[Fu[12]]+zu[Fu[13]]+zu[Fu[14]]+zu[Fu[15]]}}$u.UUID=void 0,(function(ju){ju.uuid4=Bu($u.Random.getRandomValues)})($u.UUID||($u.UUID={})),$u.MimeData=Iu,$u.PluginRegistry=Pu,$u.PromiseDelegate=Mu,$u.Token=Du}))})(dist$2,dist$2.exports)),dist$2.exports}var minimist,hasRequiredMinimist;function requireMinimist(){if(hasRequiredMinimist)return minimist;hasRequiredMinimist=1;function Au(Ru,Iu){var Pu=Ru;Iu.slice(0,-1).forEach(function(Mu){Pu=Pu[Mu]||{}});var Ou=Iu[Iu.length-1];return Ou in Pu}function lo(Ru){return typeof Ru=="number"||/^0x[0-9a-f]+$/i.test(Ru)?!0:/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(Ru)}function $u(Ru,Iu){return Iu==="constructor"&&typeof Ru[Iu]=="function"||Iu==="__proto__"}return minimist=function(Ru,Iu){Iu||(Iu={});var Pu={bools:{},strings:{},unknownFn:null};typeof Iu.unknown=="function"&&(Pu.unknownFn=Iu.unknown),typeof Iu.boolean=="boolean"&&Iu.boolean?Pu.allBools=!0:[].concat(Iu.boolean).filter(Boolean).forEach(function(ed){Pu.bools[ed]=!0});var Ou={};function Mu(ed){return Ou[ed].some(function(td){return Pu.bools[td]})}Object.keys(Iu.alias||{}).forEach(function(ed){Ou[ed]=[].concat(Iu.alias[ed]),Ou[ed].forEach(function(td){Ou[td]=[ed].concat(Ou[ed].filter(function(nd){return td!==nd}))})}),[].concat(Iu.string).filter(Boolean).forEach(function(ed){Pu.strings[ed]=!0,Ou[ed]&&[].concat(Ou[ed]).forEach(function(td){Pu.strings[td]=!0})});var Du=Iu.default||{},Lu={_:[]};function Bu(ed,td){return Pu.allBools&&/^--[^=]+$/.test(td)||Pu.strings[ed]||Pu.bools[ed]||Ou[ed]}function ju(ed,td,nd){for(var od=ed,sd=0;sd<td.length-1;sd++){var ad=td[sd];if($u(od,ad))return;od[ad]===void 0&&(od[ad]={}),(od[ad]===Object.prototype||od[ad]===Number.prototype||od[ad]===String.prototype)&&(od[ad]={}),od[ad]===Array.prototype&&(od[ad]=[]),od=od[ad]}var pd=td[td.length-1];$u(od,pd)||((od===Object.prototype||od===Number.prototype||od===String.prototype)&&(od={}),od===Array.prototype&&(od=[]),od[pd]===void 0||Pu.bools[pd]||typeof od[pd]=="boolean"?od[pd]=nd:Array.isArray(od[pd])?od[pd].push(nd):od[pd]=[od[pd],nd])}function Fu(ed,td,nd){if(!(nd&&Pu.unknownFn&&!Bu(ed,nd)&&Pu.unknownFn(nd)===!1)){var od=!Pu.strings[ed]&&lo(td)?Number(td):td;ju(Lu,ed.split("."),od),(Ou[ed]||[]).forEach(function(sd){ju(Lu,sd.split("."),od)})}}Object.keys(Pu.bools).forEach(function(ed){Fu(ed,Du[ed]===void 0?!1:Du[ed])});var zu=[];Ru.indexOf("--")!==-1&&(zu=Ru.slice(Ru.indexOf("--")+1),Ru=Ru.slice(0,Ru.indexOf("--")));for(var Uu=0;Uu<Ru.length;Uu++){var Hu=Ru[Uu],Vu,Gu;if(/^--.+=/.test(Hu)){var Wu=Hu.match(/^--([^=]+)=([\s\S]*)$/);Vu=Wu[1];var Ku=Wu[2];Pu.bools[Vu]&&(Ku=Ku!=="false"),Fu(Vu,Ku,Hu)}else if(/^--no-.+/.test(Hu))Vu=Hu.match(/^--no-(.+)/)[1],Fu(Vu,!1,Hu);else if(/^--.+/.test(Hu))Vu=Hu.match(/^--(.+)/)[1],Gu=Ru[Uu+1],Gu!==void 0&&!/^(-|--)[^-]/.test(Gu)&&!Pu.bools[Vu]&&!Pu.allBools&&(!Ou[Vu]||!Mu(Vu))?(Fu(Vu,Gu,Hu),Uu+=1):/^(true|false)$/.test(Gu)?(Fu(Vu,Gu==="true",Hu),Uu+=1):Fu(Vu,Pu.strings[Vu]?"":!0,Hu);else if(/^-[^-]+/.test(Hu)){for(var Ju=Hu.slice(1,-1).split(""),Yu=!1,Xu=0;Xu<Ju.length;Xu++){if(Gu=Hu.slice(Xu+2),Gu==="-"){Fu(Ju[Xu],Gu,Hu);continue}if(/[A-Za-z]/.test(Ju[Xu])&&Gu[0]==="="){Fu(Ju[Xu],Gu.slice(1),Hu),Yu=!0;break}if(/[A-Za-z]/.test(Ju[Xu])&&/-?\d+(\.\d*)?(e-?\d+)?$/.test(Gu)){Fu(Ju[Xu],Gu,Hu),Yu=!0;break}if(Ju[Xu+1]&&Ju[Xu+1].match(/\W/)){Fu(Ju[Xu],Hu.slice(Xu+2),Hu),Yu=!0;break}else Fu(Ju[Xu],Pu.strings[Ju[Xu]]?"":!0,Hu)}Vu=Hu.slice(-1)[0],!Yu&&Vu!=="-"&&(Ru[Uu+1]&&!/^(-|--)[^-]/.test(Ru[Uu+1])&&!Pu.bools[Vu]&&(!Ou[Vu]||!Mu(Vu))?(Fu(Vu,Ru[Uu+1],Hu),Uu+=1):Ru[Uu+1]&&/^(true|false)$/.test(Ru[Uu+1])?(Fu(Vu,Ru[Uu+1]==="true",Hu),Uu+=1):Fu(Vu,Pu.strings[Vu]?"":!0,Hu))}else if((!Pu.unknownFn||Pu.unknownFn(Hu)!==!1)&&Lu._.push(Pu.strings._||!lo(Hu)?Hu:Number(Hu)),Iu.stopEarly){Lu._.push.apply(Lu._,Ru.slice(Uu+1));break}}return Object.keys(Du).forEach(function(ed){Au(Lu,ed.split("."))||(ju(Lu,ed.split("."),Du[ed]),(Ou[ed]||[]).forEach(function(td){ju(Lu,td.split("."),Du[ed])}))}),Iu["--"]?Lu["--"]=zu.slice():zu.forEach(function(ed){Lu._.push(ed)}),Lu},minimist}var url={},pathBrowserify,hasRequiredPathBrowserify;function requirePathBrowserify(){if(hasRequiredPathBrowserify)return pathBrowserify;hasRequiredPathBrowserify=1;function Au(Iu){if(typeof Iu!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(Iu))}function lo(Iu,Pu){for(var Ou="",Mu=0,Du=-1,Lu=0,Bu,ju=0;ju<=Iu.length;++ju){if(ju<Iu.length)Bu=Iu.charCodeAt(ju);else{if(Bu===47)break;Bu=47}if(Bu===47){if(!(Du===ju-1||Lu===1))if(Du!==ju-1&&Lu===2){if(Ou.length<2||Mu!==2||Ou.charCodeAt(Ou.length-1)!==46||Ou.charCodeAt(Ou.length-2)!==46){if(Ou.length>2){var Fu=Ou.lastIndexOf("/");if(Fu!==Ou.length-1){Fu===-1?(Ou="",Mu=0):(Ou=Ou.slice(0,Fu),Mu=Ou.length-1-Ou.lastIndexOf("/")),Du=ju,Lu=0;continue}}else if(Ou.length===2||Ou.length===1){Ou="",Mu=0,Du=ju,Lu=0;continue}}Pu&&(Ou.length>0?Ou+="/..":Ou="..",Mu=2)}else Ou.length>0?Ou+="/"+Iu.slice(Du+1,ju):Ou=Iu.slice(Du+1,ju),Mu=ju-Du-1;Du=ju,Lu=0}else Bu===46&&Lu!==-1?++Lu:Lu=-1}return Ou}function $u(Iu,Pu){var Ou=Pu.dir||Pu.root,Mu=Pu.base||(Pu.name||"")+(Pu.ext||"");return Ou?Ou===Pu.root?Ou+Mu:Ou+Iu+Mu:Mu}var Ru={resolve:function(){for(var Pu="",Ou=!1,Mu,Du=arguments.length-1;Du>=-1&&!Ou;Du--){var Lu;Du>=0?Lu=arguments[Du]:(Mu===void 0&&(Mu=process.cwd()),Lu=Mu),Au(Lu),Lu.length!==0&&(Pu=Lu+"/"+Pu,Ou=Lu.charCodeAt(0)===47)}return Pu=lo(Pu,!Ou),Ou?Pu.length>0?"/"+Pu:"/":Pu.length>0?Pu:"."},normalize:function(Pu){if(Au(Pu),Pu.length===0)return".";var Ou=Pu.charCodeAt(0)===47,Mu=Pu.charCodeAt(Pu.length-1)===47;return Pu=lo(Pu,!Ou),Pu.length===0&&!Ou&&(Pu="."),Pu.length>0&&Mu&&(Pu+="/"),Ou?"/"+Pu:Pu},isAbsolute:function(Pu){return Au(Pu),Pu.length>0&&Pu.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var Pu,Ou=0;Ou<arguments.length;++Ou){var Mu=arguments[Ou];Au(Mu),Mu.length>0&&(Pu===void 0?Pu=Mu:Pu+="/"+Mu)}return Pu===void 0?".":Ru.normalize(Pu)},relative:function(Pu,Ou){if(Au(Pu),Au(Ou),Pu===Ou||(Pu=Ru.resolve(Pu),Ou=Ru.resolve(Ou),Pu===Ou))return"";for(var Mu=1;Mu<Pu.length&&Pu.charCodeAt(Mu)===47;++Mu);for(var Du=Pu.length,Lu=Du-Mu,Bu=1;Bu<Ou.length&&Ou.charCodeAt(Bu)===47;++Bu);for(var ju=Ou.length,Fu=ju-Bu,zu=Lu<Fu?Lu:Fu,Uu=-1,Hu=0;Hu<=zu;++Hu){if(Hu===zu){if(Fu>zu){if(Ou.charCodeAt(Bu+Hu)===47)return Ou.slice(Bu+Hu+1);if(Hu===0)return Ou.slice(Bu+Hu)}else Lu>zu&&(Pu.charCodeAt(Mu+Hu)===47?Uu=Hu:Hu===0&&(Uu=0));break}var Vu=Pu.charCodeAt(Mu+Hu),Gu=Ou.charCodeAt(Bu+Hu);if(Vu!==Gu)break;Vu===47&&(Uu=Hu)}var Wu="";for(Hu=Mu+Uu+1;Hu<=Du;++Hu)(Hu===Du||Pu.charCodeAt(Hu)===47)&&(Wu.length===0?Wu+="..":Wu+="/..");return Wu.length>0?Wu+Ou.slice(Bu+Uu):(Bu+=Uu,Ou.charCodeAt(Bu)===47&&++Bu,Ou.slice(Bu))},_makeLong:function(Pu){return Pu},dirname:function(Pu){if(Au(Pu),Pu.length===0)return".";for(var Ou=Pu.charCodeAt(0),Mu=Ou===47,Du=-1,Lu=!0,Bu=Pu.length-1;Bu>=1;--Bu)if(Ou=Pu.charCodeAt(Bu),Ou===47){if(!Lu){Du=Bu;break}}else Lu=!1;return Du===-1?Mu?"/":".":Mu&&Du===1?"//":Pu.slice(0,Du)},basename:function(Pu,Ou){if(Ou!==void 0&&typeof Ou!="string")throw new TypeError('"ext" argument must be a string');Au(Pu);var Mu=0,Du=-1,Lu=!0,Bu;if(Ou!==void 0&&Ou.length>0&&Ou.length<=Pu.length){if(Ou.length===Pu.length&&Ou===Pu)return"";var ju=Ou.length-1,Fu=-1;for(Bu=Pu.length-1;Bu>=0;--Bu){var zu=Pu.charCodeAt(Bu);if(zu===47){if(!Lu){Mu=Bu+1;break}}else Fu===-1&&(Lu=!1,Fu=Bu+1),ju>=0&&(zu===Ou.charCodeAt(ju)?--ju===-1&&(Du=Bu):(ju=-1,Du=Fu))}return Mu===Du?Du=Fu:Du===-1&&(Du=Pu.length),Pu.slice(Mu,Du)}else{for(Bu=Pu.length-1;Bu>=0;--Bu)if(Pu.charCodeAt(Bu)===47){if(!Lu){Mu=Bu+1;break}}else Du===-1&&(Lu=!1,Du=Bu+1);return Du===-1?"":Pu.slice(Mu,Du)}},extname:function(Pu){Au(Pu);for(var Ou=-1,Mu=0,Du=-1,Lu=!0,Bu=0,ju=Pu.length-1;ju>=0;--ju){var Fu=Pu.charCodeAt(ju);if(Fu===47){if(!Lu){Mu=ju+1;break}continue}Du===-1&&(Lu=!1,Du=ju+1),Fu===46?Ou===-1?Ou=ju:Bu!==1&&(Bu=1):Ou!==-1&&(Bu=-1)}return Ou===-1||Du===-1||Bu===0||Bu===1&&Ou===Du-1&&Ou===Mu+1?"":Pu.slice(Ou,Du)},format:function(Pu){if(Pu===null||typeof Pu!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof Pu);return $u("/",Pu)},parse:function(Pu){Au(Pu);var Ou={root:"",dir:"",base:"",ext:"",name:""};if(Pu.length===0)return Ou;var Mu=Pu.charCodeAt(0),Du=Mu===47,Lu;Du?(Ou.root="/",Lu=1):Lu=0;for(var Bu=-1,ju=0,Fu=-1,zu=!0,Uu=Pu.length-1,Hu=0;Uu>=Lu;--Uu){if(Mu=Pu.charCodeAt(Uu),Mu===47){if(!zu){ju=Uu+1;break}continue}Fu===-1&&(zu=!1,Fu=Uu+1),Mu===46?Bu===-1?Bu=Uu:Hu!==1&&(Hu=1):Bu!==-1&&(Hu=-1)}return Bu===-1||Fu===-1||Hu===0||Hu===1&&Bu===Fu-1&&Bu===ju+1?Fu!==-1&&(ju===0&&Du?Ou.base=Ou.name=Pu.slice(1,Fu):Ou.base=Ou.name=Pu.slice(ju,Fu)):(ju===0&&Du?(Ou.name=Pu.slice(1,Bu),Ou.base=Pu.slice(1,Fu)):(Ou.name=Pu.slice(ju,Bu),Ou.base=Pu.slice(ju,Fu)),Ou.ext=Pu.slice(Bu,Fu)),ju>0?Ou.dir=Pu.slice(0,ju-1):Du&&(Ou.dir="/"),Ou},sep:"/",delimiter:":",win32:null,posix:null};return Ru.posix=Ru,pathBrowserify=Ru,pathBrowserify}var requiresPort,hasRequiredRequiresPort;function requireRequiresPort(){return hasRequiredRequiresPort||(hasRequiredRequiresPort=1,requiresPort=function(lo,$u){if($u=$u.split(":")[0],lo=+lo,!lo)return!1;switch($u){case"http":case"ws":return lo!==80;case"https":case"wss":return lo!==443;case"ftp":return lo!==21;case"gopher":return lo!==70;case"file":return!1}return lo!==0}),requiresPort}var querystringify={},hasRequiredQuerystringify;function requireQuerystringify(){if(hasRequiredQuerystringify)return querystringify;hasRequiredQuerystringify=1;var Au=Object.prototype.hasOwnProperty,lo;function $u(Ou){try{return decodeURIComponent(Ou.replace(/\+/g," "))}catch{return null}}function Ru(Ou){try{return encodeURIComponent(Ou)}catch{return null}}function Iu(Ou){for(var Mu=/([^=?#&]+)=?([^&]*)/g,Du={},Lu;Lu=Mu.exec(Ou);){var Bu=$u(Lu[1]),ju=$u(Lu[2]);Bu===null||ju===null||Bu in Du||(Du[Bu]=ju)}return Du}function Pu(Ou,Mu){Mu=Mu||"";var Du=[],Lu,Bu;typeof Mu!="string"&&(Mu="?");for(Bu in Ou)if(Au.call(Ou,Bu)){if(Lu=Ou[Bu],!Lu&&(Lu===null||Lu===lo||isNaN(Lu))&&(Lu=""),Bu=Ru(Bu),Lu=Ru(Lu),Bu===null||Lu===null)continue;Du.push(Bu+"="+Lu)}return Du.length?Mu+Du.join("&"):""}return querystringify.stringify=Pu,querystringify.parse=Iu,querystringify}var urlParse$1,hasRequiredUrlParse;function requireUrlParse(){if(hasRequiredUrlParse)return urlParse$1;hasRequiredUrlParse=1;var Au=requireRequiresPort(),lo=requireQuerystringify(),$u=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/,Ru=/[\n\r\t]/g,Iu=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,Pu=/:\d+$/,Ou=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,Mu=/^[a-zA-Z]:/;function Du(Wu){return(Wu||"").toString().replace($u,"")}var Lu=[["#","hash"],["?","query"],function(Ku,Ju){return Fu(Ju.protocol)?Ku.replace(/\\/g,"/"):Ku},["/","pathname"],["@","auth",1],[NaN,"host",void 0,1,1],[/:(\d*)$/,"port",void 0,1],[NaN,"hostname",void 0,1,1]],Bu={hash:1,query:1};function ju(Wu){var Ku;typeof window<"u"?Ku=window:typeof globalThis<"u"?Ku=globalThis:typeof self<"u"?Ku=self:Ku={};var Ju=Ku.location||{};Wu=Wu||Ju;var Yu={},Xu=typeof Wu,ed;if(Wu.protocol==="blob:")Yu=new Hu(unescape(Wu.pathname),{});else if(Xu==="string"){Yu=new Hu(Wu,{});for(ed in Bu)delete Yu[ed]}else if(Xu==="object"){for(ed in Wu)ed in Bu||(Yu[ed]=Wu[ed]);Yu.slashes===void 0&&(Yu.slashes=Iu.test(Wu.href))}return Yu}function Fu(Wu){return Wu==="file:"||Wu==="ftp:"||Wu==="http:"||Wu==="https:"||Wu==="ws:"||Wu==="wss:"}function zu(Wu,Ku){Wu=Du(Wu),Wu=Wu.replace(Ru,""),Ku=Ku||{};var Ju=Ou.exec(Wu),Yu=Ju[1]?Ju[1].toLowerCase():"",Xu=!!Ju[2],ed=!!Ju[3],td=0,nd;return Xu?ed?(nd=Ju[2]+Ju[3]+Ju[4],td=Ju[2].length+Ju[3].length):(nd=Ju[2]+Ju[4],td=Ju[2].length):ed?(nd=Ju[3]+Ju[4],td=Ju[3].length):nd=Ju[4],Yu==="file:"?td>=2&&(nd=nd.slice(2)):Fu(Yu)?nd=Ju[4]:Yu?Xu&&(nd=nd.slice(2)):td>=2&&Fu(Ku.protocol)&&(nd=Ju[4]),{protocol:Yu,slashes:Xu||Fu(Yu),slashesCount:td,rest:nd}}function Uu(Wu,Ku){if(Wu==="")return Ku;for(var Ju=(Ku||"/").split("/").slice(0,-1).concat(Wu.split("/")),Yu=Ju.length,Xu=Ju[Yu-1],ed=!1,td=0;Yu--;)Ju[Yu]==="."?Ju.splice(Yu,1):Ju[Yu]===".."?(Ju.splice(Yu,1),td++):td&&(Yu===0&&(ed=!0),Ju.splice(Yu,1),td--);return ed&&Ju.unshift(""),(Xu==="."||Xu==="..")&&Ju.push(""),Ju.join("/")}function Hu(Wu,Ku,Ju){if(Wu=Du(Wu),Wu=Wu.replace(Ru,""),!(this instanceof Hu))return new Hu(Wu,Ku,Ju);var Yu,Xu,ed,td,nd,od,sd=Lu.slice(),ad=typeof Ku,pd=this,gd=0;for(ad!=="object"&&ad!=="string"&&(Ju=Ku,Ku=null),Ju&&typeof Ju!="function"&&(Ju=lo.parse),Ku=ju(Ku),Xu=zu(Wu||"",Ku),Yu=!Xu.protocol&&!Xu.slashes,pd.slashes=Xu.slashes||Yu&&Ku.slashes,pd.protocol=Xu.protocol||Ku.protocol||"",Wu=Xu.rest,(Xu.protocol==="file:"&&(Xu.slashesCount!==2||Mu.test(Wu))||!Xu.slashes&&(Xu.protocol||Xu.slashesCount<2||!Fu(pd.protocol)))&&(sd[3]=[/(.*)/,"pathname"]);gd<sd.length;gd++){if(td=sd[gd],typeof td=="function"){Wu=td(Wu,pd);continue}ed=td[0],od=td[1],ed!==ed?pd[od]=Wu:typeof ed=="string"?(nd=ed==="@"?Wu.lastIndexOf(ed):Wu.indexOf(ed),~nd&&(typeof td[2]=="number"?(pd[od]=Wu.slice(0,nd),Wu=Wu.slice(nd+td[2])):(pd[od]=Wu.slice(nd),Wu=Wu.slice(0,nd)))):(nd=ed.exec(Wu))&&(pd[od]=nd[1],Wu=Wu.slice(0,nd.index)),pd[od]=pd[od]||Yu&&td[3]&&Ku[od]||"",td[4]&&(pd[od]=pd[od].toLowerCase())}Ju&&(pd.query=Ju(pd.query)),Yu&&Ku.slashes&&pd.pathname.charAt(0)!=="/"&&(pd.pathname!==""||Ku.pathname!=="")&&(pd.pathname=Uu(pd.pathname,Ku.pathname)),pd.pathname.charAt(0)!=="/"&&Fu(pd.protocol)&&(pd.pathname="/"+pd.pathname),Au(pd.port,pd.protocol)||(pd.host=pd.hostname,pd.port=""),pd.username=pd.password="",pd.auth&&(nd=pd.auth.indexOf(":"),~nd?(pd.username=pd.auth.slice(0,nd),pd.username=encodeURIComponent(decodeURIComponent(pd.username)),pd.password=pd.auth.slice(nd+1),pd.password=encodeURIComponent(decodeURIComponent(pd.password))):pd.username=encodeURIComponent(decodeURIComponent(pd.auth)),pd.auth=pd.password?pd.username+":"+pd.password:pd.username),pd.origin=pd.protocol!=="file:"&&Fu(pd.protocol)&&pd.host?pd.protocol+"//"+pd.host:"null",pd.href=pd.toString()}function Vu(Wu,Ku,Ju){var Yu=this;switch(Wu){case"query":typeof Ku=="string"&&Ku.length&&(Ku=(Ju||lo.parse)(Ku)),Yu[Wu]=Ku;break;case"port":Yu[Wu]=Ku,Au(Ku,Yu.protocol)?Ku&&(Yu.host=Yu.hostname+":"+Ku):(Yu.host=Yu.hostname,Yu[Wu]="");break;case"hostname":Yu[Wu]=Ku,Yu.port&&(Ku+=":"+Yu.port),Yu.host=Ku;break;case"host":Yu[Wu]=Ku,Pu.test(Ku)?(Ku=Ku.split(":"),Yu.port=Ku.pop(),Yu.hostname=Ku.join(":")):(Yu.hostname=Ku,Yu.port="");break;case"protocol":Yu.protocol=Ku.toLowerCase(),Yu.slashes=!Ju;break;case"pathname":case"hash":if(Ku){var Xu=Wu==="pathname"?"/":"#";Yu[Wu]=Ku.charAt(0)!==Xu?Xu+Ku:Ku}else Yu[Wu]=Ku;break;case"username":case"password":Yu[Wu]=encodeURIComponent(Ku);break;case"auth":var ed=Ku.indexOf(":");~ed?(Yu.username=Ku.slice(0,ed),Yu.username=encodeURIComponent(decodeURIComponent(Yu.username)),Yu.password=Ku.slice(ed+1),Yu.password=encodeURIComponent(decodeURIComponent(Yu.password))):Yu.username=encodeURIComponent(decodeURIComponent(Ku))}for(var td=0;td<Lu.length;td++){var nd=Lu[td];nd[4]&&(Yu[nd[1]]=Yu[nd[1]].toLowerCase())}return Yu.auth=Yu.password?Yu.username+":"+Yu.password:Yu.username,Yu.origin=Yu.protocol!=="file:"&&Fu(Yu.protocol)&&Yu.host?Yu.protocol+"//"+Yu.host:"null",Yu.href=Yu.toString(),Yu}function Gu(Wu){(!Wu||typeof Wu!="function")&&(Wu=lo.stringify);var Ku,Ju=this,Yu=Ju.host,Xu=Ju.protocol;Xu&&Xu.charAt(Xu.length-1)!==":"&&(Xu+=":");var ed=Xu+(Ju.protocol&&Ju.slashes||Fu(Ju.protocol)?"//":"");return Ju.username?(ed+=Ju.username,Ju.password&&(ed+=":"+Ju.password),ed+="@"):Ju.password?(ed+=":"+Ju.password,ed+="@"):Ju.protocol!=="file:"&&Fu(Ju.protocol)&&!Yu&&Ju.pathname!=="/"&&(ed+="@"),(Yu[Yu.length-1]===":"||Pu.test(Ju.hostname)&&!Ju.port)&&(Yu+=":"),ed+=Yu+Ju.pathname,Ku=typeof Ju.query=="object"?Wu(Ju.query):Ju.query,Ku&&(ed+=Ku.charAt(0)!=="?"?"?"+Ku:Ku),Ju.hash&&(ed+=Ju.hash),ed}return Hu.prototype={set:Vu,toString:Gu},Hu.extractProtocol=zu,Hu.location=ju,Hu.trimLeft=Du,Hu.qs=lo,urlParse$1=Hu,urlParse$1}var hasRequiredUrl;function requireUrl(){if(hasRequiredUrl)return url;hasRequiredUrl=1;var Au=url&&url.__importDefault||function(Iu){return Iu&&Iu.__esModule?Iu:{default:Iu}};Object.defineProperty(url,"__esModule",{value:!0}),url.URLExt=void 0;const lo=requirePathBrowserify(),$u=Au(requireUrlParse());var Ru;return(function(Iu){function Pu(zu){if(typeof document<"u"&&document){const Uu=document.createElement("a");return Uu.href=zu,Uu}return(0,$u.default)(zu)}Iu.parse=Pu;function Ou(zu){return(0,$u.default)(zu).hostname}Iu.getHostName=Ou;function Mu(zu){return zu&&Pu(zu).toString()}Iu.normalize=Mu;function Du(...zu){let Uu=(0,$u.default)(zu[0],{});const Hu=Uu.protocol===""&&Uu.slashes;Hu&&(Uu=(0,$u.default)(zu[0],"https:"+zu[0]));const Vu=`${Hu?"":Uu.protocol}${Uu.slashes?"//":""}${Uu.auth}${Uu.auth?"@":""}${Uu.host}`,Gu=lo.posix.join(`${Vu&&Uu.pathname[0]!=="/"?"/":""}${Uu.pathname}`,...zu.slice(1));return`${Vu}${Gu==="."?"":Gu}`}Iu.join=Du;function Lu(zu){return Du(...zu.split("/").map(encodeURIComponent))}Iu.encodeParts=Lu;function Bu(zu){const Uu=Object.keys(zu).filter(Hu=>Hu.length>0);return Uu.length?"?"+Uu.map(Hu=>{const Vu=encodeURIComponent(String(zu[Hu]));return Hu+(Vu?"="+Vu:"")}).join("&"):""}Iu.objectToQueryString=Bu;function ju(zu){return zu.replace(/^\?/,"").split("&").reduce((Uu,Hu)=>{const[Vu,Gu]=Hu.split("=");return Vu.length>0&&(Uu[Vu]=decodeURIComponent(Gu||"")),Uu},{})}Iu.queryStringToObject=ju;function Fu(zu,Uu=!1){const{protocol:Hu}=Pu(zu);return(!Hu||zu.toLowerCase().indexOf(Hu)!==0)&&(Uu?zu.indexOf("//")!==0:zu.indexOf("/")!==0)}Iu.isLocal=Fu})(Ru||(url.URLExt=Ru={})),url}var hasRequiredPageconfig;function requirePageconfig(){if(hasRequiredPageconfig)return pageconfig;hasRequiredPageconfig=1;var define_process_env_default={},__importDefault=pageconfig&&pageconfig.__importDefault||function(Au){return Au&&Au.__esModule?Au:{default:Au}};Object.defineProperty(pageconfig,"__esModule",{value:!0}),pageconfig.PageConfig=void 0,pageconfig.compareVersions=compareVersions;const coreutils_1=requireDist(),minimist_1=__importDefault(requireMinimist()),url_1=requireUrl();var PageConfig;(function(PageConfig){function getOption(name){if(configData)return configData[name]||getBodyData(name);configData=Object.create(null);let found=!1;if(typeof document<"u"&&document){const Au=document.getElementById("jupyter-config-data");Au&&(configData=JSON.parse(Au.textContent||""),found=!0)}if(!found&&typeof process<"u"&&process.argv)try{const cli=(0,minimist_1.default)(process.argv.slice(2)),path=requirePathBrowserify();let fullPath="";"jupyter-config-data"in cli?fullPath=path.resolve(cli["jupyter-config-data"]):"JUPYTER_CONFIG_DATA"in define_process_env_default&&(fullPath=path.resolve(define_process_env_default.JUPYTER_CONFIG_DATA)),fullPath&&(configData=eval("require")(fullPath))}catch(Au){console.error(Au)}if(!coreutils_1.JSONExt.isObject(configData))configData=Object.create(null);else for(const Au in configData)typeof configData[Au]!="string"&&(configData[Au]=JSON.stringify(configData[Au]));return configData[name]||getBodyData(name)}PageConfig.getOption=getOption;function setOption(Au,lo){const $u=getOption(Au);return configData[Au]=lo,$u}PageConfig.setOption=setOption;function getBaseUrl(){return url_1.URLExt.normalize(getOption("baseUrl")||"/")}PageConfig.getBaseUrl=getBaseUrl;function getTreeUrl(){return url_1.URLExt.join(getBaseUrl(),getOption("treeUrl"))}PageConfig.getTreeUrl=getTreeUrl;function getShareUrl(){return url_1.URLExt.normalize(getOption("shareUrl")||getBaseUrl())}PageConfig.getShareUrl=getShareUrl;function getTreeShareUrl(){return url_1.URLExt.normalize(url_1.URLExt.join(getShareUrl(),getOption("treeUrl")))}PageConfig.getTreeShareUrl=getTreeShareUrl;function getUrl(Au){var lo,$u,Ru;let Iu=Au.toShare?getShareUrl():getBaseUrl();const Pu=(lo=Au.mode)!==null&&lo!==void 0?lo:getOption("mode"),Ou=($u=Au.workspace)!==null&&$u!==void 0?$u:getOption("workspace"),Mu=Pu==="single-document"?"doc":"lab";Iu=url_1.URLExt.join(Iu,Mu),Ou!==PageConfig.defaultWorkspace&&(Iu=url_1.URLExt.join(Iu,"workspaces",encodeURIComponent(Ou)));const Du=(Ru=Au.treePath)!==null&&Ru!==void 0?Ru:getOption("treePath");return Du&&(Iu=url_1.URLExt.join(Iu,"tree",url_1.URLExt.encodeParts(Du))),Iu}PageConfig.getUrl=getUrl,PageConfig.defaultWorkspace="default";function getWsUrl(Au){let lo=getOption("wsUrl");if(!lo){if(Au=Au?url_1.URLExt.normalize(Au):getBaseUrl(),Au.indexOf("http")!==0)return"";lo="ws"+Au.slice(4)}return url_1.URLExt.normalize(lo)}PageConfig.getWsUrl=getWsUrl;function getNBConvertURL({path:Au,format:lo,download:$u}){const Ru=url_1.URLExt.encodeParts(Au),Iu=url_1.URLExt.join(getBaseUrl(),"nbconvert",lo,Ru);return $u?Iu+"?download=true":Iu}PageConfig.getNBConvertURL=getNBConvertURL;function getToken(){return getOption("token")||getBodyData("jupyterApiToken")}PageConfig.getToken=getToken;function getNotebookVersion(){const Au=getOption("notebookVersion");return Au===""?[0,0,0]:JSON.parse(Au)}PageConfig.getNotebookVersion=getNotebookVersion;let configData=null;function getBodyData(Au){if(typeof document>"u"||!document.body)return"";const lo=document.body.dataset[Au];return typeof lo>"u"?"":decodeURIComponent(lo)}(function(Au){function lo(Iu){try{const Pu=getOption(Iu);if(Pu)return JSON.parse(Pu)}catch(Pu){console.warn(`Unable to parse ${Iu}.`,Pu)}return[]}Au.deferred=lo("deferredExtensions"),Au.disabled=lo("disabledExtensions");function $u(Iu){const Pu=Iu.indexOf(":");let Ou="";return Pu!==-1&&(Ou=Iu.slice(0,Pu)),Au.deferred.some(Mu=>Mu===Iu||Ou&&Mu===Ou)}Au.isDeferred=$u;function Ru(Iu){const Pu=Iu.indexOf(":");let Ou="";return Pu!==-1&&(Ou=Iu.slice(0,Pu)),Au.disabled.some(Mu=>Mu===Iu||Ou&&Mu===Ou)}Au.isDisabled=Ru})(PageConfig.Extension||(PageConfig.Extension={}))})(PageConfig||(pageconfig.PageConfig=PageConfig={}));function compareVersions(Au,lo){for(let $u=0;$u<3;$u++)if(Au[$u]!==lo[$u])return Au[$u]-lo[$u];return 0}return pageconfig}var path$2={},hasRequiredPath;function requirePath(){if(hasRequiredPath)return path$2;hasRequiredPath=1,Object.defineProperty(path$2,"__esModule",{value:!0}),path$2.PathExt=void 0;const Au=requirePathBrowserify();var lo;return(function($u){function Ru(...zu){const Uu=Au.posix.join(...zu);return Uu==="."?"":Fu(Uu)}$u.join=Ru;function Iu(...zu){const Uu=Au.posix.join(...zu);return Uu==="."?"":Uu}$u.joinWithLeadingSlash=Iu;function Pu(zu,Uu){return Au.posix.basename(zu,Uu)}$u.basename=Pu;function Ou(zu){const Uu=Fu(Au.posix.dirname(zu));return Uu==="."?"":Uu}$u.dirname=Ou;function Mu(zu){return Au.posix.extname(zu)}$u.extname=Mu;function Du(zu){return zu===""?"":Fu(Au.posix.normalize(zu))}$u.normalize=Du;function Lu(...zu){return Fu(Au.posix.resolve(...zu))}$u.resolve=Lu;function Bu(zu,Uu){return Fu(Au.posix.relative(zu,Uu))}$u.relative=Bu;function ju(zu){return zu.length>0&&zu.indexOf(".")!==0&&(zu=`.${zu}`),zu}$u.normalizeExtension=ju;function Fu(zu){return zu.indexOf("/")===0&&(zu=zu.slice(1)),zu}$u.removeSlash=Fu})(lo||(path$2.PathExt=lo={})),path$2}var signal$1={},hasRequiredSignal;function requireSignal(){if(hasRequiredSignal)return signal$1;hasRequiredSignal=1,Object.defineProperty(signal$1,"__esModule",{value:!0}),signal$1.signalToPromise=lo;const Au=requireDist();function lo($u,Ru){const Iu=new Au.PromiseDelegate;function Pu(){$u.disconnect(Ou)}function Ou(Mu,Du){Pu(),Iu.resolve([Mu,Du])}return $u.connect(Ou),(Ru??0)>0&&setTimeout(()=>{Pu(),Iu.reject(`Signal not emitted within ${Ru} ms.`)},Ru),Iu.promise}return signal$1}var text$j={},hasRequiredText;function requireText(){if(hasRequiredText)return text$j;hasRequiredText=1,Object.defineProperty(text$j,"__esModule",{value:!0}),text$j.Text=void 0;var Au;return(function(lo){function Ru(Mu,Du){let Lu=Mu;for(let Bu=0;Bu+1<Du.length&&Bu<Mu;Bu++){const ju=Du.charCodeAt(Bu);if(ju>=55296&&ju<=56319){const Fu=Du.charCodeAt(Bu+1);Fu>=56320&&Fu<=57343&&(Lu--,Bu++)}}return Lu}lo.jsIndexToCharIndex=Ru;function Iu(Mu,Du){let Lu=Mu;for(let Bu=0;Bu+1<Du.length&&Bu<Lu;Bu++){const ju=Du.charCodeAt(Bu);if(ju>=55296&&ju<=56319){const Fu=Du.charCodeAt(Bu+1);Fu>=56320&&Fu<=57343&&(Lu++,Bu++)}}return Lu}lo.charIndexToJsIndex=Iu;function Pu(Mu,Du=!1){return Mu.replace(/^(\w)|[\s-_:]+(\w)/g,function(Lu,Bu,ju){return ju?ju.toUpperCase():Du?Bu.toUpperCase():Bu.toLowerCase()})}lo.camelCase=Pu;function Ou(Mu){return(Mu||"").toLowerCase().split(" ").map(Du=>Du.charAt(0).toUpperCase()+Du.slice(1)).join(" ")}lo.titleCase=Ou})(Au||(text$j.Text=Au={})),text$j}var time$2={},hasRequiredTime;function requireTime(){if(hasRequiredTime)return time$2;hasRequiredTime=1,Object.defineProperty(time$2,"__esModule",{value:!0}),time$2.Time=void 0;const Au=[{name:"years",milliseconds:365*24*60*60*1e3},{name:"months",milliseconds:720*60*60*1e3},{name:"days",milliseconds:1440*60*1e3},{name:"hours",milliseconds:3600*1e3},{name:"minutes",milliseconds:60*1e3},{name:"seconds",milliseconds:1e3}];var lo;return(function($u){function Ru(Pu,Ou="long"){const Mu=document.documentElement.lang||"en",Du=new Intl.RelativeTimeFormat(Mu,{numeric:"auto",style:Ou}),Lu=new Date(Pu).getTime()-Date.now();for(let Bu of Au){const ju=Math.ceil(Lu/Bu.milliseconds);if(ju!==0)return Du.format(ju,Bu.name)}return Du.format(0,"seconds")}$u.formatHuman=Ru;function Iu(Pu){const Ou=document.documentElement.lang||"en";return new Intl.DateTimeFormat(Ou,{dateStyle:"short",timeStyle:"short"}).format(new Date(Pu))}$u.format=Iu})(lo||(time$2.Time=lo={})),time$2}var pluginregistry={},hasRequiredPluginregistry;function requirePluginregistry(){if(hasRequiredPluginregistry)return pluginregistry;hasRequiredPluginregistry=1,Object.defineProperty(pluginregistry,"__esModule",{value:!0}),pluginregistry.JupyterPluginRegistry=void 0;const Au=requireDist(),lo=5e3;class $u extends Au.PluginRegistry{constructor(Iu){var Pu;super(Iu),this._pluginData=new Map,this._expectedActivationTime=(Pu=Iu?.expectedActivationTime)!==null&&Pu!==void 0?Pu:lo}registerPlugin(Iu){return this._pluginData.set(Iu.id,Iu),super.registerPlugin(Iu)}async activatePlugin(Iu){const Pu=performance.now();let Ou=setTimeout(()=>{console.warn(`Plugin ${Iu} is taking too long to activate.`)},this._expectedActivationTime);try{const Mu=await super.activatePlugin(Iu);clearTimeout(Ou);const Lu=performance.now()-Pu;if(Lu>=this._expectedActivationTime){const Bu=this._getDependentCount(Iu);console.warn(`Plugin ${Iu} (with ${Bu} dependants) took ${Lu.toFixed(2)}ms to activate.`)}return Mu}catch(Mu){throw clearTimeout(Ou),console.error(`Error activating plugin: ${Iu}`,Mu),Mu}}_getDependentCount(Iu){var Pu;const Ou=this._pluginData.get(Iu);if(!Ou?.provides)return 0;const Mu=Ou.provides.name;let Du=0;for(const[Lu,Bu]of this._pluginData.entries()){if(Lu===Iu)continue;!((Pu=Bu.requires)===null||Pu===void 0)&&Pu.filter(Fu=>!!Fu).some(Fu=>Fu.name===Mu)&&Du++}return Du}}return pluginregistry.JupyterPluginRegistry=$u,pluginregistry}var hasRequiredLib$b;function requireLib$b(){return hasRequiredLib$b||(hasRequiredLib$b=1,(function(Au){var lo=lib$d&&lib$d.__createBinding||(Object.create?(function(Ru,Iu,Pu,Ou){Ou===void 0&&(Ou=Pu);var Mu=Object.getOwnPropertyDescriptor(Iu,Pu);(!Mu||("get"in Mu?!Iu.__esModule:Mu.writable||Mu.configurable))&&(Mu={enumerable:!0,get:function(){return Iu[Pu]}}),Object.defineProperty(Ru,Ou,Mu)}):(function(Ru,Iu,Pu,Ou){Ou===void 0&&(Ou=Pu),Ru[Ou]=Iu[Pu]})),$u=lib$d&&lib$d.__exportStar||function(Ru,Iu){for(var Pu in Ru)Pu!=="default"&&!Object.prototype.hasOwnProperty.call(Iu,Pu)&&lo(Iu,Ru,Pu)};Object.defineProperty(Au,"__esModule",{value:!0}),$u(requireActivitymonitor(),Au),$u(requireInterfaces$1(),Au),$u(requireLru(),Au),$u(requireMarkdowncodeblocks(),Au),$u(requirePageconfig(),Au),$u(requirePath(),Au),$u(requireSignal(),Au),$u(requireText(),Au),$u(requireTime(),Au),$u(requireUrl(),Au),$u(requirePluginregistry(),Au)})(lib$d)),lib$d}var libExports$5=requireLib$b();let _insideJupyterLab=null;function isInsideJupyterLab(){return _insideJupyterLab===null&&(_insideJupyterLab=libExports$5.PageConfig.getOption("appName")==="JupyterLab"),_insideJupyterLab}const sleep$1=async Au=>new Promise(lo=>setTimeout(lo,Au)),strip=(Au,lo=50)=>Au?Au.length>lo?Au.substring(0,lo)+"…":Au:"",availableCredits=(Au,lo=[])=>{const $u=Au.quota,Ru=typeof $u=="number"?$u-Au.credits:Au.credits;if(!Number.isFinite(Ru))return 0;const Iu=lo.reduce((Pu,Ou)=>Pu+(Number.isFinite(Ou.credits)?Ou.credits:0),0);return Math.max(0,Ru-Iu)};function linkedAccountOf(Au){if(typeof Au!="string"||Au.trim()==="")return{};try{const lo=JSON.parse(Au);return lo&&typeof lo=="object"&&!Array.isArray(lo)?lo:{}}catch{return{}}}function asIAMProviderLinked(Au){return{iamProviderName:String(Au.iam_provider_name_s??"").trim().toLowerCase(),linkedAccount:linkedAccountOf(Au.linked_account_s),linkedAccountUrl:Au.linked_account_url_s??"",linkedAccountId:Au.linked_account_id_s??""}}class IAMProvidersSpecs{constructor(){}static getProvider(lo){switch(lo){case"github":return this.GitHub;case"google":return this.Google;case"okta":return this.Okta;default:return this.GitHub}}static GitHub={name:"github",oauth2CallbackServerRoute:"jupyter_iam/oauth2/callback",oauth2CallbackUIRoute:"/iam/oauth2/github/callback",accessTokenCookieName:lo=>`__datalayer__github_access_token_${lo.id}`,refreshTokenCookieName:"__datalayer__github_refresh_token",userInfoURL:"https://api.github.com/user",tokenRefreshURL:"https://github.com/login/oauth/access_token",postShareURL:"",registerUploadURL:""};static Google={name:"google",oauth2CallbackServerRoute:"jupyter_iam/oauth2/callback",oauth2CallbackUIRoute:"/iam/oauth2/google/callback",accessTokenCookieName:lo=>`__datalayer__google_access_token_${lo.id}`,refreshTokenCookieName:"__datalayer__google_refresh_token",userInfoURL:"https://openidconnect.googleapis.com/v1/userinfo",tokenRefreshURL:"https://oauth2.googleapis.com/token",postShareURL:"",registerUploadURL:""};static LinkedIn={name:"linkedin",oauth2CallbackServerRoute:"jupyter_iam/oauth2/callback",oauth2CallbackUIRoute:"/iam/oauth2/linkedin/callback"};static Okta={name:"okta",oauth2CallbackServerRoute:"jupyter_iam/oauth2/callback",oauth2CallbackUIRoute:"/iam/oauth2/linkedin/callback",accessTokenCookieName:lo=>`__datalayer__okta_access_token_${lo.id}`,refreshTokenCookieName:"__datalayer__okta_refresh_token",userInfoURL:"https://trial-4368308.okta.com/oauth2/default/v1/userinfo",tokenRefreshURL:"",postShareURL:"",registerUploadURL:""}}const BOOTSTRAP_USER_ONBOARDING={clients:{Platform:0,JupyterLab:0,CLI:0,VSCode:0},position:"top",tours:{"welcome-runtime":{status:"ready"}}},userOnboardingOf=Au=>{const lo=Array.isArray(Au)?Au[0]:Au,$u={clients:{...BOOTSTRAP_USER_ONBOARDING.clients},position:BOOTSTRAP_USER_ONBOARDING.position,tours:{...BOOTSTRAP_USER_ONBOARDING.tours}};if(!lo||typeof lo!="object")return $u;typeof lo.position_s=="string"&&($u.position=lo.position_s);for(const[Ru,Iu]of Object.entries(lo)){const Pu=/^client_(.+)_i$/.exec(Ru)?.[1];Pu&&typeof Iu=="number"&&($u.clients[Pu]=Iu);const Ou=/^tour_(.+)_status_s$/.exec(Ru)?.[1];Ou&&typeof Iu=="string"&&($u.tours[Ou]={status:Iu})}return $u},AI_AGENTS_URL_KEY="aiAgents_url_s",CAN_INVITE_URL_KEY="can_invite_b",DOCS_IN_PLACE_KEY="docs_in_place_b",SHOW_ADVANCED_KEY="show_advanced_b";class UserSettings{_aiAgentsUrl;_canInvite;_docsInPlace;_showAdvanced;constructor(lo){this._aiAgentsUrl=lo[AI_AGENTS_URL_KEY]??void 0,this._canInvite=lo[CAN_INVITE_URL_KEY]??void 0,this._docsInPlace=lo[DOCS_IN_PLACE_KEY]??void 0,this._showAdvanced=lo[SHOW_ADVANCED_KEY]??void 0}get aiAgentsUrl(){return this._aiAgentsUrl}set aiAgentsUrl(lo){this._aiAgentsUrl=lo}get canInvite(){return this._canInvite}set canInvite(lo){this._canInvite=lo}get docsInPlace(){return this._docsInPlace}set docsInPlace(lo){this._docsInPlace=lo}get showAdvanced(){return this._showAdvanced}set showAdvanced(lo){this._showAdvanced=lo}}const asUserEvent=Au=>({id:Au.uid,message:Au.message_t??"",subType:Au.sub_type_s,detailsJson:Au.details_json_t??"",token:Au.token_s,eventDate:Au.event_ts_dt}),ANONYMOUS_USER=void 0,ANONYMOUS_USER_TOKEN=void 0;class User{id;uid;handle;email;firstName;lastName;initials;displayName;friendlyName;joinDate;roles;credits;creditsCustomerId;avatarUrl;avatarIcon;banner;showOrbits;origin;invites;iamProviders;settings;unsubscribedFromOutbounds;mfaUrl;onboarding;linkedContactId;events;subscription;constructor(lo){this.id=lo.uid||lo.id,this.uid=lo.uid||lo.id,this.handle=lo.handle_s,this.email=lo.email_s,this.firstName=lo.first_name_t,this.lastName=lo.last_name_t,this.initials=namesAsInitials(lo.first_name_t,lo.last_name_t);const $u=asDisplayName(lo.first_name_t,lo.last_name_t);this.displayName=$u===""?lo.handle_s:$u,this.friendlyName=toFriendlyName(lo.first_name_t,lo.last_name_t)||lo.handle_s,this.avatarUrl=lo.avatar_url_s,this.avatarIcon=lo.avatar_icon_s??lo.avatarIcon,this.banner=lo.banner_s??lo.banner,this.showOrbits=!!(lo.show_orbits_b??lo.showOrbits??!1),this.origin=lo.origin_s,this.joinDate=lo.join_ts_dt?new Date(lo.join_ts_dt):void 0,this.credits=lo.credits_i?Number(lo.credits_i):0,this.creditsCustomerId=lo.stripe_customer_id_s,this.roles=lo.roles_ss??[];const Ru=lo.iam_providers??[];this.iamProviders=(Array.isArray(Ru)?Ru:[Ru]).map(asIAMProviderLinked),this.settings=new UserSettings(lo.settings??{}),this.unsubscribedFromOutbounds=lo.unsubscribed_from_outbounds_b??!1,this.mfaUrl=lo.mfa_url_s,this.onboarding=userOnboardingOf(lo.onboarding),this.linkedContactId=lo.linked_contact_uid,this.subscription=lo.subscription;let Iu=lo.events??[];Array.isArray(Iu)||(Iu=[Iu]),this.events=Iu.map(Pu=>asUserEvent(Pu)),this.events.sort((Pu,Ou)=>Pu.eventDate<Ou.eventDate?1:-1)}setRoles(lo){this.roles=lo}}function asUser(Au){return new User(Au)}var lib$c={exports:{}},atob$4,hasRequiredAtob;function requireAtob(){if(hasRequiredAtob)return atob$4;hasRequiredAtob=1;var Au="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function lo(Ru){this.message=Ru}lo.prototype=new Error,lo.prototype.name="InvalidCharacterError";function $u(Ru){var Iu=String(Ru).replace(/=+$/,"");if(Iu.length%4==1)throw new lo("'atob' failed: The string to be decoded is not correctly encoded.");for(var Pu=0,Ou,Mu,Du=0,Lu="";Mu=Iu.charAt(Du++);~Mu&&(Ou=Pu%4?Ou*64+Mu:Mu,Pu++%4)?Lu+=String.fromCharCode(255&Ou>>(-2*Pu&6)):0)Mu=Au.indexOf(Mu);return Lu}return atob$4=typeof window<"u"&&window.atob&&window.atob.bind(window)||$u,atob$4}var base64_url_decode,hasRequiredBase64_url_decode;function requireBase64_url_decode(){if(hasRequiredBase64_url_decode)return base64_url_decode;hasRequiredBase64_url_decode=1;var Au=requireAtob();function lo($u){return decodeURIComponent(Au($u).replace(/(.)/g,function(Ru,Iu){var Pu=Iu.charCodeAt(0).toString(16).toUpperCase();return Pu.length<2&&(Pu="0"+Pu),"%"+Pu}))}return base64_url_decode=function($u){var Ru=$u.replace(/-/g,"+").replace(/_/g,"/");switch(Ru.length%4){case 0:break;case 2:Ru+="==";break;case 3:Ru+="=";break;default:throw"Illegal base64url string!"}try{return lo(Ru)}catch{return Au(Ru)}},base64_url_decode}var hasRequiredLib$a;function requireLib$a(){if(hasRequiredLib$a)return lib$c.exports;hasRequiredLib$a=1;var Au=requireBase64_url_decode();function lo($u){this.message=$u}return lo.prototype=new Error,lo.prototype.name="InvalidTokenError",lib$c.exports=function($u,Ru){if(typeof $u!="string")throw new lo("Invalid token specified");Ru=Ru||{};var Iu=Ru.header===!0?0:1;try{return JSON.parse(Au($u.split(".")[Iu]))}catch(Pu){throw new lo("Invalid token specified: "+Pu.message)}},lib$c.exports.InvalidTokenError=lo,lib$c.exports}var libExports$4=requireLib$a();const jwt_decode=getDefaultExportFromCjs(libExports$4);let _localStorageAvailable;function isLocalStorageAvailable(){if(_localStorageAvailable!==void 0)return _localStorageAvailable;try{if(typeof window>"u"||!window.localStorage)return _localStorageAvailable=!1,!1;const Au="__datalayer_ls_test__";return window.localStorage.setItem(Au,"test"),window.localStorage.removeItem(Au),_localStorageAvailable=!0,!0}catch{return _localStorageAvailable=!1,!1}}const JWT_DATALAYER_ISSUER="https://id.datalayer.run",DATALAYER_IAM_USER_KEY="@datalayer/iam:user",DATALAYER_IAM_TOKEN_KEY="@datalayer/iam:token",JWT_REFRESH_TOKEN_COOKIE_NAME="refresh_token",getStoredUser=()=>{if(!isLocalStorageAvailable())return ANONYMOUS_USER;const Au=window.localStorage.getItem(DATALAYER_IAM_USER_KEY);if(Au)try{const lo=JSON.parse(Au);return lo.joinDate=new Date(lo.joinDate),lo}catch{return ANONYMOUS_USER}return ANONYMOUS_USER},storeUser=Au=>{isLocalStorageAvailable()&&(Au?window.localStorage.setItem(DATALAYER_IAM_USER_KEY,JSON.stringify(Au)):window.localStorage.removeItem(DATALAYER_IAM_USER_KEY))},getStoredToken=()=>{if(!isLocalStorageAvailable())return ANONYMOUS_USER_TOKEN;const Au=window.localStorage.getItem(DATALAYER_IAM_TOKEN_KEY);return Au||ANONYMOUS_USER_TOKEN},storeToken=Au=>{if(isLocalStorageAvailable())if(Au){if(Au!==ANONYMOUS_USER_TOKEN)try{const lo=jwt_decode(Au);console.debug("JWT Token",lo)}catch(lo){throw console.error("Error while decoding JWT Token.",lo),lo}window.localStorage.setItem(DATALAYER_IAM_TOKEN_KEY,Au)}else window.localStorage.removeItem(DATALAYER_IAM_TOKEN_KEY)};function loadRefreshTokenFromCookie(){return getCookie$1(JWT_REFRESH_TOKEN_COOKIE_NAME)}function bind(Au,lo){return function(){return Au.apply(lo,arguments)}}const{toString:toString$3}=Object.prototype,{getPrototypeOf:getPrototypeOf$1}=Object,{iterator,toStringTag}=Symbol,hasOwnProperty$2=(({hasOwnProperty:Au})=>(lo,$u)=>Au.call(lo,$u))(Object.prototype),isUnsafeObjectKey=Au=>typeof Au=="string"&&(Au==="__proto__"||Au==="constructor"||Au==="prototype"),isPrototypeBoundary=(Au,lo,$u)=>Au===Object.prototype||!$u&&lo===null,isSafeAndFullyMutable=Au=>{if(!Object.isExtensible(Au))return!1;const lo=Object.getOwnPropertyNames(Au);return Object.getOwnPropertySymbols&&lo.push(...Object.getOwnPropertySymbols(Au)),lo.every($u=>{if(isUnsafeObjectKey($u))return!1;const Ru=Object.getOwnPropertyDescriptor(Au,$u);return!!Ru&&Ru.configurable&&Ru.writable===!0})},hasOwnInPrototypeChain=(Au,lo)=>{let $u=Au;const Ru=[];for(;$u!=null;){if(Ru.indexOf($u)!==-1)return!1;Ru.push($u);const Iu=getPrototypeOf$1($u);if(isPrototypeBoundary($u,Iu,$u===Au))return!1;if(hasOwnProperty$2($u,lo))return!0;$u=Iu}return!1},getSafeProp=(Au,lo)=>Au!=null&&hasOwnInPrototypeChain(Au,lo)?Au[lo]:void 0,toSafeFlatObject=Au=>{if(Au==null||typeof Au!="object"&&typeof Au!="function")return Au;const lo=getPrototypeOf$1(Au);if(lo===null&&isSafeAndFullyMutable(Au))return Au;const $u=Object.create(null),Ru=Object.create(null),Iu=[];let Pu=Au;for(;Pu!=null&&Iu.indexOf(Pu)===-1;){Iu.push(Pu);const Ou=Pu===Au?lo:getPrototypeOf$1(Pu);if(isPrototypeBoundary(Pu,Ou,Pu===Au))break;const Mu=Object.getOwnPropertyNames(Pu);Object.getOwnPropertySymbols&&Mu.push(...Object.getOwnPropertySymbols(Pu));for(const Du of Mu)isUnsafeObjectKey(Du)||hasOwnProperty$2(Ru,Du)||($u[Du]=Au[Du],Ru[Du]=!0);Pu=Ou}return $u},kindOf$1=(Au=>lo=>{const $u=toString$3.call(lo);return Au[$u]||(Au[$u]=$u.slice(8,-1).toLowerCase())})(Object.create(null)),kindOfTest=Au=>(Au=Au.toLowerCase(),lo=>kindOf$1(lo)===Au),typeOfTest=Au=>lo=>typeof lo===Au,{isArray:isArray$1}=Array,isUndefined=typeOfTest("undefined");function isBuffer$2(Au){return Au!==null&&!isUndefined(Au)&&Au.constructor!==null&&!isUndefined(Au.constructor)&&isFunction$2(Au.constructor.isBuffer)&&Au.constructor.isBuffer(Au)}const isArrayBuffer=kindOfTest("ArrayBuffer");function isArrayBufferView(Au){let lo;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?lo=ArrayBuffer.isView(Au):lo=Au&&Au.buffer&&isArrayBuffer(Au.buffer),lo}const isString$4=typeOfTest("string"),isFunction$2=typeOfTest("function"),isNumber$4=typeOfTest("number"),isObject$6=Au=>Au!==null&&typeof Au=="object",isBoolean=Au=>Au===!0||Au===!1,isPlainObject$7=Au=>{if(!isObject$6(Au))return!1;const lo=getPrototypeOf$1(Au);return(lo===null||lo===Object.prototype||getPrototypeOf$1(lo)===null)&&!hasOwnInPrototypeChain(Au,toStringTag)&&!hasOwnInPrototypeChain(Au,iterator)},isEmptyObject$1=Au=>{if(!isObject$6(Au)||isBuffer$2(Au))return!1;try{return Object.keys(Au).length===0&&Object.getPrototypeOf(Au)===Object.prototype}catch{return!1}},isDate=kindOfTest("Date"),isFile=kindOfTest("File"),isReactNativeBlob=Au=>!!(Au&&typeof Au.uri<"u"),isReactNative$1=Au=>Au&&typeof Au.getParts<"u",isBlob=kindOfTest("Blob"),isFileList=kindOfTest("FileList"),isSet=kindOfTest("Set"),isStream$1=Au=>isObject$6(Au)&&isFunction$2(Au.pipe);function getGlobal$1(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof globalThis<"u"?globalThis:{}}const G$3=getGlobal$1(),FormDataCtor=typeof G$3.FormData<"u"?G$3.FormData:void 0,isFormData=Au=>{if(!Au)return!1;if(FormDataCtor&&Au instanceof FormDataCtor)return!0;const lo=getPrototypeOf$1(Au);if(!lo||lo===Object.prototype||!isFunction$2(Au.append))return!1;const $u=kindOf$1(Au);return $u==="formdata"||$u==="object"&&isFunction$2(Au.toString)&&Au.toString()==="[object FormData]"},isURLSearchParams=kindOfTest("URLSearchParams"),[isReadableStream,isRequest,isResponse,isHeaders]=["ReadableStream","Request","Response","Headers"].map(kindOfTest),trim=Au=>Au.trim?Au.trim():Au.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function forEach$1(Au,lo,{allOwnKeys:$u=!1}={}){if(Au===null||typeof Au>"u")return;let Ru,Iu;if(typeof Au!="object"&&(Au=[Au]),isArray$1(Au))for(Ru=0,Iu=Au.length;Ru<Iu;Ru++)lo.call(null,Au[Ru],Ru,Au);else{if(isBuffer$2(Au))return;const Pu=$u?Object.getOwnPropertyNames(Au):Object.keys(Au),Ou=Pu.length;let Mu;for(Ru=0;Ru<Ou;Ru++)Mu=Pu[Ru],lo.call(null,Au[Mu],Mu,Au)}}function findKey(Au,lo){if(isBuffer$2(Au))return null;lo=lo.toLowerCase();const $u=Object.keys(Au);let Ru=$u.length,Iu;for(;Ru-- >0;)if(Iu=$u[Ru],lo===Iu.toLowerCase())return Iu;return null}const _global=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:globalThis,isContextDefined=Au=>!isUndefined(Au)&&Au!==_global;function merge$3(...Au){const{caseless:lo,skipUndefined:$u}=isContextDefined(this)&&this||{},Ru={},Iu=(Pu,Ou)=>{if(Ou==="__proto__"||Ou==="constructor"||Ou==="prototype")return;const Mu=lo&&typeof Ou=="string"&&findKey(Ru,Ou)||Ou,Du=hasOwnProperty$2(Ru,Mu)?Ru[Mu]:void 0;isPlainObject$7(Du)&&isPlainObject$7(Pu)?Ru[Mu]=merge$3(Du,Pu):isPlainObject$7(Pu)?Ru[Mu]=merge$3({},Pu):isArray$1(Pu)?Ru[Mu]=Pu.slice():(!$u||!isUndefined(Pu))&&(Ru[Mu]=Pu)};for(let Pu=0,Ou=Au.length;Pu<Ou;Pu++){const Mu=Au[Pu];if(!Mu||isBuffer$2(Mu)||(forEach$1(Mu,Iu),typeof Mu!="object"||isArray$1(Mu)))continue;const Du=Object.getOwnPropertySymbols(Mu);for(let Lu=0;Lu<Du.length;Lu++){const Bu=Du[Lu];propertyIsEnumerable.call(Mu,Bu)&&Iu(Mu[Bu],Bu)}}return Ru}const extend$3=(Au,lo,$u,{allOwnKeys:Ru}={})=>(forEach$1(lo,(Iu,Pu)=>{$u&&isFunction$2(Iu)?Object.defineProperty(Au,Pu,{__proto__:null,value:bind(Iu,$u),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(Au,Pu,{__proto__:null,value:Iu,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:Ru}),Au),stripBOM=Au=>(Au.charCodeAt(0)===65279&&(Au=Au.slice(1)),Au),inherits=(Au,lo,$u,Ru)=>{Au.prototype=Object.create(lo.prototype,Ru),Object.defineProperty(Au.prototype,"constructor",{__proto__:null,value:Au,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(Au,"super",{__proto__:null,value:lo.prototype}),$u&&Object.assign(Au.prototype,$u)},toFlatObject=(Au,lo,$u,Ru)=>{let Iu,Pu,Ou;const Mu={};if(lo=lo||{},Au==null)return lo;do{for(Iu=Object.getOwnPropertyNames(Au),Pu=Iu.length;Pu-- >0;)Ou=Iu[Pu],(!Ru||Ru(Ou,Au,lo))&&!Mu[Ou]&&(lo[Ou]=Au[Ou],Mu[Ou]=!0);Au=$u!==!1&&getPrototypeOf$1(Au)}while(Au&&(!$u||$u(Au,lo))&&Au!==Object.prototype);return lo},endsWith=(Au,lo,$u)=>{Au=String(Au),($u===void 0||$u>Au.length)&&($u=Au.length),$u-=lo.length;const Ru=Au.indexOf(lo,$u);return Ru!==-1&&Ru===$u},toArray=Au=>{if(!Au)return null;if(isArray$1(Au))return Au;let lo=Au.length;if(!isNumber$4(lo))return null;const $u=new Array(lo);for(;lo-- >0;)$u[lo]=Au[lo];return $u},isTypedArray=(Au=>lo=>Au&&lo instanceof Au)(typeof Uint8Array<"u"&&getPrototypeOf$1(Uint8Array)),forEachEntry=(Au,lo)=>{const Ru=(Au&&Au[iterator]).call(Au);let Iu;for(;(Iu=Ru.next())&&!Iu.done;){const Pu=Iu.value;lo.call(Au,Pu[0],Pu[1])}},matchAll=(Au,lo)=>{let $u;const Ru=[];for(;($u=Au.exec(lo))!==null;)Ru.push($u);return Ru},isHTMLForm=kindOfTest("HTMLFormElement"),toCamelCase$1=Au=>Au.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function($u,Ru,Iu){return Ru.toUpperCase()+Iu}),{propertyIsEnumerable}=Object.prototype,isRegExp$1=kindOfTest("RegExp"),reduceDescriptors=(Au,lo)=>{const $u=Object.getOwnPropertyDescriptors(Au),Ru={};forEach$1($u,(Iu,Pu)=>{let Ou;(Ou=lo(Iu,Pu,Au))!==!1&&(Ru[Pu]=Ou||Iu)}),Object.defineProperties(Au,Ru)},freezeMethods=Au=>{reduceDescriptors(Au,(lo,$u)=>{if(isFunction$2(Au)&&["arguments","caller","callee"].includes($u))return!1;const Ru=Au[$u];if(isFunction$2(Ru)){if(lo.enumerable=!1,"writable"in lo){lo.writable=!1;return}lo.set||(lo.set=()=>{throw Error("Can not rewrite read-only method '"+$u+"'")})}})},toObjectSet=(Au,lo)=>{const $u={},Ru=Iu=>{Iu.forEach(Pu=>{$u[Pu]=!0})};return isArray$1(Au)?Ru(Au):Ru(String(Au).split(lo)),$u},noop$1=()=>{},toFiniteNumber=(Au,lo)=>Au!=null&&Number.isFinite(Au=+Au)?Au:lo;function isSpecCompliantForm(Au){return!!(Au&&isFunction$2(Au.append)&&Au[toStringTag]==="FormData"&&Au[iterator])}const toJSONObject=Au=>{const lo=new WeakSet,$u=Ru=>{if(isObject$6(Ru)){if(lo.has(Ru))return;if(isBuffer$2(Ru))return Ru;if(!("toJSON"in Ru)){lo.add(Ru);let Iu;if(isSet(Ru)){Iu=[];for(const Pu of Ru){const Ou=$u(Pu);!isUndefined(Ou)&&Iu.push(Ou)}}else Iu=isArray$1(Ru)?[]:{},forEach$1(Ru,(Pu,Ou)=>{const Mu=$u(Pu);!isUndefined(Mu)&&(Iu[Ou]=Mu)});return lo.delete(Ru),Iu}}return Ru};return $u(Au)},isAsyncFn=kindOfTest("AsyncFunction"),isThenable=Au=>Au&&(isObject$6(Au)||isFunction$2(Au))&&isFunction$2(Au.then)&&isFunction$2(Au.catch),_setImmediate=((Au,lo)=>Au?setImmediate:lo?(($u,Ru)=>(_global.addEventListener("message",({source:Iu,data:Pu})=>{Iu===_global&&Pu===$u&&Ru.length&&Ru.shift()()},!1),Iu=>{Ru.push(Iu),_global.postMessage($u,"*")}))(`axios@${Math.random()}`,[]):$u=>setTimeout($u))(typeof setImmediate=="function",isFunction$2(_global.postMessage)),asap=typeof queueMicrotask<"u"?queueMicrotask.bind(_global):typeof process<"u"&&process.nextTick||_setImmediate,isIterable=Au=>Au!=null&&isFunction$2(Au[iterator]),isSafeIterable=Au=>Au!=null&&hasOwnInPrototypeChain(Au,iterator)&&isIterable(Au),utils$3={isArray:isArray$1,isArrayBuffer,isBuffer:isBuffer$2,isFormData,isArrayBufferView,isString:isString$4,isNumber:isNumber$4,isBoolean,isObject:isObject$6,isPlainObject:isPlainObject$7,isEmptyObject:isEmptyObject$1,isReadableStream,isRequest,isResponse,isHeaders,isUndefined,isDate,isFile,isReactNativeBlob,isReactNative:isReactNative$1,isBlob,isRegExp:isRegExp$1,isFunction:isFunction$2,isStream:isStream$1,isURLSearchParams,isTypedArray,isFileList,forEach:forEach$1,merge:merge$3,extend:extend$3,trim,stripBOM,inherits,toFlatObject,kindOf:kindOf$1,kindOfTest,endsWith,toArray,forEachEntry,matchAll,isHTMLForm,hasOwnProperty:hasOwnProperty$2,hasOwnProp:hasOwnProperty$2,hasOwnInPrototypeChain,getSafeProp,toSafeFlatObject,reduceDescriptors,freezeMethods,toObjectSet,toCamelCase:toCamelCase$1,noop:noop$1,toFiniteNumber,findKey,global:_global,isContextDefined,isSpecCompliantForm,toJSONObject,isAsyncFn,isThenable,setImmediate:_setImmediate,asap,isIterable,isSafeIterable},ignoreDuplicateOf=utils$3.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),parseHeaders=Au=>{const lo={};let $u,Ru,Iu;return Au&&Au.split(`
|
|
255
255
|
`).forEach(function(Ou){Iu=Ou.indexOf(":"),$u=Ou.substring(0,Iu).trim().toLowerCase(),Ru=Ou.substring(Iu+1).trim();const Mu=utils$3.hasOwnProp(lo,$u);!$u||Mu&&utils$3.hasOwnProp(ignoreDuplicateOf,$u)||($u==="set-cookie"?Mu?lo[$u].push(Ru):lo[$u]=[Ru]:lo[$u]=Mu?lo[$u]+", "+Ru:Ru)}),lo};function trimSPorHTAB(Au){let lo=0,$u=Au.length;for(;lo<$u;){const Ru=Au.charCodeAt(lo);if(Ru!==9&&Ru!==32)break;lo+=1}for(;$u>lo;){const Ru=Au.charCodeAt($u-1);if(Ru!==9&&Ru!==32)break;$u-=1}return lo===0&&$u===Au.length?Au:Au.slice(lo,$u)}const INVALID_UNICODE_HEADER_VALUE_CHARS=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),INVALID_BYTE_STRING_HEADER_VALUE_CHARS=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function sanitizeValue(Au,lo){return utils$3.isArray(Au)?Au.map($u=>sanitizeValue($u,lo)):trimSPorHTAB(String(Au).replace(lo,""))}const sanitizeHeaderValue=Au=>sanitizeValue(Au,INVALID_UNICODE_HEADER_VALUE_CHARS),sanitizeByteStringHeaderValue=Au=>sanitizeValue(Au,INVALID_BYTE_STRING_HEADER_VALUE_CHARS);function toByteStringHeaderObject(Au){const lo=Object.create(null);return utils$3.forEach(Au.toJSON(),($u,Ru)=>{lo[Ru]=sanitizeByteStringHeaderValue($u)}),lo}const $internals$1=Symbol("internals");function normalizeHeader(Au){return Au&&String(Au).trim().toLowerCase()}function normalizeValue$1(Au){return Au===!1||Au==null?Au:utils$3.isArray(Au)?Au.map(normalizeValue$1):sanitizeHeaderValue(String(Au))}function parseTokens$1(Au){const lo=Object.create(null),$u=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let Ru;for(;Ru=$u.exec(Au);)lo[Ru[1]]=Ru[2];return lo}const parameterNameRE=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function trimOWS(Au){let lo=0,$u=Au.length;for(;lo<$u;){const Ru=Au.charCodeAt(lo);if(Ru!==9&&Ru!==32)break;lo+=1}for(;$u>lo;){const Ru=Au.charCodeAt($u-1);if(Ru!==9&&Ru!==32)break;$u-=1}return lo===0&&$u===Au.length?Au:Au.slice(lo,$u)}function decodeQuotedString(Au){const lo=Au.length-1;if(lo<1||Au.charCodeAt(0)!==34||Au.charCodeAt(lo)!==34)return Au;let $u="";for(let Ru=1;Ru<lo;Ru++){const Iu=Au.charCodeAt(Ru);if(Iu===34||Iu===92&&(Ru+=1,Ru>=lo))return Au;$u+=Au[Ru]}return $u}function parseParameters(Au){const lo=Object.create(null),$u=String(Au);let Ru=0,Iu=!1,Pu=!1;function Ou(Mu){const Du=trimOWS($u.slice(Ru,Mu)),Lu=Du.indexOf("=");if(Lu<1)return;const Bu=trimOWS(Du.slice(0,Lu));if(!parameterNameRE.test(Bu))return;const ju=Bu.toLowerCase();if(ju==="__proto__"||ju==="constructor"||ju==="prototype")return;const Fu=trimOWS(Du.slice(Lu+1));lo[ju]=decodeQuotedString(Fu)}for(let Mu=0;Mu<$u.length;Mu++){const Du=$u.charCodeAt(Mu);Iu?Pu?Pu=!1:Du===92?Pu=!0:Du===34&&(Iu=!1):Du===34?Iu=!0:(Du===44||Du===59)&&(Ou(Mu),Ru=Mu+1)}return Ou($u.length),lo}const isValidHeaderName=Au=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(Au.trim());function matchHeaderValue(Au,lo,$u,Ru,Iu){if(utils$3.isFunction(Ru))return Ru.call(this,lo,$u);if(Iu&&(lo=$u),!!utils$3.isString(lo)){if(utils$3.isString(Ru))return lo.indexOf(Ru)!==-1;if(utils$3.isRegExp(Ru))return Ru.test(lo)}}function formatHeader$1(Au){return Au.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(lo,$u,Ru)=>$u.toUpperCase()+Ru)}function buildAccessors(Au,lo){const $u=utils$3.toCamelCase(" "+lo);["get","set","has"].forEach(Ru=>{Object.defineProperty(Au,Ru+$u,{__proto__:null,value:function(Iu,Pu,Ou){return this[Ru].call(this,lo,Iu,Pu,Ou)},configurable:!0})})}let AxiosHeaders$1=class{constructor(lo){lo&&this.set(lo)}set(lo,$u,Ru){const Iu=this;function Pu(Mu,Du,Lu){const Bu=normalizeHeader(Du);if(!Bu)return;const ju=utils$3.findKey(Iu,Bu);(!ju||Iu[ju]===void 0||Lu===!0||Lu===void 0&&Iu[ju]!==!1)&&(Iu[ju||Du]=normalizeValue$1(Mu))}const Ou=(Mu,Du)=>utils$3.forEach(Mu,(Lu,Bu)=>Pu(Lu,Bu,Du));if(utils$3.isPlainObject(lo)||lo instanceof this.constructor)Ou(lo,$u);else if(utils$3.isString(lo)&&(lo=lo.trim())&&!isValidHeaderName(lo))Ou(parseHeaders(lo),$u);else if(utils$3.isObject(lo)&&utils$3.isSafeIterable(lo)){let Mu=Object.create(null),Du,Lu;for(const Bu of lo){if(!utils$3.isArray(Bu))throw new TypeError("Object iterator must return a key-value pair");Lu=Bu[0],utils$3.hasOwnProp(Mu,Lu)?(Du=Mu[Lu],Mu[Lu]=utils$3.isArray(Du)?[...Du,Bu[1]]:[Du,Bu[1]]):Mu[Lu]=Bu[1]}Ou(Mu,$u)}else lo!=null&&Pu($u,lo,Ru);return this}get(lo,$u){if(lo=normalizeHeader(lo),lo){const Ru=utils$3.findKey(this,lo);if(Ru){const Iu=this[Ru];if(!$u)return Iu;if($u===!0)return parseTokens$1(Iu);if(utils$3.isFunction($u))return $u.call(this,Iu,Ru);if(utils$3.isRegExp($u))return $u.exec(Iu);throw new TypeError("parser must be boolean|regexp|function")}}}has(lo,$u){if(lo=normalizeHeader(lo),lo){const Ru=utils$3.findKey(this,lo);return!!(Ru&&this[Ru]!==void 0&&(!$u||matchHeaderValue(this,this[Ru],Ru,$u)))}return!1}delete(lo,$u){const Ru=this;let Iu=!1;function Pu(Ou){if(Ou=normalizeHeader(Ou),Ou){const Mu=utils$3.findKey(Ru,Ou);Mu&&(!$u||matchHeaderValue(Ru,Ru[Mu],Mu,$u))&&(delete Ru[Mu],Iu=!0)}}return utils$3.isArray(lo)?lo.forEach(Pu):Pu(lo),Iu}clear(lo){const $u=Object.keys(this);let Ru=$u.length,Iu=!1;for(;Ru--;){const Pu=$u[Ru];(!lo||matchHeaderValue(this,this[Pu],Pu,lo,!0))&&(delete this[Pu],Iu=!0)}return Iu}normalize(lo){const $u=this,Ru={};return utils$3.forEach(this,(Iu,Pu)=>{const Ou=utils$3.findKey(Ru,Pu);if(Ou){$u[Ou]=normalizeValue$1(Iu),delete $u[Pu];return}const Mu=lo?formatHeader$1(Pu):String(Pu).trim();Mu!==Pu&&delete $u[Pu],$u[Mu]=normalizeValue$1(Iu),Ru[Mu]=!0}),this}concat(...lo){return this.constructor.concat(this,...lo)}toJSON(lo){const $u=Object.create(null);return utils$3.forEach(this,(Ru,Iu)=>{Ru!=null&&Ru!==!1&&($u[Iu]=lo&&utils$3.isArray(Ru)?Ru.join(", "):Ru)}),$u}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([lo,$u])=>lo+": "+$u).join(`
|
|
@@ -2191,7 +2191,7 @@ ${Ou}
|
|
|
2191
2191
|
`,{prompt:Ru,stopSequences:[`
|
|
2192
2192
|
${lo}:`]}}function getResponseMetadata2({id:Au,model:lo,created:$u}){return{id:Au??void 0,modelId:lo??void 0,timestamp:$u!=null?new Date($u*1e3):void 0}}function mapOpenAIFinishReason2(Au){switch(Au){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var openaiCompletionResponseSchema=lazySchema(()=>zodSchema(object({id:string$2().nullish(),created:number$2().nullish(),model:string$2().nullish(),choices:array(object({text:string$2(),finish_reason:string$2(),logprobs:object({tokens:array(string$2()),token_logprobs:array(number$2()),top_logprobs:array(record$2(string$2(),number$2())).nullish()}).nullish()})),usage:object({prompt_tokens:number$2(),completion_tokens:number$2(),total_tokens:number$2()}).nullish()}))),openaiCompletionChunkSchema=lazySchema(()=>zodSchema(union([object({id:string$2().nullish(),created:number$2().nullish(),model:string$2().nullish(),choices:array(object({text:string$2(),finish_reason:string$2().nullish(),index:number$2(),logprobs:object({tokens:array(string$2()),token_logprobs:array(number$2()),top_logprobs:array(record$2(string$2(),number$2())).nullish()}).nullish()})),usage:object({prompt_tokens:number$2(),completion_tokens:number$2(),total_tokens:number$2()}).nullish()}),openaiErrorDataSchema]))),openaiLanguageModelCompletionOptions=lazySchema(()=>zodSchema(object({echo:boolean$1().optional(),logitBias:record$2(string$2(),number$2()).optional(),suffix:string$2().optional(),user:string$2().optional(),logprobs:union([boolean$1(),number$2()]).optional()}))),OpenAICompletionLanguageModel=class VS{constructor(lo,$u){this.specificationVersion="v4",this.supportedUrls={},this.modelId=lo,this.config=$u}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}static[WORKFLOW_SERIALIZE](lo){return serializeModelOptions({modelId:lo.modelId,config:lo.config})}static[WORKFLOW_DESERIALIZE](lo){return new VS(lo.modelId,lo.config)}get provider(){return this.config.provider}async getArgs({prompt:lo,maxOutputTokens:$u,temperature:Ru,topP:Iu,topK:Pu,frequencyPenalty:Ou,presencePenalty:Mu,stopSequences:Du,responseFormat:Lu,tools:Bu,toolChoice:ju,seed:Fu,providerOptions:zu}){const Uu=[],Hu={...await parseProviderOptions({provider:"openai",providerOptions:zu,schema:openaiLanguageModelCompletionOptions}),...await parseProviderOptions({provider:this.providerOptionsName,providerOptions:zu,schema:openaiLanguageModelCompletionOptions})};Pu!=null&&Uu.push({type:"unsupported",feature:"topK"}),Bu?.length&&Uu.push({type:"unsupported",feature:"tools"}),ju!=null&&Uu.push({type:"unsupported",feature:"toolChoice"}),Lu!=null&&Lu.type!=="text"&&Uu.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:Vu,stopSequences:Gu}=convertToOpenAICompletionPrompt({prompt:lo}),Wu=[...Gu??[],...Du??[]];return{args:{model:this.modelId,echo:Hu.echo,logit_bias:Hu.logitBias,logprobs:Hu?.logprobs===!0?0:Hu?.logprobs===!1?void 0:Hu?.logprobs,suffix:Hu.suffix,user:Hu.user,max_tokens:$u,temperature:Ru,top_p:Iu,frequency_penalty:Ou,presence_penalty:Mu,seed:Fu,prompt:Vu,stop:Wu.length>0?Wu:void 0},warnings:Uu}}async doGenerate(lo){var $u,Ru,Iu;const{args:Pu,warnings:Ou}=await this.getArgs(lo),{responseHeaders:Mu,value:Du,rawValue:Lu}=await postJsonToApi({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:combineHeaders((Ru=($u=this.config).headers)==null?void 0:Ru.call($u),lo.headers),body:Pu,failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler(openaiCompletionResponseSchema),abortSignal:lo.abortSignal,fetch:this.config.fetch}),Bu=Du.choices[0],ju={openai:{}};return Bu.logprobs!=null&&(ju.openai.logprobs=Bu.logprobs),{content:[{type:"text",text:Bu.text}],usage:convertOpenAICompletionUsage(Du.usage),finishReason:{unified:mapOpenAIFinishReason2(Bu.finish_reason),raw:(Iu=Bu.finish_reason)!=null?Iu:void 0},request:{body:Pu},response:{...getResponseMetadata2(Du),headers:Mu,body:Lu},providerMetadata:ju,warnings:Ou}}async doStream(lo){var $u,Ru;const{args:Iu,warnings:Pu}=await this.getArgs(lo),Ou={...Iu,stream:!0,stream_options:{include_usage:!0}},Mu=this.config.url({path:"/completions",modelId:this.modelId}),{responseHeaders:Du,value:Lu}=await postJsonToApi({url:Mu,headers:combineHeaders((Ru=($u=this.config).headers)==null?void 0:Ru.call($u),lo.headers),body:Ou,failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createEventSourceResponseHandler(openaiCompletionChunkSchema),abortSignal:lo.abortSignal,fetch:this.config.fetch}),Bu=await throwIfOpenAIStreamErrorBeforeOutput({stream:Lu,getError:Vu=>"error"in Vu?Vu.error:void 0,isOutputChunk:isOpenAICompletionOutputChunk,url:Mu,requestBodyValues:Ou,responseHeaders:Du});let ju={unified:"other",raw:void 0};const Fu={openai:{}};let zu,Uu=!0;return{stream:Bu.pipeThrough(new TransformStream({start(Vu){Vu.enqueue({type:"stream-start",warnings:Pu})},transform(Vu,Gu){if(lo.includeRawChunks&&Gu.enqueue({type:"raw",rawValue:Vu.rawValue}),!Vu.success){ju={unified:"error",raw:void 0},Gu.enqueue({type:"error",error:Vu.error});return}const Wu=Vu.value;if("error"in Wu){ju={unified:"error",raw:void 0},Gu.enqueue({type:"error",error:Wu.error});return}Uu&&(Uu=!1,Gu.enqueue({type:"response-metadata",...getResponseMetadata2(Wu)}),Gu.enqueue({type:"text-start",id:"0"})),Wu.usage!=null&&(zu=Wu.usage);const Ku=Wu.choices[0];Ku?.finish_reason!=null&&(ju={unified:mapOpenAIFinishReason2(Ku.finish_reason),raw:Ku.finish_reason}),Ku?.logprobs!=null&&(Fu.openai.logprobs=Ku.logprobs),Ku?.text!=null&&Ku.text.length>0&&Gu.enqueue({type:"text-delta",id:"0",delta:Ku.text})},flush(Vu){Uu||Vu.enqueue({type:"text-end",id:"0"}),Vu.enqueue({type:"finish",finishReason:ju,providerMetadata:Fu,usage:convertOpenAICompletionUsage(zu)})}})),request:{body:Ou},response:{headers:Du}}}};function isOpenAICompletionOutputChunk(Au){return!("error"in Au)&&Au.choices.some(lo=>lo.text.length>0)}var openaiEmbeddingModelOptions=lazySchema(()=>zodSchema(object({dimensions:number$2().optional(),user:string$2().optional()}))),openaiTextEmbeddingResponseSchema=lazySchema(()=>zodSchema(object({data:array(object({embedding:array(number$2())})),usage:object({prompt_tokens:number$2()}).nullish()}))),OpenAIEmbeddingModel=class GS{constructor(lo,$u){this.specificationVersion="v4",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=lo,this.config=$u}static[WORKFLOW_SERIALIZE](lo){return serializeModelOptions({modelId:lo.modelId,config:lo.config})}static[WORKFLOW_DESERIALIZE](lo){return new GS(lo.modelId,lo.config)}get provider(){return this.config.provider}async doEmbed({values:lo,headers:$u,abortSignal:Ru,providerOptions:Iu}){var Pu,Ou,Mu;if(lo.length>this.maxEmbeddingsPerCall)throw new TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:lo});const Du=(Pu=await parseProviderOptions({provider:"openai",providerOptions:Iu,schema:openaiEmbeddingModelOptions}))!=null?Pu:{},{responseHeaders:Lu,value:Bu,rawValue:ju}=await postJsonToApi({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:combineHeaders((Mu=(Ou=this.config).headers)==null?void 0:Mu.call(Ou),$u),body:{model:this.modelId,input:lo,encoding_format:"float",dimensions:Du.dimensions,user:Du.user},failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler(openaiTextEmbeddingResponseSchema),abortSignal:Ru,fetch:this.config.fetch});return{warnings:[],embeddings:Bu.data.map(Fu=>Fu.embedding),usage:Bu.usage?{tokens:Bu.usage.prompt_tokens}:void 0,response:{headers:Lu,body:ju}}}},openaiFilesResponseSchema=lazySchema(()=>zodSchema(object({id:string$2(),object:string$2().nullish(),bytes:number$2().nullish(),created_at:number$2().nullish(),filename:string$2().nullish(),purpose:string$2().nullish(),status:string$2().nullish(),expires_at:number$2().nullish()}))),openaiFilesOptionsSchema=lazySchema(()=>zodSchema(object({purpose:string$2().optional(),expiresAfter:number$2().optional()}))),OpenAIFiles=class{constructor(Au){this.config=Au,this.specificationVersion="v4"}get provider(){return this.config.provider}async uploadFile({data:Au,mediaType:lo,filename:$u,providerOptions:Ru}){var Iu,Pu,Ou;const Mu=await parseProviderOptions({provider:"openai",providerOptions:Ru,schema:openaiFilesOptionsSchema}),Du=convertInlineFileDataToUint8Array(Au),Lu=new Blob([Du],{type:lo}),Bu=new FormData;$u!=null?Bu.append("file",Lu,$u):Bu.append("file",Lu),Bu.append("purpose",(Iu=Mu?.purpose)!=null?Iu:"assistants"),Mu?.expiresAfter!=null&&Bu.append("expires_after",String(Mu.expiresAfter));const{value:ju}=await postFormDataToApi({url:`${this.config.baseURL}/files`,headers:combineHeaders(this.config.headers()),formData:Bu,failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler(openaiFilesResponseSchema),fetch:this.config.fetch});return{warnings:[],providerReference:{openai:ju.id},...((Pu=ju.filename)!=null?Pu:$u)?{filename:(Ou=ju.filename)!=null?Ou:$u}:{},...lo!=null?{mediaType:lo}:{},providerMetadata:{openai:{...ju.filename!=null?{filename:ju.filename}:{},...ju.purpose!=null?{purpose:ju.purpose}:{},...ju.bytes!=null?{bytes:ju.bytes}:{},...ju.created_at!=null?{createdAt:ju.created_at}:{},...ju.status!=null?{status:ju.status}:{},...ju.expires_at!=null?{expiresAt:ju.expires_at}:{}}}}}},openaiImageResponseSchema=lazySchema(()=>zodSchema(object({created:number$2().nullish(),data:array(object({b64_json:string$2(),revised_prompt:string$2().nullish()})),background:string$2().nullish(),output_format:string$2().nullish(),size:string$2().nullish(),quality:string$2().nullish(),usage:object({input_tokens:number$2().nullish(),output_tokens:number$2().nullish(),total_tokens:number$2().nullish(),input_tokens_details:object({image_tokens:number$2().nullish(),text_tokens:number$2().nullish()}).nullish()}).nullish()}))),modelMaxImagesPerCall={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"gpt-image-2":10,"chatgpt-image-latest":10},defaultResponseFormatPrefixes=["chatgpt-image-","gpt-image-"];function hasDefaultResponseFormat(Au){return defaultResponseFormatPrefixes.some(lo=>Au.startsWith(lo))}function getMaxImagesPerCall(Au){var lo;return(lo=modelMaxImagesPerCall[Au])!=null?lo:Au.startsWith("gpt-image-")?10:1}var baseImageModelOptionsObject=object({quality:_enum(["standard","hd","low","medium","high","auto"]).optional(),background:_enum(["transparent","opaque","auto"]).optional(),outputFormat:_enum(["png","jpeg","webp"]).optional(),outputCompression:number$2().int().min(0).max(100).optional(),user:string$2().optional()}),openaiImageModelGenerationOptions=lazySchema(()=>zodSchema(baseImageModelOptionsObject.extend({style:_enum(["vivid","natural"]).optional(),moderation:_enum(["auto","low"]).optional()}))),openaiImageModelEditOptions=lazySchema(()=>zodSchema(baseImageModelOptionsObject.extend({inputFidelity:_enum(["high","low"]).optional()}))),OpenAIImageModel=class WS{constructor(lo,$u){this.modelId=lo,this.config=$u,this.specificationVersion="v4"}static[WORKFLOW_SERIALIZE](lo){return serializeModelOptions({modelId:lo.modelId,config:lo.config})}static[WORKFLOW_DESERIALIZE](lo){return new WS(lo.modelId,lo.config)}get maxImagesPerCall(){return getMaxImagesPerCall(this.modelId)}get provider(){return this.config.provider}async doGenerate({prompt:lo,files:$u,mask:Ru,n:Iu,size:Pu,aspectRatio:Ou,seed:Mu,providerOptions:Du,headers:Lu,abortSignal:Bu}){var ju,Fu,zu,Uu,Hu,Vu,Gu,Wu,Ku,Ju,Yu,Xu,ed,td,nd;const od=[];Ou!=null&&od.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),Mu!=null&&od.push({type:"unsupported",feature:"seed"});const sd=(zu=(Fu=(ju=this.config._internal)==null?void 0:ju.currentDate)==null?void 0:Fu.call(ju))!=null?zu:new Date;if($u!=null){const yd=(Uu=await parseProviderOptions({provider:"openai",providerOptions:Du,schema:openaiImageModelEditOptions}))!=null?Uu:{},{value:_d,responseHeaders:bd}=await postFormDataToApi({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:combineHeaders((Vu=(Hu=this.config).headers)==null?void 0:Vu.call(Hu),Lu),formData:convertToFormData({model:this.modelId,prompt:lo,image:await Promise.all($u.map(wd=>wd.type==="file"?new Blob([wd.data instanceof Uint8Array?new Blob([wd.data],{type:wd.mediaType}):new Blob([convertBase64ToUint8Array(wd.data)],{type:wd.mediaType})],{type:wd.mediaType}):downloadBlob(wd.url))),mask:Ru!=null?await fileToBlob(Ru):void 0,n:Iu,size:Pu,quality:yd.quality,background:yd.background,output_format:yd.outputFormat,output_compression:yd.outputCompression,input_fidelity:yd.inputFidelity,user:yd.user}),failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler(openaiImageResponseSchema),abortSignal:Bu,fetch:this.config.fetch});return{images:_d.data.map(wd=>wd.b64_json),warnings:od,usage:_d.usage!=null?{inputTokens:(Gu=_d.usage.input_tokens)!=null?Gu:void 0,outputTokens:(Wu=_d.usage.output_tokens)!=null?Wu:void 0,totalTokens:(Ku=_d.usage.total_tokens)!=null?Ku:void 0}:void 0,response:{timestamp:sd,modelId:this.modelId,headers:bd},providerMetadata:{openai:{images:_d.data.map((wd,Ed)=>{var cd,ud,md,ld,hd,vd;return{...wd.revised_prompt?{revisedPrompt:wd.revised_prompt}:{},created:(cd=_d.created)!=null?cd:void 0,size:(ud=_d.size)!=null?ud:void 0,quality:(md=_d.quality)!=null?md:void 0,background:(ld=_d.background)!=null?ld:void 0,outputFormat:(hd=_d.output_format)!=null?hd:void 0,...distributeTokenDetails((vd=_d.usage)==null?void 0:vd.input_tokens_details,Ed,_d.data.length)}})}}}}const ad=(Ju=await parseProviderOptions({provider:"openai",providerOptions:Du,schema:openaiImageModelGenerationOptions}))!=null?Ju:{},{value:pd,responseHeaders:gd}=await postJsonToApi({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:combineHeaders((Xu=(Yu=this.config).headers)==null?void 0:Xu.call(Yu),Lu),body:{model:this.modelId,prompt:lo,n:Iu,size:Pu,quality:ad.quality,style:ad.style,background:ad.background,moderation:ad.moderation,output_format:ad.outputFormat,output_compression:ad.outputCompression,user:ad.user,...hasDefaultResponseFormat(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler(openaiImageResponseSchema),abortSignal:Bu,fetch:this.config.fetch});return{images:pd.data.map(yd=>yd.b64_json),warnings:od,usage:pd.usage!=null?{inputTokens:(ed=pd.usage.input_tokens)!=null?ed:void 0,outputTokens:(td=pd.usage.output_tokens)!=null?td:void 0,totalTokens:(nd=pd.usage.total_tokens)!=null?nd:void 0}:void 0,response:{timestamp:sd,modelId:this.modelId,headers:gd},providerMetadata:{openai:{images:pd.data.map((yd,_d)=>{var bd,wd,Ed,cd,ud,md;return{...yd.revised_prompt?{revisedPrompt:yd.revised_prompt}:{},created:(bd=pd.created)!=null?bd:void 0,size:(wd=pd.size)!=null?wd:void 0,quality:(Ed=pd.quality)!=null?Ed:void 0,background:(cd=pd.background)!=null?cd:void 0,outputFormat:(ud=pd.output_format)!=null?ud:void 0,...distributeTokenDetails((md=pd.usage)==null?void 0:md.input_tokens_details,_d,pd.data.length)}})}}}}};function distributeTokenDetails(Au,lo,$u){if(Au==null)return{};const Ru={};if(Au.image_tokens!=null){const Iu=Math.floor(Au.image_tokens/$u),Pu=Au.image_tokens-Iu*($u-1);Ru.imageTokens=lo===$u-1?Pu:Iu}if(Au.text_tokens!=null){const Iu=Math.floor(Au.text_tokens/$u),Pu=Au.text_tokens-Iu*($u-1);Ru.textTokens=lo===$u-1?Pu:Iu}return Ru}async function fileToBlob(Au){if(!Au)return;if(Au.type==="url")return downloadBlob(Au.url);const lo=Au.data instanceof Uint8Array?Au.data:convertBase64ToUint8Array(Au.data);return new Blob([lo],{type:Au.mediaType})}var applyPatchInputSchema=lazySchema(()=>zodSchema(object({callId:string$2(),operation:discriminatedUnion("type",[object({type:literal("create_file"),path:string$2(),diff:string$2()}),object({type:literal("delete_file"),path:string$2()}),object({type:literal("update_file"),path:string$2(),diff:string$2()})])}))),applyPatchOutputSchema=lazySchema(()=>zodSchema(object({status:_enum(["completed","failed"]),output:string$2().optional()}))),applyPatchToolFactory=createProviderDefinedToolFactoryWithOutputSchema({id:"openai.apply_patch",inputSchema:applyPatchInputSchema,outputSchema:applyPatchOutputSchema}),applyPatch=applyPatchToolFactory,codeInterpreterInputSchema=lazySchema(()=>zodSchema(object({code:string$2().nullish(),containerId:string$2()}))),codeInterpreterOutputSchema=lazySchema(()=>zodSchema(object({outputs:array(discriminatedUnion("type",[object({type:literal("logs"),logs:string$2()}),object({type:literal("image"),url:string$2()})])).nullish()}))),codeInterpreterArgsSchema=lazySchema(()=>zodSchema(object({container:union([string$2(),object({fileIds:array(string$2()).optional()})]).optional()}))),codeInterpreterToolFactory=createProviderExecutedToolFactory({id:"openai.code_interpreter",inputSchema:codeInterpreterInputSchema,outputSchema:codeInterpreterOutputSchema}),codeInterpreter=(Au={})=>codeInterpreterToolFactory(Au),safetyCheckSchema=object({id:string$2(),code:string$2().optional(),message:string$2().optional()}),computerActionSchema=discriminatedUnion("type",[object({type:literal("click"),button:_enum(["left","right","wheel","back","forward"]),x:number$2(),y:number$2(),keys:array(string$2()).optional()}),object({type:literal("double_click"),x:number$2(),y:number$2(),keys:array(string$2()).optional()}),object({type:literal("drag"),path:array(object({x:number$2(),y:number$2()})),keys:array(string$2()).optional()}),object({type:literal("keypress"),keys:array(string$2())}),object({type:literal("move"),x:number$2(),y:number$2(),keys:array(string$2()).optional()}),object({type:literal("screenshot")}),object({type:literal("scroll"),x:number$2(),y:number$2(),scrollX:number$2(),scrollY:number$2(),keys:array(string$2()).optional()}),object({type:literal("type"),text:string$2()}),object({type:literal("wait")})]),computerInputSchema=lazySchema(()=>zodSchema(object({actions:array(computerActionSchema),pendingSafetyChecks:array(safetyCheckSchema),status:_enum(["in_progress","completed","incomplete"])}))),computerOutputSchema=lazySchema(()=>zodSchema(object({output:union([object({type:literal("computer_screenshot"),imageUrl:string$2(),fileId:string$2().optional(),detail:_enum(["auto","low","high","original"]).optional()}),object({type:literal("computer_screenshot"),fileId:string$2(),imageUrl:string$2().optional(),detail:_enum(["auto","low","high","original"]).optional()})]),acknowledgedSafetyChecks:array(safetyCheckSchema).optional()}))),computerToolFactory=createProviderDefinedToolFactoryWithOutputSchema({id:"openai.computer",inputSchema:computerInputSchema,outputSchema:computerOutputSchema}),computer=(Au={})=>computerToolFactory(Au),customArgsSchema=lazySchema(()=>zodSchema(object({description:string$2().optional(),format:union([object({type:literal("grammar"),syntax:_enum(["regex","lark"]),definition:string$2()}),object({type:literal("text")})]).optional()}))),customInputSchema=lazySchema(()=>zodSchema(string$2())),customToolFactory=createProviderDefinedToolFactory({id:"openai.custom",inputSchema:customInputSchema}),customTool=Au=>customToolFactory(Au),comparisonFilterSchema=object({key:string$2(),type:_enum(["eq","ne","gt","gte","lt","lte","in","nin"]),value:union([string$2(),number$2(),boolean$1(),array(string$2())])}),compoundFilterSchema=object({type:_enum(["and","or"]),filters:array(union([comparisonFilterSchema,lazy(()=>compoundFilterSchema)]))}),fileSearchArgsSchema=lazySchema(()=>zodSchema(object({vectorStoreIds:array(string$2()),maxNumResults:number$2().optional(),ranking:object({ranker:string$2().optional(),scoreThreshold:number$2().optional()}).optional(),filters:union([comparisonFilterSchema,compoundFilterSchema]).optional()}))),fileSearchOutputSchema=lazySchema(()=>zodSchema(object({queries:array(string$2()),results:array(object({attributes:record$2(string$2(),unknown$1()),fileId:string$2(),filename:string$2(),score:number$2(),text:string$2()})).nullable()}))),fileSearch=createProviderExecutedToolFactory({id:"openai.file_search",inputSchema:object({}),outputSchema:fileSearchOutputSchema}),imageGenerationArgsSchema=lazySchema(()=>zodSchema(object({background:_enum(["auto","opaque","transparent"]).optional(),inputFidelity:_enum(["low","high"]).optional(),inputImageMask:object({fileId:string$2().optional(),imageUrl:string$2().optional()}).optional(),model:string$2().optional(),moderation:_enum(["auto"]).optional(),outputCompression:number$2().int().min(0).max(100).optional(),outputFormat:_enum(["png","jpeg","webp"]).optional(),partialImages:number$2().int().min(0).max(3).optional(),quality:_enum(["auto","low","medium","high"]).optional(),size:_enum(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),imageGenerationInputSchema=lazySchema(()=>zodSchema(object({}))),imageGenerationOutputSchema=lazySchema(()=>zodSchema(object({result:string$2()}))),imageGenerationToolFactory=createProviderExecutedToolFactory({id:"openai.image_generation",inputSchema:imageGenerationInputSchema,outputSchema:imageGenerationOutputSchema}),imageGeneration=(Au={})=>imageGenerationToolFactory(Au),localShellInputSchema=lazySchema(()=>zodSchema(object({action:object({type:literal("exec"),command:array(string$2()),timeoutMs:number$2().optional(),user:string$2().optional(),workingDirectory:string$2().optional(),env:record$2(string$2(),string$2()).optional()})}))),localShellOutputSchema=lazySchema(()=>zodSchema(object({output:string$2()}))),localShell=createProviderDefinedToolFactoryWithOutputSchema({id:"openai.local_shell",inputSchema:localShellInputSchema,outputSchema:localShellOutputSchema}),shellInputSchema=lazySchema(()=>zodSchema(object({action:object({commands:array(string$2()),timeoutMs:number$2().optional(),maxOutputLength:number$2().optional()})}))),shellOutputSchema=lazySchema(()=>zodSchema(object({output:array(object({stdout:string$2(),stderr:string$2(),outcome:discriminatedUnion("type",[object({type:literal("timeout")}),object({type:literal("exit"),exitCode:number$2()})])}))}))),shellSkillsSchema=array(discriminatedUnion("type",[object({type:literal("skillReference"),providerReference:record$2(string$2(),string$2()),version:string$2().optional()}),object({type:literal("inline"),name:string$2(),description:string$2(),source:object({type:literal("base64"),mediaType:literal("application/zip"),data:string$2()})})])).optional(),shellArgsSchema=lazySchema(()=>zodSchema(object({environment:union([object({type:literal("containerAuto"),fileIds:array(string$2()).optional(),memoryLimit:_enum(["1g","4g","16g","64g"]).optional(),networkPolicy:discriminatedUnion("type",[object({type:literal("disabled")}),object({type:literal("allowlist"),allowedDomains:array(string$2()),domainSecrets:array(object({domain:string$2(),name:string$2(),value:string$2()})).optional()})]).optional(),skills:shellSkillsSchema}),object({type:literal("containerReference"),containerId:string$2()}),object({type:literal("local").optional(),skills:array(object({name:string$2(),description:string$2(),path:string$2()})).optional()})]).optional()}))),shell=createProviderDefinedToolFactoryWithOutputSchema({id:"openai.shell",inputSchema:shellInputSchema,outputSchema:shellOutputSchema}),toolSearchArgsSchema=lazySchema(()=>zodSchema(object({execution:_enum(["server","client"]).optional(),description:string$2().optional(),parameters:record$2(string$2(),unknown$1()).optional()}))),toolSearchInputSchema=lazySchema(()=>zodSchema(object({arguments:unknown$1().optional(),call_id:string$2().nullish()}))),toolSearchOutputSchema=lazySchema(()=>zodSchema(object({tools:array(record$2(string$2(),unknown$1()))}))),toolSearchToolFactory=createProviderDefinedToolFactoryWithOutputSchema({id:"openai.tool_search",inputSchema:toolSearchInputSchema,outputSchema:toolSearchOutputSchema}),toolSearch=(Au={})=>toolSearchToolFactory(Au),webSearchArgsSchema=lazySchema(()=>zodSchema(object({externalWebAccess:boolean$1().optional(),filters:object({allowedDomains:array(string$2()).optional()}).optional(),searchContextSize:_enum(["low","medium","high"]).optional(),userLocation:object({type:literal("approximate"),country:string$2().optional(),city:string$2().optional(),region:string$2().optional(),timezone:string$2().optional()}).optional()}))),webSearchInputSchema=lazySchema(()=>zodSchema(object({}))),webSearchOutputSchema=lazySchema(()=>zodSchema(object({action:discriminatedUnion("type",[object({type:literal("search"),query:string$2().optional(),queries:array(string$2()).optional()}),object({type:literal("openPage"),url:string$2().nullish()}),object({type:literal("findInPage"),url:string$2().nullish(),pattern:string$2().nullish()})]).optional(),sources:array(discriminatedUnion("type",[object({type:literal("url"),url:string$2()}),object({type:literal("api"),name:string$2()})])).optional()}))),webSearchToolFactory=createProviderExecutedToolFactory({id:"openai.web_search",inputSchema:webSearchInputSchema,outputSchema:webSearchOutputSchema}),webSearch=(Au={})=>webSearchToolFactory(Au),webSearchPreviewArgsSchema=lazySchema(()=>zodSchema(object({searchContextSize:_enum(["low","medium","high"]).optional(),userLocation:object({type:literal("approximate"),country:string$2().optional(),city:string$2().optional(),region:string$2().optional(),timezone:string$2().optional()}).optional()}))),webSearchPreviewInputSchema=lazySchema(()=>zodSchema(object({}))),webSearchPreviewOutputSchema=lazySchema(()=>zodSchema(object({action:discriminatedUnion("type",[object({type:literal("search"),query:string$2().optional()}),object({type:literal("openPage"),url:string$2().nullish()}),object({type:literal("findInPage"),url:string$2().nullish(),pattern:string$2().nullish()})]).optional()}))),webSearchPreview=createProviderExecutedToolFactory({id:"openai.web_search_preview",inputSchema:webSearchPreviewInputSchema,outputSchema:webSearchPreviewOutputSchema}),jsonValueSchema=lazy(()=>union([string$2(),number$2(),boolean$1(),_null(),array(jsonValueSchema),record$2(string$2(),jsonValueSchema)])),mcpArgsSchema=lazySchema(()=>zodSchema(object({serverLabel:string$2(),allowedTools:union([array(string$2()),object({readOnly:boolean$1().optional(),toolNames:array(string$2()).optional()})]).optional(),authorization:string$2().optional(),connectorId:string$2().optional(),headers:record$2(string$2(),string$2()).optional(),requireApproval:union([_enum(["always","never"]),object({never:object({toolNames:array(string$2()).optional()}).optional()})]).optional(),serverDescription:string$2().optional(),serverUrl:string$2().optional()}).refine(Au=>Au.serverUrl!=null||Au.connectorId!=null,"One of serverUrl or connectorId must be provided."))),mcpInputSchema=lazySchema(()=>zodSchema(object({}))),mcpOutputSchema=lazySchema(()=>zodSchema(object({type:literal("call"),serverLabel:string$2(),name:string$2(),arguments:string$2(),output:string$2().nullish(),error:union([string$2(),jsonValueSchema]).optional()}))),mcpToolFactory=createProviderExecutedToolFactory({id:"openai.mcp",inputSchema:mcpInputSchema,outputSchema:mcpOutputSchema}),mcp=Au=>mcpToolFactory(Au),programmaticToolCallingInputSchema=lazySchema(()=>zodSchema(object({code:string$2(),fingerprint:string$2()}))),programmaticToolCallingOutputSchema=lazySchema(()=>zodSchema(object({result:string$2(),status:_enum(["completed","incomplete"])}))),programmaticToolCallingFactory=createProviderExecutedToolFactory({id:"openai.programmatic_tool_calling",inputSchema:programmaticToolCallingInputSchema,outputSchema:programmaticToolCallingOutputSchema,supportsDeferredResults:!0}),programmaticToolCalling=()=>programmaticToolCallingFactory({}),openaiTools={applyPatch,customTool,codeInterpreter,computer,fileSearch,imageGeneration,localShell,shell,webSearchPreview,webSearch,mcp,programmaticToolCalling,toolSearch};function parseOpenAIRealtimeServerEvent(Au){var lo,$u,Ru,Iu,Pu,Ou,Mu,Du,Lu,Bu,ju,Fu,zu,Uu,Hu,Vu,Gu,Wu,Ku;const Ju=Au,Yu=Ju.type;switch(Yu){case"session.created":return{type:"session-created",sessionId:(lo=Ju.session)==null?void 0:lo.id,raw:Au};case"session.updated":return{type:"session-updated",raw:Au};case"input_audio_buffer.speech_started":return{type:"speech-started",itemId:Ju.item_id,raw:Au};case"input_audio_buffer.speech_stopped":return{type:"speech-stopped",itemId:Ju.item_id,raw:Au};case"input_audio_buffer.committed":return{type:"audio-committed",itemId:Ju.item_id,previousItemId:Ju.previous_item_id,raw:Au};case"conversation.item.added":return{type:"conversation-item-added",itemId:(Ru=($u=Ju.item)==null?void 0:$u.id)!=null?Ru:Ju.item_id,item:Ju.item,raw:Au};case"conversation.item.input_audio_transcription.completed":return{type:"input-transcription-completed",itemId:Ju.item_id,transcript:(Iu=Ju.transcript)!=null?Iu:"",raw:Au};case"response.created":return{type:"response-created",responseId:(Ou=(Pu=Ju.response)==null?void 0:Pu.id)!=null?Ou:Ju.response_id,raw:Au};case"response.done":return{type:"response-done",responseId:(Du=(Mu=Ju.response)==null?void 0:Mu.id)!=null?Du:Ju.response_id,status:(Bu=(Lu=Ju.response)==null?void 0:Lu.status)!=null?Bu:"completed",raw:Au};case"response.output_item.added":return{type:"output-item-added",responseId:Ju.response_id,itemId:(Fu=(ju=Ju.item)==null?void 0:ju.id)!=null?Fu:Ju.item_id,raw:Au};case"response.output_item.done":return{type:"output-item-done",responseId:Ju.response_id,itemId:(Uu=(zu=Ju.item)==null?void 0:zu.id)!=null?Uu:Ju.item_id,raw:Au};case"response.content_part.added":return{type:"content-part-added",responseId:Ju.response_id,itemId:Ju.item_id,raw:Au};case"response.content_part.done":return{type:"content-part-done",responseId:Ju.response_id,itemId:Ju.item_id,raw:Au};case"response.output_audio.delta":return{type:"audio-delta",responseId:Ju.response_id,itemId:Ju.item_id,delta:Ju.delta,raw:Au};case"response.output_audio.done":return{type:"audio-done",responseId:Ju.response_id,itemId:Ju.item_id,raw:Au};case"response.output_audio_transcript.delta":return{type:"audio-transcript-delta",responseId:Ju.response_id,itemId:Ju.item_id,delta:Ju.delta,raw:Au};case"response.output_audio_transcript.done":return{type:"audio-transcript-done",responseId:Ju.response_id,itemId:Ju.item_id,transcript:Ju.transcript,raw:Au};case"response.output_text.delta":return{type:"text-delta",responseId:Ju.response_id,itemId:Ju.item_id,delta:Ju.delta,raw:Au};case"response.output_text.done":return{type:"text-done",responseId:Ju.response_id,itemId:Ju.item_id,text:Ju.text,raw:Au};case"response.function_call_arguments.delta":return{type:"function-call-arguments-delta",responseId:Ju.response_id,itemId:Ju.item_id,callId:Ju.call_id,delta:Ju.delta,raw:Au};case"response.function_call_arguments.done":return{type:"function-call-arguments-done",responseId:Ju.response_id,itemId:Ju.item_id,callId:Ju.call_id,name:Ju.name,arguments:Ju.arguments,raw:Au};case"error":return{type:"error",message:(Gu=(Vu=(Hu=Ju.error)==null?void 0:Hu.message)!=null?Vu:Ju.message)!=null?Gu:"Unknown error",code:(Ku=(Wu=Ju.error)==null?void 0:Wu.code)!=null?Ku:Ju.code,raw:Au};default:return{type:"custom",rawType:Yu,raw:Au}}}function serializeOpenAIRealtimeClientEvent(Au,lo){switch(Au.type){case"session-update":return{type:"session.update",session:buildOpenAISessionConfig(Au.config,lo)};case"input-audio-append":return{type:"input_audio_buffer.append",audio:Au.audio};case"input-audio-commit":return{type:"input_audio_buffer.commit"};case"input-audio-clear":return{type:"input_audio_buffer.clear"};case"conversation-item-create":{const $u=Au.item;switch($u.type){case"text-message":return{type:"conversation.item.create",item:{type:"message",role:$u.role,content:[{type:"input_text",text:$u.text}]}};case"audio-message":return{type:"conversation.item.create",item:{type:"message",role:$u.role,content:[{type:"input_audio",audio:$u.audio}]}};case"function-call-output":return{type:"conversation.item.create",item:{type:"function_call_output",call_id:$u.callId,output:$u.output}}}break}case"conversation-item-truncate":return{type:"conversation.item.truncate",item_id:Au.itemId,content_index:Au.contentIndex,audio_end_ms:Au.audioEndMs};case"response-create":return{type:"response.create",...Au.options!=null?{response:{...Au.options.modalities!=null?{output_modalities:Au.options.modalities}:{},...Au.options.instructions!=null?{instructions:Au.options.instructions}:{},...Au.options.metadata!=null?{metadata:Au.options.metadata}:{}}}:{}};case"response-cancel":return{type:"response.cancel"}}}function buildOpenAISessionConfig(Au,lo){var $u;const Ru={type:"realtime",model:lo};Au.instructions!=null&&(Ru.instructions=Au.instructions),Au.outputModalities!=null&&(Ru.output_modalities=Au.outputModalities);const Iu={};if(Au.inputAudioFormat!=null||Au.inputAudioTranscription!=null||Au.turnDetection!=null){const Pu={};if(Au.inputAudioFormat!=null&&(Pu.format={type:Au.inputAudioFormat.type,...Au.inputAudioFormat.rate!=null?{rate:Au.inputAudioFormat.rate}:{}}),Au.turnDetection!=null)if(Au.turnDetection.type==="disabled")Pu.turn_detection=null;else{const Ou={type:Au.turnDetection.type==="server-vad"?"server_vad":"semantic_vad"};Au.turnDetection.threshold!=null&&(Ou.threshold=Au.turnDetection.threshold),Au.turnDetection.silenceDurationMs!=null&&(Ou.silence_duration_ms=Au.turnDetection.silenceDurationMs),Au.turnDetection.prefixPaddingMs!=null&&(Ou.prefix_padding_ms=Au.turnDetection.prefixPaddingMs),Pu.turn_detection=Ou}Au.inputAudioTranscription!=null&&(Pu.transcription={model:($u=Au.inputAudioTranscription.model)!=null?$u:"gpt-realtime-whisper",...Au.inputAudioTranscription.language!=null?{language:Au.inputAudioTranscription.language}:{},...Au.inputAudioTranscription.prompt!=null?{prompt:Au.inputAudioTranscription.prompt}:{}}),Iu.input=Pu}if(Au.outputAudioFormat!=null||Au.voice!=null){const Pu={};Au.outputAudioFormat!=null&&(Pu.format={type:Au.outputAudioFormat.type,...Au.outputAudioFormat.rate!=null?{rate:Au.outputAudioFormat.rate}:{}}),Au.voice!=null&&(Pu.voice=Au.voice),Iu.output=Pu}return Object.keys(Iu).length>0&&(Ru.audio=Iu),Au.tools!=null&&Au.tools.length>0&&(Ru.tools=Au.tools.map(Pu=>({type:Pu.type,name:Pu.name,description:Pu.description,parameters:Pu.parameters})),Ru.tool_choice="auto"),Au.providerOptions!=null&&Object.assign(Ru,Au.providerOptions),Ru}var OpenAIRealtimeModel=class{constructor(Au,lo){this.specificationVersion="v4",this.modelId=Au,this.provider=lo.provider,this.config=lo}async doCreateClientSecret(Au){var lo;const $u=(lo=this.config.fetch)!=null?lo:fetch,Ru=`${this.config.baseURL}/realtime/client_secrets`,Iu=Au.sessionConfig!=null?buildOpenAISessionConfig(Au.sessionConfig,this.modelId):{type:"realtime",model:this.modelId},Pu=await $u(Ru,{method:"POST",headers:{...this.config.headers(),"Content-Type":"application/json"},body:JSON.stringify({session:Iu,...Au.expiresAfterSeconds!=null?{expires_after:{anchor:"created_at",seconds:Au.expiresAfterSeconds}}:{}})});if(!Pu.ok){const Mu=await Pu.text();throw new Error(`OpenAI realtime client secret request failed: ${Pu.status} ${Mu}`)}const Ou=await Pu.json();return{token:Ou.value,url:`wss://${new URL(this.config.baseURL).host}/v1/realtime?model=${encodeURIComponent(this.modelId)}`,expiresAt:Ou.expires_at}}getWebSocketConfig(Au){return{url:Au.url,protocols:["realtime",`openai-insecure-api-key.${Au.token}`]}}parseServerEvent(Au){return parseOpenAIRealtimeServerEvent(Au)}serializeClientEvent(Au){return serializeOpenAIRealtimeClientEvent(Au,this.modelId)}buildSessionConfig(Au){return buildOpenAISessionConfig(Au,this.modelId)}};function convertOpenAIResponsesUsage(Au){var lo,$u,Ru,Iu,Pu,Ou;if(Au==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const Mu=Au.input_tokens,Du=Au.output_tokens,Lu=($u=(lo=Au.input_tokens_details)==null?void 0:lo.cached_tokens)!=null?$u:0,Bu=(Iu=(Ru=Au.input_tokens_details)==null?void 0:Ru.cache_write_tokens)!=null?Iu:void 0,ju=(Ou=(Pu=Au.output_tokens_details)==null?void 0:Pu.reasoning_tokens)!=null?Ou:0;return{inputTokens:{total:Mu,noCache:Mu-Lu-(Bu??0),cacheRead:Lu,cacheWrite:Bu},outputTokens:{total:Du,text:Du-ju,reasoning:ju},raw:Au}}function serializeToolCallArguments2(Au){return JSON.stringify(Au===void 0?{}:Au)}function mapToolCaller(Au){return Au==null?void 0:Au.type==="program"?{type:"program",caller_id:Au.callerId}:Au}function getPromptCacheBreakpoint2(Au,lo){var $u;return($u=Au?.[lo])==null?void 0:$u.promptCacheBreakpoint}function isFileId(Au,lo){return lo?lo.some($u=>Au.startsWith($u)):!1}async function convertToOpenAIResponsesInput({prompt:Au,toolNameMapping:lo,systemMessageMode:$u,providerOptionsName:Ru,fileIdPrefixes:Iu,passThroughUnsupportedFiles:Pu=!1,store:Ou,hasConversation:Mu=!1,hasPreviousResponseId:Du=!1,hasLocalShellTool:Lu=!1,hasShellTool:Bu=!1,hasApplyPatchTool:ju=!1,hasComputerTool:Fu=!1,customProviderToolNames:zu}){var Uu,Hu,Vu,Gu,Wu,Ku,Ju,Yu,Xu,ed,td,nd,od,sd,ad,pd,gd,yd,_d,bd,wd,Ed,cd,ud,md,ld,hd,vd,Sd,kd,Rd,Od,jd,Cd,Ad,$d,Vd,Dd;let Hd=[];const rh=[],Jd=new Set;for(const{role:vh,content:sh,providerOptions:Eh}of Au)switch(vh){case"system":{switch($u){case"system":{const bh=getPromptCacheBreakpoint2(Eh,Ru);Hd.push({role:"system",content:bh==null?sh:[{type:"input_text",text:sh,prompt_cache_breakpoint:bh}]});break}case"developer":{const bh=getPromptCacheBreakpoint2(Eh,Ru);Hd.push({role:"developer",content:bh==null?sh:[{type:"input_text",text:sh,prompt_cache_breakpoint:bh}]});break}case"remove":{rh.push({type:"other",message:"system messages are removed for this model"});break}default:{const bh=$u;throw new Error(`Unsupported system message mode: ${bh}`)}}break}case"user":{Hd.push({role:"user",content:sh.map((bh,Qd)=>{var th,uh,Ph,Gd,Fd;switch(bh.type){case"text":{const Id=getPromptCacheBreakpoint2(bh.providerOptions,Ru);return{type:"input_text",text:bh.text,...Id!=null&&{prompt_cache_breakpoint:Id}}}case"file":{const Id=getPromptCacheBreakpoint2(bh.providerOptions,Ru);switch(bh.data.type){case"reference":{const Pd=resolveProviderReference({reference:bh.data.reference,provider:Ru});return getTopLevelMediaType(bh.mediaType)==="image"?{type:"input_image",file_id:Pd,detail:(uh=(th=bh.providerOptions)==null?void 0:th[Ru])==null?void 0:uh.imageDetail,...Id!=null&&{prompt_cache_breakpoint:Id}}:{type:"input_file",file_id:Pd,...Id!=null&&{prompt_cache_breakpoint:Id}}}case"text":throw new UnsupportedFunctionalityError({functionality:"text file parts"});case"url":case"data":{if(getTopLevelMediaType(bh.mediaType)==="image")return{type:"input_image",...bh.data.type==="url"?{image_url:bh.data.url.toString()}:typeof bh.data.data=="string"&&isFileId(bh.data.data,Iu)?{file_id:bh.data.data}:{image_url:`data:${resolveFullMediaType({part:bh})};base64,${convertToBase64(bh.data.data)}`},detail:(Gd=(Ph=bh.providerOptions)==null?void 0:Ph[Ru])==null?void 0:Gd.imageDetail,...Id!=null&&{prompt_cache_breakpoint:Id}};{if(bh.data.type==="url")return{type:"input_file",file_url:bh.data.url.toString(),...Id!=null&&{prompt_cache_breakpoint:Id}};const Wd=resolveFullMediaType({part:bh});if(Wd!=="application/pdf"&&!Pu)throw new UnsupportedFunctionalityError({functionality:`file part media type ${Wd}`});return{type:"input_file",...typeof bh.data.data=="string"&&isFileId(bh.data.data,Iu)?{file_id:bh.data.data}:{filename:(Fd=bh.filename)!=null?Fd:Wd==="application/pdf"?`part-${Qd}.pdf`:`part-${Qd}`,file_data:`data:${Wd};base64,${convertToBase64(bh.data.data)}`},...Id!=null&&{prompt_cache_breakpoint:Id}}}}}}}})});break}case"assistant":{const bh={};for(const Qd of sh)switch(Qd.type){case"text":{const th=(Uu=Qd.providerOptions)==null?void 0:Uu[Ru],uh=th?.itemId,Ph=th?.phase;if(Mu&&uh!=null)break;if(Ou&&uh!=null){Hd.push({type:"item_reference",id:uh});break}Hd.push({role:"assistant",content:[{type:"output_text",text:Qd.text}],id:uh,...Ph!=null&&{phase:Ph}});break}case"tool-call":{const th=(Ku=(Vu=(Hu=Qd.providerOptions)==null?void 0:Hu[Ru])==null?void 0:Vu.itemId)!=null?Ku:(Wu=(Gu=Qd.providerMetadata)==null?void 0:Gu[Ru])==null?void 0:Wu.itemId,uh=(td=(Yu=(Ju=Qd.providerOptions)==null?void 0:Ju[Ru])==null?void 0:Yu.namespace)!=null?td:(ed=(Xu=Qd.providerMetadata)==null?void 0:Xu[Ru])==null?void 0:ed.namespace,Ph=(od=(nd=Qd.providerOptions)==null?void 0:nd[Ru])==null?void 0:od.caller;if(Mu&&th!=null)break;const Gd=lo.toProviderToolName(Qd.toolName);if(Gd==="tool_search"){if(Ou&&th!=null){Hd.push({type:"item_reference",id:th});break}const Id=typeof Qd.input=="string"?await parseJSON({text:Qd.input,schema:toolSearchInputSchema}):await validateTypes({value:Qd.input,schema:toolSearchInputSchema}),Pd=Id.call_id!=null?"client":"server";Hd.push({type:"tool_search_call",id:th??Qd.toolCallId,execution:Pd,call_id:(sd=Id.call_id)!=null?sd:null,status:"completed",arguments:Id.arguments});break}if(Gd==="programmatic_tool_calling"){if(Ou&&th!=null){Hd.push({type:"item_reference",id:th});break}const Id=await validateTypes({value:Qd.input,schema:programmaticToolCallingInputSchema});Hd.push({type:"program",id:th??Qd.toolCallId,call_id:Qd.toolCallId,code:Id.code,fingerprint:Id.fingerprint});break}if(Qd.providerExecuted){Ou&&th!=null&&Hd.push({type:"item_reference",id:th});break}if(Du&&Ou&&th!=null)break;const Fd=Lu&&Gd==="local_shell"||Bu&&Gd==="shell"||ju&&Gd==="apply_patch"||Fu&&Gd==="computer"||((ad=zu?.has(Gd))!=null?ad:!1);if(Ou&&th!=null&&Fd){Hd.push({type:"item_reference",id:th});break}if(Lu&&Gd==="local_shell"){const Id=await validateTypes({value:Qd.input,schema:localShellInputSchema});Hd.push({type:"local_shell_call",call_id:Qd.toolCallId,id:th,action:{type:"exec",command:Id.action.command,timeout_ms:Id.action.timeoutMs,user:Id.action.user,working_directory:Id.action.workingDirectory,env:Id.action.env}});break}if(Bu&&Gd==="shell"){const Id=await validateTypes({value:Qd.input,schema:shellInputSchema});Hd.push({type:"shell_call",call_id:Qd.toolCallId,id:th,status:"completed",action:{commands:Id.action.commands,timeout_ms:Id.action.timeoutMs,max_output_length:Id.action.maxOutputLength}});break}if(ju&&Gd==="apply_patch"){const Id=await validateTypes({value:Qd.input,schema:applyPatchInputSchema});Hd.push({type:"apply_patch_call",call_id:Id.callId,id:th,status:"completed",operation:Id.operation});break}if(Fu&&Gd==="computer"){const Id=await validateTypes({value:Qd.input,schema:computerInputSchema});Hd.push({type:"computer_call",call_id:Qd.toolCallId,id:th,status:Id.status,actions:Id.actions.map(Pd=>{switch(Pd.type){case"click":case"double_click":case"move":return{...Pd,keys:Pd.keys};case"drag":return{...Pd,keys:Pd.keys};case"scroll":return{type:"scroll",x:Pd.x,y:Pd.y,scroll_x:Pd.scrollX,scroll_y:Pd.scrollY,keys:Pd.keys};default:return Pd}}),pending_safety_checks:Id.pendingSafetyChecks.map(Pd=>({id:Pd.id,code:Pd.code,message:Pd.message}))});break}if(zu?.has(Gd)){Hd.push({type:"custom_tool_call",call_id:Qd.toolCallId,name:Gd,input:typeof Qd.input=="string"?Qd.input:JSON.stringify(Qd.input),id:th});break}Hd.push({type:"function_call",call_id:Qd.toolCallId,name:Gd,arguments:serializeToolCallArguments2(Qd.input),...uh!=null&&{namespace:uh},...Ph!=null&&{caller:mapToolCaller(Ph)}});break}case"tool-result":{if(Qd.output.type==="execution-denied"||Qd.output.type==="json"&&typeof Qd.output.value=="object"&&Qd.output.value!=null&&"type"in Qd.output.value&&Qd.output.value.type==="execution-denied"||Mu)break;const th=lo.toProviderToolName(Qd.toolName);if(th==="tool_search"){const uh=(wd=(bd=(gd=(pd=Qd.providerOptions)==null?void 0:pd[Ru])==null?void 0:gd.itemId)!=null?bd:(_d=(yd=Qd.providerMetadata)==null?void 0:yd[Ru])==null?void 0:_d.itemId)!=null?wd:Qd.toolCallId;if(Ou)Hd.push({type:"item_reference",id:uh});else if(Qd.output.type==="json"){const Ph=await validateTypes({value:Qd.output.value,schema:toolSearchOutputSchema});Hd.push({type:"tool_search_output",id:uh,execution:"server",call_id:null,status:"completed",tools:Ph.tools})}break}if(th==="programmatic_tool_calling"){const uh=(hd=(ld=(cd=(Ed=Qd.providerOptions)==null?void 0:Ed[Ru])==null?void 0:cd.itemId)!=null?ld:(md=(ud=Qd.providerMetadata)==null?void 0:ud[Ru])==null?void 0:md.itemId)!=null?hd:Qd.toolCallId;if(Ou)Hd.push({type:"item_reference",id:uh});else if(Qd.output.type==="json"){const Ph=await validateTypes({value:Qd.output.value,schema:programmaticToolCallingOutputSchema});Hd.push({type:"program_output",id:uh,call_id:Qd.toolCallId,result:Ph.result,status:Ph.status})}break}if(Bu&&th==="shell"){if(Qd.output.type==="json"){const uh=await validateTypes({value:Qd.output.value,schema:shellOutputSchema});Hd.push({type:"shell_call_output",call_id:Qd.toolCallId,output:uh.output.map(Ph=>({stdout:Ph.stdout,stderr:Ph.stderr,outcome:Ph.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:Ph.outcome.exitCode}}))})}break}if(Ou){const uh=(kd=(Sd=(vd=Qd.providerOptions)==null?void 0:vd[Ru])==null?void 0:Sd.itemId)!=null?kd:Qd.toolCallId;Hd.push({type:"item_reference",id:uh})}else rh.push({type:"other",message:`Results for OpenAI tool ${Qd.toolName} are not sent to the API when store is false`});break}case"reasoning":{const th=await parseProviderOptions({provider:Ru,providerOptions:Qd.providerOptions,schema:openaiResponsesReasoningProviderOptionsSchema}),uh=th?.itemId;if((Mu||Du)&&uh!=null)break;if(uh!=null){const Ph=bh[uh];if(Ou)Ph===void 0&&(Hd.push({type:"item_reference",id:uh}),bh[uh]={type:"reasoning",id:uh,summary:[]});else{const Gd=[];Qd.text.length>0?Gd.push({type:"summary_text",text:Qd.text}):Ph!==void 0&&rh.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(Qd)}.`}),Ph===void 0?(bh[uh]={type:"reasoning",id:uh,encrypted_content:th?.reasoningEncryptedContent,summary:Gd},Hd.push(bh[uh])):(Ph.summary.push(...Gd),th?.reasoningEncryptedContent!=null&&(Ph.encrypted_content=th.reasoningEncryptedContent))}}else{const Ph=th?.reasoningEncryptedContent;if(Ph!=null){const Gd=[];Qd.text.length>0&&Gd.push({type:"summary_text",text:Qd.text}),Hd.push({type:"reasoning",encrypted_content:Ph,summary:Gd})}else rh.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(Qd)}.`})}break}case"custom":{if(Qd.kind==="openai.compaction"){const th=(Rd=Qd.providerOptions)==null?void 0:Rd[Ru],uh=th?.itemId;if(Mu&&uh!=null)break;if(Ou&&uh!=null){Hd.push({type:"item_reference",id:uh});break}const Ph=th?.encryptedContent;uh!=null&&Hd.push({type:"compaction",id:uh,encrypted_content:Ph})}break}}break}case"tool":{for(const bh of sh){if(bh.type==="tool-approval-response"){const Gd=bh;if(Jd.has(Gd.approvalId))continue;Jd.add(Gd.approvalId),Ou&&Hd.push({type:"item_reference",id:Gd.approvalId}),Hd.push({type:"mcp_approval_response",approval_request_id:Gd.approvalId,approve:Gd.approved});continue}const Qd=bh.output;if(Qd.type==="execution-denied"&&((jd=(Od=Qd.providerOptions)==null?void 0:Od.openai)==null?void 0:jd.approvalId))continue;const th=lo.toProviderToolName(bh.toolName);if(th==="tool_search"&&Qd.type==="json"){const Gd=await validateTypes({value:Qd.value,schema:toolSearchOutputSchema});Hd.push({type:"tool_search_output",execution:"client",call_id:bh.toolCallId,status:"completed",tools:Gd.tools});continue}if(Lu&&th==="local_shell"&&Qd.type==="json"){const Gd=await validateTypes({value:Qd.value,schema:localShellOutputSchema});Hd.push({type:"local_shell_call_output",call_id:bh.toolCallId,output:Gd.output});continue}if(Bu&&th==="shell"&&Qd.type==="json"){const Gd=await validateTypes({value:Qd.value,schema:shellOutputSchema});Hd.push({type:"shell_call_output",call_id:bh.toolCallId,output:Gd.output.map(Fd=>({stdout:Fd.stdout,stderr:Fd.stderr,outcome:Fd.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:Fd.outcome.exitCode}}))});continue}if(ju&&bh.toolName==="apply_patch"&&Qd.type==="json"){const Gd=await validateTypes({value:Qd.value,schema:applyPatchOutputSchema});Hd.push({type:"apply_patch_call_output",call_id:bh.toolCallId,status:Gd.status,output:Gd.output});continue}if(Fu&&th==="computer"&&Qd.type==="json"){const Gd=await validateTypes({value:Qd.value,schema:computerOutputSchema});Hd.push({type:"computer_call_output",call_id:bh.toolCallId,output:{type:"computer_screenshot",image_url:Gd.output.imageUrl,file_id:Gd.output.fileId,detail:Gd.output.detail},acknowledged_safety_checks:(Cd=Gd.acknowledgedSafetyChecks)==null?void 0:Cd.map(Fd=>({id:Fd.id,code:Fd.code,message:Fd.message}))});continue}if(zu?.has(th)){let Gd;switch(Qd.type){case"text":case"error-text":Gd=Qd.value;break;case"execution-denied":Gd=(Ad=Qd.reason)!=null?Ad:"Tool call execution denied.";break;case"json":case"error-json":Gd=JSON.stringify(Qd.value);break;case"content":Gd=Qd.value.map(Fd=>{var Id,Pd,Wd;const Ld=getPromptCacheBreakpoint2(Fd.providerOptions,Ru);switch(Fd.type){case"text":return{type:"input_text",text:Fd.text,...Ld!=null&&{prompt_cache_breakpoint:Ld}};case"file":{const Kd=getTopLevelMediaType(Fd.mediaType),Xd=(Pd=(Id=Fd.providerOptions)==null?void 0:Id[Ru])==null?void 0:Pd.imageDetail;if(Fd.data.type==="data"){const mh=resolveFullMediaType({part:Fd});return Kd==="image"?{type:"input_image",image_url:`data:${mh};base64,${convertToBase64(Fd.data.data)}`,detail:Xd,...Ld!=null&&{prompt_cache_breakpoint:Ld}}:{type:"input_file",filename:(Wd=Fd.filename)!=null?Wd:"data",file_data:`data:${mh};base64,${convertToBase64(Fd.data.data)}`,...Ld!=null&&{prompt_cache_breakpoint:Ld}}}if(Fd.data.type==="url")return Kd==="image"?{type:"input_image",image_url:Fd.data.url.toString(),detail:Xd,...Ld!=null&&{prompt_cache_breakpoint:Ld}}:{type:"input_file",file_url:Fd.data.url.toString(),...Ld!=null&&{prompt_cache_breakpoint:Ld}};rh.push({type:"other",message:`unsupported custom tool content part type: ${Fd.type} with data type: ${Fd.data.type}`});return}default:rh.push({type:"other",message:`unsupported custom tool content part type: ${Fd.type}`});return}}).filter(isNonNullable);break;default:Gd=""}Hd.push({type:"custom_tool_call_output",call_id:bh.toolCallId,output:Gd});continue}let uh;switch(Qd.type){case"text":case"error-text":uh=Qd.value;break;case"execution-denied":uh=($d=Qd.reason)!=null?$d:"Tool call execution denied.";break;case"json":case"error-json":uh=JSON.stringify(Qd.value);break;case"content":uh=Qd.value.map(Gd=>{var Fd,Id,Pd;const Wd=getPromptCacheBreakpoint2(Gd.providerOptions,Ru);switch(Gd.type){case"text":return{type:"input_text",text:Gd.text,...Wd!=null&&{prompt_cache_breakpoint:Wd}};case"file":{const Ld=getTopLevelMediaType(Gd.mediaType),Kd=(Id=(Fd=Gd.providerOptions)==null?void 0:Fd[Ru])==null?void 0:Id.imageDetail;if(Gd.data.type==="data"){const Xd=resolveFullMediaType({part:Gd});return Ld==="image"?{type:"input_image",image_url:`data:${Xd};base64,${convertToBase64(Gd.data.data)}`,detail:Kd,...Wd!=null&&{prompt_cache_breakpoint:Wd}}:{type:"input_file",filename:(Pd=Gd.filename)!=null?Pd:"data",file_data:`data:${Xd};base64,${convertToBase64(Gd.data.data)}`,...Wd!=null&&{prompt_cache_breakpoint:Wd}}}if(Gd.data.type==="url")return Ld==="image"?{type:"input_image",image_url:Gd.data.url.toString(),detail:Kd,...Wd!=null&&{prompt_cache_breakpoint:Wd}}:{type:"input_file",file_url:Gd.data.url.toString(),...Wd!=null&&{prompt_cache_breakpoint:Wd}};rh.push({type:"other",message:`unsupported tool content part type: ${Gd.type} with data type: ${Gd.data.type}`});return}default:{rh.push({type:"other",message:`unsupported tool content part type: ${Gd.type}`});return}}}).filter(isNonNullable);break}const Ph=mapToolCaller((Dd=(Vd=bh.providerOptions)==null?void 0:Vd[Ru])==null?void 0:Dd.caller);Hd.push({type:"function_call_output",call_id:bh.toolCallId,output:uh,...Ph!=null&&{caller:Ph}})}break}default:{const bh=vh;throw new Error(`Unsupported role: ${bh}`)}}return!Ou&&Hd.some(vh=>"type"in vh&&vh.type==="reasoning"&&vh.encrypted_content==null)&&(rh.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),Hd=Hd.filter(vh=>!("type"in vh)||vh.type!=="reasoning"||vh.encrypted_content!=null)),{input:Hd,warnings:rh}}var openaiResponsesReasoningProviderOptionsSchema=object({itemId:string$2().nullish(),reasoningEncryptedContent:string$2().nullish()});function mapOpenAIResponseFinishReason({finishReason:Au,hasFunctionCall:lo}){switch(Au){case void 0:case null:return lo?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return lo?"tool-calls":"other"}}var jsonValueSchema2=lazy(()=>union([string$2(),number$2(),boolean$1(),_null(),array(jsonValueSchema2),record$2(string$2(),jsonValueSchema2.optional())])),openaiResponsesComputerSafetyCheckSchema=object({id:string$2(),code:string$2().nullish(),message:string$2().nullish()}),openaiResponsesComputerActionSchema=discriminatedUnion("type",[object({type:literal("click"),button:_enum(["left","right","wheel","back","forward"]),x:number$2(),y:number$2(),keys:array(string$2()).nullish()}),object({type:literal("double_click"),x:number$2(),y:number$2(),keys:array(string$2()).nullish()}),object({type:literal("drag"),path:array(object({x:number$2(),y:number$2()})),keys:array(string$2()).nullish()}),object({type:literal("keypress"),keys:array(string$2())}),object({type:literal("move"),x:number$2(),y:number$2(),keys:array(string$2()).nullish()}),object({type:literal("screenshot")}),object({type:literal("scroll"),x:number$2(),y:number$2(),scroll_x:number$2(),scroll_y:number$2(),keys:array(string$2()).nullish()}),object({type:literal("type"),text:string$2()}),object({type:literal("wait")})]),openaiResponsesComputerCallSchema=object({type:literal("computer_call"),id:string$2(),call_id:string$2().nullish(),status:_enum(["in_progress","completed","incomplete"]),action:openaiResponsesComputerActionSchema.nullish(),actions:array(openaiResponsesComputerActionSchema).nullish(),pending_safety_checks:array(openaiResponsesComputerSafetyCheckSchema).nullish()}),openaiResponsesToolCallerSchema=discriminatedUnion("type",[object({type:literal("direct")}),object({type:literal("program"),caller_id:string$2()})]),openaiResponsesProgramSchema=object({type:literal("program"),id:string$2(),call_id:string$2(),code:string$2(),fingerprint:string$2()}),openaiResponsesProgramOutputSchema=object({type:literal("program_output"),id:string$2(),call_id:string$2(),result:string$2(),status:_enum(["completed","incomplete"])}),openaiResponsesNestedErrorChunkSchema=object({type:literal("error"),sequence_number:number$2(),error:object({type:string$2(),code:string$2(),message:string$2(),param:string$2().nullish()})}),openaiResponsesErrorChunkSchema=object({type:literal("error"),sequence_number:number$2(),code:string$2().nullish(),message:string$2(),param:string$2().nullish()}),openaiResponsesChunkSchema=lazySchema(()=>zodSchema(union([object({type:literal("response.output_text.delta"),item_id:string$2(),delta:string$2(),logprobs:array(object({token:string$2(),logprob:number$2(),top_logprobs:array(object({token:string$2(),logprob:number$2()}))})).nullish()}),object({type:_enum(["response.completed","response.incomplete"]),response:object({incomplete_details:object({reason:string$2()}).nullish(),usage:object({input_tokens:number$2(),input_tokens_details:object({cached_tokens:number$2().nullish(),cache_write_tokens:number$2().nullish(),orchestration_input_tokens:number$2().nullish(),orchestration_input_cached_tokens:number$2().nullish()}).nullish(),output_tokens:number$2(),output_tokens_details:object({reasoning_tokens:number$2().nullish(),orchestration_output_tokens:number$2().nullish()}).nullish()}),reasoning:object({context:string$2().nullish()}).nullish(),service_tier:string$2().nullish()})}),object({type:literal("response.failed"),sequence_number:number$2(),response:object({error:object({code:string$2().nullish(),message:string$2()}).nullish(),incomplete_details:object({reason:string$2()}).nullish(),usage:object({input_tokens:number$2(),input_tokens_details:object({cached_tokens:number$2().nullish(),cache_write_tokens:number$2().nullish(),orchestration_input_tokens:number$2().nullish(),orchestration_input_cached_tokens:number$2().nullish()}).nullish(),output_tokens:number$2(),output_tokens_details:object({reasoning_tokens:number$2().nullish(),orchestration_output_tokens:number$2().nullish()}).nullish()}).nullish(),reasoning:object({context:string$2().nullish()}).nullish(),service_tier:string$2().nullish()})}),object({type:literal("response.created"),response:object({id:string$2(),created_at:number$2(),model:string$2(),service_tier:string$2().nullish()})}),object({type:literal("response.output_item.added"),output_index:number$2(),item:discriminatedUnion("type",[object({type:literal("message"),id:string$2(),phase:_enum(["commentary","final_answer"]).nullish()}),object({type:literal("reasoning"),id:string$2(),encrypted_content:string$2().nullish()}),object({type:literal("function_call"),id:string$2(),call_id:string$2(),name:string$2(),arguments:string$2(),namespace:string$2().nullish(),caller:openaiResponsesToolCallerSchema.nullish()}),openaiResponsesProgramSchema,openaiResponsesProgramOutputSchema,object({type:literal("web_search_call"),id:string$2(),status:string$2()}),openaiResponsesComputerCallSchema,object({type:literal("file_search_call"),id:string$2()}),object({type:literal("image_generation_call"),id:string$2()}),object({type:literal("code_interpreter_call"),id:string$2(),container_id:string$2(),code:string$2().nullable(),outputs:array(discriminatedUnion("type",[object({type:literal("logs"),logs:string$2()}),object({type:literal("image"),url:string$2()})])).nullable(),status:string$2()}),object({type:literal("mcp_call"),id:string$2(),status:string$2(),approval_request_id:string$2().nullish()}),object({type:literal("mcp_list_tools"),id:string$2()}),object({type:literal("mcp_approval_request"),id:string$2()}),object({type:literal("apply_patch_call"),id:string$2(),call_id:string$2(),status:_enum(["in_progress","completed"]),operation:discriminatedUnion("type",[object({type:literal("create_file"),path:string$2(),diff:string$2()}),object({type:literal("delete_file"),path:string$2()}),object({type:literal("update_file"),path:string$2(),diff:string$2()})])}),object({type:literal("custom_tool_call"),id:string$2(),call_id:string$2(),name:string$2(),input:string$2()}),object({type:literal("shell_call"),id:string$2(),call_id:string$2(),status:_enum(["in_progress","completed","incomplete"]),action:object({commands:array(string$2())})}),object({type:literal("compaction"),id:string$2(),encrypted_content:string$2().nullish()}),object({type:literal("shell_call_output"),id:string$2(),call_id:string$2(),status:_enum(["in_progress","completed","incomplete"]),output:array(object({stdout:string$2(),stderr:string$2(),outcome:discriminatedUnion("type",[object({type:literal("timeout")}),object({type:literal("exit"),exit_code:number$2()})])}))}),object({type:literal("tool_search_call"),id:string$2(),execution:_enum(["server","client"]),call_id:string$2().nullable(),status:_enum(["in_progress","completed","incomplete"]),arguments:unknown$1()}),object({type:literal("tool_search_output"),id:string$2(),execution:_enum(["server","client"]),call_id:string$2().nullable(),status:_enum(["in_progress","completed","incomplete"]),tools:array(record$2(string$2(),jsonValueSchema2.optional()))})])}),object({type:literal("response.output_item.done"),output_index:number$2(),item:discriminatedUnion("type",[object({type:literal("message"),id:string$2(),phase:_enum(["commentary","final_answer"]).nullish()}),object({type:literal("reasoning"),id:string$2(),encrypted_content:string$2().nullish()}),object({type:literal("function_call"),id:string$2(),call_id:string$2(),name:string$2(),arguments:string$2(),status:_enum(["in_progress","completed","incomplete"]),namespace:string$2().nullish(),caller:openaiResponsesToolCallerSchema.nullish()}),openaiResponsesProgramSchema,openaiResponsesProgramOutputSchema,object({type:literal("custom_tool_call"),id:string$2(),call_id:string$2(),name:string$2(),input:string$2(),status:literal("completed")}),object({type:literal("code_interpreter_call"),id:string$2(),code:string$2().nullable(),container_id:string$2(),outputs:array(discriminatedUnion("type",[object({type:literal("logs"),logs:string$2()}),object({type:literal("image"),url:string$2()})])).nullable()}),object({type:literal("image_generation_call"),id:string$2(),result:string$2()}),object({type:literal("web_search_call"),id:string$2(),status:string$2(),action:discriminatedUnion("type",[object({type:literal("search"),query:string$2().nullish(),queries:array(string$2()).nullish(),sources:array(discriminatedUnion("type",[object({type:literal("url"),url:string$2()}),object({type:literal("api"),name:string$2()})])).nullish()}),object({type:literal("open_page"),url:string$2().nullish()}),object({type:literal("find_in_page"),url:string$2().nullish(),pattern:string$2().nullish()})]).nullish()}),object({type:literal("file_search_call"),id:string$2(),queries:array(string$2()),results:array(object({attributes:record$2(string$2(),union([string$2(),number$2(),boolean$1()])),file_id:string$2(),filename:string$2(),score:number$2(),text:string$2()})).nullish()}),object({type:literal("local_shell_call"),id:string$2(),call_id:string$2(),action:object({type:literal("exec"),command:array(string$2()),timeout_ms:number$2().optional(),user:string$2().optional(),working_directory:string$2().optional(),env:record$2(string$2(),string$2()).optional()})}),openaiResponsesComputerCallSchema,object({type:literal("mcp_call"),id:string$2(),status:string$2(),arguments:string$2(),name:string$2(),server_label:string$2(),output:string$2().nullish(),error:union([string$2(),object({type:string$2().optional(),code:union([number$2(),string$2()]).optional(),message:string$2().optional()}).loose()]).nullish(),approval_request_id:string$2().nullish()}),object({type:literal("mcp_list_tools"),id:string$2(),server_label:string$2(),tools:array(object({name:string$2(),description:string$2().optional(),input_schema:any(),annotations:record$2(string$2(),unknown$1()).optional()})),error:union([string$2(),object({type:string$2().optional(),code:union([number$2(),string$2()]).optional(),message:string$2().optional()}).loose()]).optional()}),object({type:literal("mcp_approval_request"),id:string$2(),server_label:string$2(),name:string$2(),arguments:string$2(),approval_request_id:string$2().optional()}),object({type:literal("apply_patch_call"),id:string$2(),call_id:string$2(),status:_enum(["in_progress","completed"]),operation:discriminatedUnion("type",[object({type:literal("create_file"),path:string$2(),diff:string$2()}),object({type:literal("delete_file"),path:string$2()}),object({type:literal("update_file"),path:string$2(),diff:string$2()})])}),object({type:literal("shell_call"),id:string$2(),call_id:string$2(),status:_enum(["in_progress","completed","incomplete"]),action:object({commands:array(string$2())})}),object({type:literal("compaction"),id:string$2(),encrypted_content:string$2()}),object({type:literal("shell_call_output"),id:string$2(),call_id:string$2(),status:_enum(["in_progress","completed","incomplete"]),output:array(object({stdout:string$2(),stderr:string$2(),outcome:discriminatedUnion("type",[object({type:literal("timeout")}),object({type:literal("exit"),exit_code:number$2()})])}))}),object({type:literal("tool_search_call"),id:string$2(),execution:_enum(["server","client"]),call_id:string$2().nullable(),status:_enum(["in_progress","completed","incomplete"]),arguments:unknown$1()}),object({type:literal("tool_search_output"),id:string$2(),execution:_enum(["server","client"]),call_id:string$2().nullable(),status:_enum(["in_progress","completed","incomplete"]),tools:array(record$2(string$2(),jsonValueSchema2.optional()))})])}),object({type:literal("response.function_call_arguments.delta"),item_id:string$2(),output_index:number$2(),delta:string$2()}),object({type:literal("response.custom_tool_call_input.delta"),item_id:string$2(),output_index:number$2(),delta:string$2()}),object({type:literal("response.image_generation_call.partial_image"),item_id:string$2(),output_index:number$2(),partial_image_b64:string$2()}),object({type:literal("response.code_interpreter_call_code.delta"),item_id:string$2(),output_index:number$2(),delta:string$2()}),object({type:literal("response.code_interpreter_call_code.done"),item_id:string$2(),output_index:number$2(),code:string$2()}),object({type:literal("response.output_text.annotation.added"),annotation:discriminatedUnion("type",[object({type:literal("url_citation"),start_index:number$2(),end_index:number$2(),url:string$2(),title:string$2()}),object({type:literal("file_citation"),file_id:string$2(),filename:string$2(),index:number$2()}),object({type:literal("container_file_citation"),container_id:string$2(),file_id:string$2(),filename:string$2(),start_index:number$2(),end_index:number$2()}),object({type:literal("file_path"),file_id:string$2(),index:number$2()})])}),object({type:literal("response.reasoning_summary_part.added"),item_id:string$2(),summary_index:number$2()}),object({type:literal("response.reasoning_summary_text.delta"),item_id:string$2(),summary_index:number$2(),delta:string$2()}),object({type:literal("response.reasoning_summary_part.done"),item_id:string$2(),summary_index:number$2()}),object({type:literal("response.apply_patch_call_operation_diff.delta"),item_id:string$2(),output_index:number$2(),delta:string$2(),obfuscation:string$2().nullish()}),object({type:literal("response.apply_patch_call_operation_diff.done"),item_id:string$2(),output_index:number$2(),diff:string$2()}),openaiResponsesNestedErrorChunkSchema,openaiResponsesErrorChunkSchema,object({type:string$2()}).loose().transform(Au=>({type:"unknown_chunk",message:Au.type}))]))),openaiResponsesResponseSchema=lazySchema(()=>zodSchema(object({id:string$2().optional(),created_at:number$2().optional(),error:object({message:string$2(),type:string$2(),param:string$2().nullish(),code:string$2()}).nullish(),model:string$2().optional(),output:array(discriminatedUnion("type",[object({type:literal("message"),role:literal("assistant"),id:string$2(),phase:_enum(["commentary","final_answer"]).nullish(),content:array(object({type:literal("output_text"),text:string$2(),logprobs:array(object({token:string$2(),logprob:number$2(),top_logprobs:array(object({token:string$2(),logprob:number$2()}))})).nullish(),annotations:array(discriminatedUnion("type",[object({type:literal("url_citation"),start_index:number$2(),end_index:number$2(),url:string$2(),title:string$2()}),object({type:literal("file_citation"),file_id:string$2(),filename:string$2(),index:number$2()}),object({type:literal("container_file_citation"),container_id:string$2(),file_id:string$2(),filename:string$2(),start_index:number$2(),end_index:number$2()}),object({type:literal("file_path"),file_id:string$2(),index:number$2()})]))}))}),object({type:literal("web_search_call"),id:string$2(),status:string$2(),action:discriminatedUnion("type",[object({type:literal("search"),query:string$2().nullish(),queries:array(string$2()).nullish(),sources:array(discriminatedUnion("type",[object({type:literal("url"),url:string$2()}),object({type:literal("api"),name:string$2()})])).nullish()}),object({type:literal("open_page"),url:string$2().nullish()}),object({type:literal("find_in_page"),url:string$2().nullish(),pattern:string$2().nullish()})]).nullish()}),object({type:literal("file_search_call"),id:string$2(),queries:array(string$2()),results:array(object({attributes:record$2(string$2(),union([string$2(),number$2(),boolean$1()])),file_id:string$2(),filename:string$2(),score:number$2(),text:string$2()})).nullish()}),object({type:literal("code_interpreter_call"),id:string$2(),code:string$2().nullable(),container_id:string$2(),outputs:array(discriminatedUnion("type",[object({type:literal("logs"),logs:string$2()}),object({type:literal("image"),url:string$2()})])).nullable()}),object({type:literal("image_generation_call"),id:string$2(),result:string$2()}),object({type:literal("local_shell_call"),id:string$2(),call_id:string$2(),action:object({type:literal("exec"),command:array(string$2()),timeout_ms:number$2().optional(),user:string$2().optional(),working_directory:string$2().optional(),env:record$2(string$2(),string$2()).optional()})}),object({type:literal("function_call"),call_id:string$2(),name:string$2(),arguments:string$2(),id:string$2(),namespace:string$2().nullish(),caller:openaiResponsesToolCallerSchema.nullish()}),openaiResponsesProgramSchema,openaiResponsesProgramOutputSchema,object({type:literal("custom_tool_call"),call_id:string$2(),name:string$2(),input:string$2(),id:string$2()}),openaiResponsesComputerCallSchema,object({type:literal("reasoning"),id:string$2(),encrypted_content:string$2().nullish(),summary:array(object({type:literal("summary_text"),text:string$2()}))}),object({type:literal("mcp_call"),id:string$2(),status:string$2(),arguments:string$2(),name:string$2(),server_label:string$2(),output:string$2().nullish(),error:union([string$2(),object({type:string$2().optional(),code:union([number$2(),string$2()]).optional(),message:string$2().optional()}).loose()]).nullish(),approval_request_id:string$2().nullish()}),object({type:literal("mcp_list_tools"),id:string$2(),server_label:string$2(),tools:array(object({name:string$2(),description:string$2().optional(),input_schema:any(),annotations:record$2(string$2(),unknown$1()).optional()})),error:union([string$2(),object({type:string$2().optional(),code:union([number$2(),string$2()]).optional(),message:string$2().optional()}).loose()]).optional()}),object({type:literal("mcp_approval_request"),id:string$2(),server_label:string$2(),name:string$2(),arguments:string$2(),approval_request_id:string$2().optional()}),object({type:literal("apply_patch_call"),id:string$2(),call_id:string$2(),status:_enum(["in_progress","completed"]),operation:discriminatedUnion("type",[object({type:literal("create_file"),path:string$2(),diff:string$2()}),object({type:literal("delete_file"),path:string$2()}),object({type:literal("update_file"),path:string$2(),diff:string$2()})])}),object({type:literal("shell_call"),id:string$2(),call_id:string$2(),status:_enum(["in_progress","completed","incomplete"]),action:object({commands:array(string$2())})}),object({type:literal("compaction"),id:string$2(),encrypted_content:string$2()}),object({type:literal("shell_call_output"),id:string$2(),call_id:string$2(),status:_enum(["in_progress","completed","incomplete"]),output:array(object({stdout:string$2(),stderr:string$2(),outcome:discriminatedUnion("type",[object({type:literal("timeout")}),object({type:literal("exit"),exit_code:number$2()})])}))}),object({type:literal("tool_search_call"),id:string$2(),execution:_enum(["server","client"]),call_id:string$2().nullable(),status:_enum(["in_progress","completed","incomplete"]),arguments:unknown$1()}),object({type:literal("tool_search_output"),id:string$2(),execution:_enum(["server","client"]),call_id:string$2().nullable(),status:_enum(["in_progress","completed","incomplete"]),tools:array(record$2(string$2(),jsonValueSchema2.optional()))})])).optional(),service_tier:string$2().nullish(),reasoning:object({context:string$2().nullish()}).nullish(),incomplete_details:object({reason:string$2()}).nullish(),usage:object({input_tokens:number$2(),input_tokens_details:object({cached_tokens:number$2().nullish(),cache_write_tokens:number$2().nullish(),orchestration_input_tokens:number$2().nullish(),orchestration_input_cached_tokens:number$2().nullish()}).nullish(),output_tokens:number$2(),output_tokens_details:object({reasoning_tokens:number$2().nullish(),orchestration_output_tokens:number$2().nullish()}).nullish()}).optional()}))),TOP_LOGPROBS_MAX=20,openaiLanguageModelResponsesOptionsSchema=lazySchema(()=>zodSchema(object({conversation:string$2().nullish(),include:array(_enum(["reasoning.encrypted_content","file_search_call.results","web_search_call.results","message.output_text.logprobs"])).nullish(),instructions:string$2().nullish(),logprobs:union([boolean$1(),number$2().min(1).max(TOP_LOGPROBS_MAX)]).optional(),maxToolCalls:number$2().nullish(),metadata:any().nullish(),parallelToolCalls:boolean$1().nullish(),previousResponseId:string$2().nullish(),promptCacheKey:string$2().nullish(),promptCacheOptions:object({mode:_enum(["implicit","explicit"]).optional(),ttl:literal("30m").optional()}).optional(),promptCacheRetention:_enum(["in_memory","24h"]).nullish(),reasoningEffort:string$2().nullish(),reasoningMode:_enum(["standard","pro"]).optional(),reasoningContext:_enum(["auto","current_turn","all_turns"]).optional(),reasoningSummary:string$2().nullish(),safetyIdentifier:string$2().nullish(),serviceTier:_enum(["auto","flex","priority","default"]).nullish(),store:boolean$1().nullish(),passThroughUnsupportedFiles:boolean$1().optional(),strictJsonSchema:boolean$1().nullish(),textVerbosity:_enum(["low","medium","high"]).nullish(),truncation:_enum(["auto","disabled"]).nullish(),user:string$2().nullish(),systemMessageMode:_enum(["system","developer","remove"]).optional(),forceReasoning:boolean$1().optional(),contextManagement:array(object({type:literal("compaction"),compactThreshold:number$2()})).nullish(),allowedTools:object({toolNames:array(string$2()).min(1),mode:_enum(["auto","required"]).optional()}).optional()})));async function prepareResponsesTools({tools:Au,toolChoice:lo,allowedTools:$u,toolNameMapping:Ru,customProviderToolNames:Iu}){var Pu,Ou,Mu;Au=Au?.length?Au:void 0;const Du=[];if(Au==null)return{tools:void 0,toolChoice:void 0,toolWarnings:Du};const Lu=[],Bu=new Map,ju=Iu??new Set;for(const zu of Au)switch(zu.type){case"function":{const Uu=(Pu=zu.providerOptions)==null?void 0:Pu.openai,Hu=prepareFunctionTool({tool:zu,options:Uu}),Vu=Uu?.namespace;if(Vu==null)Lu.push(Hu);else{let Gu=Bu.get(Vu.name);if(Gu==null)Gu={type:"namespace",name:Vu.name,description:Vu.description,tools:[]},Bu.set(Vu.name,Gu),Lu.push(Gu);else if(Gu.description!==Vu.description)throw new UnsupportedFunctionalityError({functionality:`conflicting descriptions for OpenAI tool namespace "${Vu.name}"`});Gu.tools.push(Hu)}break}case"provider":{switch(zu.id){case"openai.file_search":{const Uu=await validateTypes({value:zu.args,schema:fileSearchArgsSchema});Lu.push({type:"file_search",vector_store_ids:Uu.vectorStoreIds,max_num_results:Uu.maxNumResults,ranking_options:Uu.ranking?{ranker:Uu.ranking.ranker,score_threshold:Uu.ranking.scoreThreshold}:void 0,filters:Uu.filters});break}case"openai.local_shell":{Lu.push({type:"local_shell"});break}case"openai.shell":{const Uu=await validateTypes({value:zu.args,schema:shellArgsSchema});Lu.push({type:"shell",...Uu.environment&&{environment:mapShellEnvironment(Uu.environment)}});break}case"openai.apply_patch":{Lu.push({type:"apply_patch"});break}case"openai.computer":{Lu.push({type:"computer"});break}case"openai.web_search_preview":{const Uu=await validateTypes({value:zu.args,schema:webSearchPreviewArgsSchema});Lu.push({type:"web_search_preview",search_context_size:Uu.searchContextSize,user_location:Uu.userLocation});break}case"openai.web_search":{const Uu=await validateTypes({value:zu.args,schema:webSearchArgsSchema});Lu.push({type:"web_search",filters:Uu.filters!=null?{allowed_domains:Uu.filters.allowedDomains}:void 0,external_web_access:Uu.externalWebAccess,search_context_size:Uu.searchContextSize,user_location:Uu.userLocation});break}case"openai.code_interpreter":{const Uu=await validateTypes({value:zu.args,schema:codeInterpreterArgsSchema});Lu.push({type:"code_interpreter",container:Uu.container==null?{type:"auto",file_ids:void 0}:typeof Uu.container=="string"?Uu.container:{type:"auto",file_ids:Uu.container.fileIds}});break}case"openai.image_generation":{const Uu=await validateTypes({value:zu.args,schema:imageGenerationArgsSchema});Lu.push({type:"image_generation",background:Uu.background,input_fidelity:Uu.inputFidelity,input_image_mask:Uu.inputImageMask?{file_id:Uu.inputImageMask.fileId,image_url:Uu.inputImageMask.imageUrl}:void 0,model:Uu.model,moderation:Uu.moderation,partial_images:Uu.partialImages,quality:Uu.quality,output_compression:Uu.outputCompression,output_format:Uu.outputFormat,size:Uu.size});break}case"openai.mcp":{const Uu=await validateTypes({value:zu.args,schema:mcpArgsSchema}),Hu=Wu=>({tool_names:Wu.toolNames}),Vu=Uu.requireApproval,Gu=Vu==null?void 0:typeof Vu=="string"?Vu:Vu.never!=null?{never:Hu(Vu.never)}:void 0;Lu.push({type:"mcp",server_label:Uu.serverLabel,allowed_tools:Array.isArray(Uu.allowedTools)?Uu.allowedTools:Uu.allowedTools?{read_only:Uu.allowedTools.readOnly,tool_names:Uu.allowedTools.toolNames}:void 0,authorization:Uu.authorization,connector_id:Uu.connectorId,headers:Uu.headers,require_approval:Gu??"never",server_description:Uu.serverDescription,server_url:Uu.serverUrl});break}case"openai.custom":{const Uu=await validateTypes({value:zu.args,schema:customArgsSchema});Lu.push({type:"custom",name:zu.name,description:Uu.description,format:Uu.format}),ju.add(zu.name);break}case"openai.programmatic_tool_calling":{Lu.push({type:"programmatic_tool_calling"});break}case"openai.tool_search":{const Uu=await validateTypes({value:zu.args,schema:toolSearchArgsSchema});Lu.push({type:"tool_search",...Uu.execution!=null?{execution:Uu.execution}:{},...Uu.description!=null?{description:Uu.description}:{},...Uu.parameters!=null?{parameters:Uu.parameters}:{}});break}}break}default:Du.push({type:"unsupported",feature:`function tool ${zu}`});break}if($u!=null)return{tools:Lu,toolChoice:{type:"allowed_tools",mode:(Ou=$u.mode)!=null?Ou:"auto",tools:$u.toolNames.map(zu=>{var Uu;return{type:"function",name:(Uu=Ru?.toProviderToolName(zu))!=null?Uu:zu}})},toolWarnings:Du};if(lo==null)return{tools:Lu,toolChoice:void 0,toolWarnings:Du};const Fu=lo.type;switch(Fu){case"auto":case"none":case"required":return{tools:Lu,toolChoice:Fu,toolWarnings:Du};case"tool":{const zu=(Mu=Ru?.toProviderToolName(lo.toolName))!=null?Mu:lo.toolName;return{tools:Lu,toolChoice:zu==="code_interpreter"||zu==="file_search"||zu==="image_generation"||zu==="web_search_preview"||zu==="web_search"||zu==="mcp"||zu==="apply_patch"||zu==="computer"||zu==="programmatic_tool_calling"?{type:zu}:ju.has(zu)?{type:"custom",name:zu}:{type:"function",name:zu},toolWarnings:Du}}default:{const zu=Fu;throw new UnsupportedFunctionalityError({functionality:`tool choice type: ${zu}`})}}}function prepareFunctionTool({tool:Au,options:lo}){const $u=lo?.deferLoading;return{type:"function",name:Au.name,description:Au.description,parameters:Au.inputSchema,...Au.strict!=null?{strict:Au.strict}:{},...$u!=null?{defer_loading:$u}:{},...lo?.allowedCallers!=null?{allowed_callers:lo.allowedCallers}:{},...lo?.outputSchema!=null?{output_schema:lo.outputSchema}:{}}}function mapShellEnvironment(Au){if(Au.type==="containerReference")return{type:"container_reference",container_id:Au.containerId};if(Au.type==="containerAuto"){const $u=Au;return{type:"container_auto",file_ids:$u.fileIds,memory_limit:$u.memoryLimit,network_policy:$u.networkPolicy==null?void 0:$u.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:$u.networkPolicy.allowedDomains,domain_secrets:$u.networkPolicy.domainSecrets},skills:mapShellSkills($u.skills)}}return{type:"local",skills:Au.skills}}function mapShellSkills(Au){return Au?.map(lo=>{var $u,Ru;return lo.type==="skillReference"?{type:"skill_reference",skill_id:resolveProviderReference({reference:($u=lo.providerReference)!=null?$u:{},provider:"openai"}),version:(Ru=lo.version)!=null?Ru:"latest"}:{type:"inline",name:lo.name,description:lo.description,source:{type:"base64",media_type:lo.source.mediaType,data:lo.source.data}}})}function extractApprovalRequestIdToToolCallIdMapping(Au){var lo,$u;const Ru={};for(const Iu of Au)if(Iu.role==="assistant")for(const Pu of Iu.content){if(Pu.type!=="tool-call")continue;const Ou=($u=(lo=Pu.providerOptions)==null?void 0:lo.openai)==null?void 0:$u.approvalRequestId;Ou!=null&&(Ru[Ou]=Pu.toolCallId)}return Ru}function mapComputerAction(Au){switch(Au.type){case"click":return{type:"click",button:Au.button,x:Au.x,y:Au.y,...Au.keys!=null&&{keys:Au.keys}};case"double_click":return{type:"double_click",x:Au.x,y:Au.y,...Au.keys!=null&&{keys:Au.keys}};case"drag":return{type:"drag",path:Au.path,...Au.keys!=null&&{keys:Au.keys}};case"keypress":return Au;case"move":return{type:"move",x:Au.x,y:Au.y,...Au.keys!=null&&{keys:Au.keys}};case"screenshot":return Au;case"scroll":return{type:"scroll",x:Au.x,y:Au.y,scrollX:Au.scroll_x,scrollY:Au.scroll_y,...Au.keys!=null&&{keys:Au.keys}};case"type":return Au;case"wait":return Au}}function mapComputerCallInput({action:Au,actions:lo,pending_safety_checks:$u,status:Ru}){var Iu;return{actions:(lo??(Au!=null?[Au]:[])).map(mapComputerAction),pendingSafetyChecks:(Iu=$u?.map(Pu=>({id:Pu.id,...Pu.code!=null&&{code:Pu.code},...Pu.message!=null&&{message:Pu.message}})))!=null?Iu:[],status:Ru}}var OpenAIResponsesLanguageModel=class KS{constructor(lo,$u){this.specificationVersion="v4",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=lo,this.config=$u}static[WORKFLOW_SERIALIZE](lo){return serializeModelOptions({modelId:lo.modelId,config:lo.config})}static[WORKFLOW_DESERIALIZE](lo){return new KS(lo.modelId,lo.config)}get provider(){return this.config.provider}async getArgs({maxOutputTokens:lo,temperature:$u,stopSequences:Ru,topP:Iu,topK:Pu,presencePenalty:Ou,frequencyPenalty:Mu,seed:Du,prompt:Lu,reasoning:Bu,providerOptions:ju,tools:Fu,toolChoice:zu,responseFormat:Uu}){var Hu,Vu,Gu,Wu,Ku,Ju,Yu,Xu,ed,td,nd,od;const sd=[],ad=getOpenAILanguageModelCapabilities(this.modelId);Pu!=null&&sd.push({type:"unsupported",feature:"topK"}),Du!=null&&sd.push({type:"unsupported",feature:"seed"}),Ou!=null&&sd.push({type:"unsupported",feature:"presencePenalty"}),Mu!=null&&sd.push({type:"unsupported",feature:"frequencyPenalty"}),Ru!=null&&sd.push({type:"unsupported",feature:"stopSequences"});const pd=this.config.provider.includes("azure")?"azure":"openai";let gd=await parseProviderOptions({provider:pd,providerOptions:ju,schema:openaiLanguageModelResponsesOptionsSchema});gd==null&&pd!=="openai"&&(gd=await parseProviderOptions({provider:"openai",providerOptions:ju,schema:openaiLanguageModelResponsesOptionsSchema}));const yd=(Hu=gd?.reasoningEffort)!=null?Hu:isCustomReasoning(Bu)?Bu:void 0,_d=gd?.reasoningSummary!==void 0?gd.reasoningSummary:yd!=null&&yd!=="none"?"detailed":void 0,bd=(Vu=gd?.forceReasoning)!=null?Vu:ad.isReasoningModel;gd?.conversation&&gd?.previousResponseId&&sd.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const wd=createToolNameMapping({tools:Fu,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.computer":"computer","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch","openai.tool_search":"tool_search","openai.programmatic_tool_calling":"programmatic_tool_calling"}}),Ed=new Set,{tools:cd,toolChoice:ud,toolWarnings:md}=await prepareResponsesTools({tools:Fu,toolChoice:zu,allowedTools:(Gu=gd?.allowedTools)!=null?Gu:void 0,toolNameMapping:wd,customProviderToolNames:Ed}),{input:ld,warnings:hd}=await convertToOpenAIResponsesInput({prompt:Lu,toolNameMapping:wd,systemMessageMode:(Wu=gd?.systemMessageMode)!=null?Wu:bd?"developer":ad.systemMessageMode,providerOptionsName:pd,fileIdPrefixes:this.config.fileIdPrefixes,passThroughUnsupportedFiles:(Ku=gd?.passThroughUnsupportedFiles)!=null?Ku:!1,store:(Ju=gd?.store)!=null?Ju:!0,hasConversation:gd?.conversation!=null,hasPreviousResponseId:gd?.previousResponseId!=null,hasLocalShellTool:Rd("openai.local_shell"),hasShellTool:Rd("openai.shell"),hasApplyPatchTool:Rd("openai.apply_patch"),hasComputerTool:Rd("openai.computer"),customProviderToolNames:Ed.size>0?Ed:void 0});sd.push(...hd);const vd=(Yu=gd?.strictJsonSchema)!=null?Yu:!0;let Sd=gd?.include;function kd(Dd){Sd==null?Sd=[Dd]:Sd.includes(Dd)||(Sd=[...Sd,Dd])}function Rd(Dd){return Fu?.find(Hd=>Hd.type==="provider"&&Hd.id===Dd)!=null}const Od=typeof gd?.logprobs=="number"?gd?.logprobs:gd?.logprobs===!0?TOP_LOGPROBS_MAX:void 0;Od&&kd("message.output_text.logprobs");const jd=(Xu=Fu?.find(Dd=>Dd.type==="provider"&&(Dd.id==="openai.web_search"||Dd.id==="openai.web_search_preview")))==null?void 0:Xu.name;jd&&kd("web_search_call.action.sources"),Rd("openai.code_interpreter")&&kd("code_interpreter_call.outputs");const Cd=gd?.store;Cd===!1&&bd&&kd("reasoning.encrypted_content");const Ad={model:this.modelId,input:ld,temperature:$u,top_p:Iu,max_output_tokens:lo,...(Uu?.type==="json"||gd?.textVerbosity)&&{text:{...Uu?.type==="json"&&{format:Uu.schema!=null?{type:"json_schema",strict:vd,name:(ed=Uu.name)!=null?ed:"response",description:Uu.description,schema:Uu.schema}:{type:"json_object"}},...gd?.textVerbosity&&{verbosity:gd.textVerbosity}}},conversation:gd?.conversation,max_tool_calls:gd?.maxToolCalls,metadata:gd?.metadata,parallel_tool_calls:gd?.parallelToolCalls,previous_response_id:gd?.previousResponseId,store:Cd,user:gd?.user,instructions:gd?.instructions,service_tier:gd?.serviceTier,include:Sd,prompt_cache_key:gd?.promptCacheKey,prompt_cache_options:gd?.promptCacheOptions,prompt_cache_retention:gd?.promptCacheRetention,safety_identifier:gd?.safetyIdentifier,top_logprobs:Od,truncation:gd?.truncation,...gd?.contextManagement&&{context_management:gd.contextManagement.map(Dd=>({type:Dd.type,compact_threshold:Dd.compactThreshold}))},...bd&&(yd!=null||_d!=null||gd?.reasoningMode!=null||gd?.reasoningContext!=null)&&{reasoning:{...yd!=null&&{effort:yd},..._d!=null&&{summary:_d},...gd?.reasoningMode!=null&&{mode:gd.reasoningMode},...gd?.reasoningContext!=null&&{context:gd.reasoningContext}}}};bd?yd==="none"&&ad.supportsNonReasoningParameters||(Ad.temperature!=null&&(Ad.temperature=void 0,sd.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),Ad.top_p!=null&&(Ad.top_p=void 0,sd.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(gd?.reasoningEffort!=null&&sd.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),gd?.reasoningSummary!=null&&sd.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"}),gd?.reasoningMode!=null&&sd.push({type:"unsupported",feature:"reasoningMode",details:"reasoningMode is not supported for non-reasoning models"}),gd?.reasoningContext!=null&&sd.push({type:"unsupported",feature:"reasoningContext",details:"reasoningContext is not supported for non-reasoning models"})),gd?.serviceTier==="flex"&&!ad.supportsFlexProcessing&&(sd.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete Ad.service_tier),gd?.serviceTier==="priority"&&!ad.supportsPriorityProcessing&&(sd.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete Ad.service_tier);const $d=(od=(nd=(td=Fu?.find(Dd=>Dd.type==="provider"&&Dd.id==="openai.shell"))==null?void 0:td.args)==null?void 0:nd.environment)==null?void 0:od.type,Vd=$d==="containerAuto"||$d==="containerReference";return{webSearchToolName:jd,args:{...Ad,tools:cd,tool_choice:ud},warnings:[...sd,...md],store:Cd,toolNameMapping:wd,providerOptionsName:pd,isShellProviderExecuted:Vd}}async doGenerate(lo){var $u,Ru,Iu,Pu,Ou,Mu,Du,Lu,Bu,ju,Fu,zu,Uu,Hu,Vu,Gu,Wu,Ku,Ju,Yu,Xu,ed,td,nd,od,sd,ad,pd,gd,yd,_d,bd;const{args:wd,warnings:Ed,webSearchToolName:cd,toolNameMapping:ud,providerOptionsName:md,isShellProviderExecuted:ld}=await this.getArgs(lo),hd=this.config.url({path:"/responses",modelId:this.modelId}),vd=extractApprovalRequestIdToToolCallIdMapping(lo.prompt),{responseHeaders:Sd,value:kd,rawValue:Rd}=await postJsonToApi({url:hd,headers:combineHeaders((Ru=($u=this.config).headers)==null?void 0:Ru.call($u),lo.headers),body:wd,failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler(openaiResponsesResponseSchema),abortSignal:lo.abortSignal,fetch:this.config.fetch});if(kd.error)throw new APICallError({message:kd.error.message,url:hd,requestBodyValues:wd,statusCode:400,responseHeaders:Sd,responseBody:Rd,isRetryable:!1});if(kd.output==null){const Dd=(Iu=kd.incomplete_details)==null?void 0:Iu.reason;throw new APICallError({message:Dd?`Responses API returned no output (${Dd})`:"Responses API returned no output",url:hd,requestBodyValues:wd,statusCode:500,responseHeaders:Sd,responseBody:Rd,isRetryable:!1})}const Od=[],jd=[];let Cd=!1;const Ad=[];for(const Dd of kd.output)switch(Dd.type){case"reasoning":{Dd.summary.length===0&&Dd.summary.push({type:"summary_text",text:""});for(const Hd of Dd.summary)Od.push({type:"reasoning",text:Hd.text,providerMetadata:{[md]:{itemId:Dd.id,reasoningEncryptedContent:(Pu=Dd.encrypted_content)!=null?Pu:null}}});break}case"image_generation_call":{Od.push({type:"tool-call",toolCallId:Dd.id,toolName:ud.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),Od.push({type:"tool-result",toolCallId:Dd.id,toolName:ud.toCustomToolName("image_generation"),result:{result:Dd.result}});break}case"tool_search_call":{const Hd=(Ou=Dd.call_id)!=null?Ou:Dd.id,rh=Dd.execution==="server";rh&&Ad.push(Hd),Od.push({type:"tool-call",toolCallId:Hd,toolName:ud.toCustomToolName("tool_search"),input:JSON.stringify({arguments:Dd.arguments,call_id:Dd.call_id}),...rh?{providerExecuted:!0}:{},providerMetadata:{[md]:{itemId:Dd.id}}});break}case"tool_search_output":{const Hd=(Du=(Mu=Dd.call_id)!=null?Mu:Ad.shift())!=null?Du:Dd.id;Od.push({type:"tool-result",toolCallId:Hd,toolName:ud.toCustomToolName("tool_search"),result:{tools:Dd.tools},providerMetadata:{[md]:{itemId:Dd.id}}});break}case"local_shell_call":{Od.push({type:"tool-call",toolCallId:Dd.call_id,toolName:ud.toCustomToolName("local_shell"),input:JSON.stringify({action:Dd.action}),providerMetadata:{[md]:{itemId:Dd.id}}});break}case"shell_call":{Od.push({type:"tool-call",toolCallId:Dd.call_id,toolName:ud.toCustomToolName("shell"),input:JSON.stringify({action:{commands:Dd.action.commands}}),...ld&&{providerExecuted:!0},providerMetadata:{[md]:{itemId:Dd.id}}});break}case"shell_call_output":{Od.push({type:"tool-result",toolCallId:Dd.call_id,toolName:ud.toCustomToolName("shell"),result:{output:Dd.output.map(Hd=>({stdout:Hd.stdout,stderr:Hd.stderr,outcome:Hd.outcome.type==="exit"?{type:"exit",exitCode:Hd.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const Hd of Dd.content){(Bu=(Lu=lo.providerOptions)==null?void 0:Lu[md])!=null&&Bu.logprobs&&Hd.logprobs&&jd.push(Hd.logprobs);const rh={itemId:Dd.id,...Dd.phase!=null&&{phase:Dd.phase},...Hd.annotations.length>0&&{annotations:Hd.annotations}};Od.push({type:"text",text:Hd.text,providerMetadata:{[md]:rh}});for(const Jd of Hd.annotations)Jd.type==="url_citation"?Od.push({type:"source",sourceType:"url",id:(zu=(Fu=(ju=this.config).generateId)==null?void 0:Fu.call(ju))!=null?zu:generateId(),url:Jd.url,title:Jd.title}):Jd.type==="file_citation"?Od.push({type:"source",sourceType:"document",id:(Vu=(Hu=(Uu=this.config).generateId)==null?void 0:Hu.call(Uu))!=null?Vu:generateId(),mediaType:"text/plain",title:Jd.filename,filename:Jd.filename,providerMetadata:{[md]:{type:Jd.type,fileId:Jd.file_id,index:Jd.index}}}):Jd.type==="container_file_citation"?Od.push({type:"source",sourceType:"document",id:(Ku=(Wu=(Gu=this.config).generateId)==null?void 0:Wu.call(Gu))!=null?Ku:generateId(),mediaType:"text/plain",title:Jd.filename,filename:Jd.filename,providerMetadata:{[md]:{type:Jd.type,fileId:Jd.file_id,containerId:Jd.container_id}}}):Jd.type==="file_path"&&Od.push({type:"source",sourceType:"document",id:(Xu=(Yu=(Ju=this.config).generateId)==null?void 0:Yu.call(Ju))!=null?Xu:generateId(),mediaType:"application/octet-stream",title:Jd.file_id,filename:Jd.file_id,providerMetadata:{[md]:{type:Jd.type,fileId:Jd.file_id,index:Jd.index}}})}break}case"function_call":{Cd=!0,Od.push({type:"tool-call",toolCallId:Dd.call_id,toolName:Dd.name,input:Dd.arguments,providerMetadata:{[md]:{itemId:Dd.id,...Dd.namespace!=null&&{namespace:Dd.namespace},...Dd.caller!=null&&{caller:Dd.caller.type==="program"?{type:"program",callerId:Dd.caller.caller_id}:Dd.caller}}}});break}case"program":{Od.push({type:"tool-call",toolCallId:Dd.call_id,toolName:ud.toCustomToolName("programmatic_tool_calling"),input:JSON.stringify({code:Dd.code,fingerprint:Dd.fingerprint}),providerExecuted:!0,providerMetadata:{[md]:{itemId:Dd.id}}});break}case"program_output":{Od.push({type:"tool-result",toolCallId:Dd.call_id,toolName:ud.toCustomToolName("programmatic_tool_calling"),result:{result:Dd.result,status:Dd.status},providerMetadata:{[md]:{itemId:Dd.id}}});break}case"custom_tool_call":{Cd=!0;const Hd=ud.toCustomToolName(Dd.name);Od.push({type:"tool-call",toolCallId:Dd.call_id,toolName:Hd,input:JSON.stringify(Dd.input),providerMetadata:{[md]:{itemId:Dd.id}}});break}case"web_search_call":{Od.push({type:"tool-call",toolCallId:Dd.id,toolName:ud.toCustomToolName(cd??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),Od.push({type:"tool-result",toolCallId:Dd.id,toolName:ud.toCustomToolName(cd??"web_search"),result:mapWebSearchOutput(Dd.action)});break}case"mcp_call":{const Hd=Dd.approval_request_id!=null&&(ed=vd[Dd.approval_request_id])!=null?ed:Dd.id,rh=`mcp.${Dd.name}`;Od.push({type:"tool-call",toolCallId:Hd,toolName:rh,input:Dd.arguments,providerExecuted:!0,dynamic:!0}),Od.push({type:"tool-result",toolCallId:Hd,toolName:rh,result:{type:"call",serverLabel:Dd.server_label,name:Dd.name,arguments:Dd.arguments,...Dd.output!=null?{output:Dd.output}:{},...Dd.error!=null?{error:Dd.error}:{}},providerMetadata:{[md]:{itemId:Dd.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const Hd=(td=Dd.approval_request_id)!=null?td:Dd.id,rh=(sd=(od=(nd=this.config).generateId)==null?void 0:od.call(nd))!=null?sd:generateId(),Jd=`mcp.${Dd.name}`;Od.push({type:"tool-call",toolCallId:rh,toolName:Jd,input:Dd.arguments,providerExecuted:!0,dynamic:!0}),Od.push({type:"tool-approval-request",approvalId:Hd,toolCallId:rh});break}case"computer_call":{if(Dd.call_id==null){Od.push({type:"tool-call",toolCallId:Dd.id,toolName:ud.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),Od.push({type:"tool-result",toolCallId:Dd.id,toolName:ud.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:Dd.status}});break}Cd=!0;const Hd=ud.toCustomToolName("computer");Od.push({type:"tool-call",toolCallId:Dd.call_id,toolName:Hd,input:JSON.stringify(mapComputerCallInput(Dd)),providerMetadata:{[md]:{itemId:Dd.id}}});break}case"file_search_call":{Od.push({type:"tool-call",toolCallId:Dd.id,toolName:ud.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),Od.push({type:"tool-result",toolCallId:Dd.id,toolName:ud.toCustomToolName("file_search"),result:{queries:Dd.queries,results:(pd=(ad=Dd.results)==null?void 0:ad.map(Hd=>({attributes:Hd.attributes,fileId:Hd.file_id,filename:Hd.filename,score:Hd.score,text:Hd.text})))!=null?pd:null}});break}case"code_interpreter_call":{Od.push({type:"tool-call",toolCallId:Dd.id,toolName:ud.toCustomToolName("code_interpreter"),input:JSON.stringify({code:Dd.code,containerId:Dd.container_id}),providerExecuted:!0}),Od.push({type:"tool-result",toolCallId:Dd.id,toolName:ud.toCustomToolName("code_interpreter"),result:{outputs:Dd.outputs}});break}case"apply_patch_call":{Od.push({type:"tool-call",toolCallId:Dd.call_id,toolName:ud.toCustomToolName("apply_patch"),input:JSON.stringify({callId:Dd.call_id,operation:Dd.operation}),providerMetadata:{[md]:{itemId:Dd.id}}});break}case"compaction":{Od.push({type:"custom",kind:"openai.compaction",providerMetadata:{[md]:{type:"compaction",itemId:Dd.id,encryptedContent:Dd.encrypted_content}}});break}}const $d={[md]:{responseId:kd.id,...jd.length>0?{logprobs:jd}:{},...typeof kd.service_tier=="string"?{serviceTier:kd.service_tier}:{},...((gd=kd.reasoning)==null?void 0:gd.context)!=null?{reasoningContext:kd.reasoning.context}:{}}},Vd=kd.usage;return{content:Od,finishReason:{unified:mapOpenAIResponseFinishReason({finishReason:(yd=kd.incomplete_details)==null?void 0:yd.reason,hasFunctionCall:Cd}),raw:(bd=(_d=kd.incomplete_details)==null?void 0:_d.reason)!=null?bd:void 0},usage:convertOpenAIResponsesUsage(Vd),request:{body:wd},response:{id:kd.id,timestamp:new Date(kd.created_at*1e3),modelId:kd.model,headers:Sd,body:Rd},providerMetadata:$d,warnings:Ed}}async doStream(lo){var $u,Ru;const{args:Iu,warnings:Pu,webSearchToolName:Ou,toolNameMapping:Mu,store:Du,providerOptionsName:Lu,isShellProviderExecuted:Bu}=await this.getArgs(lo),ju=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:Fu,value:zu}=await postJsonToApi({url:ju,headers:combineHeaders((Ru=($u=this.config).headers)==null?void 0:Ru.call($u),lo.headers),body:{...Iu,stream:!0},failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createEventSourceResponseHandler(openaiResponsesChunkSchema),abortSignal:lo.abortSignal,fetch:this.config.fetch}),Uu=await throwIfOpenAIStreamErrorBeforeOutput({stream:zu,getError:_d=>isErrorChunk(_d)||isResponseFailedChunk(_d)&&_d.response.error!=null?_d:void 0,isOutputChunk:isResponseOutputChunk,url:ju,requestBodyValues:Iu,responseHeaders:Fu}),Hu=this,Vu=extractApprovalRequestIdToToolCallIdMapping(lo.prompt),Gu=new Map;let Wu={unified:"other",raw:void 0},Ku;const Ju=[];let Yu=null;const Xu={},ed=[];let td,nd=!1;const od={};let sd,ad;const pd=[];let gd=!1;return{stream:Uu.pipeThrough(new TransformStream({start(_d){_d.enqueue({type:"stream-start",warnings:Pu})},transform(_d,bd){var wd,Ed,cd,ud,md,ld,hd,vd,Sd,kd,Rd,Od,jd,Cd,Ad,$d,Vd,Dd,Hd,rh,Jd,vh,sh,Eh,bh,Qd,th,uh,Ph,Gd,Fd,Id,Pd,Wd,Ld,Kd,Xd,mh,Sh,wh,Vh;if(lo.includeRawChunks&&bd.enqueue({type:"raw",rawValue:_d.rawValue}),!_d.success){const xd=isOpenAIChatCompletionChunk(_d.rawValue)?createOpenAIResponsesChatCompletionsMismatchError({value:_d.rawValue,cause:_d.error,url:ju,requestBodyValues:Iu,responseHeaders:Fu}):_d.error;Wu={unified:"error",raw:void 0},bd.enqueue({type:"error",error:xd});return}const Md=_d.value;if(isResponseOutputItemAddedChunk(Md)){if(Md.item.type==="function_call")Xu[Md.output_index]={toolName:Md.item.name,toolCallId:Md.item.call_id},bd.enqueue({type:"tool-input-start",id:Md.item.call_id,toolName:Md.item.name});else if(Md.item.type==="custom_tool_call"){const xd=Mu.toCustomToolName(Md.item.name);Xu[Md.output_index]={toolName:xd,toolCallId:Md.item.call_id},bd.enqueue({type:"tool-input-start",id:Md.item.call_id,toolName:xd})}else if(Md.item.type==="web_search_call")Xu[Md.output_index]={toolName:Mu.toCustomToolName(Ou??"web_search"),toolCallId:Md.item.id},bd.enqueue({type:"tool-input-start",id:Md.item.id,toolName:Mu.toCustomToolName(Ou??"web_search"),providerExecuted:!0}),bd.enqueue({type:"tool-input-end",id:Md.item.id}),bd.enqueue({type:"tool-call",toolCallId:Md.item.id,toolName:Mu.toCustomToolName(Ou??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(Md.item.type==="computer_call"){const xd=(wd=Md.item.call_id)!=null?wd:Md.item.id;Xu[Md.output_index]={toolName:Mu.toCustomToolName("computer"),toolCallId:xd},bd.enqueue({type:"tool-input-start",id:xd,toolName:Mu.toCustomToolName("computer")})}else if(Md.item.type==="code_interpreter_call")Xu[Md.output_index]={toolName:Mu.toCustomToolName("code_interpreter"),toolCallId:Md.item.id,codeInterpreter:{containerId:Md.item.container_id}},bd.enqueue({type:"tool-input-start",id:Md.item.id,toolName:Mu.toCustomToolName("code_interpreter"),providerExecuted:!0}),bd.enqueue({type:"tool-input-delta",id:Md.item.id,delta:`{"containerId":"${Md.item.container_id}","code":"`});else if(Md.item.type==="file_search_call")bd.enqueue({type:"tool-call",toolCallId:Md.item.id,toolName:Mu.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(Md.item.type==="image_generation_call")bd.enqueue({type:"tool-call",toolCallId:Md.item.id,toolName:Mu.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(Md.item.type==="tool_search_call"){const xd=Md.item.id,qd=Mu.toCustomToolName("tool_search"),Zd=Md.item.execution==="server";Xu[Md.output_index]={toolName:qd,toolCallId:xd,toolSearchExecution:(Ed=Md.item.execution)!=null?Ed:"server"},Zd&&bd.enqueue({type:"tool-input-start",id:xd,toolName:qd,providerExecuted:!0})}else if(Md.item.type!=="tool_search_output"){if(!(Md.item.type==="mcp_call"||Md.item.type==="mcp_list_tools"||Md.item.type==="mcp_approval_request"))if(Md.item.type==="apply_patch_call"){const{call_id:xd,operation:qd}=Md.item;if(Xu[Md.output_index]={toolName:Mu.toCustomToolName("apply_patch"),toolCallId:xd,applyPatch:{hasDiff:qd.type==="delete_file",endEmitted:qd.type==="delete_file"}},bd.enqueue({type:"tool-input-start",id:xd,toolName:Mu.toCustomToolName("apply_patch")}),qd.type==="delete_file"){const Zd=JSON.stringify({callId:xd,operation:qd});bd.enqueue({type:"tool-input-delta",id:xd,delta:Zd}),bd.enqueue({type:"tool-input-end",id:xd})}else bd.enqueue({type:"tool-input-delta",id:xd,delta:`{"callId":"${escapeJSONDelta(xd)}","operation":{"type":"${escapeJSONDelta(qd.type)}","path":"${escapeJSONDelta(qd.path)}","diff":"`})}else Md.item.type==="shell_call"?Xu[Md.output_index]={toolName:Mu.toCustomToolName("shell"),toolCallId:Md.item.call_id}:Md.item.type==="shell_call_output"||(Md.item.type==="message"?(ed.splice(0,ed.length),td=(cd=Md.item.phase)!=null?cd:void 0,bd.enqueue({type:"text-start",id:Md.item.id,providerMetadata:{[Lu]:{itemId:Md.item.id,...Md.item.phase!=null&&{phase:Md.item.phase}}}})):isResponseOutputItemAddedChunk(Md)&&Md.item.type==="reasoning"&&(od[Md.item.id]={encryptedContent:Md.item.encrypted_content,summaryParts:{0:"active"}},bd.enqueue({type:"reasoning-start",id:`${Md.item.id}:0`,providerMetadata:{[Lu]:{itemId:Md.item.id,reasoningEncryptedContent:(ud=Md.item.encrypted_content)!=null?ud:null}}})))}}else if(isResponseOutputItemDoneChunk(Md))if(Md.item.type==="message"){const xd=(md=Md.item.phase)!=null?md:td;td=void 0,bd.enqueue({type:"text-end",id:Md.item.id,providerMetadata:{[Lu]:{itemId:Md.item.id,...xd!=null&&{phase:xd},...ed.length>0&&{annotations:ed}}}})}else if(Md.item.type==="function_call")Xu[Md.output_index]=void 0,nd=!0,bd.enqueue({type:"tool-input-end",id:Md.item.call_id,...Md.item.namespace!=null&&{providerMetadata:{[Lu]:{namespace:Md.item.namespace}}}}),bd.enqueue({type:"tool-call",toolCallId:Md.item.call_id,toolName:Md.item.name,input:Md.item.arguments,providerMetadata:{[Lu]:{itemId:Md.item.id,...Md.item.namespace!=null&&{namespace:Md.item.namespace},...Md.item.caller!=null&&{caller:Md.item.caller.type==="program"?{type:"program",callerId:Md.item.caller.caller_id}:Md.item.caller}}}});else if(Md.item.type==="program")bd.enqueue({type:"tool-call",toolCallId:Md.item.call_id,toolName:Mu.toCustomToolName("programmatic_tool_calling"),input:JSON.stringify({code:Md.item.code,fingerprint:Md.item.fingerprint}),providerExecuted:!0,providerMetadata:{[Lu]:{itemId:Md.item.id}}});else if(Md.item.type==="program_output")bd.enqueue({type:"tool-result",toolCallId:Md.item.call_id,toolName:Mu.toCustomToolName("programmatic_tool_calling"),result:{result:Md.item.result,status:Md.item.status},providerMetadata:{[Lu]:{itemId:Md.item.id}}});else if(Md.item.type==="custom_tool_call"){Xu[Md.output_index]=void 0,nd=!0;const xd=Mu.toCustomToolName(Md.item.name);bd.enqueue({type:"tool-input-end",id:Md.item.call_id}),bd.enqueue({type:"tool-call",toolCallId:Md.item.call_id,toolName:xd,input:JSON.stringify(Md.item.input),providerMetadata:{[Lu]:{itemId:Md.item.id}}})}else if(Md.item.type==="web_search_call")Xu[Md.output_index]=void 0,bd.enqueue({type:"tool-result",toolCallId:Md.item.id,toolName:Mu.toCustomToolName(Ou??"web_search"),result:mapWebSearchOutput(Md.item.action)});else if(Md.item.type==="computer_call"){if(Xu[Md.output_index]=void 0,Md.item.call_id==null){bd.enqueue({type:"tool-input-end",id:Md.item.id}),bd.enqueue({type:"tool-call",toolCallId:Md.item.id,toolName:Mu.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),bd.enqueue({type:"tool-result",toolCallId:Md.item.id,toolName:Mu.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:Md.item.status}});return}nd=!0;const xd=Mu.toCustomToolName("computer"),qd=JSON.stringify(mapComputerCallInput(Md.item));bd.enqueue({type:"tool-input-delta",id:Md.item.call_id,delta:qd}),bd.enqueue({type:"tool-input-end",id:Md.item.call_id}),bd.enqueue({type:"tool-call",toolCallId:Md.item.call_id,toolName:xd,input:qd,providerMetadata:{[Lu]:{itemId:Md.item.id}}})}else if(Md.item.type==="file_search_call")Xu[Md.output_index]=void 0,bd.enqueue({type:"tool-result",toolCallId:Md.item.id,toolName:Mu.toCustomToolName("file_search"),result:{queries:Md.item.queries,results:(hd=(ld=Md.item.results)==null?void 0:ld.map(xd=>({attributes:xd.attributes,fileId:xd.file_id,filename:xd.filename,score:xd.score,text:xd.text})))!=null?hd:null}});else if(Md.item.type==="code_interpreter_call")Xu[Md.output_index]=void 0,bd.enqueue({type:"tool-result",toolCallId:Md.item.id,toolName:Mu.toCustomToolName("code_interpreter"),result:{outputs:Md.item.outputs}});else if(Md.item.type==="image_generation_call")bd.enqueue({type:"tool-result",toolCallId:Md.item.id,toolName:Mu.toCustomToolName("image_generation"),result:{result:Md.item.result}});else if(Md.item.type==="tool_search_call"){const xd=Xu[Md.output_index],qd=Md.item.execution==="server";if(xd!=null){const Zd=qd?xd.toolCallId:(vd=Md.item.call_id)!=null?vd:Md.item.id;qd?pd.push(Zd):bd.enqueue({type:"tool-input-start",id:Zd,toolName:xd.toolName}),bd.enqueue({type:"tool-input-end",id:Zd}),bd.enqueue({type:"tool-call",toolCallId:Zd,toolName:xd.toolName,input:JSON.stringify({arguments:Md.item.arguments,call_id:qd?null:Zd}),...qd?{providerExecuted:!0}:{},providerMetadata:{[Lu]:{itemId:Md.item.id}}})}Xu[Md.output_index]=void 0}else if(Md.item.type==="tool_search_output"){const xd=(kd=(Sd=Md.item.call_id)!=null?Sd:pd.shift())!=null?kd:Md.item.id;bd.enqueue({type:"tool-result",toolCallId:xd,toolName:Mu.toCustomToolName("tool_search"),result:{tools:Md.item.tools},providerMetadata:{[Lu]:{itemId:Md.item.id}}})}else if(Md.item.type==="mcp_call"){Xu[Md.output_index]=void 0;const xd=(Rd=Md.item.approval_request_id)!=null?Rd:void 0,qd=xd!=null&&(jd=(Od=Gu.get(xd))!=null?Od:Vu[xd])!=null?jd:Md.item.id,Zd=`mcp.${Md.item.name}`;bd.enqueue({type:"tool-call",toolCallId:qd,toolName:Zd,input:Md.item.arguments,providerExecuted:!0,dynamic:!0}),bd.enqueue({type:"tool-result",toolCallId:qd,toolName:Zd,result:{type:"call",serverLabel:Md.item.server_label,name:Md.item.name,arguments:Md.item.arguments,...Md.item.output!=null?{output:Md.item.output}:{},...Md.item.error!=null?{error:Md.item.error}:{}},providerMetadata:{[Lu]:{itemId:Md.item.id}}})}else if(Md.item.type==="mcp_list_tools")Xu[Md.output_index]=void 0;else if(Md.item.type==="apply_patch_call"){const xd=Xu[Md.output_index];xd?.applyPatch&&!xd.applyPatch.endEmitted&&Md.item.operation.type!=="delete_file"&&(xd.applyPatch.hasDiff||bd.enqueue({type:"tool-input-delta",id:xd.toolCallId,delta:escapeJSONDelta(Md.item.operation.diff)}),bd.enqueue({type:"tool-input-delta",id:xd.toolCallId,delta:'"}}'}),bd.enqueue({type:"tool-input-end",id:xd.toolCallId}),xd.applyPatch.endEmitted=!0),xd&&Md.item.status==="completed"&&bd.enqueue({type:"tool-call",toolCallId:xd.toolCallId,toolName:Mu.toCustomToolName("apply_patch"),input:JSON.stringify({callId:Md.item.call_id,operation:Md.item.operation}),providerMetadata:{[Lu]:{itemId:Md.item.id}}}),Xu[Md.output_index]=void 0}else if(Md.item.type==="mcp_approval_request"){Xu[Md.output_index]=void 0;const xd=($d=(Ad=(Cd=Hu.config).generateId)==null?void 0:Ad.call(Cd))!=null?$d:generateId(),qd=(Vd=Md.item.approval_request_id)!=null?Vd:Md.item.id;Gu.set(qd,xd);const Zd=`mcp.${Md.item.name}`;bd.enqueue({type:"tool-call",toolCallId:xd,toolName:Zd,input:Md.item.arguments,providerExecuted:!0,dynamic:!0}),bd.enqueue({type:"tool-approval-request",approvalId:qd,toolCallId:xd})}else if(Md.item.type==="local_shell_call")Xu[Md.output_index]=void 0,bd.enqueue({type:"tool-call",toolCallId:Md.item.call_id,toolName:Mu.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:Md.item.action.command,timeoutMs:Md.item.action.timeout_ms,user:Md.item.action.user,workingDirectory:Md.item.action.working_directory,env:Md.item.action.env}}),providerMetadata:{[Lu]:{itemId:Md.item.id}}});else if(Md.item.type==="shell_call")Xu[Md.output_index]=void 0,bd.enqueue({type:"tool-call",toolCallId:Md.item.call_id,toolName:Mu.toCustomToolName("shell"),input:JSON.stringify({action:{commands:Md.item.action.commands}}),...Bu&&{providerExecuted:!0},providerMetadata:{[Lu]:{itemId:Md.item.id}}});else if(Md.item.type==="shell_call_output")bd.enqueue({type:"tool-result",toolCallId:Md.item.call_id,toolName:Mu.toCustomToolName("shell"),result:{output:Md.item.output.map(xd=>({stdout:xd.stdout,stderr:xd.stderr,outcome:xd.outcome.type==="exit"?{type:"exit",exitCode:xd.outcome.exit_code}:{type:"timeout"}}))}});else if(Md.item.type==="reasoning"){const xd=od[Md.item.id],qd=Object.entries(xd.summaryParts).filter(([Zd,gh])=>gh==="active"||gh==="can-conclude").map(([Zd])=>Zd);for(const Zd of qd)bd.enqueue({type:"reasoning-end",id:`${Md.item.id}:${Zd}`,providerMetadata:{[Lu]:{itemId:Md.item.id,reasoningEncryptedContent:(Dd=Md.item.encrypted_content)!=null?Dd:null}}});delete od[Md.item.id]}else Md.item.type==="compaction"&&bd.enqueue({type:"custom",kind:"openai.compaction",providerMetadata:{[Lu]:{type:"compaction",itemId:Md.item.id,encryptedContent:Md.item.encrypted_content}}});else if(isResponseFunctionCallArgumentsDeltaChunk(Md)){const xd=Xu[Md.output_index];xd!=null&&bd.enqueue({type:"tool-input-delta",id:xd.toolCallId,delta:Md.delta})}else if(isResponseCustomToolCallInputDeltaChunk(Md)){const xd=Xu[Md.output_index];xd!=null&&bd.enqueue({type:"tool-input-delta",id:xd.toolCallId,delta:Md.delta})}else if(isResponseApplyPatchCallOperationDiffDeltaChunk(Md)){const xd=Xu[Md.output_index];xd?.applyPatch&&(bd.enqueue({type:"tool-input-delta",id:xd.toolCallId,delta:escapeJSONDelta(Md.delta)}),xd.applyPatch.hasDiff=!0)}else if(isResponseApplyPatchCallOperationDiffDoneChunk(Md)){const xd=Xu[Md.output_index];xd?.applyPatch&&!xd.applyPatch.endEmitted&&(xd.applyPatch.hasDiff||(bd.enqueue({type:"tool-input-delta",id:xd.toolCallId,delta:escapeJSONDelta(Md.diff)}),xd.applyPatch.hasDiff=!0),bd.enqueue({type:"tool-input-delta",id:xd.toolCallId,delta:'"}}'}),bd.enqueue({type:"tool-input-end",id:xd.toolCallId}),xd.applyPatch.endEmitted=!0)}else if(isResponseImageGenerationCallPartialImageChunk(Md))bd.enqueue({type:"tool-result",toolCallId:Md.item_id,toolName:Mu.toCustomToolName("image_generation"),result:{result:Md.partial_image_b64},preliminary:!0});else if(isResponseCodeInterpreterCallCodeDeltaChunk(Md)){const xd=Xu[Md.output_index];xd!=null&&bd.enqueue({type:"tool-input-delta",id:xd.toolCallId,delta:escapeJSONDelta(Md.delta)})}else if(isResponseCodeInterpreterCallCodeDoneChunk(Md)){const xd=Xu[Md.output_index];xd!=null&&(bd.enqueue({type:"tool-input-delta",id:xd.toolCallId,delta:'"}'}),bd.enqueue({type:"tool-input-end",id:xd.toolCallId}),bd.enqueue({type:"tool-call",toolCallId:xd.toolCallId,toolName:Mu.toCustomToolName("code_interpreter"),input:JSON.stringify({code:Md.code,containerId:xd.codeInterpreter.containerId}),providerExecuted:!0}))}else if(isResponseCreatedChunk(Md))Yu=Md.response.id,bd.enqueue({type:"response-metadata",id:Md.response.id,timestamp:new Date(Md.response.created_at*1e3),modelId:Md.response.model});else if(isTextDeltaChunk(Md))bd.enqueue({type:"text-delta",id:Md.item_id,delta:Md.delta}),(rh=(Hd=lo.providerOptions)==null?void 0:Hd[Lu])!=null&&rh.logprobs&&Md.logprobs&&Ju.push(Md.logprobs);else if(Md.type==="response.reasoning_summary_part.added"){if(Md.summary_index>0){const xd=od[Md.item_id];xd.summaryParts[Md.summary_index]="active";for(const qd of Object.keys(xd.summaryParts))xd.summaryParts[qd]==="can-conclude"&&(bd.enqueue({type:"reasoning-end",id:`${Md.item_id}:${qd}`,providerMetadata:{[Lu]:{itemId:Md.item_id}}}),xd.summaryParts[qd]="concluded");bd.enqueue({type:"reasoning-start",id:`${Md.item_id}:${Md.summary_index}`,providerMetadata:{[Lu]:{itemId:Md.item_id,reasoningEncryptedContent:(vh=(Jd=od[Md.item_id])==null?void 0:Jd.encryptedContent)!=null?vh:null}}})}}else if(Md.type==="response.reasoning_summary_text.delta")bd.enqueue({type:"reasoning-delta",id:`${Md.item_id}:${Md.summary_index}`,delta:Md.delta,providerMetadata:{[Lu]:{itemId:Md.item_id}}});else if(Md.type==="response.reasoning_summary_part.done")Du?(bd.enqueue({type:"reasoning-end",id:`${Md.item_id}:${Md.summary_index}`,providerMetadata:{[Lu]:{itemId:Md.item_id}}}),od[Md.item_id].summaryParts[Md.summary_index]="concluded"):od[Md.item_id].summaryParts[Md.summary_index]="can-conclude";else if(isResponseFinishedChunk(Md))Wu={unified:mapOpenAIResponseFinishReason({finishReason:(sh=Md.response.incomplete_details)==null?void 0:sh.reason,hasFunctionCall:nd}),raw:(bh=(Eh=Md.response.incomplete_details)==null?void 0:Eh.reason)!=null?bh:void 0},Ku=Md.response.usage,typeof Md.response.service_tier=="string"&&(sd=Md.response.service_tier),((Qd=Md.response.reasoning)==null?void 0:Qd.context)!=null&&(ad=Md.response.reasoning.context);else if(isResponseFailedChunk(Md)){const xd=(th=Md.response.incomplete_details)==null?void 0:th.reason;Wu={unified:xd?mapOpenAIResponseFinishReason({finishReason:xd,hasFunctionCall:nd}):"error",raw:xd??"error"},Ku=(uh=Md.response.usage)!=null?uh:void 0,((Ph=Md.response.reasoning)==null?void 0:Ph.context)!=null&&(ad=Md.response.reasoning.context),!gd&&Md.response.error!=null&&(gd=!0,bd.enqueue({type:"error",error:{type:"response.failed",sequence_number:Md.sequence_number,response:{error:Md.response.error,incomplete_details:Md.response.incomplete_details,service_tier:Md.response.service_tier}}}))}else isResponseAnnotationAddedChunk(Md)?(ed.push(Md.annotation),Md.annotation.type==="url_citation"?bd.enqueue({type:"source",sourceType:"url",id:(Id=(Fd=(Gd=Hu.config).generateId)==null?void 0:Fd.call(Gd))!=null?Id:generateId(),url:Md.annotation.url,title:Md.annotation.title}):Md.annotation.type==="file_citation"?bd.enqueue({type:"source",sourceType:"document",id:(Ld=(Wd=(Pd=Hu.config).generateId)==null?void 0:Wd.call(Pd))!=null?Ld:generateId(),mediaType:"text/plain",title:Md.annotation.filename,filename:Md.annotation.filename,providerMetadata:{[Lu]:{type:Md.annotation.type,fileId:Md.annotation.file_id,index:Md.annotation.index}}}):Md.annotation.type==="container_file_citation"?bd.enqueue({type:"source",sourceType:"document",id:(mh=(Xd=(Kd=Hu.config).generateId)==null?void 0:Xd.call(Kd))!=null?mh:generateId(),mediaType:"text/plain",title:Md.annotation.filename,filename:Md.annotation.filename,providerMetadata:{[Lu]:{type:Md.annotation.type,fileId:Md.annotation.file_id,containerId:Md.annotation.container_id}}}):Md.annotation.type==="file_path"&&bd.enqueue({type:"source",sourceType:"document",id:(Vh=(wh=(Sh=Hu.config).generateId)==null?void 0:wh.call(Sh))!=null?Vh:generateId(),mediaType:"application/octet-stream",title:Md.annotation.file_id,filename:Md.annotation.file_id,providerMetadata:{[Lu]:{type:Md.annotation.type,fileId:Md.annotation.file_id,index:Md.annotation.index}}})):isErrorChunk(Md)&&(gd=!0,Wu={unified:"error",raw:"error"},bd.enqueue({type:"error",error:Md}))},flush(_d){const bd={[Lu]:{responseId:Yu,...Ju.length>0?{logprobs:Ju}:{},...sd!==void 0?{serviceTier:sd}:{},...ad!==void 0?{reasoningContext:ad}:{}}};_d.enqueue({type:"finish",finishReason:Wu,usage:convertOpenAIResponsesUsage(Ku),providerMetadata:bd})}})),request:{body:Iu},response:{headers:Fu}}}};function isTextDeltaChunk(Au){return Au.type==="response.output_text.delta"}function isOpenAIChatCompletionChunk(Au){const lo=asRecord2(Au);return lo!=null&&Array.isArray(lo.choices)&&typeof lo.type!="string"}function createOpenAIResponsesChatCompletionsMismatchError({value:Au,cause:lo,url:$u,requestBodyValues:Ru,responseHeaders:Iu}){return new APICallError({message:"Received a Chat Completions stream while using the OpenAI Responses API. The default OpenAI provider model uses the Responses API. If your custom baseURL targets a Chat Completions-compatible endpoint, use openai.chat('model-id') or createOpenAI(...).chat('model-id') instead. You can also use @ai-sdk/openai-compatible for OpenAI-compatible providers.",url:$u,requestBodyValues:Ru,responseHeaders:Iu,responseBody:JSON.stringify(Au),cause:lo,data:Au,isRetryable:!1})}function asRecord2(Au){return typeof Au=="object"&&Au!=null?Au:void 0}function isResponseOutputItemDoneChunk(Au){return Au.type==="response.output_item.done"}function isResponseFinishedChunk(Au){return Au.type==="response.completed"||Au.type==="response.incomplete"}function isResponseFailedChunk(Au){return Au.type==="response.failed"}function isResponseCreatedChunk(Au){return Au.type==="response.created"}function isResponseFunctionCallArgumentsDeltaChunk(Au){return Au.type==="response.function_call_arguments.delta"}function isResponseCustomToolCallInputDeltaChunk(Au){return Au.type==="response.custom_tool_call_input.delta"}function isResponseImageGenerationCallPartialImageChunk(Au){return Au.type==="response.image_generation_call.partial_image"}function isResponseCodeInterpreterCallCodeDeltaChunk(Au){return Au.type==="response.code_interpreter_call_code.delta"}function isResponseCodeInterpreterCallCodeDoneChunk(Au){return Au.type==="response.code_interpreter_call_code.done"}function isResponseApplyPatchCallOperationDiffDeltaChunk(Au){return Au.type==="response.apply_patch_call_operation_diff.delta"}function isResponseApplyPatchCallOperationDiffDoneChunk(Au){return Au.type==="response.apply_patch_call_operation_diff.done"}function isResponseOutputItemAddedChunk(Au){return Au.type==="response.output_item.added"}function isResponseAnnotationAddedChunk(Au){return Au.type==="response.output_text.annotation.added"}function isErrorChunk(Au){return Au.type==="error"}function isResponseOutputChunk(Au){return!(Au.type==="response.created"||Au.type==="response.failed"||Au.type==="error"||Au.type==="unknown_chunk")}function mapWebSearchOutput(Au){var lo;if(Au==null)return{};switch(Au.type){case"search":return{action:{type:"search",query:(lo=Au.query)!=null?lo:void 0,...Au.queries!=null&&{queries:Au.queries}},...Au.sources!=null&&{sources:Au.sources}};case"open_page":return{action:{type:"openPage",url:Au.url}};case"find_in_page":return{action:{type:"findInPage",url:Au.url,pattern:Au.pattern}}}}function escapeJSONDelta(Au){return JSON.stringify(Au).slice(1,-1)}var openaiSpeechModelOptionsSchema=lazySchema(()=>zodSchema(object({instructions:string$2().nullish(),speed:number$2().min(.25).max(4).default(1).nullish()}))),OpenAISpeechModel=class ZS{constructor(lo,$u){this.modelId=lo,this.config=$u,this.specificationVersion="v4"}static[WORKFLOW_SERIALIZE](lo){return serializeModelOptions({modelId:lo.modelId,config:lo.config})}static[WORKFLOW_DESERIALIZE](lo){return new ZS(lo.modelId,lo.config)}get provider(){return this.config.provider}async getArgs({text:lo,voice:$u="alloy",outputFormat:Ru="mp3",speed:Iu,instructions:Pu,language:Ou,providerOptions:Mu}){const Du=[],Lu=await parseProviderOptions({provider:"openai",providerOptions:Mu,schema:openaiSpeechModelOptionsSchema}),Bu={model:this.modelId,input:lo,voice:$u,response_format:"mp3",speed:Iu,instructions:Pu};if(Ru&&(["mp3","opus","aac","flac","wav","pcm"].includes(Ru)?Bu.response_format=Ru:Du.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${Ru}. Using mp3 instead.`})),Lu){const ju={};for(const Fu in ju){const zu=ju[Fu];zu!==void 0&&(Bu[Fu]=zu)}}return Ou&&Du.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${Ou}" was ignored.`}),{requestBody:Bu,warnings:Du}}async doGenerate(lo){var $u,Ru,Iu,Pu,Ou;const Mu=(Iu=(Ru=($u=this.config._internal)==null?void 0:$u.currentDate)==null?void 0:Ru.call($u))!=null?Iu:new Date,{requestBody:Du,warnings:Lu}=await this.getArgs(lo),{value:Bu,responseHeaders:ju,rawValue:Fu}=await postJsonToApi({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:combineHeaders((Ou=(Pu=this.config).headers)==null?void 0:Ou.call(Pu),lo.headers),body:Du,failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createBinaryResponseHandler(),abortSignal:lo.abortSignal,fetch:this.config.fetch});return{audio:Bu,warnings:Lu,request:{body:JSON.stringify(Du)},response:{timestamp:Mu,modelId:this.modelId,headers:ju,body:Fu}}}},openaiTranscriptionResponseSchema=lazySchema(()=>zodSchema(object({text:string$2(),language:string$2().nullish(),duration:number$2().nullish(),words:array(object({word:string$2(),start:number$2(),end:number$2()})).nullish(),segments:array(object({id:number$2(),seek:number$2(),start:number$2(),end:number$2(),text:string$2(),tokens:array(number$2()),temperature:number$2(),avg_logprob:number$2(),compression_ratio:number$2(),no_speech_prob:number$2()})).nullish()}))),openAITranscriptionModelOptions=lazySchema(()=>zodSchema(object({include:array(string$2()).optional(),language:string$2().optional(),prompt:string$2().optional(),temperature:number$2().min(0).max(1).default(0).optional(),timestampGranularities:array(_enum(["word","segment"])).default(["segment"]).optional(),streaming:object({delay:_enum(["minimal","low","medium","high","xhigh"]).optional(),include:array(string$2()).optional()}).optional()})));function isRealtimeTranscriptionModelId(Au){return Au==="gpt-realtime-whisper"||Au.startsWith("gpt-realtime-whisper-")}var languageMap={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},OpenAITranscriptionModel=class YS{constructor(lo,$u){this.modelId=lo,this.config=$u,this.specificationVersion="v4"}static[WORKFLOW_SERIALIZE](lo){return serializeModelOptions({modelId:lo.modelId,config:lo.config})}static[WORKFLOW_DESERIALIZE](lo){return new YS(lo.modelId,lo.config)}get provider(){return this.config.provider}async getArgs({audio:lo,mediaType:$u,providerOptions:Ru}){const Iu=[],Pu=await parseProviderOptions({provider:"openai",providerOptions:Ru,schema:openAITranscriptionModelOptions}),Ou=new FormData,Mu=lo instanceof Uint8Array?new Blob([lo]):new Blob([convertBase64ToUint8Array(lo)]);Ou.append("model",this.modelId);const Du=mediaTypeToExtension($u);if(Ou.append("file",new File([Mu],"audio",{type:$u}),`audio.${Du}`),this.modelId==="whisper-1"&&Ou.append("response_format","verbose_json"),Pu){const Lu=["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId),Bu={include:Pu.include,language:Pu.language,prompt:Pu.prompt,...this.modelId!=="whisper-1"&&{response_format:Lu?"json":"verbose_json"},temperature:Pu.temperature,timestamp_granularities:Pu.timestampGranularities};for(const[ju,Fu]of Object.entries(Bu))if(Fu!=null)if(Array.isArray(Fu))for(const zu of Fu)Ou.append(`${ju}[]`,String(zu));else Ou.append(ju,String(Fu))}return{formData:Ou,warnings:Iu}}async doGenerate(lo){var $u,Ru,Iu,Pu,Ou,Mu,Du,Lu,Bu,ju;if(isRealtimeTranscriptionModelId(this.modelId))throw new UnsupportedFunctionalityError({functionality:`non-streaming transcription with ${this.modelId}`});const Fu=(Iu=(Ru=($u=this.config._internal)==null?void 0:$u.currentDate)==null?void 0:Ru.call($u))!=null?Iu:new Date,{formData:zu,warnings:Uu}=await this.getArgs(lo),{value:Hu,responseHeaders:Vu,rawValue:Gu}=await postFormDataToApi({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:combineHeaders((Ou=(Pu=this.config).headers)==null?void 0:Ou.call(Pu),lo.headers),formData:zu,failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler(openaiTranscriptionResponseSchema),abortSignal:lo.abortSignal,fetch:this.config.fetch}),Wu=Hu.language!=null&&Hu.language in languageMap?languageMap[Hu.language]:void 0;return{text:Hu.text,segments:(Bu=(Lu=(Mu=Hu.segments)==null?void 0:Mu.map(Ku=>({text:Ku.text,startSecond:Ku.start,endSecond:Ku.end})))!=null?Lu:(Du=Hu.words)==null?void 0:Du.map(Ku=>({text:Ku.word,startSecond:Ku.start,endSecond:Ku.end})))!=null?Bu:[],language:Wu,durationInSeconds:(ju=Hu.duration)!=null?ju:void 0,warnings:Uu,response:{timestamp:Fu,modelId:this.modelId,headers:Vu,body:Gu}}}async doStream(lo){var $u,Ru,Iu,Pu,Ou,Mu,Du;if(!isRealtimeTranscriptionModelId(this.modelId))throw new UnsupportedFunctionalityError({functionality:`streaming transcription with ${this.modelId}`});const Lu=(Iu=(Ru=($u=this.config._internal)==null?void 0:$u.currentDate)==null?void 0:Ru.call($u))!=null?Iu:new Date,Bu=await parseProviderOptions({provider:"openai",providerOptions:lo.providerOptions,schema:openAITranscriptionModelOptions}),ju=[],Fu=(Ou=(Pu=lo.providerOptions)==null?void 0:Pu.openai)!=null?Ou:{};for(const Hu of["include","prompt","temperature","timestampGranularities"])Fu[Hu]!=null&&ju.push({type:"unsupported",feature:`providerOptions.openai.${Hu}`,details:`OpenAI streaming transcription does not support ${Hu}.`});const zu=combineHeaders((Du=(Mu=this.config).headers)==null?void 0:Du.call(Mu),lo.headers),Uu=buildOpenAIRealtimeTranscriptionSession({modelId:this.modelId,inputAudioFormat:lo.inputAudioFormat,providerOptions:Bu});return{request:{body:Uu},response:{timestamp:Lu,modelId:this.modelId},stream:createOpenAIRealtimeTranscriptionStream({webSocket:this.config.webSocket,url:toWebSocketUrl(this.config.url({path:"/realtime?intent=transcription",modelId:this.modelId})),headers:zu,sessionUpdate:Uu,language:Bu?.language,warnings:ju,audio:lo.audio,abortSignal:lo.abortSignal,includeRawChunks:lo.includeRawChunks})}}};function createOpenAIRealtimeTranscriptionStream({webSocket:Au,url:lo,headers:$u,sessionUpdate:Ru,language:Iu,warnings:Pu,audio:Ou,abortSignal:Mu,includeRawChunks:Du}){let Lu=!1,Bu=()=>{};return new ReadableStream({start:ju=>{const Fu=getOpenAIRealtimeConnection($u);let zu,Uu;Bu=Wu=>{zu!=null?zu.cancel().catch(()=>{}):Ou.cancel().catch(()=>{}),Uu?.close(Wu)};const Hu=Wu=>{Lu||(Lu=!0,Bu(),ju.error(Wu))},Vu=(Wu,Ku)=>{Lu||(Lu=!0,Ku!=null&&ju.enqueue({type:"transcript-final",id:Ku,text:Wu}),ju.enqueue({type:"finish",text:Wu,segments:[],language:Iu}),ju.close(),Bu(1e3))},Gu=async Wu=>{zu=Ou.getReader();try{for(;;){const{done:Ku,value:Ju}=await zu.read();if(Ku||Lu)break;Wu.send(JSON.stringify({type:"input_audio_buffer.append",audio:convertToBase64(Ju)})),await waitForWebSocketBufferDrain(Wu)}}finally{zu.releaseLock(),zu=void 0}Lu||Wu.send(JSON.stringify({type:"input_audio_buffer.commit"}))};Uu=connectToWebSocket({url:lo,protocols:Fu.protocols,headers:Fu.headers,webSocket:Au,abortSignal:Mu,onAbort:Hu,onProcessingError:Hu,onOpen:Wu=>{ju.enqueue({type:"stream-start",warnings:Pu}),Wu.send(JSON.stringify(Ru)),Gu(Wu).catch(Hu)},onMessageText:async Wu=>{var Ku,Ju,Yu,Xu;const ed=await safeParseJSON({text:Wu});if(!ed.success)return;const td=ed.value;switch(Du&&ju.enqueue({type:"raw",rawValue:td}),td.type){case"conversation.item.input_audio_transcription.delta":{ju.enqueue({type:"transcript-delta",id:td.item_id,delta:(Ku=td.delta)!=null?Ku:""});break}case"conversation.item.input_audio_transcription.completed":{Vu((Ju=td.transcript)!=null?Ju:"",td.item_id);break}case"error":{Hu(new Error((Xu=(Yu=td.error)==null?void 0:Yu.message)!=null?Xu:"OpenAI realtime error"));break}}},onSocketError:()=>{Hu(new Error("OpenAI realtime transcription error"))},onClose:()=>{Lu||(Lu=!0,Bu(),ju.close())}})},cancel:()=>{Lu||(Lu=!0,Bu())}})}function buildOpenAIRealtimeTranscriptionSession({modelId:Au,inputAudioFormat:lo,providerOptions:$u}){var Ru,Iu;return{type:"session.update",session:{type:"transcription",audio:{input:{format:{type:lo.type,...lo.rate!=null?{rate:lo.rate}:{}},transcription:{model:Au,...$u?.language!=null?{language:$u.language}:{},...((Ru=$u?.streaming)==null?void 0:Ru.delay)!=null?{delay:$u.streaming.delay}:{}},turn_detection:null}},...((Iu=$u?.streaming)==null?void 0:Iu.include)!=null?{include:$u.streaming.include}:{}}}}function getOpenAIRealtimeConnection(Au){var lo;let $u;for(const[Iu,Pu]of Object.entries(Au))Iu.toLowerCase()==="authorization"&&Pu!=null&&($u=Pu);const Ru=(lo=$u?.match(/^bearer\s+(.+)$/i))==null?void 0:lo[1];return Ru==null?{protocols:["realtime"],headers:Au}:{protocols:["realtime",`openai-insecure-api-key.${Ru}`],headers:Object.fromEntries(Object.entries(Au).filter(([Iu])=>Iu.toLowerCase()!=="authorization"))}}var openaiSkillResponseSchema=lazySchema(()=>zodSchema(object({id:string$2(),name:string$2().nullish(),description:string$2().nullish(),default_version:string$2().nullish(),latest_version:string$2().nullish(),created_at:number$2(),updated_at:number$2().nullish()}))),OpenAISkills=class{constructor(Au){this.config=Au,this.specificationVersion="v4"}get provider(){return this.config.provider}async uploadSkill(Au){const lo=[];Au.displayTitle!=null&&lo.push({type:"unsupported",feature:"displayTitle"});const $u=new FormData;for(const Iu of Au.files){const Pu=convertInlineFileDataToUint8Array(Iu.data);$u.append("files[]",new Blob([Pu]),Iu.path)}const{value:Ru}=await postFormDataToApi({url:this.config.url({path:"/skills"}),headers:combineHeaders(this.config.headers()),formData:$u,failedResponseHandler:openaiFailedResponseHandler,successfulResponseHandler:createJsonResponseHandler(openaiSkillResponseSchema),fetch:this.config.fetch});return{providerReference:{openai:Ru.id},...Ru.name!=null?{name:Ru.name}:{},...Ru.description!=null?{description:Ru.description}:{},...Ru.latest_version!=null?{latestVersion:Ru.latest_version}:{},providerMetadata:{openai:{...Ru.default_version!=null?{defaultVersion:Ru.default_version}:{},...Ru.created_at!=null?{createdAt:Ru.created_at}:{},...Ru.updated_at!=null?{updatedAt:Ru.updated_at}:{}}},warnings:lo}}},VERSION$1="4.0.20";function createOpenAI(Au={}){var lo,$u;const Ru=(lo=withoutTrailingSlash(validateBaseURL(loadOptionalSetting({settingValue:Au.baseURL,environmentVariableName:"OPENAI_BASE_URL"}))))!=null?lo:"https://api.openai.com/v1",Iu=($u=Au.name)!=null?$u:"openai",Pu=()=>withUserAgentSuffix({Authorization:`Bearer ${loadApiKey({apiKey:Au.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":Au.organization,"OpenAI-Project":Au.project,...Au.headers},`ai-sdk/openai/${VERSION$1}`),Ou=Ku=>new OpenAIChatLanguageModel(Ku,{provider:`${Iu}.chat`,url:({path:Ju})=>`${Ru}${Ju}`,headers:Pu,fetch:Au.fetch}),Mu=Ku=>new OpenAICompletionLanguageModel(Ku,{provider:`${Iu}.completion`,url:({path:Ju})=>`${Ru}${Ju}`,headers:Pu,fetch:Au.fetch}),Du=Ku=>new OpenAIEmbeddingModel(Ku,{provider:`${Iu}.embedding`,url:({path:Ju})=>`${Ru}${Ju}`,headers:Pu,fetch:Au.fetch}),Lu=Ku=>new OpenAIImageModel(Ku,{provider:`${Iu}.image`,url:({path:Ju})=>`${Ru}${Ju}`,headers:Pu,fetch:Au.fetch}),Bu=Ku=>new OpenAITranscriptionModel(Ku,{provider:`${Iu}.transcription`,url:({path:Ju})=>`${Ru}${Ju}`,headers:Pu,fetch:Au.fetch,webSocket:Au.webSocket}),ju=Ku=>new OpenAISpeechModel(Ku,{provider:`${Iu}.speech`,url:({path:Ju})=>`${Ru}${Ju}`,headers:Pu,fetch:Au.fetch}),Fu=()=>new OpenAIFiles({provider:`${Iu}.files`,baseURL:Ru,headers:Pu,fetch:Au.fetch}),zu=()=>new OpenAISkills({provider:`${Iu}.skills`,url:({path:Ku})=>`${Ru}${Ku}`,headers:Pu,fetch:Au.fetch}),Uu=Ku=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return Hu(Ku)},Hu=Ku=>new OpenAIResponsesLanguageModel(Ku,{provider:`${Iu}.responses`,url:({path:Ju})=>`${Ru}${Ju}`,headers:Pu,fetch:Au.fetch,fileIdPrefixes:["file-"]}),Vu=Ku=>new OpenAIRealtimeModel(Ku,{provider:`${Iu}.realtime`,baseURL:Ru,headers:Pu,fetch:Au.fetch}),Gu=Object.assign(Ku=>Vu(Ku),{getToken:async Ku=>{const Yu=await Vu(Ku.model).doCreateClientSecret({sessionConfig:Ku.sessionConfig,expiresAfterSeconds:Ku.expiresAfterSeconds});return{token:Yu.token,url:Yu.url,expiresAt:Yu.expiresAt}}}),Wu=function(Ku){return Uu(Ku)};return Wu.specificationVersion="v4",Wu.languageModel=Uu,Wu.chat=Ou,Wu.completion=Mu,Wu.responses=Hu,Wu.embedding=Du,Wu.embeddingModel=Du,Wu.textEmbedding=Du,Wu.textEmbeddingModel=Du,Wu.image=Lu,Wu.imageModel=Lu,Wu.transcription=Bu,Wu.transcriptionModel=Bu,Wu.speech=ju,Wu.speechModel=ju,Wu.files=Fu,Wu.skills=zu,Wu.experimental_realtime=Gu,Wu.tools=openaiTools,Wu}createOpenAI();const INFERENCE_API_PATH="/api/ai-inference/v1",DEFAULT_BROWSER_MODEL="bedrock:us.anthropic.claude-sonnet-4-6";function browserModelRequiresSignIn(Au){return!Au.token?.trim()}function inferenceApiUrl(Au){const lo=Au.replace(/\/+$/,"");return lo.endsWith(INFERENCE_API_PATH)?lo:`${lo}${INFERENCE_API_PATH}`}function describingFetch(Au,lo){return async($u,Ru)=>{try{return await Au($u,Ru)}catch(Iu){throw new Error(`Could not reach the inference service at ${lo}. Check that this is the right host — the service runs with the control plane, not the runtimes plane — and that it allows this origin. (${Iu instanceof Error?Iu.message:String(Iu)})`,{cause:Iu})}}}function createBrowserModel(Au){const lo=inferenceApiUrl(Au.inferenceUrl);return createOpenAI({name:"datalayer-ai-inference",baseURL:lo,apiKey:Au.token?.trim()||"anonymous",headers:Au.headers,fetch:describingFetch(Au.fetch??globalThis.fetch,lo)}).chat(Au.model||DEFAULT_BROWSER_MODEL)}const DEFAULT_BROWSER_MAX_STEPS=24,DEFAULT_TTL_MS=3e5,RETRY_MS=3e3;let pendingTimer;function readJwtClaims(Au){const lo=Au.split(".")[1];if(lo)try{const $u=lo.replace(/-/g,"+").replace(/_/g,"/"),Ru=$u.padEnd($u.length+(4-$u.length%4)%4,"="),Iu=JSON.parse(atob(Ru));return Iu&&typeof Iu=="object"?Iu:void 0}catch{return}}function tokenLifetimeMs(Au,lo){const $u=readJwtClaims(Au);return $u?.exp&&$u?.iat&&$u.exp>$u.iat?($u.exp-$u.iat)*1e3:lo&&lo>0?lo*1e3:DEFAULT_TTL_MS}async function fetchAnonymousToken(Au,lo){const $u=Au.replace(/\/+$/,""),Ru=await fetch(`${$u}/api/ai-inference/v1/anonymous/token`,{method:"POST",headers:{"Content-Type":"application/json"},signal:lo});if(!Ru.ok)throw new Error(`Anonymous inference token refused by ${$u} (HTTP ${Ru.status})`);const Iu=await Ru.json();if(!Iu.token)throw new Error(`No token in the reply from ${$u}`);const Pu=tokenLifetimeMs(Iu.token,Iu.expires_in);return{token:Iu.token,lifetimeMs:Pu,expiresAt:Date.now()+Pu}}const useAnonymousSessionStore=create$g((Au,lo)=>{const $u=Ru=>{Au({status:"minting",error:void 0}),fetchAnonymousToken(Ru).then(Iu=>{lo().status==="minting"&&(Au({status:"active",token:Iu.token,expiresAt:Iu.expiresAt,grantedMs:Iu.lifetimeMs,error:void 0}),clearTimeout(pendingTimer),pendingTimer=setTimeout(()=>lo().expire(),Math.max(0,Iu.expiresAt-Date.now())))}).catch(Iu=>{if(lo().status!=="minting")return;const Pu=Iu instanceof Error?Iu.message:String(Iu);console.warn("[anonymousToken] could not mint a token",Iu);const Ou=!lo().retried;Au({status:"failed",error:Pu,retried:!0}),Ou&&(clearTimeout(pendingTimer),pendingTimer=setTimeout(()=>{lo().status==="failed"&&$u(Ru)},RETRY_MS))})};return{status:"idle",start:Ru=>{const{status:Iu}=lo();Iu==="idle"&&Ru&&$u(Ru)},expire:()=>{const{status:Ru}=lo();Ru==="idle"||Ru==="expired"||(clearTimeout(pendingTimer),pendingTimer=void 0,Au({status:"expired",token:void 0}))},clear:()=>{lo().status!=="idle"&&(clearTimeout(pendingTimer),pendingTimer=void 0,Au({status:"idle",token:void 0,expiresAt:void 0,grantedMs:void 0,error:void 0,retried:!1}))}}});function useAnonymousSession(){return useAnonymousSessionStore()}function useAnonymousInferenceSession(Au,lo){const $u=useAnonymousSession();return reactExports.useEffect(()=>{const{start:Ru,clear:Iu}=useAnonymousSessionStore.getState();if(lo&&Au){Ru(Au);return}Iu()},[Au,lo]),$u}const SUBAGENT_STOPPED="Stopped.",isObject$2=Au=>!!Au&&typeof Au=="object";function parseAgentStreamMessage(Au){return isObject$2(Au)?typeof Au.type=="string"&&isObject$2(Au.payload)?{version:typeof Au.version=="string"?Au.version:"1.0",type:Au.type,agentId:typeof Au.agentId=="string"?Au.agentId:void 0,timestamp:typeof Au.timestamp=="string"?Au.timestamp:new Date().toISOString(),payload:Au.payload,event:typeof Au.event=="string"?Au.event:void 0,data:Au.data}:typeof Au.event=="string"&&isObject$2(Au.data)?{version:"1.0",type:Au.event,timestamp:new Date().toISOString(),payload:Au.data,event:Au.event,data:Au.data}:null:null}const DEFAULT_SUBAGENT_MAX_STEPS=12,TASK_SCHEMA={type:"object",properties:{task:{type:"string",description:"What to do, stated so that it can be carried out without the rest of this conversation."}},required:["task"]};function subagentTools(Au){const{subagents:lo,inference:$u,model:Ru,sharing:Iu="shared",maxSteps:Pu=DEFAULT_SUBAGENT_MAX_STEPS,tools:Ou,onEvent:Mu,signal:Du}=Au,Lu={};for(const Bu of lo)Lu[Bu.name]={description:Bu.description,inputSchema:jsonSchema$1(TASK_SCHEMA),execute:async(ju,Fu)=>{const{task:zu}=ju??{};if(!zu?.trim())return{error:"A delegated task needs to say what to do."};const Uu=Fu?.toolCallId??null;let Hu=!1;const Vu=Ku=>{if(Ku.phase==="end"||Ku.phase==="error"){if(Hu)return;Hu=!0}Mu?.({subagentName:Bu.name,toolCallId:Uu,...Ku})},Gu=new ToolLoopAgent({id:Bu.name,model:createBrowserModel({...$u,model:Bu.model??Ru}),instructions:Bu.instructions,tools:Bu.tools??Ou??{},stopWhen:isStepCount(Pu)}),Wu=anySignal([Fu?.abortSignal,Du?.()]);Vu({phase:"start",task:zu});try{const Ku=Iu==="shared"?Fu?.messages??[]:[],Ju=await Gu.stream({messages:[...Ku,{role:"user",content:zu}],abortSignal:Wu}),Yu=await relaySubagentRun(Ju.fullStream,Vu,Wu);if(Wu?.aborted)return Vu({phase:"error",error:STOPPED}),{agent:Bu.name,error:STOPPED};const Xu=Yu||await Ju.text;return Vu({phase:"end",output:Xu}),{agent:Bu.name,result:Xu}}catch(Ku){const Ju=Wu?.aborted?STOPPED:Ku instanceof Error?Ku.message:String(Ku);return Vu({phase:"error",error:Ju}),{agent:Bu.name,error:Ju}}},toModelOutput:({output:ju})=>{const Fu=ju;return{type:"text",value:Fu?.error?`${Bu.name} could not finish: ${Fu.error}`:Fu?.result??"Done."}}};return Lu}const STOPPED=SUBAGENT_STOPPED;function anySignal(Au){const lo=Au.filter(Ru=>!!Ru);if(lo.length<=1)return lo[0];if(typeof AbortSignal.any=="function")return AbortSignal.any(lo);const $u=new AbortController;for(const Ru of lo){if(Ru.aborted){$u.abort(Ru.reason);break}Ru.addEventListener("abort",()=>$u.abort(Ru.reason),{once:!0})}return $u.signal}function preview(Au){const lo=typeof Au=="string"?Au:JSON.stringify(Au);return lo.length>400?`${lo.slice(0,400)}…`:lo}async function relaySubagentRun(Au,lo,$u){let Ru="";for await(const Iu of Au){if($u?.aborted)break;switch(Iu.type){case"text-delta":Ru+=Iu.text??"",lo({phase:"text",text:Iu.text??""});break;case"reasoning-delta":lo({phase:"thinking",text:Iu.text??""});break;case"tool-call":lo({phase:"tool_call",toolName:Iu.toolName,toolArgs:Iu.input??{}});break;case"tool-result":lo({phase:"tool_result",toolName:Iu.toolName,result:preview(Iu.output)});break;case"tool-error":lo({phase:"tool_result",toolName:Iu.toolName,result:preview(Iu.error)});break;case"error":lo({phase:"error",error:Iu.error instanceof Error?Iu.error.message:String(Iu.error)});break}}return Ru}function messageText$2(Au){return typeof Au.content=="string"?Au.content:Au.content.map(lo=>typeof lo=="string"?lo:lo.text??"").join("")}function isModelRole(Au){return Au==="user"||Au==="assistant"||Au==="system"}class BrowserAgentAdapter extends BaseProtocolAdapter{protocol="browser-vercel-ai";protocolTransport="http";browserConfig;abortController=null;tools;constructor(lo){super(lo),this.browserConfig=lo;const $u=frontendToolsToVercelAI(lo.frontendTools??[],{onHitlRequired:lo.onHitlRequired,onStatusChange:lo.onStatusChange});this.tools={...$u,...lo.subagents?.length&&lo.inference?subagentTools({subagents:lo.subagents,inference:lo.inference,model:lo.model,sharing:lo.sharing,tools:$u,onEvent:lo.onSubagentEvent,signal:()=>this.abortController?.signal}):{}}}async connect(){this.setConnectionState("connected")}disconnect(){this.abortController?.abort(),this.abortController=null,this.setConnectionState("disconnected")}stopGeneration(){this.abortController?.abort()}supportsFeature(lo){return lo==="tools"}async sendToolResult(){}resolveModel(lo){const{languageModel:$u,inference:Ru,model:Iu}=this.browserConfig;if($u)return $u;if(!Ru)throw new Error("A browser agent needs either a `languageModel` or an `inference` endpoint to reach one.");return createBrowserModel({...Ru,model:lo||Iu})}runModes(lo){const $u=lo?.loop,Ru=$u?.modes??{},Iu=$u?.profile||void 0;if(Object.keys(Ru).length===0&&!Iu)return;const{modeEffect:Pu,languageModel:Ou}=this.browserConfig;if(!Pu)throw new Error("This agent has no modes or profiles: what was chosen in the composer cannot be applied to it.");const Mu=Pu(Ru,Iu);if(Mu.model&&Ou)throw new Error(`The mode or profile chosen runs on ${Mu.model}, and this agent's model is its host's own: it cannot run on another.`);return Mu}async sendMessage(lo,$u){this.abortController?.abort();const Ru=new AbortController;this.abortController=Ru;const Iu=($u?.messages??[]).filter(Bu=>isModelRole(Bu.role)).map(Bu=>({role:Bu.role,content:messageText$2(Bu)})).filter(Bu=>Bu.content.length>0),Pu=messageText$2(lo);Pu&&Iu[Iu.length-1]?.content!==Pu&&Iu.push({role:"user",content:Pu});let Ou=null,Mu="";const Du=()=>{Ou=generateMessageId(),Mu=""},Lu=()=>{const Bu=createAssistantMessage(Mu);Bu.id=Ou,this.emit({type:"message",message:Bu,timestamp:new Date})};try{const Bu=this.runModes($u?.forwardedProps),{instructions:ju}=this.browserConfig,Fu=Bu?.instructions?[ju?.trim(),Bu.instructions].filter(Boolean).join(`
|
|
2193
2193
|
|
|
2194
|
-
`):ju,zu=streamText({model:this.resolveModel(Bu?.model||$u?.model),system:Fu,messages:Iu,tools:this.tools,stopWhen:isStepCount(this.browserConfig.maxSteps??DEFAULT_BROWSER_MAX_STEPS),abortSignal:Ru.signal});for await(const Uu of zu.fullStream){if(Ru.signal.aborted)break;switch(Uu.type){case"text-start":Du();break;case"text-delta":Ou===null&&Du(),Mu+=Uu.text,Lu();break;case"tool-call":this.emit({type:"tool-call",toolCall:{toolCallId:Uu.toolCallId,toolName:Uu.toolName,args:Uu.input??{},argsComplete:!0},timestamp:new Date});break;case"tool-result":this.emit({type:"tool-result",toolResult:{toolCallId:Uu.toolCallId,success:!0,result:Uu.output},timestamp:new Date});break;case"tool-error":this.emit({type:"tool-result",toolResult:{toolCallId:Uu.toolCallId,success:!1,error:Uu.error instanceof Error?Uu.error.message:String(Uu.error)},timestamp:new Date});break;case"error":this.emit({type:"error",error:Uu.error instanceof Error?Uu.error:new Error(String(Uu.error)),timestamp:new Date});break;case"finish":{const Hu=Uu.totalUsage,Vu=Hu?.inputTokens??0,Gu=Hu?.outputTokens??0,Wu=Hu?.totalTokens??(Vu+Gu>0?Vu+Gu:void 0);this.emit({type:"done",usage:{promptTokens:Vu,completionTokens:Gu,totalTokens:Wu},timestamp:new Date});break}default:break}}}catch(Bu){if(Ru.signal.aborted)return;this.emit({type:"error",error:Bu instanceof Error?Bu:new Error(String(Bu)),timestamp:new Date}),this.emit({type:"done",timestamp:new Date})}finally{this.abortController===Ru&&(this.abortController=null)}}}const AGENT_METHODS={authenticate:"authenticate",initialize:"initialize",session_cancel:"session/cancel",session_fork:"session/fork",session_list:"session/list",session_load:"session/load",session_new:"session/new",session_prompt:"session/prompt",session_set_mode:"session/set_mode",session_set_model:"session/set_model"},CLIENT_METHODS={fs_read_text_file:"fs/read_text_file",fs_write_text_file:"fs/write_text_file",session_request_permission:"session/request_permission",session_update:"session/update",terminal_create:"terminal/create",terminal_kill:"terminal/kill",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit"},PROTOCOL_VERSION=1,zAuthMethod=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),description:union([string$2(),_null()]).optional(),id:string$2(),name:string$2()}),zAuthenticateRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),methodId:string$2()}),zAuthenticateResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zBlobResourceContents=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),blob:string$2(),mimeType:union([string$2(),_null()]).optional(),uri:string$2()}),zCreateTerminalResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),terminalId:string$2()}),zDiff=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),newText:string$2(),oldText:union([string$2(),_null()]).optional(),path:string$2()}),zEnvVariable=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),name:string$2(),value:string$2()}),zErrorCode=union([literal(-32700),literal(-32600),literal(-32601),literal(-32602),literal(-32603),literal(-32e3),literal(-32002),number$2().int()]),zError=object({code:zErrorCode,data:unknown$1().optional(),message:string$2()}),zExtNotification=unknown$1(),zExtRequest=unknown$1(),zExtResponse=unknown$1(),zFileSystemCapability=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),readTextFile:boolean$1().optional().default(!1),writeTextFile:boolean$1().optional().default(!1)}),zClientCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),fs:zFileSystemCapability.optional().default({readTextFile:!1,writeTextFile:!1}),terminal:boolean$1().optional().default(!1)}),zHttpHeader=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),name:string$2(),value:string$2()}),zImplementation=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),name:string$2(),title:union([string$2(),_null()]).optional(),version:string$2()}),zKillTerminalCommandResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zListSessionsRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),cursor:union([string$2(),_null()]).optional(),cwd:union([string$2(),_null()]).optional()}),zMcpCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),http:boolean$1().optional().default(!1),sse:boolean$1().optional().default(!1)}),zMcpServerHttp=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),headers:array(zHttpHeader),name:string$2(),url:string$2()}),zMcpServerSse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),headers:array(zHttpHeader),name:string$2(),url:string$2()}),zMcpServerStdio=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),args:array(string$2()),command:string$2(),env:array(zEnvVariable),name:string$2()}),zMcpServer=union([zMcpServerHttp.and(object({type:literal("http")})),zMcpServerSse.and(object({type:literal("sse")})),zMcpServerStdio]),zModelId=string$2(),zModelInfo=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),description:union([string$2(),_null()]).optional(),modelId:zModelId,name:string$2()}),zNewSessionRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),cwd:string$2(),mcpServers:array(zMcpServer)}),zPermissionOptionId=string$2(),zPermissionOptionKind=union([literal("allow_once"),literal("allow_always"),literal("reject_once"),literal("reject_always")]),zPermissionOption=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),kind:zPermissionOptionKind,name:string$2(),optionId:zPermissionOptionId}),zPlanEntryPriority=union([literal("high"),literal("medium"),literal("low")]),zPlanEntryStatus=union([literal("pending"),literal("in_progress"),literal("completed")]),zPlanEntry=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:string$2(),priority:zPlanEntryPriority,status:zPlanEntryStatus}),zPlan=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),entries:array(zPlanEntry)}),zPromptCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),audio:boolean$1().optional().default(!1),embeddedContext:boolean$1().optional().default(!1),image:boolean$1().optional().default(!1)}),zProtocolVersion=number$2().int().gte(0).lte(65535),zInitializeRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),clientCapabilities:zClientCapabilities.optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:union([zImplementation,_null()]).optional(),protocolVersion:zProtocolVersion}),zReadTextFileResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:string$2()}),zReleaseTerminalResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zRequestId=union([_null(),bigint(),string$2()]),zRole=_enum(["assistant","user"]),zAnnotations=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),audience:union([array(zRole),_null()]).optional(),lastModified:union([string$2(),_null()]).optional(),priority:union([number$2(),_null()]).optional()}),zAudioContent=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),annotations:union([zAnnotations,_null()]).optional(),data:string$2(),mimeType:string$2()}),zImageContent=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),annotations:union([zAnnotations,_null()]).optional(),data:string$2(),mimeType:string$2(),uri:union([string$2(),_null()]).optional()}),zResourceLink=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),annotations:union([zAnnotations,_null()]).optional(),description:union([string$2(),_null()]).optional(),mimeType:union([string$2(),_null()]).optional(),name:string$2(),size:union([bigint(),_null()]).optional(),title:union([string$2(),_null()]).optional(),uri:string$2()}),zSelectedPermissionOutcome=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),optionId:zPermissionOptionId}),zRequestPermissionOutcome=union([object({outcome:literal("cancelled")}),zSelectedPermissionOutcome.and(object({outcome:literal("selected")}))]),zRequestPermissionResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),outcome:zRequestPermissionOutcome}),zSessionForkCapabilities=object({_meta:unknown$1().optional()}),zSessionId=string$2(),zCancelNotification=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId});object({method:string$2(),params:union([union([zCancelNotification,zExtNotification]),_null()]).optional()});const zCreateTerminalRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),args:array(string$2()).optional(),command:string$2(),cwd:union([string$2(),_null()]).optional(),env:array(zEnvVariable).optional(),outputByteLimit:union([number$2().int().gte(0),_null()]).optional(),sessionId:zSessionId}),zForkSessionRequest=object({_meta:unknown$1().optional(),sessionId:zSessionId}),zKillTerminalCommandRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId,terminalId:string$2()}),zLoadSessionRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),cwd:string$2(),mcpServers:array(zMcpServer),sessionId:zSessionId}),zReadTextFileRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),limit:union([number$2().int().gte(0),_null()]).optional(),line:union([number$2().int().gte(0),_null()]).optional(),path:string$2(),sessionId:zSessionId}),zReleaseTerminalRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId,terminalId:string$2()}),zSessionInfo=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),cwd:string$2(),sessionId:zSessionId,title:union([string$2(),_null()]).optional(),updatedAt:union([string$2(),_null()]).optional()}),zListSessionsResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),nextCursor:union([string$2(),_null()]).optional(),sessions:array(zSessionInfo)}),zSessionListCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zSessionCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),fork:union([zSessionForkCapabilities,_null()]).optional(),list:union([zSessionListCapabilities,_null()]).optional()}),zAgentCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),loadSession:boolean$1().optional().default(!1),mcpCapabilities:zMcpCapabilities.optional().default({http:!1,sse:!1}),promptCapabilities:zPromptCapabilities.optional().default({audio:!1,embeddedContext:!1,image:!1}),sessionCapabilities:zSessionCapabilities.optional().default({})}),zInitializeResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),agentCapabilities:zAgentCapabilities.optional().default({loadSession:!1,mcpCapabilities:{http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:union([zImplementation,_null()]).optional(),authMethods:array(zAuthMethod).optional().default([]),protocolVersion:zProtocolVersion}),zSessionModeId=string$2(),zCurrentModeUpdate=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),currentModeId:zSessionModeId}),zSessionMode=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),description:union([string$2(),_null()]).optional(),id:zSessionModeId,name:string$2()}),zSessionModeState=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),availableModes:array(zSessionMode),currentModeId:zSessionModeId}),zSessionModelState=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),availableModels:array(zModelInfo),currentModelId:zModelId}),zForkSessionResponse=object({_meta:unknown$1().optional(),models:union([zSessionModelState,_null()]).optional(),modes:union([zSessionModeState,_null()]).optional(),sessionId:zSessionId}),zLoadSessionResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),models:union([zSessionModelState,_null()]).optional(),modes:union([zSessionModeState,_null()]).optional()}),zNewSessionResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),models:union([zSessionModelState,_null()]).optional(),modes:union([zSessionModeState,_null()]).optional(),sessionId:zSessionId}),zSetSessionModeRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),modeId:zSessionModeId,sessionId:zSessionId}),zSetSessionModeResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zSetSessionModelRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),modelId:zModelId,sessionId:zSessionId}),zSetSessionModelResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zStopReason=union([literal("end_turn"),literal("max_tokens"),literal("max_turn_requests"),literal("refusal"),literal("cancelled")]),zPromptResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),stopReason:zStopReason});union([object({id:zRequestId,result:union([zInitializeResponse,zAuthenticateResponse,zNewSessionResponse,zLoadSessionResponse,zListSessionsResponse,zForkSessionResponse,zSetSessionModeResponse,zPromptResponse,zSetSessionModelResponse,zExtResponse])}),object({error:zError,id:zRequestId})]);const zTerminal=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),terminalId:string$2()}),zTerminalExitStatus=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),exitCode:union([number$2().int().gte(0),_null()]).optional(),signal:union([string$2(),_null()]).optional()}),zTerminalOutputRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId,terminalId:string$2()}),zTerminalOutputResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),exitStatus:union([zTerminalExitStatus,_null()]).optional(),output:string$2(),truncated:boolean$1()}),zTextContent=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),annotations:union([zAnnotations,_null()]).optional(),text:string$2()}),zTextResourceContents=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),mimeType:union([string$2(),_null()]).optional(),text:string$2(),uri:string$2()}),zEmbeddedResourceResource=union([zTextResourceContents,zBlobResourceContents]),zEmbeddedResource=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),annotations:union([zAnnotations,_null()]).optional(),resource:zEmbeddedResourceResource}),zContentBlock=union([zTextContent.and(object({type:literal("text")})),zImageContent.and(object({type:literal("image")})),zAudioContent.and(object({type:literal("audio")})),zResourceLink.and(object({type:literal("resource_link")})),zEmbeddedResource.and(object({type:literal("resource")}))]),zContent=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:zContentBlock}),zContentChunk=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:zContentBlock}),zPromptRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),prompt:array(zContentBlock),sessionId:zSessionId});object({id:zRequestId,method:string$2(),params:union([union([zInitializeRequest,zAuthenticateRequest,zNewSessionRequest,zLoadSessionRequest,zListSessionsRequest,zForkSessionRequest,zSetSessionModeRequest,zPromptRequest,zSetSessionModelRequest,zExtRequest]),_null()]).optional()});const zToolCallContent=union([zContent.and(object({type:literal("content")})),zDiff.and(object({type:literal("diff")})),zTerminal.and(object({type:literal("terminal")}))]),zToolCallId=string$2(),zToolCallLocation=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),line:union([number$2().int().gte(0),_null()]).optional(),path:string$2()}),zToolCallStatus=union([literal("pending"),literal("in_progress"),literal("completed"),literal("failed")]),zToolKind=union([literal("read"),literal("edit"),literal("delete"),literal("move"),literal("search"),literal("execute"),literal("think"),literal("fetch"),literal("switch_mode"),literal("other")]),zToolCall=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:array(zToolCallContent).optional(),kind:zToolKind.optional(),locations:array(zToolCallLocation).optional(),rawInput:unknown$1().optional(),rawOutput:unknown$1().optional(),status:zToolCallStatus.optional(),title:string$2(),toolCallId:zToolCallId}),zToolCallUpdate=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:union([array(zToolCallContent),_null()]).optional(),kind:union([zToolKind,_null()]).optional(),locations:union([array(zToolCallLocation),_null()]).optional(),rawInput:unknown$1().optional(),rawOutput:unknown$1().optional(),status:union([zToolCallStatus,_null()]).optional(),title:union([string$2(),_null()]).optional(),toolCallId:zToolCallId}),zRequestPermissionRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),options:array(zPermissionOption),sessionId:zSessionId,toolCall:zToolCallUpdate}),zUnstructuredCommandInput=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),hint:string$2()}),zAvailableCommandInput=zUnstructuredCommandInput,zAvailableCommand=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),description:string$2(),input:union([zAvailableCommandInput,_null()]).optional(),name:string$2()}),zAvailableCommandsUpdate=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),availableCommands:array(zAvailableCommand)}),zSessionUpdate=union([zContentChunk.and(object({sessionUpdate:literal("user_message_chunk")})),zContentChunk.and(object({sessionUpdate:literal("agent_message_chunk")})),zContentChunk.and(object({sessionUpdate:literal("agent_thought_chunk")})),zToolCall.and(object({sessionUpdate:literal("tool_call")})),zToolCallUpdate.and(object({sessionUpdate:literal("tool_call_update")})),zPlan.and(object({sessionUpdate:literal("plan")})),zAvailableCommandsUpdate.and(object({sessionUpdate:literal("available_commands_update")})),zCurrentModeUpdate.and(object({sessionUpdate:literal("current_mode_update")}))]),zSessionNotification=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId,update:zSessionUpdate});object({method:string$2(),params:union([union([zSessionNotification,zExtNotification]),_null()]).optional()});const zWaitForTerminalExitRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId,terminalId:string$2()}),zWaitForTerminalExitResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),exitCode:union([number$2().int().gte(0),_null()]).optional(),signal:union([string$2(),_null()]).optional()}),zWriteTextFileRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:string$2(),path:string$2(),sessionId:zSessionId});object({id:zRequestId,method:string$2(),params:union([union([zWriteTextFileRequest,zReadTextFileRequest,zRequestPermissionRequest,zCreateTerminalRequest,zTerminalOutputRequest,zReleaseTerminalRequest,zWaitForTerminalExitRequest,zKillTerminalCommandRequest,zExtRequest]),_null()]).optional()});const zWriteTextFileResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()});union([object({id:zRequestId,result:union([zWriteTextFileResponse,zReadTextFileResponse,zRequestPermissionResponse,zCreateTerminalResponse,zTerminalOutputResponse,zReleaseTerminalResponse,zWaitForTerminalExitResponse,zKillTerminalCommandResponse,zExtResponse])}),object({error:zError,id:zRequestId})]);class ACPAdapter extends BaseProtocolAdapter{protocol="acp";protocolTransport="websocket";acpConfig;ws=null;session=null;agent=null;streamingContent="";streamingMessageId=null;pendingPermission=null;pendingRequests=new Map;constructor(lo){super(lo),this.acpConfig=lo}getSession(){return this.session}getAgent(){return this.agent}getPendingPermission(){return this.pendingPermission}async connect(){if(this.ws?.readyState!==WebSocket.OPEN)return this.setConnectionState("connecting"),new Promise((lo,$u)=>{try{const Ru=this.acpConfig.wsUrl||this.config.baseUrl,Iu=this.config.agentId,Pu=Iu?`${Ru}/${Iu}`:Ru;this.ws=new WebSocket(Pu),this.ws.onopen=async()=>{this.reconnectAttempts=0;try{const Ou=await this.sendRequest("initialize",{protocolVersion:PROTOCOL_VERSION,clientCapabilities:this.acpConfig.clientCapabilities||{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}});Ou.agentCapabilities?.agent&&(this.agent=Ou.agentCapabilities.agent);const Mu=await this.sendRequest(AGENT_METHODS.session_new,{});Mu.sessionId?this.session={sessionId:Mu.sessionId,agentId:this.config.agentId||"",createdAt:new Date().toISOString(),status:"active"}:Ou.session_id&&(this.session={sessionId:Ou.session_id,agentId:this.config.agentId||"",createdAt:new Date().toISOString(),status:"active"}),this.setConnectionState("connected"),lo()}catch(Ou){console.error("[ACPAdapter] Initialization error:",Ou),this.setConnectionState("connected"),lo()}},this.ws.onmessage=Ou=>{this.handleMessage(Ou)},this.ws.onerror=Ou=>{console.error("[ACPAdapter] WebSocket error:",Ou),this.emit({type:"error",error:new Error("WebSocket error"),timestamp:new Date})},this.ws.onclose=()=>{this.ws=null,this.setConnectionState("disconnected"),this.handleReconnect()}}catch(Ru){this.setConnectionState("error"),this.emit({type:"error",error:Ru instanceof Error?Ru:new Error(String(Ru)),timestamp:new Date}),$u(Ru)}})}disconnect(){this.session&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.terminateSession(this.session.sessionId).catch(lo=>{console.warn("[ACPAdapter] Failed to terminate session:",lo)});for(const[,{reject:lo}]of this.pendingRequests)lo(new Error("Connection closed"));this.pendingRequests.clear(),this.ws&&(this.ws.close(),this.ws=null),this.session=null,this.agent=null,this.pendingPermission=null,this.setConnectionState("disconnected")}async terminateSession(lo){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){console.warn("[ACPAdapter] Cannot terminate: WebSocket not connected");return}try{const $u=lo||this.session?.sessionId;if(!$u){console.warn("[ACPAdapter] Cannot terminate: No session ID");return}const Ru={jsonrpc:"2.0",method:"session/cancel",params:{sessionId:$u}};this.ws.send(JSON.stringify(Ru)),console.debug("[ACPAdapter] Sent session/cancel for:",$u)}catch($u){console.debug("[ACPAdapter] Terminate request error:",$u)}}async sendMessage(lo,$u){if(!this.session)throw new Error("No active session");this.streamingContent="",this.streamingMessageId=generateMessageId();try{const Ru=typeof lo.content=="string"?lo.content:lo.content.filter(Pu=>Pu.type==="text").map(Pu=>Pu.text||"").join("");$u?.model&&console.log("[ACPAdapter] Sending with model:",$u.model),$u?.identities&&$u.identities.length>0&&console.log("[ACPAdapter] Sending with identities:",$u.identities.map(Pu=>Pu.provider));const Iu={};$u?.model&&(Iu.model=$u.model),$u?.identities&&$u.identities.length>0&&(Iu.identities=$u.identities),await this.sendRequest(AGENT_METHODS.session_prompt,{sessionId:this.session.sessionId,prompt:[{type:"text",text:Ru}],...Object.keys(Iu).length>0&&{metadata:Iu}})}catch(Ru){throw this.emit({type:"error",error:Ru instanceof Error?Ru:new Error(String(Ru)),timestamp:new Date}),Ru}}async sendToolResult(lo,$u){if(!this.session)throw new Error("No active session");this.emit({type:"tool-result",toolResult:$u,timestamp:new Date}),this.pendingPermission&&this.grantPermission()}grantPermission(lo){if(this.pendingPermission){const $u=lo||this.pendingPermission.options[0]?.optionId||"allow";this.sendResponse(this.pendingPermission.requestId,{outcome:{outcome:"selected",optionId:$u}}),this.pendingPermission=null}}denyPermission(){this.pendingPermission&&(this.sendResponse(this.pendingPermission.requestId,{outcome:{outcome:"cancelled"}}),this.pendingPermission=null)}supportsFeature(lo){return["streaming","tools","permissions","session-management","bidirectional"].includes(lo)}generateId(){return`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}async sendRequest(lo,$u={}){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("Not connected to agent");const Ru=this.generateId(),Iu={jsonrpc:"2.0",id:Ru,method:lo,params:$u};return new Promise((Pu,Ou)=>{this.pendingRequests.set(Ru,{resolve:Pu,reject:Ou}),this.ws&&this.ws.send(JSON.stringify(Iu)),setTimeout(()=>{this.pendingRequests.has(Ru)&&(this.pendingRequests.delete(Ru),Ou(new Error("Request timeout")))},this.config.timeout||3e4)})}sendResponse(lo,$u){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){console.error("[ACPAdapter] Cannot send response: not connected");return}const Ru={jsonrpc:"2.0",id:lo,result:$u};this.ws.send(JSON.stringify(Ru))}handleMessage(lo){try{const $u=JSON.parse(lo.data);if($u.id&&this.pendingRequests.has($u.id)){const Ru=this.pendingRequests.get($u.id);if(!Ru)return;const{resolve:Iu,reject:Pu}=Ru;this.pendingRequests.delete($u.id),$u.error?Pu(new Error($u.error.message)):Iu($u.result),$u.result&&typeof $u.result=="object"&&"stopReason"in $u.result&&this.handleCompletion($u.result);return}if($u.method==="session/update"){this.handleSessionUpdate($u.params||{});return}if($u.method===CLIENT_METHODS.session_request_permission&&$u.id){this.handlePermissionRequest($u.id,$u.params);return}$u.result&&typeof $u.result=="object"&&"stopReason"in $u.result&&this.handleCompletion($u.result)}catch($u){console.error("[ACPAdapter] Failed to parse message:",$u)}}handleSessionUpdate(lo){const $u=lo.update;if(!$u)return;const Ru=$u.sessionUpdate,Iu=Pu=>Pu&&typeof Pu=="object"&&Pu.type==="text"?String(Pu.text??""):"";if(Ru==="agent_message_chunk"){const Pu=Iu($u.content);if(Pu){this.streamingContent+=Pu;const Ou=createAssistantMessage(this.streamingContent);this.streamingMessageId&&(Ou.id=this.streamingMessageId),this.emit({type:"message",message:Ou,timestamp:new Date})}}if(Ru==="tool_call"){const Pu=$u;this.emit({type:"tool-call",toolCall:{toolCallId:Pu.toolCallId||generateMessageId(),toolName:Pu.title||"",args:Pu.rawInput||{}},timestamp:new Date})}if(Ru==="tool_call_update"){const Pu=$u;(Pu.status==="completed"||Pu.status==="failed")&&this.emit({type:"tool-result",toolResult:{toolCallId:Pu.toolCallId??"",success:Pu.status==="completed",result:Pu.rawOutput},timestamp:new Date})}if(Ru==="agent_thought_chunk"){const Pu=Iu($u.content);Pu&&this.emit({type:"activity",activity:{type:"thought",data:Pu},timestamp:new Date})}}handlePermissionRequest(lo,$u){this.pendingPermission={requestId:lo,sessionId:$u.sessionId,toolCall:$u.toolCall,options:$u.options},this.emit({type:"tool-call",toolCall:{toolCallId:$u.toolCall.toolCallId,toolName:$u.toolCall.title||"",args:$u.toolCall.rawInput||{}},timestamp:new Date}),this.acpConfig.onPermissionRequest?.(this.pendingPermission)}handleCompletion(lo){if(this.streamingContent){const $u=createAssistantMessage(this.streamingContent);$u.id=this.streamingMessageId||generateMessageId(),this.emit({type:"message",message:$u,timestamp:new Date}),this.streamingContent="",this.streamingMessageId=null}this.emit({type:"activity",activity:{type:"completed",data:{stopReason:lo.stopReason}},timestamp:new Date})}}const internalQueryClient=new QueryClient({defaultOptions:{queries:{staleTime:300*1e3,refetchOnWindowFocus:!1}}});function isToolCallMessage(Au){return"type"in Au&&Au.type==="tool-call"}function getMessageText(Au){const lo=typeof Au.content=="string"?Au.content:Au.content.filter($u=>$u.type==="text").map($u=>$u.text).join("");return Au.role==="assistant"?sanitizeAssistantContent(lo):lo}function formatTokenCount(Au){return Au>=1e6?`${(Au/1e6).toFixed(1)}M`:Au>=1e3?`${(Au/1e3).toFixed(1)}K`:Au.toString()}function getApiBaseFromConfig(Au){return Au.replace(/\/(config|configure)\/?$/,"")}function createProtocolAdapter(Au){const lo={protocol:Au.type,baseUrl:Au.endpoint,authToken:Au.authToken,agentId:Au.agentId,...Au.options};switch(Au.type){case"ag-ui":if(Au.ownRoutesOnly&&!Au.appSessions)throw new Error("A chat whose runtime answers only the application’s own routes is an application’s: it needs its sessions (appSessions).");return new AGUIAdapter({...lo,...Au.appSessions?{appSessions:Au.appSessions}:{}});case"a2a":return new A2AAdapter(lo);case"vercel-ai":return new VercelAIAdapter(lo);case"acp":return new ACPAdapter(lo);case"browser-vercel-ai":return new BrowserAgentAdapter(lo);default:return console.warn(`[ChatBase] Unknown protocol type: ${Au.type}`),null}}const PAP_SIGN_IN_WORDS={title:Au=>`Sign in at ${Au}`,direct:"Open the company’s page through Datalayer, sign in there, and this conversation goes on once you are back.",device:"Open the company’s page and enter this code there.",mediatedTitle:Au=>`Sign in through ${Au}`,mediated:"Open this page: it names the company and asks what the company needs. Type it there, never in this conversation.",sentTo:Au=>`The company sent a code to ${Au}.`,needs:Au=>`It needs: ${Au.join(", ")}.`,open:Au=>`Open ${Au}`,code:"Your code",copy:"Copy the code",copied:"Copied",until:Au=>`Until ${new Date(Au).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}.`,checkAgain:"I have signed in: check again",tellMe:"Tell me when you are done.",checkMessage:Au=>`I have signed in at ${Au}. Please check again.`,refused:"This sign-in link cannot be opened safely, so it is not shown.",qr:Au=>`A code to scan to open ${Au} on your phone`,returned:{signed_in:Au=>`Signed in at ${Au}: checking again.`,denied:Au=>`You did not sign in at ${Au}: ask again when you want to.`,refused:Au=>`That sign-in at ${Au} was refused, and nothing was kept: start it again here.`}},PAP_SIGN_IN_CHANNEL="datalayer-pap-sign-in",SCOPE=/^[\x21\x23-\x5B\x5D-\x7E]{1,128}$/,DOMAIN=/^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;function signInReturnOf(Au,lo){if(!Au||typeof Au!="object"||Array.isArray(Au))return null;const $u=Au,Ru=$u.outcome;return $u.company===lo&&(Ru==="signed_in"||Ru==="denied"||Ru==="refused")?Ru:null}const PAP_SIGN_IN_TOOL=/(^|[_.:\-/])pa(?:p|ct)_sign_in$/,isPapSignInTool=Au=>PAP_SIGN_IN_TOOL.test(Au);function unwrapped(Au){let lo=Au;if(typeof lo=="string")try{lo=JSON.parse(lo)}catch{return null}if(!lo||typeof lo!="object"||Array.isArray(lo))return null;const $u=lo;if($u.structuredContent&&typeof $u.structuredContent=="object")return unwrapped($u.structuredContent);if(Array.isArray($u.content)){const Ru=$u.content.find(Iu=>Iu?.type==="text"&&typeof Iu.text=="string");return Ru?unwrapped(Ru.text):null}return $u.result&&typeof $u.result=="object"&&!("status"in $u)?unwrapped($u.result):$u}function safeSignInUrl(Au){if(typeof Au!="string")return null;try{const lo=new URL(Au);return lo.protocol==="https:"&&lo.hostname?lo:null}catch{return null}}function readPapSignIn(Au){const lo=unwrapped(Au);if(!lo||lo.status!=="waiting_for_the_person"||lo.mode!=="direct"&&lo.mode!=="device"&&lo.mode!=="mediated")return null;const $u=safeSignInUrl(lo.open);if(!$u)return{refused:PAP_SIGN_IN_WORDS.refused};if(lo.mode==="device"&&(typeof lo.code!="string"||!lo.code))return null;const Ru=typeof lo.company=="string"&&DOMAIN.test(lo.company)?lo.company:"",Iu=Array.isArray(lo.needs)?lo.needs.filter(Pu=>typeof Pu=="string"&&SCOPE.test(Pu)):[];return{mode:lo.mode,open:$u.toString(),host:$u.hostname,...Ru?{company:Ru}:{},...typeof lo.code=="string"&&lo.code?{code:lo.code}:{},...lo.mode==="mediated"&&typeof lo.sent_to=="string"&&lo.sent_to?{sentTo:lo.sent_to}:{},...typeof lo.expires_at=="string"&&lo.expires_at?{expiresAt:lo.expires_at}:{},...Iu.length>0?{needs:Iu}:{}}}const PAP_SIGN_IN_TYPE$1="application/vnd.datalayer.pap.sign-in+json",PAP_CONFIRM_TYPE="application/vnd.datalayer.pap.confirm+json",PAP_OUTCOME_TYPE="application/vnd.datalayer.pap.outcome+json",PAP_REPLIES_TYPE="application/vnd.datalayer.pap.replies+json",SHIELD_DIFF_TYPE="application/vnd.datalayer.shield.diff+json",SHIELD_TERMINAL_TYPE="application/vnd.datalayer.shield.terminal+json",DISPLAY_META_KEY="reactor.ui/display",record$1=Au=>Au&&typeof Au=="object"&&!Array.isArray(Au)?Au:null,text$h=Au=>typeof Au=="string"?Au:"",words=Au=>text$h(Au).trim(),count=Au=>typeof Au=="number"&&Number.isInteger(Au)&&Au>=1?Au:0,ACTIONS=["read","write","send","buy","delete","publish"],OUTCOMES=["in_progress","succeeded","failed","cancelled","expired"],STATUSES=["working","idle","queued","closed"],who=Au=>Au==="agent"||Au==="human"?Au:null;function protocolDisplayOf(Au){const lo=record$1(Au);if(!lo||!text$h(lo.type))return null;const $u=text$h(lo.id),Ru=record$1(lo.data)??{},Iu={kind:"unknown",id:$u,type:text$h(lo.type),version:typeof lo.version=="number"?lo.version:0,text:text$h(lo.text)};switch(lo.type){case PAP_SIGN_IN_TYPE$1:{const Pu=readPapSignIn({status:"waiting_for_the_person",...Ru});return Pu?"refused"in Pu?{kind:"sign-in-refused",id:$u,why:Pu.refused}:{kind:"sign-in",id:$u,...Pu}:Iu}case PAP_CONFIRM_TYPE:{const Pu=words(Ru.company),Ou=text$h(Ru.summary),Mu=words(Ru.operation_ref),Du=count(Ru.revision),Lu=record$1(Ru.terms),Bu=record$1(Ru.was),ju=Bu?count(Bu.revision):0;if(!Pu||!Ou.trim()||!Mu||!Du||!Lu||!$u.endsWith("-confirm")||Bu&&(!ju||ju>=Du))return Iu;const Fu=Ru.does===null||Ru.does===void 0?null:ACTIONS.find(Uu=>Uu===Ru.does);if(Fu===void 0)return Iu;const zu=record$1(Ru.session);return{kind:"confirm",id:$u,approvalId:$u.slice(0,-8),company:Pu,summary:Ou,terms:Lu,operationRef:Mu,revision:Du,does:Fu,signedIn:zu&&typeof zu.signed_in=="boolean"?zu.signed_in:null,expiresAt:text$h(Ru.expires_at),was:Bu?{revision:ju,terms:record$1(Bu.terms)??{}}:null,onlyThePerson:Ru.only_the_person===!0}}case PAP_OUTCOME_TYPE:{const Pu=OUTCOMES.find(Lu=>Lu===Ru.state),Ou=words(Ru.company),Mu=text$h(Ru.summary),Du=text$h(Ru.result);return!Pu||!Ou||!Mu.trim()||!words(Ru.operation_ref)||!count(Ru.revision)||Pu==="in_progress"!=!Du.trim()?Iu:{kind:"outcome",id:$u,company:Ou,summary:Mu,operationRef:words(Ru.operation_ref),revision:count(Ru.revision),state:Pu,result:Du,approvedBy:Ru.approved_by==="user"||Ru.approved_by==="standing_permission"?Ru.approved_by:null}}case PAP_REPLIES_TYPE:{const Pu=words(Ru.company),Ou=text$h(Ru.conversation),Mu=Array.isArray(Ru.replies)?Ru.replies.map(record$1).map(Du=>({sender:who(Du?.sender),text:text$h(Du?.text)})):[];return!Pu||!/^[A-Za-z0-9_-]{1,256}$/.test(Ou)||!Mu.length||Mu.some(Du=>!Du.sender||!Du.text.trim())?Iu:{kind:"replies",id:$u,company:Pu,conversation:Ou,replies:Mu,status:STATUSES.find(Du=>Du===Ru.status)??null,responder:who(Ru.responder)}}case SHIELD_DIFF_TYPE:{const Pu=words(Ru.path);return!Pu||typeof Ru.new_text!="string"||!(Ru.old_text===null||Ru.old_text===void 0||typeof Ru.old_text=="string")?Iu:{kind:"diff",id:$u,path:Pu,oldText:typeof Ru.old_text=="string"?Ru.old_text:null,newText:Ru.new_text,language:words(Ru.language)||languageOf$1(Pu)}}case SHIELD_TERMINAL_TYPE:{const Pu=words(Ru.terminal_id);if(!Pu)return Iu;const Ou=typeof Ru.exit_code=="number"&&Number.isInteger(Ru.exit_code)?Ru.exit_code:null;return Ru.exit_code!==null&&Ru.exit_code!==void 0&&Ou===null?Iu:{kind:"terminal",id:$u,terminalId:Pu,command:text$h(Ru.command),output:text$h(Ru.output),exitCode:Ou,released:Ru.released===!0}}default:return Iu}}const PAP_HANDOFF_TOOL=/(^|[_.:\-/])pap_handoff$/;function displayOfToolResult(Au,lo,$u=""){const Ru=record$1(lo),Iu=record$1(Ru?._meta)?.[DISPLAY_META_KEY];if(Iu!==void 0)return protocolDisplayOf(Iu);if(isPapSignInTool(Au)){const Pu=readPapSignIn(lo);return Pu?"refused"in Pu?{kind:"sign-in-refused",id:$u,why:Pu.refused}:{kind:"sign-in",id:$u,...Pu}:null}if(PAP_HANDOFF_TOOL.test(Au)&&Ru){const Pu=text$h(Ru.status);return Pu?{kind:"handoff",id:$u,handed:Pu!=="closed"&&Pu!=="direct_conversation_open",responder:who(Ru.responder),note:text$h(Ru.note)}:null}return null}function displayLine(Au){switch(Au.kind){case"sign-in":return Au.mode==="mediated"?`Sign in through ${Au.host}`:`Sign in at ${Au.company||Au.host}`;case"sign-in-refused":return Au.why;case"confirm":return`${Au.company} asks you to confirm: ${Au.summary} (version ${Au.revision})`;case"outcome":return Au.state==="in_progress"?`Still in progress at ${Au.company}: ${Au.summary}`:`${OUTCOME_LEADS[Au.state]} ${Au.company}: ${Au.result}`;case"replies":return`${Au.company} answered${Au.responder==="human"?": one of its people is answering":""}`;case"handoff":return Au.handed?`Handed to ${Au.responder==="human"?"one of the company’s people":"the company"}`:Au.note||"Nothing was handed over.";case"diff":{const lo=countLines(Au.newText);return Au.oldText===null?`Wrote ${Au.path} (${lo} lines)`:`Changed ${Au.path} (+${lo} −${countLines(Au.oldText)} lines)`}case"terminal":{const lo=Au.command?`Ran \`${Au.command}\``:`Terminal ${Au.terminalId}`;return Au.exitCode===null?`${lo}: running`:`${lo}: exit ${Au.exitCode}`}case"unknown":return Au.text||`A display this app cannot draw (${Au.type})`}}const OUTCOME_LEADS={succeeded:"Done at",failed:"Failed at",cancelled:"Cancelled at",expired:"Expired at"},countLines=Au=>Au===""?0:Au.split(`
|
|
2194
|
+
`):ju,zu=streamText({model:this.resolveModel(Bu?.model||$u?.model),system:Fu,messages:Iu,tools:this.tools,stopWhen:isStepCount(this.browserConfig.maxSteps??DEFAULT_BROWSER_MAX_STEPS),abortSignal:Ru.signal});for await(const Uu of zu.fullStream){if(Ru.signal.aborted)break;switch(Uu.type){case"text-start":Du();break;case"text-delta":Ou===null&&Du(),Mu+=Uu.text,Lu();break;case"tool-call":this.emit({type:"tool-call",toolCall:{toolCallId:Uu.toolCallId,toolName:Uu.toolName,args:Uu.input??{},argsComplete:!0},timestamp:new Date});break;case"tool-result":this.emit({type:"tool-result",toolResult:{toolCallId:Uu.toolCallId,success:!0,result:Uu.output},timestamp:new Date});break;case"tool-error":this.emit({type:"tool-result",toolResult:{toolCallId:Uu.toolCallId,success:!1,error:Uu.error instanceof Error?Uu.error.message:String(Uu.error)},timestamp:new Date});break;case"error":this.emit({type:"error",error:Uu.error instanceof Error?Uu.error:new Error(String(Uu.error)),timestamp:new Date});break;case"finish":{const Hu=Uu.totalUsage,Vu=Hu?.inputTokens??0,Gu=Hu?.outputTokens??0,Wu=Hu?.totalTokens??(Vu+Gu>0?Vu+Gu:void 0);this.emit({type:"done",usage:{promptTokens:Vu,completionTokens:Gu,totalTokens:Wu},timestamp:new Date});break}default:break}}}catch(Bu){if(Ru.signal.aborted)return;this.emit({type:"error",error:Bu instanceof Error?Bu:new Error(String(Bu)),timestamp:new Date}),this.emit({type:"done",timestamp:new Date})}finally{this.abortController===Ru&&(this.abortController=null)}}}const AGENT_METHODS={authenticate:"authenticate",initialize:"initialize",session_cancel:"session/cancel",session_fork:"session/fork",session_list:"session/list",session_load:"session/load",session_new:"session/new",session_prompt:"session/prompt",session_set_mode:"session/set_mode",session_set_model:"session/set_model"},CLIENT_METHODS={fs_read_text_file:"fs/read_text_file",fs_write_text_file:"fs/write_text_file",session_request_permission:"session/request_permission",session_update:"session/update",terminal_create:"terminal/create",terminal_kill:"terminal/kill",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit"},PROTOCOL_VERSION=1,zAuthMethod=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),description:union([string$2(),_null()]).optional(),id:string$2(),name:string$2()}),zAuthenticateRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),methodId:string$2()}),zAuthenticateResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zBlobResourceContents=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),blob:string$2(),mimeType:union([string$2(),_null()]).optional(),uri:string$2()}),zCreateTerminalResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),terminalId:string$2()}),zDiff=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),newText:string$2(),oldText:union([string$2(),_null()]).optional(),path:string$2()}),zEnvVariable=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),name:string$2(),value:string$2()}),zErrorCode=union([literal(-32700),literal(-32600),literal(-32601),literal(-32602),literal(-32603),literal(-32e3),literal(-32002),number$2().int()]),zError=object({code:zErrorCode,data:unknown$1().optional(),message:string$2()}),zExtNotification=unknown$1(),zExtRequest=unknown$1(),zExtResponse=unknown$1(),zFileSystemCapability=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),readTextFile:boolean$1().optional().default(!1),writeTextFile:boolean$1().optional().default(!1)}),zClientCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),fs:zFileSystemCapability.optional().default({readTextFile:!1,writeTextFile:!1}),terminal:boolean$1().optional().default(!1)}),zHttpHeader=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),name:string$2(),value:string$2()}),zImplementation=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),name:string$2(),title:union([string$2(),_null()]).optional(),version:string$2()}),zKillTerminalCommandResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zListSessionsRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),cursor:union([string$2(),_null()]).optional(),cwd:union([string$2(),_null()]).optional()}),zMcpCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),http:boolean$1().optional().default(!1),sse:boolean$1().optional().default(!1)}),zMcpServerHttp=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),headers:array(zHttpHeader),name:string$2(),url:string$2()}),zMcpServerSse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),headers:array(zHttpHeader),name:string$2(),url:string$2()}),zMcpServerStdio=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),args:array(string$2()),command:string$2(),env:array(zEnvVariable),name:string$2()}),zMcpServer=union([zMcpServerHttp.and(object({type:literal("http")})),zMcpServerSse.and(object({type:literal("sse")})),zMcpServerStdio]),zModelId=string$2(),zModelInfo=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),description:union([string$2(),_null()]).optional(),modelId:zModelId,name:string$2()}),zNewSessionRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),cwd:string$2(),mcpServers:array(zMcpServer)}),zPermissionOptionId=string$2(),zPermissionOptionKind=union([literal("allow_once"),literal("allow_always"),literal("reject_once"),literal("reject_always")]),zPermissionOption=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),kind:zPermissionOptionKind,name:string$2(),optionId:zPermissionOptionId}),zPlanEntryPriority=union([literal("high"),literal("medium"),literal("low")]),zPlanEntryStatus=union([literal("pending"),literal("in_progress"),literal("completed")]),zPlanEntry=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:string$2(),priority:zPlanEntryPriority,status:zPlanEntryStatus}),zPlan=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),entries:array(zPlanEntry)}),zPromptCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),audio:boolean$1().optional().default(!1),embeddedContext:boolean$1().optional().default(!1),image:boolean$1().optional().default(!1)}),zProtocolVersion=number$2().int().gte(0).lte(65535),zInitializeRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),clientCapabilities:zClientCapabilities.optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:union([zImplementation,_null()]).optional(),protocolVersion:zProtocolVersion}),zReadTextFileResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:string$2()}),zReleaseTerminalResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zRequestId=union([_null(),bigint(),string$2()]),zRole=_enum(["assistant","user"]),zAnnotations=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),audience:union([array(zRole),_null()]).optional(),lastModified:union([string$2(),_null()]).optional(),priority:union([number$2(),_null()]).optional()}),zAudioContent=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),annotations:union([zAnnotations,_null()]).optional(),data:string$2(),mimeType:string$2()}),zImageContent=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),annotations:union([zAnnotations,_null()]).optional(),data:string$2(),mimeType:string$2(),uri:union([string$2(),_null()]).optional()}),zResourceLink=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),annotations:union([zAnnotations,_null()]).optional(),description:union([string$2(),_null()]).optional(),mimeType:union([string$2(),_null()]).optional(),name:string$2(),size:union([bigint(),_null()]).optional(),title:union([string$2(),_null()]).optional(),uri:string$2()}),zSelectedPermissionOutcome=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),optionId:zPermissionOptionId}),zRequestPermissionOutcome=union([object({outcome:literal("cancelled")}),zSelectedPermissionOutcome.and(object({outcome:literal("selected")}))]),zRequestPermissionResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),outcome:zRequestPermissionOutcome}),zSessionForkCapabilities=object({_meta:unknown$1().optional()}),zSessionId=string$2(),zCancelNotification=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId});object({method:string$2(),params:union([union([zCancelNotification,zExtNotification]),_null()]).optional()});const zCreateTerminalRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),args:array(string$2()).optional(),command:string$2(),cwd:union([string$2(),_null()]).optional(),env:array(zEnvVariable).optional(),outputByteLimit:union([number$2().int().gte(0),_null()]).optional(),sessionId:zSessionId}),zForkSessionRequest=object({_meta:unknown$1().optional(),sessionId:zSessionId}),zKillTerminalCommandRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId,terminalId:string$2()}),zLoadSessionRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),cwd:string$2(),mcpServers:array(zMcpServer),sessionId:zSessionId}),zReadTextFileRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),limit:union([number$2().int().gte(0),_null()]).optional(),line:union([number$2().int().gte(0),_null()]).optional(),path:string$2(),sessionId:zSessionId}),zReleaseTerminalRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId,terminalId:string$2()}),zSessionInfo=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),cwd:string$2(),sessionId:zSessionId,title:union([string$2(),_null()]).optional(),updatedAt:union([string$2(),_null()]).optional()}),zListSessionsResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),nextCursor:union([string$2(),_null()]).optional(),sessions:array(zSessionInfo)}),zSessionListCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zSessionCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),fork:union([zSessionForkCapabilities,_null()]).optional(),list:union([zSessionListCapabilities,_null()]).optional()}),zAgentCapabilities=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),loadSession:boolean$1().optional().default(!1),mcpCapabilities:zMcpCapabilities.optional().default({http:!1,sse:!1}),promptCapabilities:zPromptCapabilities.optional().default({audio:!1,embeddedContext:!1,image:!1}),sessionCapabilities:zSessionCapabilities.optional().default({})}),zInitializeResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),agentCapabilities:zAgentCapabilities.optional().default({loadSession:!1,mcpCapabilities:{http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:union([zImplementation,_null()]).optional(),authMethods:array(zAuthMethod).optional().default([]),protocolVersion:zProtocolVersion}),zSessionModeId=string$2(),zCurrentModeUpdate=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),currentModeId:zSessionModeId}),zSessionMode=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),description:union([string$2(),_null()]).optional(),id:zSessionModeId,name:string$2()}),zSessionModeState=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),availableModes:array(zSessionMode),currentModeId:zSessionModeId}),zSessionModelState=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),availableModels:array(zModelInfo),currentModelId:zModelId}),zForkSessionResponse=object({_meta:unknown$1().optional(),models:union([zSessionModelState,_null()]).optional(),modes:union([zSessionModeState,_null()]).optional(),sessionId:zSessionId}),zLoadSessionResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),models:union([zSessionModelState,_null()]).optional(),modes:union([zSessionModeState,_null()]).optional()}),zNewSessionResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),models:union([zSessionModelState,_null()]).optional(),modes:union([zSessionModeState,_null()]).optional(),sessionId:zSessionId}),zSetSessionModeRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),modeId:zSessionModeId,sessionId:zSessionId}),zSetSessionModeResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zSetSessionModelRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),modelId:zModelId,sessionId:zSessionId}),zSetSessionModelResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()}),zStopReason=union([literal("end_turn"),literal("max_tokens"),literal("max_turn_requests"),literal("refusal"),literal("cancelled")]),zPromptResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),stopReason:zStopReason});union([object({id:zRequestId,result:union([zInitializeResponse,zAuthenticateResponse,zNewSessionResponse,zLoadSessionResponse,zListSessionsResponse,zForkSessionResponse,zSetSessionModeResponse,zPromptResponse,zSetSessionModelResponse,zExtResponse])}),object({error:zError,id:zRequestId})]);const zTerminal=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),terminalId:string$2()}),zTerminalExitStatus=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),exitCode:union([number$2().int().gte(0),_null()]).optional(),signal:union([string$2(),_null()]).optional()}),zTerminalOutputRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId,terminalId:string$2()}),zTerminalOutputResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),exitStatus:union([zTerminalExitStatus,_null()]).optional(),output:string$2(),truncated:boolean$1()}),zTextContent=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),annotations:union([zAnnotations,_null()]).optional(),text:string$2()}),zTextResourceContents=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),mimeType:union([string$2(),_null()]).optional(),text:string$2(),uri:string$2()}),zEmbeddedResourceResource=union([zTextResourceContents,zBlobResourceContents]),zEmbeddedResource=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),annotations:union([zAnnotations,_null()]).optional(),resource:zEmbeddedResourceResource}),zContentBlock=union([zTextContent.and(object({type:literal("text")})),zImageContent.and(object({type:literal("image")})),zAudioContent.and(object({type:literal("audio")})),zResourceLink.and(object({type:literal("resource_link")})),zEmbeddedResource.and(object({type:literal("resource")}))]),zContent=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:zContentBlock}),zContentChunk=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:zContentBlock}),zPromptRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),prompt:array(zContentBlock),sessionId:zSessionId});object({id:zRequestId,method:string$2(),params:union([union([zInitializeRequest,zAuthenticateRequest,zNewSessionRequest,zLoadSessionRequest,zListSessionsRequest,zForkSessionRequest,zSetSessionModeRequest,zPromptRequest,zSetSessionModelRequest,zExtRequest]),_null()]).optional()});const zToolCallContent=union([zContent.and(object({type:literal("content")})),zDiff.and(object({type:literal("diff")})),zTerminal.and(object({type:literal("terminal")}))]),zToolCallId=string$2(),zToolCallLocation=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),line:union([number$2().int().gte(0),_null()]).optional(),path:string$2()}),zToolCallStatus=union([literal("pending"),literal("in_progress"),literal("completed"),literal("failed")]),zToolKind=union([literal("read"),literal("edit"),literal("delete"),literal("move"),literal("search"),literal("execute"),literal("think"),literal("fetch"),literal("switch_mode"),literal("other")]),zToolCall=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:array(zToolCallContent).optional(),kind:zToolKind.optional(),locations:array(zToolCallLocation).optional(),rawInput:unknown$1().optional(),rawOutput:unknown$1().optional(),status:zToolCallStatus.optional(),title:string$2(),toolCallId:zToolCallId}),zToolCallUpdate=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:union([array(zToolCallContent),_null()]).optional(),kind:union([zToolKind,_null()]).optional(),locations:union([array(zToolCallLocation),_null()]).optional(),rawInput:unknown$1().optional(),rawOutput:unknown$1().optional(),status:union([zToolCallStatus,_null()]).optional(),title:union([string$2(),_null()]).optional(),toolCallId:zToolCallId}),zRequestPermissionRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),options:array(zPermissionOption),sessionId:zSessionId,toolCall:zToolCallUpdate}),zUnstructuredCommandInput=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),hint:string$2()}),zAvailableCommandInput=zUnstructuredCommandInput,zAvailableCommand=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),description:string$2(),input:union([zAvailableCommandInput,_null()]).optional(),name:string$2()}),zAvailableCommandsUpdate=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),availableCommands:array(zAvailableCommand)}),zSessionUpdate=union([zContentChunk.and(object({sessionUpdate:literal("user_message_chunk")})),zContentChunk.and(object({sessionUpdate:literal("agent_message_chunk")})),zContentChunk.and(object({sessionUpdate:literal("agent_thought_chunk")})),zToolCall.and(object({sessionUpdate:literal("tool_call")})),zToolCallUpdate.and(object({sessionUpdate:literal("tool_call_update")})),zPlan.and(object({sessionUpdate:literal("plan")})),zAvailableCommandsUpdate.and(object({sessionUpdate:literal("available_commands_update")})),zCurrentModeUpdate.and(object({sessionUpdate:literal("current_mode_update")}))]),zSessionNotification=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId,update:zSessionUpdate});object({method:string$2(),params:union([union([zSessionNotification,zExtNotification]),_null()]).optional()});const zWaitForTerminalExitRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),sessionId:zSessionId,terminalId:string$2()}),zWaitForTerminalExitResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),exitCode:union([number$2().int().gte(0),_null()]).optional(),signal:union([string$2(),_null()]).optional()}),zWriteTextFileRequest=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional(),content:string$2(),path:string$2(),sessionId:zSessionId});object({id:zRequestId,method:string$2(),params:union([union([zWriteTextFileRequest,zReadTextFileRequest,zRequestPermissionRequest,zCreateTerminalRequest,zTerminalOutputRequest,zReleaseTerminalRequest,zWaitForTerminalExitRequest,zKillTerminalCommandRequest,zExtRequest]),_null()]).optional()});const zWriteTextFileResponse=object({_meta:union([record$2(string$2(),unknown$1()),_null()]).optional()});union([object({id:zRequestId,result:union([zWriteTextFileResponse,zReadTextFileResponse,zRequestPermissionResponse,zCreateTerminalResponse,zTerminalOutputResponse,zReleaseTerminalResponse,zWaitForTerminalExitResponse,zKillTerminalCommandResponse,zExtResponse])}),object({error:zError,id:zRequestId})]);class ACPAdapter extends BaseProtocolAdapter{protocol="acp";protocolTransport="websocket";acpConfig;ws=null;session=null;agent=null;streamingContent="";streamingMessageId=null;pendingPermission=null;pendingRequests=new Map;constructor(lo){super(lo),this.acpConfig=lo}getSession(){return this.session}getAgent(){return this.agent}getPendingPermission(){return this.pendingPermission}async connect(){if(this.ws?.readyState!==WebSocket.OPEN)return this.setConnectionState("connecting"),new Promise((lo,$u)=>{try{const Ru=this.acpConfig.wsUrl||this.config.baseUrl,Iu=this.config.agentId,Pu=Iu?`${Ru}/${Iu}`:Ru;this.ws=new WebSocket(Pu),this.ws.onopen=async()=>{this.reconnectAttempts=0;try{const Ou=await this.sendRequest("initialize",{protocolVersion:PROTOCOL_VERSION,clientCapabilities:this.acpConfig.clientCapabilities||{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}});Ou.agentCapabilities?.agent&&(this.agent=Ou.agentCapabilities.agent);const Mu=await this.sendRequest(AGENT_METHODS.session_new,{});Mu.sessionId?this.session={sessionId:Mu.sessionId,agentId:this.config.agentId||"",createdAt:new Date().toISOString(),status:"active"}:Ou.session_id&&(this.session={sessionId:Ou.session_id,agentId:this.config.agentId||"",createdAt:new Date().toISOString(),status:"active"}),this.setConnectionState("connected"),lo()}catch(Ou){console.error("[ACPAdapter] Initialization error:",Ou),this.setConnectionState("connected"),lo()}},this.ws.onmessage=Ou=>{this.handleMessage(Ou)},this.ws.onerror=Ou=>{console.error("[ACPAdapter] WebSocket error:",Ou),this.emit({type:"error",error:new Error("WebSocket error"),timestamp:new Date})},this.ws.onclose=()=>{this.ws=null,this.setConnectionState("disconnected"),this.handleReconnect()}}catch(Ru){this.setConnectionState("error"),this.emit({type:"error",error:Ru instanceof Error?Ru:new Error(String(Ru)),timestamp:new Date}),$u(Ru)}})}disconnect(){this.session&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.terminateSession(this.session.sessionId).catch(lo=>{console.warn("[ACPAdapter] Failed to terminate session:",lo)});for(const[,{reject:lo}]of this.pendingRequests)lo(new Error("Connection closed"));this.pendingRequests.clear(),this.ws&&(this.ws.close(),this.ws=null),this.session=null,this.agent=null,this.pendingPermission=null,this.setConnectionState("disconnected")}async terminateSession(lo){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){console.warn("[ACPAdapter] Cannot terminate: WebSocket not connected");return}try{const $u=lo||this.session?.sessionId;if(!$u){console.warn("[ACPAdapter] Cannot terminate: No session ID");return}const Ru={jsonrpc:"2.0",method:"session/cancel",params:{sessionId:$u}};this.ws.send(JSON.stringify(Ru)),console.debug("[ACPAdapter] Sent session/cancel for:",$u)}catch($u){console.debug("[ACPAdapter] Terminate request error:",$u)}}async sendMessage(lo,$u){if(!this.session)throw new Error("No active session");this.streamingContent="",this.streamingMessageId=generateMessageId();try{const Ru=typeof lo.content=="string"?lo.content:lo.content.filter(Pu=>Pu.type==="text").map(Pu=>Pu.text||"").join("");$u?.model&&console.log("[ACPAdapter] Sending with model:",$u.model),$u?.identities&&$u.identities.length>0&&console.log("[ACPAdapter] Sending with identities:",$u.identities.map(Pu=>Pu.provider));const Iu={};$u?.model&&(Iu.model=$u.model),$u?.identities&&$u.identities.length>0&&(Iu.identities=$u.identities),await this.sendRequest(AGENT_METHODS.session_prompt,{sessionId:this.session.sessionId,prompt:[{type:"text",text:Ru}],...Object.keys(Iu).length>0&&{metadata:Iu}})}catch(Ru){throw this.emit({type:"error",error:Ru instanceof Error?Ru:new Error(String(Ru)),timestamp:new Date}),Ru}}async sendToolResult(lo,$u){if(!this.session)throw new Error("No active session");this.emit({type:"tool-result",toolResult:$u,timestamp:new Date}),this.pendingPermission&&this.grantPermission()}grantPermission(lo){if(this.pendingPermission){const $u=lo||this.pendingPermission.options[0]?.optionId||"allow";this.sendResponse(this.pendingPermission.requestId,{outcome:{outcome:"selected",optionId:$u}}),this.pendingPermission=null}}denyPermission(){this.pendingPermission&&(this.sendResponse(this.pendingPermission.requestId,{outcome:{outcome:"cancelled"}}),this.pendingPermission=null)}supportsFeature(lo){return["streaming","tools","permissions","session-management","bidirectional"].includes(lo)}generateId(){return`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}async sendRequest(lo,$u={}){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("Not connected to agent");const Ru=this.generateId(),Iu={jsonrpc:"2.0",id:Ru,method:lo,params:$u};return new Promise((Pu,Ou)=>{this.pendingRequests.set(Ru,{resolve:Pu,reject:Ou}),this.ws&&this.ws.send(JSON.stringify(Iu)),setTimeout(()=>{this.pendingRequests.has(Ru)&&(this.pendingRequests.delete(Ru),Ou(new Error("Request timeout")))},this.config.timeout||3e4)})}sendResponse(lo,$u){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){console.error("[ACPAdapter] Cannot send response: not connected");return}const Ru={jsonrpc:"2.0",id:lo,result:$u};this.ws.send(JSON.stringify(Ru))}handleMessage(lo){try{const $u=JSON.parse(lo.data);if($u.id&&this.pendingRequests.has($u.id)){const Ru=this.pendingRequests.get($u.id);if(!Ru)return;const{resolve:Iu,reject:Pu}=Ru;this.pendingRequests.delete($u.id),$u.error?Pu(new Error($u.error.message)):Iu($u.result),$u.result&&typeof $u.result=="object"&&"stopReason"in $u.result&&this.handleCompletion($u.result);return}if($u.method==="session/update"){this.handleSessionUpdate($u.params||{});return}if($u.method===CLIENT_METHODS.session_request_permission&&$u.id){this.handlePermissionRequest($u.id,$u.params);return}$u.result&&typeof $u.result=="object"&&"stopReason"in $u.result&&this.handleCompletion($u.result)}catch($u){console.error("[ACPAdapter] Failed to parse message:",$u)}}handleSessionUpdate(lo){const $u=lo.update;if(!$u)return;const Ru=$u.sessionUpdate,Iu=Pu=>Pu&&typeof Pu=="object"&&Pu.type==="text"?String(Pu.text??""):"";if(Ru==="agent_message_chunk"){const Pu=Iu($u.content);if(Pu){this.streamingContent+=Pu;const Ou=createAssistantMessage(this.streamingContent);this.streamingMessageId&&(Ou.id=this.streamingMessageId),this.emit({type:"message",message:Ou,timestamp:new Date})}}if(Ru==="tool_call"){const Pu=$u;this.emit({type:"tool-call",toolCall:{toolCallId:Pu.toolCallId||generateMessageId(),toolName:Pu.title||"",args:Pu.rawInput||{}},timestamp:new Date})}if(Ru==="tool_call_update"){const Pu=$u;(Pu.status==="completed"||Pu.status==="failed")&&this.emit({type:"tool-result",toolResult:{toolCallId:Pu.toolCallId??"",success:Pu.status==="completed",result:Pu.rawOutput},timestamp:new Date})}if(Ru==="agent_thought_chunk"){const Pu=Iu($u.content);Pu&&this.emit({type:"activity",activity:{type:"thought",data:Pu},timestamp:new Date})}}handlePermissionRequest(lo,$u){this.pendingPermission={requestId:lo,sessionId:$u.sessionId,toolCall:$u.toolCall,options:$u.options},this.emit({type:"tool-call",toolCall:{toolCallId:$u.toolCall.toolCallId,toolName:$u.toolCall.title||"",args:$u.toolCall.rawInput||{}},timestamp:new Date}),this.acpConfig.onPermissionRequest?.(this.pendingPermission)}handleCompletion(lo){if(this.streamingContent){const $u=createAssistantMessage(this.streamingContent);$u.id=this.streamingMessageId||generateMessageId(),this.emit({type:"message",message:$u,timestamp:new Date}),this.streamingContent="",this.streamingMessageId=null}this.emit({type:"activity",activity:{type:"completed",data:{stopReason:lo.stopReason}},timestamp:new Date})}}const internalQueryClient=new QueryClient({defaultOptions:{queries:{staleTime:300*1e3,refetchOnWindowFocus:!1}}});function isToolCallMessage(Au){return"type"in Au&&Au.type==="tool-call"}function getMessageText(Au){const lo=typeof Au.content=="string"?Au.content:Au.content.filter($u=>$u.type==="text").map($u=>$u.text).join("");return Au.role==="assistant"?sanitizeAssistantContent(lo):lo}function formatTokenCount(Au){return Au>=1e6?`${(Au/1e6).toFixed(1)}M`:Au>=1e3?`${(Au/1e3).toFixed(1)}K`:Au.toString()}function getApiBaseFromConfig(Au){return Au.replace(/\/(config|configure)\/?$/,"")}function createProtocolAdapter(Au){const lo={protocol:Au.type,baseUrl:Au.endpoint,authToken:Au.authToken,agentId:Au.agentId,...Au.options};switch(Au.type){case"ag-ui":if(Au.ownRoutesOnly&&!Au.appSessions)throw new Error("A chat whose runtime answers only the application’s own routes is an application’s: it needs its sessions (appSessions).");return new AGUIAdapter({...lo,...Au.appSessions?{appSessions:Au.appSessions}:{}});case"a2a":return new A2AAdapter(lo);case"vercel-ai":return new VercelAIAdapter(lo);case"acp":return new ACPAdapter(lo);case"browser-vercel-ai":return new BrowserAgentAdapter(lo);default:return console.warn(`[ChatBase] Unknown protocol type: ${Au.type}`),null}}const PAP_SIGN_IN_WORDS={title:Au=>`Sign in at ${Au}`,titleFor:(Au,lo,$u)=>`Sign in to ${Au} (${lo}) at ${$u}`,direct:"Open the company’s page through Datalayer, sign in there, and this conversation goes on once you are back.",device:"Open the company’s page and enter this code there.",mediatedTitle:Au=>`Sign in through ${Au}`,mediatedTitleFor:(Au,lo,$u)=>`Sign in to ${Au} (${lo}) through ${$u}`,mediated:"Open this page: it names the company and asks what the company needs. Type it there, never in this conversation.",sentTo:Au=>`The company sent a code to ${Au}.`,needs:Au=>`It needs: ${Au.join(", ")}.`,open:Au=>`Open ${Au}`,code:"Your code",copy:"Copy the code",copied:"Copied",until:Au=>`Until ${new Date(Au).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}.`,checkAgain:"I have signed in: check again",tellMe:"Tell me when you are done.",checkMessage:Au=>`I have signed in at ${Au}. Please check again.`,refused:"This sign-in link cannot be opened safely, so it is not shown.",qr:Au=>`A code to scan to open ${Au} on your phone`,returned:{signed_in:Au=>`Signed in at ${Au}: checking again.`,denied:Au=>`You did not sign in at ${Au}: ask again when you want to.`,refused:Au=>`That sign-in at ${Au} was refused, and nothing was kept: start it again here.`}},PAP_SIGN_IN_CHANNEL="datalayer-pap-sign-in",SCOPE=/^[\x21\x23-\x5B\x5D-\x7E]{1,128}$/,DOMAIN=/^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;function signInReturnOf(Au,lo){if(!Au||typeof Au!="object"||Array.isArray(Au))return null;const $u=Au,Ru=$u.outcome;return $u.company===lo&&(Ru==="signed_in"||Ru==="denied"||Ru==="refused")?Ru:null}const PAP_SIGN_IN_TOOL=/(^|[_.:\-/])pa(?:p|ct)_sign_in$/,isPapSignInTool=Au=>PAP_SIGN_IN_TOOL.test(Au);function unwrapped(Au){let lo=Au;if(typeof lo=="string")try{lo=JSON.parse(lo)}catch{return null}if(!lo||typeof lo!="object"||Array.isArray(lo))return null;const $u=lo;if($u.structuredContent&&typeof $u.structuredContent=="object")return unwrapped($u.structuredContent);if(Array.isArray($u.content)){const Ru=$u.content.find(Iu=>Iu?.type==="text"&&typeof Iu.text=="string");return Ru?unwrapped(Ru.text):null}return $u.result&&typeof $u.result=="object"&&!("status"in $u)?unwrapped($u.result):$u}function safeSignInUrl(Au){if(typeof Au!="string")return null;try{const lo=new URL(Au);return lo.protocol==="https:"&&lo.hostname?lo:null}catch{return null}}function readPapSignIn(Au){const lo=unwrapped(Au);if(!lo||lo.status!=="waiting_for_the_person"||lo.mode!=="direct"&&lo.mode!=="device"&&lo.mode!=="mediated")return null;const $u=safeSignInUrl(lo.open);if(!$u)return{refused:PAP_SIGN_IN_WORDS.refused};if(lo.mode==="device"&&(typeof lo.code!="string"||!lo.code))return null;const Ru=typeof lo.company=="string"&&DOMAIN.test(lo.company)?lo.company:"",Iu=typeof lo.organization_name=="string"?lo.organization_name.trim().slice(0,200):"",Pu=typeof lo.organization_domain=="string"&&DOMAIN.test(lo.organization_domain.toLowerCase())?lo.organization_domain.toLowerCase():"",Ou=Iu&&Pu?{name:Iu,domain:Pu}:void 0,Mu=Array.isArray(lo.needs)?lo.needs.filter(Du=>typeof Du=="string"&&SCOPE.test(Du)):[];return{mode:lo.mode,open:$u.toString(),host:$u.hostname,...Ru?{company:Ru}:{},...Ou?{organization:Ou}:{},...typeof lo.code=="string"&&lo.code?{code:lo.code}:{},...lo.mode==="mediated"&&typeof lo.sent_to=="string"&&lo.sent_to?{sentTo:lo.sent_to}:{},...typeof lo.expires_at=="string"&&lo.expires_at?{expiresAt:lo.expires_at}:{},...Mu.length>0?{needs:Mu}:{}}}const PAP_SIGN_IN_TYPE$1="application/vnd.datalayer.pap.sign-in+json",PAP_CONFIRM_TYPE="application/vnd.datalayer.pap.confirm+json",PAP_OUTCOME_TYPE="application/vnd.datalayer.pap.outcome+json",PAP_REPLIES_TYPE="application/vnd.datalayer.pap.replies+json",SHIELD_DIFF_TYPE="application/vnd.datalayer.shield.diff+json",SHIELD_TERMINAL_TYPE="application/vnd.datalayer.shield.terminal+json",DISPLAY_META_KEY="reactor.ui/display",record$1=Au=>Au&&typeof Au=="object"&&!Array.isArray(Au)?Au:null,text$h=Au=>typeof Au=="string"?Au:"",words=Au=>text$h(Au).trim(),count=Au=>typeof Au=="number"&&Number.isInteger(Au)&&Au>=1?Au:0,ACTIONS=["read","write","send","buy","delete","publish"],OUTCOMES=["in_progress","succeeded","failed","cancelled","expired"],STATUSES=["working","idle","queued","closed"],who=Au=>Au==="agent"||Au==="human"?Au:null;function protocolDisplayOf(Au){const lo=record$1(Au);if(!lo||!text$h(lo.type))return null;const $u=text$h(lo.id),Ru=record$1(lo.data)??{},Iu={kind:"unknown",id:$u,type:text$h(lo.type),version:typeof lo.version=="number"?lo.version:0,text:text$h(lo.text)};switch(lo.type){case PAP_SIGN_IN_TYPE$1:{const Pu=readPapSignIn({status:"waiting_for_the_person",...Ru});return Pu?"refused"in Pu?{kind:"sign-in-refused",id:$u,why:Pu.refused}:{kind:"sign-in",id:$u,...Pu}:Iu}case PAP_CONFIRM_TYPE:{const Pu=words(Ru.company),Ou=text$h(Ru.summary),Mu=words(Ru.operation_ref),Du=count(Ru.revision),Lu=record$1(Ru.terms),Bu=record$1(Ru.was),ju=Bu?count(Bu.revision):0;if(!Pu||!Ou.trim()||!Mu||!Du||!Lu||!$u.endsWith("-confirm")||Bu&&(!ju||ju>=Du))return Iu;const Fu=Ru.does===null||Ru.does===void 0?null:ACTIONS.find(Uu=>Uu===Ru.does);if(Fu===void 0)return Iu;const zu=record$1(Ru.session);return{kind:"confirm",id:$u,approvalId:$u.slice(0,-8),company:Pu,summary:Ou,terms:Lu,operationRef:Mu,revision:Du,does:Fu,signedIn:zu&&typeof zu.signed_in=="boolean"?zu.signed_in:null,expiresAt:text$h(Ru.expires_at),was:Bu?{revision:ju,terms:record$1(Bu.terms)??{}}:null,onlyThePerson:Ru.only_the_person===!0}}case PAP_OUTCOME_TYPE:{const Pu=OUTCOMES.find(Lu=>Lu===Ru.state),Ou=words(Ru.company),Mu=text$h(Ru.summary),Du=text$h(Ru.result);return!Pu||!Ou||!Mu.trim()||!words(Ru.operation_ref)||!count(Ru.revision)||Pu==="in_progress"!=!Du.trim()?Iu:{kind:"outcome",id:$u,company:Ou,summary:Mu,operationRef:words(Ru.operation_ref),revision:count(Ru.revision),state:Pu,result:Du,approvedBy:Ru.approved_by==="user"||Ru.approved_by==="standing_permission"?Ru.approved_by:null}}case PAP_REPLIES_TYPE:{const Pu=words(Ru.company),Ou=text$h(Ru.conversation),Mu=Array.isArray(Ru.replies)?Ru.replies.map(record$1).map(Du=>({sender:who(Du?.sender),text:text$h(Du?.text)})):[];return!Pu||!/^[A-Za-z0-9_-]{1,256}$/.test(Ou)||!Mu.length||Mu.some(Du=>!Du.sender||!Du.text.trim())?Iu:{kind:"replies",id:$u,company:Pu,conversation:Ou,replies:Mu,status:STATUSES.find(Du=>Du===Ru.status)??null,responder:who(Ru.responder)}}case SHIELD_DIFF_TYPE:{const Pu=words(Ru.path);return!Pu||typeof Ru.new_text!="string"||!(Ru.old_text===null||Ru.old_text===void 0||typeof Ru.old_text=="string")?Iu:{kind:"diff",id:$u,path:Pu,oldText:typeof Ru.old_text=="string"?Ru.old_text:null,newText:Ru.new_text,language:words(Ru.language)||languageOf$1(Pu)}}case SHIELD_TERMINAL_TYPE:{const Pu=words(Ru.terminal_id);if(!Pu)return Iu;const Ou=typeof Ru.exit_code=="number"&&Number.isInteger(Ru.exit_code)?Ru.exit_code:null;return Ru.exit_code!==null&&Ru.exit_code!==void 0&&Ou===null?Iu:{kind:"terminal",id:$u,terminalId:Pu,command:text$h(Ru.command),output:text$h(Ru.output),exitCode:Ou,released:Ru.released===!0}}default:return Iu}}const PAP_HANDOFF_TOOL=/(^|[_.:\-/])pap_handoff$/;function displayOfToolResult(Au,lo,$u=""){const Ru=record$1(lo),Iu=record$1(Ru?._meta)?.[DISPLAY_META_KEY];if(Iu!==void 0)return protocolDisplayOf(Iu);if(isPapSignInTool(Au)){const Pu=readPapSignIn(lo);return Pu?"refused"in Pu?{kind:"sign-in-refused",id:$u,why:Pu.refused}:{kind:"sign-in",id:$u,...Pu}:null}if(PAP_HANDOFF_TOOL.test(Au)&&Ru){const Pu=text$h(Ru.status);return Pu?{kind:"handoff",id:$u,handed:Pu!=="closed"&&Pu!=="direct_conversation_open",responder:who(Ru.responder),note:text$h(Ru.note)}:null}return null}function displayLine(Au){switch(Au.kind){case"sign-in":return Au.mode==="mediated"?`Sign in through ${Au.host}`:`Sign in at ${Au.company||Au.host}`;case"sign-in-refused":return Au.why;case"confirm":return`${Au.company} asks you to confirm: ${Au.summary} (version ${Au.revision})`;case"outcome":return Au.state==="in_progress"?`Still in progress at ${Au.company}: ${Au.summary}`:`${OUTCOME_LEADS[Au.state]} ${Au.company}: ${Au.result}`;case"replies":return`${Au.company} answered${Au.responder==="human"?": one of its people is answering":""}`;case"handoff":return Au.handed?`Handed to ${Au.responder==="human"?"one of the company’s people":"the company"}`:Au.note||"Nothing was handed over.";case"diff":{const lo=countLines(Au.newText);return Au.oldText===null?`Wrote ${Au.path} (${lo} lines)`:`Changed ${Au.path} (+${lo} −${countLines(Au.oldText)} lines)`}case"terminal":{const lo=Au.command?`Ran \`${Au.command}\``:`Terminal ${Au.terminalId}`;return Au.exitCode===null?`${lo}: running`:`${lo}: exit ${Au.exitCode}`}case"unknown":return Au.text||`A display this app cannot draw (${Au.type})`}}const OUTCOME_LEADS={succeeded:"Done at",failed:"Failed at",cancelled:"Cancelled at",expired:"Expired at"},countLines=Au=>Au===""?0:Au.split(`
|
|
2195
2195
|
`).length-(Au.endsWith(`
|
|
2196
2196
|
`)?1:0),LANGUAGES={py:"python",pyi:"python",ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",mjs:"javascript",json:"json",md:"markdown",mdx:"markdown",yaml:"yaml",yml:"yaml",toml:"toml",sh:"bash",bash:"bash",css:"css",scss:"scss",html:"html",xml:"xml",sql:"sql",rs:"rust",go:"go",java:"java",c:"c",h:"c",cpp:"cpp",rb:"ruby",ipynb:"json",txt:"text"};function languageOf$1(Au){const lo=Au.split("/").pop()??"";if(lo==="Dockerfile"||lo==="Makefile")return lo.toLowerCase();const $u=lo.lastIndexOf(".");return $u>0?LANGUAGES[lo.slice($u+1).toLowerCase()]??"text":"text"}const DIFF_LINES_LIMIT=2e3,lines=Au=>Au===""?[]:Au.replace(/\n$/,"").split(`
|
|
2197
2197
|
`);function unifiedDiffLines(Au,lo){const $u=Au===null?[]:lines(Au),Ru=lines(lo);if($u.length>DIFF_LINES_LIMIT||Ru.length>DIFF_LINES_LIMIT)return[...$u.map(Du=>({kind:"remove",text:Du})),...Ru.map(Du=>({kind:"add",text:Du}))];const Iu=[];for(let Du=0;Du<=$u.length;Du++)Iu.push(new Uint32Array(Ru.length+1));for(let Du=$u.length-1;Du>=0;Du--)for(let Lu=Ru.length-1;Lu>=0;Lu--)Iu[Du][Lu]=$u[Du]===Ru[Lu]?Iu[Du+1][Lu+1]+1:Math.max(Iu[Du+1][Lu],Iu[Du][Lu+1]);const Pu=[];let Ou=0,Mu=0;for(;Ou<$u.length&&Mu<Ru.length;)$u[Ou]===Ru[Mu]?(Pu.push({kind:"context",text:$u[Ou]}),Ou++,Mu++):Iu[Ou+1][Mu]>=Iu[Ou][Mu+1]?(Pu.push({kind:"remove",text:$u[Ou]}),Ou++):(Pu.push({kind:"add",text:Ru[Mu]}),Mu++);for(;Ou<$u.length;)Pu.push({kind:"remove",text:$u[Ou++]});for(;Mu<Ru.length;)Pu.push({kind:"add",text:Ru[Mu++]});return Pu}const THREAD_WORDS={opening:"Opening your conversation…",notOpened:Au=>`Your conversation could not be opened, so this is a new one: ${Au}`};function messagesOfThread(Au){if(!Array.isArray(Au))return[];const lo=[];for(const $u of Au){if(!$u||typeof $u!="object")continue;const{id:Ru,role:Iu,content:Pu,activityType:Ou}=$u;if(Iu==="activity"&&Ou===REACTOR_UI_NAME)throw new Error(`Activity ${String(Ru)}: what a message showed comes on the ui socket (RU-W)`);(Iu==="user"||Iu==="assistant")&&typeof Ru=="string"&&typeof Pu=="string"&&Pu.trim()&&lo.push({id:Ru,role:Iu,content:Iu==="user"?askedOf(Pu):Pu,createdAt:new Date})}return lo}function snapshotOfStream(Au){let lo;for(const $u of eventsOfStream(Au))$u.type==="MESSAGES_SNAPSHOT"&&Array.isArray($u.messages)&&(lo=$u.messages);return lo}async function detailOf(Au){try{const lo=await Au.json();if(typeof lo.detail=="string"&&lo.detail)return lo.detail}catch{}return`${Au.status}`}async function openThread({agentBaseUrl:Au,agentId:lo,uid:$u,token:Ru,fetcher:Iu=fetch}){const Pu=`${Au.replace(/\/+$/,"")}/api/v1/apps/sessions/${encodeURIComponent($u)}`,Ou=Ru?{Authorization:`Bearer ${Ru}`}:{},Mu=await Iu(`${Pu}/messages`,{headers:Ou});if(Mu.ok){const Bu=await Mu.json();return messagesOfThread(Bu.messages)}if(Mu.status!==404)throw new Error(await detailOf(Mu));const Du=await Iu(`${Pu}/resume`,{method:"POST",headers:{"Content-Type":"application/json",...Ou},body:JSON.stringify({agent:lo})});if(!Du.ok)throw new Error(await detailOf(Du));const Lu=snapshotOfStream(await Du.text());if(!Lu)throw new Error(`The runtime said nothing of session ${$u}.`);return messagesOfThread(Lu)}const ITEM_LIMIT=400,MESSAGE_TEXT_LIMIT=1e5,TOOL_TEXT_LIMIT=4e3,DIAGNOSTIC_LIMIT=50,DEVICE_LIMITS={items:ITEM_LIMIT,messageText:MESSAGE_TEXT_LIMIT,toolText:TOOL_TEXT_LIMIT,diagnostics:DIAGNOSTIC_LIMIT},BROWSER_LIMITS={items:5e3,messageText:1e6,toolText:1e6,diagnostics:DIAGNOSTIC_LIMIT},CUT_MARK="… (cut: too long to keep on this device)",emptyConversation=(Au=DEVICE_LIMITS)=>{for(const[lo,$u]of Object.entries(Au))if(!Number.isInteger($u)||$u<1)throw new Error(`A conversation's ${lo} bound is ${String($u)}: give a whole number of at least 1.`);return{items:[],running:!1,session:null,asking:null,dropped:0,diagnostics:[],turnRows:0,limits:Au}},text$g=Au=>typeof Au=="string"?Au:"",cut=(Au,lo)=>Au.length>lo?`${Au.slice(0,lo)}${CUT_MARK}`:Au,appended=(Au,lo,$u)=>Au.endsWith(CUT_MARK)?Au:cut(Au+lo,$u),isRecord$1=Au=>!!Au&&typeof Au=="object"&&!Array.isArray(Au);function withoutMeta(Au){if(isRecord$1(Au)&&"_meta"in Au){const{_meta:lo,...$u}=Au;return $u}return Au}function said(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$1(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$1(lo)||!isRecord$1(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(withoutMeta(Iu)),Ou=isRecord$1(Iu)?Iu:null,Mu=typeof Ou?.execution_error=="string"?Ou.execution_error:"",Du=isRecord$1(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$1(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$1(Ou)?Ou.function:void 0;if(!isRecord$1(Ou)||typeof Ou.id!="string"||!isRecord$1(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$1(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$1(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$1(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$1(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$1(lo.result)?lo.result:{},Iu=questionOf$1(Ru.asking),Pu=Au.items.map(Mu=>Mu.kind==="message"&&Mu.streaming?{...Mu,streaming:!1}:Mu),Ou={...Au,items:Pu,running:!1,asking:Iu};return Iu||Au.turnRows>0?Ou:withItems(Ou,[...Pu,{kind:"end",id:rowId("end"),end:"answered",words:RUN_END_WORDS.answered}])}case"RUN_ERROR":return withError(Au,text$g(lo.message)||"Run failed");default:return noted(Au,lo)}}const emptyChatLayer=()=>({extras:new Map,displays:new Map,speakers:new Map,steps:[]}),toolCardId=Au=>`tool-${Au}`,rowIdOf=Au=>"toolCallId"in Au&&Au.id===toolCardId(Au.toolCallId)?Au.toolCallId:Au.id;function cardStatusOf(Au){return Au.status!=="running"?Au.status:Au.awaiting==="approval"?"inProgress":"executing"}function toolCallOf(Au){return{id:toolCardId(Au.id),type:"tool-call",toolCallId:Au.id,toolName:Au.name,args:Au.input??{},...Au.value!==void 0?{result:Au.value}:Au.result?{result:Au.result}:{},status:cardStatusOf(Au),...Au.error?{error:Au.error}:{},...Au.executionError?{executionError:Au.executionError}:{},...Au.codeError?{codeError:{name:Au.codeError.name,value:Au.codeError.value,...Au.codeError.traceback?{traceback:Au.codeError.traceback}:{}}}:{},...Au.exitCode!==null?{exitCode:Au.exitCode}:{}}}function conversationDrawer(Au){const lo=new Map,$u=(Iu,Pu)=>{const Ou=Pu.extras.get(Iu.id),Mu=Pu.displays.get(Iu.id),Du=Pu.speakers.get(Iu.id),Lu=lo.get(Iu.id);if(Lu&&Lu.row===Iu&&Lu.extras===Ou&&Lu.displays===Mu&&Lu.speaker===Du)return Lu.item;const Bu={...Ou,createdAt:Ou?.createdAt??new Date,id:Iu.id,role:Iu.kind==="message"?Iu.role:"assistant",content:Iu.kind==="message"?Iu.text:Au(Iu.text),...Mu?{displays:Mu}:{},...Du?{speaker:Du}:{}};return lo.set(Iu.id,{row:Iu,extras:Ou,displays:Mu,speaker:Du,item:Bu}),Bu},Ru=Iu=>{const Pu=lo.get(Iu.id);if(Pu&&Pu.row===Iu)return Pu.item;const Ou=toolCallOf(Iu);return lo.set(Iu.id,{row:Iu,item:Ou}),Ou};return(Iu,Pu)=>{const Ou=[],Mu=new Map;for(const Lu of Pu.steps)Mu.set(Lu.after,[...Mu.get(Lu.after)??[],Lu.item]);Ou.push(...Mu.get(null)??[]);const Du=new Set;for(const Lu of Iu.items)Du.add(Lu.id),Lu.kind==="message"||Lu.kind==="error"?Ou.push($u(Lu,Pu)):Lu.kind==="tool"&&Ou.push(Ru(Lu)),Ou.push(...Mu.get(Lu.id)??[]);for(const[Lu,Bu]of Mu)Lu!==null&&!Du.has(Lu)&&Ou.push(...Bu);for(const Lu of lo.keys())Du.has(Lu)||lo.delete(Lu);return Ou}}function isSubagentRunOver(Au){return Au.some(lo=>lo.phase==="end"||lo.phase==="error")}function getMonitoringCacheKey(Au,lo){return`${Au||"__unknown_service__"}::${lo||"__unknown_agent__"}`}function getTransportEndpoint(Au,lo,$u){switch(lo){case"vercel-ai":return`${Au}/api/v1/vercel-ai/${$u}`;case"a2a":return`${Au}/api/v1/a2a/agents/${$u}/`;case"acp":return`${Au}/api/v1/acp/ws/${$u}`;default:return`${Au}/api/v1/ag-ui/${$u}/`}}function toAgentRuntimeBaseUrl(Au){const lo=Au.replace(/\/$/,"");return lo.includes("/api/agent-runtimes")?lo:lo.includes("/api/jupyter-server")?lo.replace("/api/jupyter-server","/api/agent-runtimes"):lo.includes("/jupyter/server/")?lo.replace("/jupyter/server/","/agent-runtimes/"):lo.includes("/jupyter-server/")?lo.replace("/jupyter-server/","/agent-runtimes/"):lo.replace("/jupyter/","/agent-runtimes/")}async function createAgentOnRuntime(Au,lo,$u={}){const{iamStore:Ru}=await __vitePreload(async()=>{const{iamStore:Lu}=await import("./chunks/index-fQxrRXLD.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-DiBcWu6d.js");return{runtimesStore:ju}},[],import.meta.url);$u.runtimesUrl&&Iu.setState({runtimesUrl:$u.runtimesUrl});const{runtimesUrl:Pu,...Ou}=$u,Mu=await Ru({environmentName:Ou.environmentName,creditsLimit:Ou.creditsLimit,type:Ou.type||"notebook",givenName:Ou.givenName,capabilities:Ou.capabilities,snapshot:Ou.snapshot,appSpec:Ou.appSpec,appUid:Ou.appUid,deploymentUid:Ou.deploymentUid});Au({status:"connecting"});const Du=Mu.ingress,Lu=toAgentRuntimeBaseUrl(Du),Bu={runtimeName:Mu.runtime_name,environmentName:Mu.environment.name,jupyterBaseUrl:Du,agentBaseUrl:Lu,status:"ready"};return Au({runtime:Bu,status:"ready",isLaunching:!1}),Bu}catch(Ru){const Iu=Ru instanceof Error?Ru.message:"Failed to launch runtime";throw Au({status:"error",error:Iu,isLaunching:!1}),Ru}},createAgent:async($u={})=>{const{runtime:Ru}=lo();if(!Ru)throw new Error("No runtime connected. Launch or connect to a runtime first.");try{const Iu=$u.name||Ru.runtimeName,Pu=await createAgentOnRuntime(Ru.agentBaseUrl,Iu,$u);return Au({runtime:{...Ru,agentId:Pu.agentId,endpoint:Pu.endpoint,isReady:Pu.isReady}}),Pu}catch(Iu){const Pu=Iu instanceof Error?Iu.message:"Failed to create agent";throw Au({error:Pu}),Iu}},disconnect:()=>{Au({runtime:null,status:"disconnected",error:null})},clearError:()=>Au({error:null}),setError:$u=>Au({error:$u,status:"error"}),...initialWsState,...initialNotebookState,setWsState:$u=>Au({wsState:$u}),setWs:($u,Ru)=>{_ws=$u,Ru&&($u?_wsByAgentId.set(Ru,$u):_wsByAgentId.delete(Ru))},applySnapshot:$u=>Au(Ru=>({approvals:Ru.approvals,pendingApprovalCount:Ru.pendingApprovalCount,contextSnapshot:$u.contextSnapshot??null,costUsage:$u.costUsage??null,mcpStatus:$u.mcpStatus??null,codemodeStatus:$u.codemodeStatus??null,fullContext:$u.fullContext??null})),appendSubagentEvent:$u=>Au(Ru=>{const Iu=$u.toolCallId??$u.subagentName,Pu=Ru.subagentActivity[Iu]??[];return Pu.some(Ou=>Ou.phase==="error"&&Ou.error===SUBAGENT_STOPPED)?{}:{subagentActivity:{...Ru.subagentActivity,[Iu]:[...Pu,$u]}}}),clearSubagentActivity:()=>Au({subagentActivity:{}}),stopSubagentActivity:()=>Au($u=>{let Ru=!1;const Iu={};for(const[Pu,Ou]of Object.entries($u.subagentActivity)){if(Ou.length===0||isSubagentRunOver(Ou)){Iu[Pu]=Ou;continue}Ru=!0,Iu[Pu]=[...Ou,{subagentName:Ou[0].subagentName,toolCallId:Ou[0].toolCallId??Pu,phase:"error",error:SUBAGENT_STOPPED,transport:Ou[0].transport}]}return Ru?{subagentActivity:Iu}:{}}),requestHistoryReload:()=>Au($u=>({historyVersion:$u.historyVersion+1})),requestToolDecision:$u=>Au(Ru=>({toolDecisionRequest:{seq:(Ru.toolDecisionRequest?.seq??0)+1,...$u}})),setCompaction:$u=>Au({compaction:$u}),upsertApproval:$u=>Au(Ru=>{const Iu=Ru.approvals.filter(Ou=>Ou.id!==$u.id),Pu=[$u,...Iu];return{approvals:Pu,pendingApprovalCount:countPendingApprovals(Pu)}}),removeApproval:$u=>Au(Ru=>{const Iu=Ru.approvals.filter(Pu=>Pu.id!==$u);return{approvals:Iu,pendingApprovalCount:countPendingApprovals(Iu)}}),sendDecision:($u,Ru,Iu,Pu,Ou)=>{const Mu=_resolveWs(Ou);return Mu?(Mu.send(JSON.stringify({type:"tool_approval_decision",approvalId:$u,approved:Ru,...Iu?{note:Iu}:{},...Pu?{toolCallId:Pu}:{}})),!0):!1},requestRefresh:$u=>{const Ru=_resolveWs($u);return Ru?(Ru.send(JSON.stringify({type:"request_snapshot"})),Ru.send(JSON.stringify({type:"request_otel_flush"})),!0):!1},sendRawMessage:($u,Ru)=>{const Iu=_resolveWs(Ru);return Iu?(Iu.send(JSON.stringify($u)),!0):!1},appendLocalTokenTurn:({serviceName:$u,agentId:Ru,timestampMs:Iu,promptTokens:Pu,completionTokens:Ou,totalTokens:Mu})=>{Au(Du=>{const Lu=getMonitoringCacheKey($u,Ru),Bu=Du.monitoringCache[Lu]??{tokenTurns:[],costPoints:[]},ju=[...Bu.tokenTurns],Fu=ju[ju.length-1];if(Fu&&Fu.userMessageTokens===Pu&&Fu.aiMessageTokens===Ou&&Fu.systemPromptTokens===0&&Fu.toolsDescriptionTokens===0&&Fu.toolsUsageTokens===0&&Fu.totalTokens===Mu)return ju[ju.length-1]={...Fu,timestampMs:Math.max(Fu.timestampMs,Iu)},{monitoringCache:{...Du.monitoringCache,[Lu]:{...Bu,tokenTurns:ju}}};const zu=(Fu?.turnNumber??0)+1;return ju.push({turnNumber:zu,timestampMs:Iu,systemPromptTokens:0,toolsDescriptionTokens:0,userMessageTokens:Pu,aiMessageTokens:Ou,toolsUsageTokens:0,totalTokens:Mu}),{monitoringCache:{...Du.monitoringCache,[Lu]:{...Bu,tokenTurns:ju}}}})},mergeTokenTurns:({serviceName:$u,agentId:Ru,turns:Iu})=>{Iu.length!==0&&Au(Pu=>{const Ou=getMonitoringCacheKey($u,Ru),Mu=Pu.monitoringCache[Ou]??{tokenTurns:[],costPoints:[]},Du=new Map;for(const Bu of Mu.tokenTurns)Du.set(Bu.turnNumber,Bu);for(const Bu of Iu)Du.set(Bu.turnNumber,Bu);const Lu=Array.from(Du.values()).sort((Bu,ju)=>Bu.turnNumber-ju.turnNumber);return{monitoringCache:{...Pu.monitoringCache,[Ou]:{...Mu,tokenTurns:Lu}}}})},appendLocalTokenTurnFull:({serviceName:$u,agentId:Ru,timestampMs:Iu,systemPromptTokens:Pu,toolsDescriptionTokens:Ou,userMessageTokens:Mu,aiMessageTokens:Du,toolsUsageTokens:Lu,totalTokens:Bu})=>{Au(ju=>{const Fu=getMonitoringCacheKey($u,Ru),zu=ju.monitoringCache[Fu]??{tokenTurns:[],costPoints:[]},Uu=[...zu.tokenTurns],Hu=Uu[Uu.length-1];if(Hu&&Hu.systemPromptTokens===Pu&&Hu.toolsDescriptionTokens===Ou&&Hu.userMessageTokens===Mu&&Hu.aiMessageTokens===Du&&Hu.toolsUsageTokens===Lu&&Hu.totalTokens===Bu)return Uu[Uu.length-1]={...Hu,timestampMs:Math.max(Hu.timestampMs,Iu)},{monitoringCache:{...ju.monitoringCache,[Fu]:{...zu,tokenTurns:Uu}}};const Vu=(Hu?.turnNumber??0)+1;return Uu.push({turnNumber:Vu,timestampMs:Iu,systemPromptTokens:Pu,toolsDescriptionTokens:Ou,userMessageTokens:Mu,aiMessageTokens:Du,toolsUsageTokens:Lu,totalTokens:Bu}),{monitoringCache:{...ju.monitoringCache,[Fu]:{...zu,tokenTurns:Uu}}}})},upsertLocalCostPoint:({serviceName:$u,agentId:Ru,timestampMs:Iu,cumulativeUsd:Pu})=>{Au(Ou=>{const Mu=getMonitoringCacheKey($u,Ru),Du=Ou.monitoringCache[Mu]??{tokenTurns:[],costPoints:[]},Lu=[...Du.costPoints],Bu=Lu.findIndex(ju=>Math.abs(ju.timestampMs-Iu)<1);return Bu>=0?Lu[Bu]={...Lu[Bu],cumulativeUsd:Math.max(Lu[Bu].cumulativeUsd,Pu)}:Lu.push({timestampMs:Iu,cumulativeUsd:Pu}),Lu.sort((ju,Fu)=>ju.timestampMs-Fu.timestampMs),{monitoringCache:{...Ou.monitoringCache,[Mu]:{...Du,costPoints:Lu}}}})},mergeCostPoints:({serviceName:$u,agentId:Ru,points:Iu})=>{Iu.length!==0&&Au(Pu=>{const Ou=getMonitoringCacheKey($u,Ru),Mu=Pu.monitoringCache[Ou]??{tokenTurns:[],costPoints:[]},Du=new Map;for(const Bu of Mu.costPoints)Du.set(Bu.timestampMs,Bu);for(const Bu of Iu){const ju=Du.get(Bu.timestampMs);ju?Du.set(Bu.timestampMs,{timestampMs:Bu.timestampMs,cumulativeUsd:Math.max(ju.cumulativeUsd,Bu.cumulativeUsd)}):Du.set(Bu.timestampMs,Bu)}const Lu=Array.from(Du.values()).sort((Bu,ju)=>Bu.timestampMs-ju.timestampMs);return{monitoringCache:{...Pu.monitoringCache,[Ou]:{...Mu,costPoints:Lu}}}})},reset:()=>{if(_ws)try{_ws.close(1e3,"reset")}catch{}_ws=null,_wsByAgentId.clear(),Au($u=>({...initialRuntimeState,...initialWsState,ephemeralNotebookModels:$u.ephemeralNotebookModels,ephemeralDocumentModels:$u.ephemeralDocumentModels,editorModeByRuntime:$u.editorModeByRuntime}))},resetWs:()=>{if(_ws)try{_ws.close(1e3,"reset")}catch{}_ws=null,_wsByAgentId.clear(),Au($u=>({...initialWsState,ephemeralNotebookModels:$u.ephemeralNotebookModels,ephemeralDocumentModels:$u.ephemeralDocumentModels,editorModeByRuntime:$u.editorModeByRuntime,subagentActivity:$u.subagentActivity}))}}),{name:"agent-runtimes-storage",storage:createJSONStorage(()=>localStorage),partialize:Au=>({agents:Au.agents.map(lo=>({id:lo.id,name:lo.name,description:lo.description,baseUrl:lo.baseUrl,transport:lo.protocol,status:lo.status,lastUpdated:lo.lastUpdated,documentId:lo.documentId,runtimeId:lo.runtimeId})),monitoringCache:Au.monitoringCache,loadedSkillsByAgentId:Au.loadedSkillsByAgentId,ephemeralNotebookModels:Au.ephemeralNotebookModels,ephemeralDocumentModels:Au.ephemeralDocumentModels,editorModeByRuntime:Au.editorModeByRuntime})})));function useAgentRuntimeStore(Au){return useStore$1(agentRuntimeStore,Au||($u=>$u))}const useAgentRuntimeStoreWithStatics=useAgentRuntimeStore;useAgentRuntimeStoreWithStatics.getState=agentRuntimeStore.getState;useAgentRuntimeStoreWithStatics.subscribe=agentRuntimeStore.subscribe;const useAgentRuntimeConnection=()=>useAgentRuntimeStore(Au=>Au.runtime),useAgentRuntimeStatus=()=>useAgentRuntimeStore(Au=>Au.status),useAgentRuntimeError=()=>useAgentRuntimeStore(Au=>Au.error),useAgentRuntimeIsLaunching=()=>useAgentRuntimeStore(Au=>Au.isLaunching),useAgentRuntimeMcpStatus=()=>useAgentRuntimeStore(Au=>Au.mcpStatus),useAgentRuntimeFullContext=()=>useAgentRuntimeStore(Au=>Au.fullContext),useAgentRuntimeContextSnapshot=()=>useAgentRuntimeStore(Au=>Au.contextSnapshot),useAgentRuntimeCodemodeStatus=()=>useAgentRuntimeStore(Au=>Au.codemodeStatus),useAgentRuntimeWsState=()=>useAgentRuntimeStore(Au=>Au.wsState),EMPTY_SUBAGENT_EVENTS=[],useAgentRuntimeSubagentActivity=Au=>useAgentRuntimeStore(lo=>Au?lo.subagentActivity[Au]??EMPTY_SUBAGENT_EVENTS:EMPTY_SUBAGENT_EVENTS),useAgentRuntimeSubagentActivityByToolCall=(Au,lo)=>useAgentRuntimeStore($u=>{if(Au){const Ru=$u.subagentActivity[Au];if(Ru&&Ru.length>0)return Ru}if(lo){const Ru=$u.subagentActivity[lo];if(Ru&&Ru.length>0)return Ru;let Iu;for(const Pu of Object.values($u.subagentActivity))Pu.length>0&&Pu[0]?.subagentName===lo&&(Iu=Pu);if(Iu)return Iu}return EMPTY_SUBAGENT_EVENTS}),useAgentRuntimeActiveSubagentToolCallId=()=>useAgentRuntimeStore(Au=>{let lo=null;for(const[$u,Ru]of Object.entries(Au.subagentActivity))Ru.length!==0&&(isSubagentRunOver(Ru)||(lo=$u));return lo});agentRuntimeStore.subscribe;async function requestAPI(Au="",lo={}){const $u=libExports$3.ServerConnection.makeSettings(),Ru=libExports$5.URLExt.join($u.baseUrl,"agent_runtimes",Au);let Iu;try{Iu=await libExports$3.ServerConnection.makeRequest(Ru,lo,$u)}catch(Ou){throw new libExports$3.ServerConnection.NetworkError(Ou)}let Pu=await Iu.text();if(Pu.length>0)try{Pu=JSON.parse(Pu)}catch{}if(!Iu.ok)throw new libExports$3.ServerConnection.ResponseError(Iu,Pu.message||Pu);return Pu}function useConfig(Au,lo,$u,Ru){return reactExports.useContext(QueryClientContext)?useQuery({queryFn:async()=>{if(lo){const Pu={"Content-Type":"application/json"};$u&&(Pu.Authorization=`Bearer ${$u}`);let Ou=lo;if(Ru){const Du=new URL(lo,window.location.origin);Du.searchParams.set("agent_id",Ru),Ou=Du.toString()}const Mu=await fetch(Ou,{headers:Pu});if(!Mu.ok)throw new Error(`Config fetch failed: ${Mu.statusText}`);return Mu.json()}return requestAPI("configure")},queryKey:["models",lo||"jupyter-server",Ru||"global"],enabled:Au,retry:1}):{data:void 0,isLoading:!1,isError:!1,error:null,refetch:()=>Promise.resolve({data:void 0})}}function parseSkillStatus(Au){return Au==="available"||Au==="enabled"||Au==="loaded"?Au:"available"}function useSkills(Au,lo,$u){const Ru=useAgentRuntimeCodemodeStatus(),Iu=reactExports.useMemo(()=>{if(!Ru)return;const Pu=(Ru.skills??[]).map(Ou=>({id:Ou.id??Ou.name,name:Ou.name,description:Ou.description,tags:Ou.tags,has_scripts:Ou.has_scripts,has_resources:Ou.has_resources,status:parseSkillStatus(Ou.status),approved:Ou.approved!==!1,skill_definition:Ou.skill_definition??null,source_variant:Ou.source_variant,module:Ou.module,package:Ou.package,method:Ou.method,path:Ou.path}));return{skills:Pu,total:Pu.length}},[Ru]);return{data:Iu,isLoading:!1,isError:!1,error:null,refetch:()=>Promise.resolve({data:Iu})}}function useSkillActions(Au){const lo=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_enable",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_enable dropped: websocket not ready"),Ou},[Au]),$u=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_disable",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_disable dropped: websocket not ready"),Ou},[Au]),Ru=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_approve",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_approve dropped: websocket not ready"),Ou},[Au]),Iu=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_unapprove",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_unapprove dropped: websocket not ready"),Ou},[Au]);return{enableSkill:lo,disableSkill:$u,approveSkill:Ru,unapproveSkill:Iu}}function useContextSnapshot(Au,lo,$u,Ru){return{data:useAgentRuntimeContextSnapshot()??void 0,isLoading:!1,isError:!1,error:null}}const RECONNECT_BASE_MS$1=1e3,RECONNECT_MAX_MS$1=3e4;function isRetryableCloseCode(Au){return!new Set([1002,1003,1007,1008,4401,4403]).has(Au)}function useSandbox(Au,lo,$u,Ru){const[Iu,Pu]=reactExports.useState(void 0),Ou=reactExports.useRef(null);reactExports.useEffect(()=>{if(!Au||!lo){Pu(void 0);return}const Du=getApiBaseFromConfig(lo);if(!Du)return;const Lu=Du.replace(/^http/,"ws"),Bu=[];Ru&&Bu.push(`agent_id=${encodeURIComponent(Ru)}`),$u&&Bu.push(`token=${encodeURIComponent($u)}`);const ju=`${Lu}/configure/sandbox/ws${Bu.length?`?${Bu.join("&")}`:""}`;let Fu=!1,zu,Uu=0;const Hu=Gu=>{if(Fu||!isRetryableCloseCode(Gu))return;const Wu=Math.min(RECONNECT_BASE_MS$1*2**Uu,RECONNECT_MAX_MS$1);Uu+=1,zu=setTimeout(Vu,Wu)},Vu=()=>{if(Fu)return;const Gu=new WebSocket(ju);Ou.current=Gu,Gu.onopen=()=>{Uu=0},Gu.onmessage=Wu=>{try{const Ku=JSON.parse(Wu.data);if(Ku&&Ku.action==="interrupt")return;const Ju=typeof Ku?.variant=="string"?Ku.variant:"";Pu({available:Ju!=="unavailable"&&Ju!=="error",sandbox_running:!!Ku?.sandbox_running,is_executing:!!Ku?.is_executing,variant:Ju})}catch{}},Gu.onclose=Wu=>{Ou.current=null,Hu(Wu.code)},Gu.onerror=()=>{Gu.close()}};return Vu(),()=>{Fu=!0,zu&&clearTimeout(zu),Ou.current?.close(),Ou.current=null,Pu(void 0)}},[Au,lo,$u,Ru]);const Mu=reactExports.useCallback(()=>{const Du=Ou.current;Du&&Du.readyState===WebSocket.OPEN&&Du.send(JSON.stringify({action:"interrupt"}))},[]);return{data:Iu,interrupt:Mu}}function _typeof$8(Au){"@babel/helpers - typeof";return _typeof$8=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$8(Au)}function _createClass$8(Au,lo,$u){return Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _classCallCheck$8(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _callSuper$1(Au,lo,$u){return lo=_getPrototypeOf$1(lo),_possibleConstructorReturn$1(Au,_isNativeReflectConstruct$1()?Reflect.construct(lo,$u||[],_getPrototypeOf$1(Au).constructor):lo.apply(Au,$u))}function _possibleConstructorReturn$1(Au,lo){if(lo&&(_typeof$8(lo)==="object"||typeof lo=="function"))return lo;if(lo!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized$1(Au)}function _assertThisInitialized$1(Au){if(Au===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return Au}function _inherits$1(Au,lo){if(typeof lo!="function"&&lo!==null)throw new TypeError("Super expression must either be null or a function");Au.prototype=Object.create(lo&&lo.prototype,{constructor:{value:Au,writable:!0,configurable:!0}}),Object.defineProperty(Au,"prototype",{writable:!1}),lo&&_setPrototypeOf$1(Au,lo)}function _wrapNativeSuper(Au){var lo=typeof Map=="function"?new Map:void 0;return _wrapNativeSuper=function(Ru){if(Ru===null||!_isNativeFunction(Ru))return Ru;if(typeof Ru!="function")throw new TypeError("Super expression must either be null or a function");if(typeof lo<"u"){if(lo.has(Ru))return lo.get(Ru);lo.set(Ru,Iu)}function Iu(){return _construct(Ru,arguments,_getPrototypeOf$1(this).constructor)}return Iu.prototype=Object.create(Ru.prototype,{constructor:{value:Iu,enumerable:!1,writable:!0,configurable:!0}}),_setPrototypeOf$1(Iu,Ru)},_wrapNativeSuper(Au)}function _construct(Au,lo,$u){if(_isNativeReflectConstruct$1())return Reflect.construct.apply(null,arguments);var Ru=[null];Ru.push.apply(Ru,lo);var Iu=new(Au.bind.apply(Au,Ru));return $u&&_setPrototypeOf$1(Iu,$u.prototype),Iu}function _isNativeReflectConstruct$1(){try{var Au=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(_isNativeReflectConstruct$1=function(){return!!Au})()}function _isNativeFunction(Au){try{return Function.toString.call(Au).indexOf("[native code]")!==-1}catch{return typeof Au=="function"}}function _setPrototypeOf$1(Au,lo){return _setPrototypeOf$1=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(Ru,Iu){return Ru.__proto__=Iu,Ru},_setPrototypeOf$1(Au,lo)}function _getPrototypeOf$1(Au){return _getPrototypeOf$1=Object.setPrototypeOf?Object.getPrototypeOf.bind():function($u){return $u.__proto__||Object.getPrototypeOf($u)},_getPrototypeOf$1(Au)}var DetailedError=(function(Au){function lo($u){var Ru,Iu=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,Pu=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,Ou=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null;if(_classCallCheck$8(this,lo),Ru=_callSuper$1(this,lo,[$u]),Ru.originalRequest=Pu,Ru.originalResponse=Ou,Ru.causingError=Iu,Iu!=null&&($u+=", caused by ".concat(Iu.toString())),Pu!=null){var Mu=Pu.getHeader("X-Request-ID")||"n/a",Du=Pu.getMethod(),Lu=Pu.getURL(),Bu=Ou?Ou.getStatus():"n/a",ju=Ou?Ou.getBody()||"":"n/a";$u+=", originated from request (method: ".concat(Du,", url: ").concat(Lu,", response code: ").concat(Bu,", response text: ").concat(ju,", request id: ").concat(Mu,")")}return Ru.message=$u,Ru}return _inherits$1(lo,Au),_createClass$8(lo)})(_wrapNativeSuper(Error));function log(Au){}function _typeof$7(Au){"@babel/helpers - typeof";return _typeof$7=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$7(Au)}function _classCallCheck$7(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$7(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$7(Ru.key),Ru)}}function _createClass$7(Au,lo,$u){return lo&&_defineProperties$7(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$7(Au){var lo=_toPrimitive$7(Au,"string");return _typeof$7(lo)=="symbol"?lo:lo+""}function _toPrimitive$7(Au,lo){if(_typeof$7(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$7(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var NoopUrlStorage=(function(){function Au(){_classCallCheck$7(this,Au)}return _createClass$7(Au,[{key:"listAllUploads",value:function(){return Promise.resolve([])}},{key:"findUploadsByFingerprint",value:function($u){return Promise.resolve([])}},{key:"removeUpload",value:function($u){return Promise.resolve()}},{key:"addUpload",value:function($u,Ru){return Promise.resolve(null)}}])})();const version$1="3.9.4",VERSION=version$1,_TD=typeof TextDecoder=="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,_TE=typeof TextEncoder=="function"?new TextEncoder:void 0,b64ch="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",b64chs=Array.prototype.slice.call(b64ch),b64tab=(Au=>{let lo={};return Au.forEach(($u,Ru)=>lo[$u]=Ru),lo})(b64chs),b64re=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,_fromCC=String.fromCharCode.bind(String),_U8Afrom=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):Au=>new Uint8Array(Array.prototype.slice.call(Au,0)),_mkUriSafe=Au=>Au.replace(/=/g,"").replace(/[+\/]/g,lo=>lo=="+"?"-":"_"),_tidyB64=Au=>Au.replace(/[^A-Za-z0-9\+\/]/g,""),btoaPolyfill=Au=>{let lo,$u,Ru,Iu,Pu="";const Ou=Au.length%3;for(let Mu=0;Mu<Au.length;){if(($u=Au.charCodeAt(Mu++))>255||(Ru=Au.charCodeAt(Mu++))>255||(Iu=Au.charCodeAt(Mu++))>255)throw new TypeError("invalid character found");lo=$u<<16|Ru<<8|Iu,Pu+=b64chs[lo>>18&63]+b64chs[lo>>12&63]+b64chs[lo>>6&63]+b64chs[lo&63]}return Ou?Pu.slice(0,Ou-3)+"===".substring(Ou):Pu},_btoa=typeof btoa=="function"?Au=>btoa(Au):btoaPolyfill,_fromUint8Array=typeof Uint8Array.prototype.toBase64=="function"?Au=>Au.toBase64():Au=>{let $u=[];for(let Ru=0,Iu=Au.length;Ru<Iu;Ru+=4096)$u.push(_fromCC.apply(null,Au.subarray(Ru,Ru+4096)));return _btoa($u.join(""))},fromUint8Array=(Au,lo=!1)=>lo?_mkUriSafe(_fromUint8Array(Au)):_fromUint8Array(Au),cb_utob=Au=>{if(Au.length<2){var lo=Au.charCodeAt(0);return lo<128?Au:lo<2048?_fromCC(192|lo>>>6)+_fromCC(128|lo&63):_fromCC(224|lo>>>12&15)+_fromCC(128|lo>>>6&63)+_fromCC(128|lo&63)}else{var lo=65536+(Au.charCodeAt(0)-55296)*1024+(Au.charCodeAt(1)-56320);return _fromCC(240|lo>>>18&7)+_fromCC(128|lo>>>12&63)+_fromCC(128|lo>>>6&63)+_fromCC(128|lo&63)}},re_utob=/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\x00-\x7F]/g,utob=Au=>Au.replace(re_utob,cb_utob),_encode=_TE?Au=>_fromUint8Array(_TE.encode(Au)):Au=>_btoa(utob(Au)),encode$2=(Au,lo=!1)=>lo?_mkUriSafe(_encode(Au)):_encode(Au),encodeURI$1=Au=>encode$2(Au,!0),re_btou=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,cb_btou=Au=>{switch(Au.length){case 4:var lo=(7&Au.charCodeAt(0))<<18|(63&Au.charCodeAt(1))<<12|(63&Au.charCodeAt(2))<<6|63&Au.charCodeAt(3),$u=lo-65536;return _fromCC(($u>>>10)+55296)+_fromCC(($u&1023)+56320);case 3:return _fromCC((15&Au.charCodeAt(0))<<12|(63&Au.charCodeAt(1))<<6|63&Au.charCodeAt(2));default:return _fromCC((31&Au.charCodeAt(0))<<6|63&Au.charCodeAt(1))}},btou=Au=>Au.replace(re_btou,cb_btou),atobPolyfill=Au=>{if(Au=Au.replace(/\s+/g,""),!b64re.test(Au))throw new TypeError("malformed base64.");Au+="==".slice(2-(Au.length&3));let lo,$u,Ru,Iu=[];for(let Pu=0;Pu<Au.length;)lo=b64tab[Au.charAt(Pu++)]<<18|b64tab[Au.charAt(Pu++)]<<12|($u=b64tab[Au.charAt(Pu++)])<<6|(Ru=b64tab[Au.charAt(Pu++)]),$u===64?Iu.push(_fromCC(lo>>16&255)):Ru===64?Iu.push(_fromCC(lo>>16&255,lo>>8&255)):Iu.push(_fromCC(lo>>16&255,lo>>8&255,lo&255));return Iu.join("")},_atob=typeof atob=="function"?Au=>atob(_tidyB64(Au)):atobPolyfill,_toUint8Array=typeof Uint8Array.fromBase64=="function"?Au=>Uint8Array.fromBase64(Au):Au=>_U8Afrom(_atob(Au).split("").map(lo=>lo.charCodeAt(0))),toUint8Array=Au=>_toUint8Array(_unURI(Au)),_decode=_TD?Au=>_TD.decode(_toUint8Array(Au)):Au=>btou(_atob(Au)),_unURI=Au=>_tidyB64(Au.replace(/[-_]/g,lo=>lo=="-"?"+":"/")),decode$3=Au=>_decode(_unURI(Au)),isValid$1=Au=>{if(typeof Au!="string")return!1;const lo=Au.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(lo)||!/[^\s0-9a-zA-Z\-_]/.test(lo)},_noEnum=Au=>({value:Au,enumerable:!1,writable:!0,configurable:!0}),extendString=function(){const Au=(lo,$u)=>Object.defineProperty(String.prototype,lo,_noEnum($u));Au("fromBase64",function(){return decode$3(this)}),Au("toBase64",function(lo){return encode$2(this,lo)}),Au("toBase64URI",function(){return encode$2(this,!0)}),Au("toBase64URL",function(){return encode$2(this,!0)}),Au("toUint8Array",function(){return toUint8Array(this)})},extendUint8Array=function(){const Au=(lo,$u)=>Object.defineProperty(Uint8Array.prototype,lo,_noEnum($u));Au("toBase64",function(lo){return fromUint8Array(this,lo)}),Au("toBase64URI",function(){return fromUint8Array(this,!0)}),Au("toBase64URL",function(){return fromUint8Array(this,!0)})},extendBuiltins=()=>{extendString(),extendUint8Array()},gBase64={version:version$1,VERSION,atob:_atob,atobPolyfill,btoa:_btoa,btoaPolyfill,fromBase64:decode$3,toBase64:encode$2,encode:encode$2,encodeURI:encodeURI$1,encodeURL:encodeURI$1,utob,btou,decode:decode$3,isValid:isValid$1,fromUint8Array,toUint8Array,extendString,extendUint8Array,extendBuiltins};var urlParseExports=requireUrlParse();const URL$1=getDefaultExportFromCjs(urlParseExports);function uuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(Au){var lo=Math.random()*16|0,$u=Au==="x"?lo:lo&3|8;return $u.toString(16)})}function _regeneratorRuntime$1(){_regeneratorRuntime$1=function(){return lo};var Au,lo={},$u=Object.prototype,Ru=$u.hasOwnProperty,Iu=Object.defineProperty||function(_d,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,Ed,cd){return wd[Ed]=cd}}function Bu(_d,bd,wd,Ed){var cd=bd&&bd.prototype instanceof Gu?bd:Gu,ud=Object.create(cd.prototype),md=new gd(Ed||[]);return Iu(ud,"_invoke",{value:od(_d,wd,md)}),ud}function ju(_d,bd,wd){try{return{type:"normal",arg:_d.call(bd,wd)}}catch(Ed){return{type:"throw",arg:Ed}}}lo.wrap=Bu;var Fu="suspendedStart",zu="suspendedYield",Uu="executing",Hu="completed",Vu={};function Gu(){}function Wu(){}function Ku(){}var Ju={};Lu(Ju,Ou,function(){return this});var Yu=Object.getPrototypeOf,Xu=Yu&&Yu(Yu(yd([])));Xu&&Xu!==$u&&Ru.call(Xu,Ou)&&(Ju=Xu);var ed=Ku.prototype=Gu.prototype=Object.create(Ju);function td(_d){["next","throw","return"].forEach(function(bd){Lu(_d,bd,function(wd){return this._invoke(bd,wd)})})}function nd(_d,bd){function wd(cd,ud,md,ld){var hd=ju(_d[cd],_d,ud);if(hd.type!=="throw"){var vd=hd.arg,Sd=vd.value;return Sd&&_typeof$6(Sd)=="object"&&Ru.call(Sd,"__await")?bd.resolve(Sd.__await).then(function(kd){wd("next",kd,md,ld)},function(kd){wd("throw",kd,md,ld)}):bd.resolve(Sd).then(function(kd){vd.value=kd,md(vd)},function(kd){return wd("throw",kd,md,ld)})}ld(hd.arg)}var Ed;Iu(this,"_invoke",{value:function(ud,md){function ld(){return new bd(function(hd,vd){wd(ud,md,hd,vd)})}return Ed=Ed?Ed.then(ld,ld):ld()}})}function od(_d,bd,wd){var Ed=Fu;return function(cd,ud){if(Ed===Uu)throw Error("Generator is already running");if(Ed===Hu){if(cd==="throw")throw ud;return{value:Au,done:!0}}for(wd.method=cd,wd.arg=ud;;){var md=wd.delegate;if(md){var ld=sd(md,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(Ed===Fu)throw Ed=Hu,wd.arg;wd.dispatchException(wd.arg)}else wd.method==="return"&&wd.abrupt("return",wd.arg);Ed=Uu;var hd=ju(_d,bd,wd);if(hd.type==="normal"){if(Ed=wd.done?Hu:zu,hd.arg===Vu)continue;return{value:hd.arg,done:wd.done}}hd.type==="throw"&&(Ed=Hu,wd.method="throw",wd.arg=hd.arg)}}}function sd(_d,bd){var wd=bd.method,Ed=_d.iterator[wd];if(Ed===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 cd=ju(Ed,_d.iterator,bd.arg);if(cd.type==="throw")return bd.method="throw",bd.arg=cd.arg,bd.delegate=null,Vu;var ud=cd.arg;return ud?ud.done?(bd[_d.resultName]=ud.value,bd.next=_d.nextLoc,bd.method!=="return"&&(bd.method="next",bd.arg=Au),bd.delegate=null,Vu):ud:(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 gd(_d){this.tryEntries=[{tryLoc:"root"}],_d.forEach(ad,this),this.reset(!0)}function yd(_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,Ed=function cd(){for(;++wd<_d.length;)if(Ru.call(_d,wd))return cd.value=_d[wd],cd.done=!1,cd;return cd.value=Au,cd.done=!0,cd};return Ed.next=Ed}}throw new TypeError(_typeof$6(_d)+" is not iterable")}return Wu.prototype=Ku,Iu(ed,"constructor",{value:Ku,configurable:!0}),Iu(Ku,"constructor",{value:Wu,configurable:!0}),Wu.displayName=Lu(Ku,Du,"GeneratorFunction"),lo.isGeneratorFunction=function(_d){var 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,Ku):(_d.__proto__=Ku,Lu(_d,Du,"GeneratorFunction")),_d.prototype=Object.create(ed),_d},lo.awrap=function(_d){return{__await:_d}},td(nd.prototype),Lu(nd.prototype,Mu,function(){return this}),lo.AsyncIterator=nd,lo.async=function(_d,bd,wd,Ed,cd){cd===void 0&&(cd=Promise);var ud=new nd(Bu(_d,bd,wd,Ed),cd);return lo.isGeneratorFunction(bd)?ud:ud.next().then(function(md){return md.done?md.value:ud.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 Ed in bd)wd.push(Ed);return wd.reverse(),function cd(){for(;wd.length;){var ud=wd.pop();if(ud in bd)return cd.value=ud,cd.done=!1,cd}return cd.done=!0,cd}},lo.values=yd,gd.prototype={constructor:gd,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 Ed(vd,Sd){return md.type="throw",md.arg=bd,wd.next=vd,Sd&&(wd.method="next",wd.arg=Au),!!Sd}for(var cd=this.tryEntries.length-1;cd>=0;--cd){var ud=this.tryEntries[cd],md=ud.completion;if(ud.tryLoc==="root")return Ed("end");if(ud.tryLoc<=this.prev){var ld=Ru.call(ud,"catchLoc"),hd=Ru.call(ud,"finallyLoc");if(ld&&hd){if(this.prev<ud.catchLoc)return Ed(ud.catchLoc,!0);if(this.prev<ud.finallyLoc)return Ed(ud.finallyLoc)}else if(ld){if(this.prev<ud.catchLoc)return Ed(ud.catchLoc,!0)}else{if(!hd)throw Error("try statement without catch or finally");if(this.prev<ud.finallyLoc)return Ed(ud.finallyLoc)}}}},abrupt:function(bd,wd){for(var Ed=this.tryEntries.length-1;Ed>=0;--Ed){var cd=this.tryEntries[Ed];if(cd.tryLoc<=this.prev&&Ru.call(cd,"finallyLoc")&&this.prev<cd.finallyLoc){var ud=cd;break}}ud&&(bd==="break"||bd==="continue")&&ud.tryLoc<=wd&&wd<=ud.finallyLoc&&(ud=null);var md=ud?ud.completion:{};return md.type=bd,md.arg=wd,ud?(this.method="next",this.next=ud.finallyLoc,Vu):this.complete(md)},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 Ed=this.tryEntries[wd];if(Ed.finallyLoc===bd)return this.complete(Ed.completion,Ed.afterLoc),pd(Ed),Vu}},catch:function(bd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ed=this.tryEntries[wd];if(Ed.tryLoc===bd){var cd=Ed.completion;if(cd.type==="throw"){var ud=cd.arg;pd(Ed)}return ud}}throw Error("illegal catch attempt")},delegateYield:function(bd,wd,Ed){return this.delegate={iterator:yd(bd),resultName:wd,nextLoc:Ed},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.
|
|
@@ -3859,7 +3859,7 @@ ${Mu}`:ju,inputs:Mu,clear:Ou?[]:[DRAFT.path],loop:Lu()}:{refused:"Nothing to sen
|
|
|
3859
3859
|
}`;function SubagentPulse(){const Au=useAgentRuntimeActiveSubagentToolCallId(),lo=useAgentRuntimeSubagentActivity(Au??void 0),$u=useOptionalReactorPlatform(),Ru=lo[0]?.subagentName??Au??"",Iu=$u?.getOutput(AGENTS_PLUGIN_NAME)?.team?.members.find(Du=>Du.name===Ru),Pu=agentIcon(Iu?.icon);if(!Au)return null;const Mu=lo.some(Du=>Du.transport==="a2a")?`${Ru} is working over A2A…`:`${Ru} is working…`;return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("style",{children:KEYFRAMES}),jsxRuntimeExports.jsx(Tooltip,{text:Mu,direction:"n",children:jsxRuntimeExports.jsx(Box,{as:"button",type:"button","aria-label":Mu,"data-subagent-pulse":Ru,display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,p:0,border:0,bg:"transparent",color:"accent.fg",cursor:"default",animation:`${PULSE_ANIMATION} 1.4s ease-in-out infinite`,children:jsxRuntimeExports.jsx(Pu,{size:16})})})]})}const SUBAGENT_ACTIVITY_PLUGIN_NAME="@datalayer/loop-plugin-subagent-activity",SubagentActivityPlugin={name:SUBAGENT_ACTIVITY_PLUGIN_NAME,displayName:"Subagent activity",description:"A delegated agent's icon, pulsing in the prompt's header while it works.",octicon:"people",emoji:"👥",dependencies:[InputPromptPlugin],build:()=>({components:[{id:"subagent-pulse",slot:LoopSlots.inpromptMenu,order:0,Component:SubagentPulse}]})},A2UI_PLUGIN_NAME="@datalayer/loop-plugin-a2ui",A2uiPlugin={name:A2UI_PLUGIN_NAME,displayName:"A2UI surfaces",description:"The last execution, rendered as a surface rather than dumped.",octicon:"browser",emoji:"🖼",dependencies:[AgentsPlugin],contributes:[contribution(LoopViewType,{viewType:"a2ui",title:"Surface",icon:BrowserIcon,order:30,canOpen:Au=>Au.sandbox.state==="running"&&Au.sandbox.variant!=="pyodide",unavailableReason:Au=>Au.sandbox.variant==="pyodide"?"Surfaces are rendered by the server; this sandbox runs in the browser":"Needs a running sandbox",load:()=>__vitePreload(()=>import("./chunks/A2uiView-EmeKVJZp.js"),[],import.meta.url)},{id:"a2ui",order:30}),contribution(LoopCommand,{name:"a2ui",aliases:["surface"],description:"Show the last execution as a rendered surface",group:"Open",keybinding:"Mod+Alt+U",run:async({workspace:Au})=>{Au.setActiveViewType("a2ui")}},{id:"a2ui"})]},NONE_VIEW="none";let state={viewId:NONE_VIEW,options:[],allowNone:!0},announcer=()=>!0;const listeners=new Set;function notify(){for(const Au of[...listeners])Au()}function getViewChoice(){return state}function subscribeViewChoice(Au){return listeners.add(Au),()=>{listeners.delete(Au)}}function setViewAnnouncer(Au){const lo=announcer;return announcer=Au,()=>{announcer=lo}}function setViewOptions(Au,lo=!0){if(lo===state.allowNone&&Au.length===state.options.length&&Au.every((Ru,Iu)=>Ru===state.options[Iu]))return;state={viewId:!lo&&!Au.includes(state.viewId)?Au[0]??NONE_VIEW:state.viewId,options:Au,allowNone:lo},notify()}function chooseView(Au){return state={...state,viewId:Au},notify(),announcer(Au)}function seedViewChoice(Au){state.viewId!==Au&&(state={...state,viewId:Au},notify())}function nextView(){const Au=state.allowNone?[NONE_VIEW,...state.options]:[...state.options];if(Au.length===0)return NONE_VIEW;const lo=Au.indexOf(state.viewId);return Au[(lo+1)%Au.length]}function ViewSelector({point:Au,describe:lo,context:$u,noneLabel:Ru,ariaLabel:Iu,allowNone:Pu=!0}){const Ou=useContributions(Au),Mu=reactExports.useSyncExternalStore(subscribeViewChoice,getViewChoice),[Du,Lu]=reactExports.useState(null),Bu=reactExports.useRef(null),ju=()=>{Bu.current!==null&&(window.clearTimeout(Bu.current),Bu.current=null)},Fu=Vu=>{ju(),Lu(Vu)},zu=()=>{ju(),Bu.current=window.setTimeout(()=>{Lu(null),Bu.current=null},250)};reactExports.useEffect(()=>ju,[]);const Uu=reactExports.useMemo(()=>Ou.map(Vu=>lo(Vu.value,$u)).sort((Vu,Gu)=>(Vu.order??100)-(Gu.order??100)),[Ou,lo,$u]);if(reactExports.useEffect(()=>{setViewOptions(Uu.map(Vu=>Vu.id),Pu)},[Uu,Pu]),Uu.length<(Pu?1:2))return null;const Hu=Uu.find(Vu=>Vu.id===Du&&Vu.details);return jsxRuntimeExports.jsxs(Box$1,{sx:{marginLeft:"auto",display:"flex",alignItems:"center",position:"relative"},children:[jsxRuntimeExports.jsxs(SegmentedControl,{"aria-label":Iu,size:"small",children:[Pu?jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:Mu.viewId===NONE_VIEW,onClick:()=>chooseView(NONE_VIEW),children:Ru}):null,Uu.map(Vu=>jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:Mu.viewId===Vu.id,"aria-disabled":Vu.disabled||void 0,title:Vu.disabled?Vu.disabledReason:Vu.title,leadingIcon:Vu.icon,onMouseEnter:Vu.details?()=>Fu(Vu.id):void 0,onMouseLeave:Vu.details?zu:void 0,onClick:()=>{Vu.disabled||chooseView(Vu.id)},children:Vu.badge?`${Vu.title} (${Vu.badge})`:Vu.title},Vu.id))]}),Hu?jsxRuntimeExports.jsx(Box$1,{onMouseEnter:ju,onMouseLeave:zu,sx:{position:"absolute",top:"calc(100% + 6px)",right:0,minWidth:260,maxWidth:380,maxHeight:320,overflowY:"auto",p:2,bg:"canvas.overlay",border:"1px solid",borderColor:"border.default",borderRadius:2,boxShadow:"shadow.large",zIndex:40,fontSize:0,color:"fg.default",textAlign:"left"},children:Hu.details}):null]})}const SHELL_PLUGIN_NAME$1="@datalayer/reactor-shell",ShellView=defineContributionPoint("reactor.shell.view"),describeAsIs=Au=>Au,ShellPlugin$1={name:SHELL_PLUGIN_NAME$1,displayName:"Shell",description:"A view point, its selector, and the choice as a command.",octicon:"columns",emoji:"📑",config:{point:ShellView,describe:describeAsIs,slot:"header",defaultView:NONE_VIEW,showSelector:!0,allowNone:!0,noneLabel:"None",ariaLabel:"View",announce:()=>!0,commandId:"shell.cycleView",commandName:"Switch the view",commandDescription:"Cycle through the contributed views, and none",keybinding:"Mod+Alt+E"},contributionPoints:[ShellView],register:({config:Au,registerCommand:lo})=>{const $u=setViewAnnouncer(Au.announce),Ru=lo({id:Au.commandId,name:Au.commandName,description:Au.commandDescription,emoji:"📑",category:"Workspace",keybinding:Au.keybinding||void 0,execute:()=>{chooseView(nextView())}});return()=>{$u(),Ru()}},build:({config:Au})=>(seedViewChoice(Au.defaultView||NONE_VIEW),{components:Au.showSelector?[{id:"view-selector",slot:Au.slot,Component:lo=>jsxRuntimeExports.jsx(ViewSelector,{point:Au.point,describe:Au.describe,context:lo,noneLabel:Au.noneLabel,allowNone:Au.allowNone,ariaLabel:Au.ariaLabel})}]:[]})};setViewAnnouncer(requestSurface);const NONE_EDITOR=NONE_VIEW;let mappedFor=null,mapped=null;function getEditorChoice(){const Au=getViewChoice();return(Au!==mappedFor||!mapped)&&(mappedFor=Au,mapped={editorId:Au.viewId,options:Au.options}),mapped}const subscribeEditorChoice=subscribeViewChoice,setEditorOptions=setViewOptions,chooseEditor=chooseView,seedEditorChoice=seedViewChoice,nextEditor=nextView;let jupyterReact=null;function loadJupyterReact(){return jupyterReact?Promise.resolve(jupyterReact):__vitePreload(()=>import("./chunks/index-Dzf9vro3.js").then(Au=>Au.r),[],import.meta.url).then(Au=>(jupyterReact=Au,Au))}const PREVIEW_LENGTH=56;function stripped(Au){const $u=(Au.split(`
|
|
3860
3860
|
`).find(Ru=>Ru.trim())??"").trim();return $u.length>PREVIEW_LENGTH?`${$u.slice(0,PREVIEW_LENGTH-1)}…`:$u||"(empty)"}function PreviewList({title:Au,rows:lo}){return jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold",display:"block",mb:1},children:Au}),lo.length===0?jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted"},children:"Empty so far."}):lo.map(($u,Ru)=>jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,py:"2px",alignItems:"baseline",children:[jsxRuntimeExports.jsxs(Text$3,{sx:{color:"fg.muted",flexShrink:0,fontFamily:"mono"},children:[Ru," · ",$u.kind]}),jsxRuntimeExports.jsx(Text$3,{sx:{fontFamily:"mono",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:$u.text})]},Ru))]})}function useOfferedEditors(){return reactExports.useSyncExternalStore(subscribeEditorChoice,()=>getEditorChoice().options)}function useNotebookRows(Au,lo){const[$u,Ru]=reactExports.useState(0);return reactExports.useEffect(()=>{if(!lo)return;let Iu=!1;const Pu=()=>Ru(Du=>Du+1),Ou=[],Mu=jupyterReact!==null;return loadJupyterReact().then(({notebookStore:Du})=>{if(!Iu)try{const Lu=Du.subscribe?.(Pu);Lu&&Ou.push(Lu);const Bu=Du.getState()?.notebooks?.get(Au)?.model;if(Bu){const ju=[Bu.contentChanged,Bu.cells?.changed];for(const Fu of ju)Fu?.connect&&(Fu.connect(Pu),Ou.push(()=>Fu.disconnect(Pu)))}Mu||Pu()}catch{}}),()=>{Iu=!0;for(const Du of Ou)try{Du()}catch{}}},[lo,Au,$u]),reactExports.useMemo(()=>{if(!lo)return null;const Iu=safeModel(Au);if(!Iu)return null;const Pu=[],Ou=Iu.cells;for(let Mu=0;Mu<Ou.length;Mu+=1){const Du=Ou.get(Mu);Pu.push({kind:Du.type,text:stripped(Du.sharedModel.getSource())})}return Pu},[lo,Au,$u])}function safeModel(Au){try{return jupyterReact?.notebookStore.getState()?.notebooks?.get(Au)?.model??null}catch{return null}}function useDocumentRows(Au,lo){const[$u,Ru]=reactExports.useState(null);return reactExports.useEffect(()=>{if(!lo){Ru(null);return}let Iu=!1,Pu,Ou=!1;return __vitePreload(()=>import("./chunks/PrismCss-CcU1ChRk.js").then(Mu=>Mu.a),[],import.meta.url).then(()=>__vitePreload(()=>import("./chunks/index-2ciQBsIP.js"),[],import.meta.url)).then(({lexicalStore:Mu})=>{if(Iu)return;const Du=()=>{Ou||(Ou=!0,Mu.getState().readAllBlocks(Au,"brief").then(Lu=>{Ou=!1,!(Iu||!Array.isArray(Lu))&&Ru(Lu.map(Bu=>({kind:Bu.block_type??"block",text:stripped(Bu.preview??"")})))}).catch(()=>{Ou=!1,Iu||Ru(null)}))};Du(),Pu=Mu.subscribe(Du)}).catch(()=>{Iu||Ru(null)}),()=>{Iu=!0,Pu?.()}},[lo,Au]),$u}function useEditorPreviews(Au){const lo=useOfferedEditors(),$u=useNotebookRows(Au,lo.includes("notebook")),Ru=useDocumentRows(Au,lo.includes("document"));return reactExports.useMemo(()=>{const Iu={};return $u&&(Iu.notebook={badge:String($u.length),details:jsxRuntimeExports.jsx(PreviewList,{title:"Cells",rows:$u})}),Ru&&(Iu.document={badge:String(Ru.length),details:jsxRuntimeExports.jsx(PreviewList,{title:"Blocks",rows:Ru})}),Iu},[$u,Ru])}const SHELL_PLUGIN_NAME="@datalayer/loop-plugin-shell";function describeEditor(Au,lo){const $u=Au,Ru=lo?.workspace,Iu=Ru?canOpenView($u,Ru):!0;return{id:$u.surfaceId,title:$u.title,icon:$u.icon,order:$u.order,disabled:!Iu,disabledReason:Iu?void 0:Ru&&$u.unavailableReason?.(Ru)||"Not available right now"}}function EditorSelectorComponent(Au){const lo=Au.workspace,$u=useEditorPreviews(lo?.surfaceId??""),Ru=(Iu,Pu)=>{const Ou=describeEditor(Iu,Pu),Mu=$u[Ou.id];return Mu?{...Ou,badge:Mu.badge,details:Mu.details}:Ou};return jsxRuntimeExports.jsx(ViewSelector,{point:LoopEditorView,describe:Ru,context:Au,noneLabel:"Chat",ariaLabel:"Editor"})}const ShellPlugin={name:SHELL_PLUGIN_NAME,displayName:"Loop shell",description:"The Loop workspace’s extension points, and the editor choice.",octicon:"columns",emoji:"📑",config:{defaultEditor:NONE_EDITOR,showSelector:!0},dependencies:[configurePlugin(ShellPlugin$1,{point:LoopEditorView,describe:describeEditor,showSelector:!1,announce:Au=>requestSurface(Au),commandId:"loop.shell.cycleEditor",commandName:"Switch the editor",commandDescription:"Cycle through the editors beside the conversation, and none",keybinding:""})],contributionPoints:[LoopViewType,LoopEditorView],contributes:[contribution(LoopCommand,{name:"editor",aliases:["editors"],description:"Switch the editor beside the conversation",group:"Open",keybinding:"Mod+Alt+E",args:[{name:"editor",description:"Which editor: none, or a surface id. Omit to cycle.",required:!1,choices:()=>[NONE_EDITOR,...getEditorChoice().options]}],run:async({argv:Au})=>{const lo=Au.trim(),$u=lo===""?nextEditor():lo,Ru=[NONE_EDITOR,...getEditorChoice().options];if(!Ru.includes($u))throw new Error(`No editor called '${$u}'. There is: ${Ru.join(", ")}.`);if(!chooseEditor($u))throw new Error("No chat is on screen to host the editor.")}},{id:"editor"})],build:({config:Au})=>(seedEditorChoice(Au.defaultEditor||NONE_EDITOR),{components:Au.showSelector?[{id:"editor-selector",slot:LoopSlots.header,Component:EditorSelectorComponent}]:[]})};function NewChatAction({workspace:Au}){return Au?jsxRuntimeExports.jsx(IconButton,{icon:PlusIcon,"aria-label":"New conversation",title:"New conversation",variant:"invisible",size:"small",onClick:()=>{Au.submit("/new")}}):null}const PROMPT_PLUGIN_NAME="@datalayer/loop-plugin-prompt",PromptPlugin={name:PROMPT_PLUGIN_NAME,displayName:"Prompt",description:"Prompt commands: focus the composer, start over, and the +.",octicon:"paper-airplane",emoji:"🪶",contributes:[contribution(LoopCommand,{name:"prompt",description:"Focus the prompt",group:"Session",keybinding:"Mod+Alt+P",run:async()=>{if(!focusPrompt())throw new Error("No prompt is on screen to focus.")}},{id:"prompt"}),contribution(LoopCommand,{name:"new",aliases:["reset"],description:"Start the conversation over",group:"Session",keybinding:"Mod+Alt+R",run:async({workspace:Au})=>{const lo=Au.viewControls.newChat;if(!lo)throw new Error("No conversation is on screen to start over.");lo()}},{id:"new"})],build:()=>({components:[{id:"new-chat",slot:LoopSlots.promptAction,Component:NewChatAction}]})};function AgentspecPicker({workspace:Au}){const[lo,$u]=reactExports.useState([]),[Ru,Iu]=reactExports.useState(!1),[Pu,Ou]=reactExports.useState(Au.agentId),Mu=Au.sandbox.target,Du=Au.sandbox.state;reactExports.useEffect(()=>{let Fu=!1;return fetch(`${Au.serverUrl}/api/v1/agents`).then(zu=>zu.ok?zu.json():{agents:[]}).then(zu=>{Fu||$u(zu.agents??[])}).catch(()=>{}),()=>{Fu=!0}},[Au.serverUrl,Mu,Du]),reactExports.useEffect(()=>{Ou(Au.agentId)},[Au.agentId]);const Lu=reactExports.useCallback(async Fu=>{Iu(!0);try{(await fetch(`${Au.serverUrl}/api/v1/loop/sessions/${encodeURIComponent(Au.conversationId||Au.agentId||"session")}/agent`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({agent_id:Fu})})).ok&&(Ou(Fu),Au.setAgentId(Fu))}finally{Iu(!1)}},[Au.agentId,Au.conversationId,Au.serverUrl,Au.setAgentId]),Bu=lo.find(Fu=>Fu.id===Pu),ju=Bu?.name||getAgentspecs(Pu)?.name||Pu||"Agent";return lo.length===0?null:jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:1,children:[Ru?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):null,jsxRuntimeExports.jsxs(ActionMenu,{children:[jsxRuntimeExports.jsxs(ActionMenu.Button,{variant:"invisible",size:"small",children:[Bu?.emoji?`${Bu.emoji} `:"",ju]}),jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"medium",children:jsxRuntimeExports.jsx(ActionList,{selectionVariant:"single",children:lo.map(Fu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Fu.id===Pu,onSelect:()=>{Lu(Fu.id)},children:[Fu.emoji?`${Fu.emoji} `:"",Fu.name||Fu.id,Fu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:Fu.description}):null]},Fu.id))})})]})]})}const AGENTSPECS_PLUGIN_NAME="@datalayer/loop-plugin-agentspecs",AgentspecsPlugin={name:AGENTSPECS_PLUGIN_NAME,displayName:"Agentspecs",description:"Pick the agentspec this session runs.",octicon:"people",emoji:"🤖",build(){return{components:[{slot:LoopSlots.header,id:"agent-picker",Component:AgentspecPicker}]}},contributes:[contribution(LoopCommand,{name:"agents",aliases:["agent"],description:"Switch the agent this session is using",group:"Agents",keybinding:"Mod+Alt+A",args:[{name:"agent-id",description:"Agent to switch to"}],run:async({workspace:Au,argv:lo})=>{const $u=lo.trim();if(!$u)return{content:"Pick an agent from the header, or /agents <id>."};const Ru=await fetch(`${Au.serverUrl}/api/v1/loop/sessions/${encodeURIComponent(Au.conversationId||Au.agentId||"session")}/agent`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({agent_id:$u})});if(!Ru.ok)return{content:`Unknown agent: ${$u}`};const Iu=await Ru.json();return{content:`Now using ${Iu.name??Iu.agent_id}.`}}},{id:"agents"})]},CHAT_HEADER_PLUGIN_NAME="@datalayer/loop-plugin-chat-header",LazyHeaderView=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/HeaderView-DVGhaRai.js"),[],import.meta.url));function HeaderView(Au){return jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(LazyHeaderView,{...Au})})}const ChatHeaderPlugin={name:CHAT_HEADER_PLUGIN_NAME,displayName:"Chat Header",description:"The conversation’s title bar: agent, kernel, actions.",octicon:"rows",emoji:"🏷️",contributes:[contribution(LoopChatHeader,{id:"chat-header",Component:HeaderView},{id:"chat-header"})]};function readA2uiToolResult(Au,lo){if(!Au)return null;let $u=Au;if(typeof Au=="string")try{$u=JSON.parse(Au)}catch{return null}if(typeof $u!="object"||$u===null||!Array.isArray($u.messages))return null;const Ru=$u,Iu=(Ru.messages??[]).map(Pu=>{const Ou=Pu;return Ou.createSurface&&Ou.createSurface.catalogId!==lo?{...Ou,createSurface:{...Ou.createSurface,catalogId:lo}}:Pu});return{...Ru,messages:Iu}}function isEmptyA2uiValue(Au){return Au==null?!0:typeof Au=="string"?Au.trim()==="":Array.isArray(Au)?Au.length===0:typeof Au=="boolean"?Au===!1:!1}const EMAIL_PATTERN=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function validateA2uiField(Au,lo){if(isEmptyA2uiValue(lo))return Au.required?`${Au.label} is required.`:null;if(Au.format==="email"&&typeof lo=="string"&&!EMAIL_PATTERN.test(lo.trim()))return`${Au.label} must be a valid email address.`;if(Au.pattern&&typeof lo=="string"){let $u;try{$u=new RegExp(Au.pattern).test(lo.trim())}catch{$u=!0}if(!$u)return`${Au.label} is not in the expected format.`}if(Au.minLength!==void 0&&typeof lo=="string"&&lo.trim().length<Au.minLength)return`${Au.label} must be at least ${Au.minLength} characters.`;if(Au.type==="slider"&&typeof lo=="number"){if(Au.min!==void 0&&lo<Au.min)return`${Au.label} must be at least ${Au.min}.`;if(Au.max!==void 0&&lo>Au.max)return`${Au.label} must be at most ${Au.max}.`}return null}function validateA2uiSubmission(Au,lo){return Au.map($u=>validateA2uiField($u,lo[$u.id])).filter($u=>$u!==null)}const ANSWER_DISPLAY_TYPE="application/vnd.datalayer.loop.answer+json";function answerSurface(Au,lo){return Au.type!==ANSWER_DISPLAY_TYPE?null:readA2uiToolResult(Au.data?.surface,lo)}function answerPress(Au,lo){const $u=lo.name.trim(),Ru=(Au.actions??[]).find(Iu=>Iu.name===$u);return Ru?{message:$u,forwardedProps:{loop:{action:{name:$u,display_id:Au.id,token:Ru.token,payload:{...lo.context}}}}}:{refused:`“${$u||"This button"}” was not offered here.`}}function AnswerShowsView({display:Au,send:lo}){const $u=reactExports.useMemo(()=>answerSurface(Au,SURFACE_CATALOG_ID),[Au]),Ru=useOwnCatalog(),[Iu,Pu]=reactExports.useState(null);if(!$u?.messages||$u.messages.length===0)return jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted"},children:Au.text});const Ou=Mu=>{const Du=answerPress(Au,Mu);if("refused"in Du){Pu(Du.refused);return}Pu(lo(Du.message,Du.forwardedProps)?null:"The chat is not ready to take it yet.")};return jsxRuntimeExports.jsx(InlineSurface,{messages:$u.messages,onAction:Ou,validationError:Iu,catalog:Ru},JSON.stringify(Au))}function SurfaceToolResult({context:Au,send:lo,onRendered:$u,onSubmitted:Ru}){const Iu=reactExports.useMemo(()=>Au.status==="complete"?readA2uiToolResult(Au.result,SURFACE_CATALOG_ID):null,[Au.status,Au.result]),Pu=Iu?.title??"the form",[Ou,Mu]=reactExports.useState(null),Du=useOwnCatalog();reactExports.useEffect(()=>{Iu?.messages&&Iu.messages.length>0&&$u?.({toolCallId:Au.toolCallId,surfaceId:Iu.surfaceId,title:Pu,messages:Iu.messages,result:Iu})},[Iu,Au.toolCallId]);const Lu=reactExports.useCallback(Bu=>{if(Bu.name!=="submit_a2ui_form")return;const ju=Bu.context??{},Fu=validateA2uiSubmission(Iu?.fieldRules??[],ju);if(Fu.length>0){Mu(Fu.join(" "));return}Mu(null),Ru?.({surfaceId:Bu.surfaceId,title:Pu,values:ju}),lo(encodeFormSubmission({title:Pu,surfaceId:Bu.surfaceId,values:ju}))||Mu("The chat is not ready to take the submission yet.")},[Iu,Pu,lo,Ru]);return!Iu?.messages||Iu.messages.length===0?jsxRuntimeExports.jsxs(Box,{border:"1px solid",borderColor:"border.default",borderRadius:2,px:3,py:2,bg:"canvas.default",display:"flex",alignItems:"center",gap:2,children:[jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"fg.muted"},children:"Rendering A2UI surface..."})]}):jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",gap:2,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"bold"},children:Pu}),jsxRuntimeExports.jsx(InlineSurface,{messages:Iu.messages,onAction:Lu,validationError:Ou,catalog:Du})]})}const A2UI_SURFACE_PLUGIN_NAME="@datalayer/loop-plugin-a2ui-surface",A2UI_SURFACE_RENDERER="a2ui-surface",A2UI_SURFACE_TYPE="application/vnd.datalayer.a2ui.surface+json";function surfaceToolNames(){const Au=new Set;for(const lo of Object.values(AGENTSPECS))for(const $u of lo.frontendRenderTools??[])$u.renderer===A2UI_SURFACE_RENDERER&&Au.add($u.tool);return Au}let counter=0;function createA2uiSurfacePlugin(Au={}){const lo=`a2ui-surface-${counter+=1}`;let $u;const Ru=(Du,Lu)=>$u?!$u(Du,Lu):!1;function Iu({workspace:Du}){const Lu=Du?.viewControls.send;return reactExports.useEffect(()=>($u=Lu,()=>{$u===Lu&&($u=void 0)}),[Lu]),null}function Pu({context:Du}){return Du?Du.status==="error"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Du.defaultUI}):jsxRuntimeExports.jsx(SurfaceToolResult,{context:Du,send:Ru,onRendered:Au.onRendered,onSubmitted:Au.onSubmitted},Du.toolCallId):null}function Ou({display:Du}){return jsxRuntimeExports.jsx(AnswerShowsView,{display:Du,send:Ru})}return{name:counter===1?A2UI_SURFACE_PLUGIN_NAME:`${A2UI_SURFACE_PLUGIN_NAME}-${lo}`,displayName:"A2UI surfaces",description:"Generated surfaces drawn in the transcript, and submitted back to the agent.",octicon:"browser",emoji:"🪟",contributes:[contribution(Renderers,defineRenderer({type:A2UI_SURFACE_TYPE,component:Pu,rank:Au.onRendered||Au.onSubmitted?1:0}),{id:lo}),contribution(Renderers,defineRenderer({type:ANSWER_DISPLAY_TYPE,component:Ou}),{id:`${lo}:answer`}),...[...surfaceToolNames()].map(Du=>contribution(ToolBindings,{tool:Du,type:A2UI_SURFACE_TYPE},{id:`${lo}:${Du}`}))],build(){return{components:[{slot:LoopSlots.chatHeader,id:lo,Component:Iu}]}}}}const A2uiSurfacePlugin=createA2uiSurfacePlugin(),qrcode=function(Au,lo){let Iu=Au;const Pu=QRErrorCorrectionLevel[lo];let Ou=null,Mu=0,Du=null;const Lu=[],Bu={},ju=function(ed,td){Mu=Iu*4+17,Ou=(function(nd){const od=new Array(nd);for(let sd=0;sd<nd;sd+=1){od[sd]=new Array(nd);for(let ad=0;ad<nd;ad+=1)od[sd][ad]=null}return od})(Mu),Fu(0,0),Fu(Mu-7,0),Fu(0,Mu-7),Hu(),Uu(),Gu(ed,td),Iu>=7&&Vu(ed),Du==null&&(Du=Ju(Iu,Pu,Lu)),Wu(Du,td)},Fu=function(ed,td){for(let nd=-1;nd<=7;nd+=1)if(!(ed+nd<=-1||Mu<=ed+nd))for(let od=-1;od<=7;od+=1)td+od<=-1||Mu<=td+od||(0<=nd&&nd<=6&&(od==0||od==6)||0<=od&&od<=6&&(nd==0||nd==6)||2<=nd&&nd<=4&&2<=od&&od<=4?Ou[ed+nd][td+od]=!0:Ou[ed+nd][td+od]=!1)},zu=function(){let ed=0,td=0;for(let nd=0;nd<8;nd+=1){ju(!0,nd);const od=QRUtil.getLostPoint(Bu);(nd==0||ed>od)&&(ed=od,td=nd)}return td},Uu=function(){for(let ed=8;ed<Mu-8;ed+=1)Ou[ed][6]==null&&(Ou[ed][6]=ed%2==0);for(let ed=8;ed<Mu-8;ed+=1)Ou[6][ed]==null&&(Ou[6][ed]=ed%2==0)},Hu=function(){const ed=QRUtil.getPatternPosition(Iu);for(let td=0;td<ed.length;td+=1)for(let nd=0;nd<ed.length;nd+=1){const od=ed[td],sd=ed[nd];if(Ou[od][sd]==null)for(let ad=-2;ad<=2;ad+=1)for(let pd=-2;pd<=2;pd+=1)ad==-2||ad==2||pd==-2||pd==2||ad==0&&pd==0?Ou[od+ad][sd+pd]=!0:Ou[od+ad][sd+pd]=!1}},Vu=function(ed){const td=QRUtil.getBCHTypeNumber(Iu);for(let nd=0;nd<18;nd+=1){const od=!ed&&(td>>nd&1)==1;Ou[Math.floor(nd/3)][nd%3+Mu-8-3]=od}for(let nd=0;nd<18;nd+=1){const od=!ed&&(td>>nd&1)==1;Ou[nd%3+Mu-8-3][Math.floor(nd/3)]=od}},Gu=function(ed,td){const nd=Pu<<3|td,od=QRUtil.getBCHTypeInfo(nd);for(let sd=0;sd<15;sd+=1){const ad=!ed&&(od>>sd&1)==1;sd<6?Ou[sd][8]=ad:sd<8?Ou[sd+1][8]=ad:Ou[Mu-15+sd][8]=ad}for(let sd=0;sd<15;sd+=1){const ad=!ed&&(od>>sd&1)==1;sd<8?Ou[8][Mu-sd-1]=ad:sd<9?Ou[8][15-sd-1+1]=ad:Ou[8][15-sd-1]=ad}Ou[Mu-8][8]=!ed},Wu=function(ed,td){let nd=-1,od=Mu-1,sd=7,ad=0;const pd=QRUtil.getMaskFunction(td);for(let gd=Mu-1;gd>0;gd-=2)for(gd==6&&(gd-=1);;){for(let yd=0;yd<2;yd+=1)if(Ou[od][gd-yd]==null){let _d=!1;ad<ed.length&&(_d=(ed[ad]>>>sd&1)==1),pd(od,gd-yd)&&(_d=!_d),Ou[od][gd-yd]=_d,sd-=1,sd==-1&&(ad+=1,sd=7)}if(od+=nd,od<0||Mu<=od){od-=nd,nd=-nd;break}}},Ku=function(ed,td){let nd=0,od=0,sd=0;const ad=new Array(td.length),pd=new Array(td.length);for(let bd=0;bd<td.length;bd+=1){const wd=td[bd].dataCount,Ed=td[bd].totalCount-wd;od=Math.max(od,wd),sd=Math.max(sd,Ed),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 cd=QRUtil.getErrorCorrectPolynomial(Ed),md=qrPolynomial(ad[bd],cd.getLength()-1).mod(cd);pd[bd]=new Array(cd.getLength()-1);for(let ld=0;ld<pd[bd].length;ld+=1){const hd=ld+md.getLength()-pd[bd].length;pd[bd][ld]=hd>=0?md.getAt(hd):0}}let gd=0;for(let bd=0;bd<td.length;bd+=1)gd+=td[bd].totalCount;const yd=new Array(gd);let _d=0;for(let bd=0;bd<od;bd+=1)for(let wd=0;wd<td.length;wd+=1)bd<ad[wd].length&&(yd[_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&&(yd[_d]=pd[wd][bd],_d+=1);return yd},Ju=function(ed,td,nd){const od=QRRSBlock.getRSBlocks(ed,td),sd=qrBitBuffer();for(let pd=0;pd<nd.length;pd+=1){const gd=nd[pd];sd.put(gd.getMode(),4),sd.put(gd.getLength(),QRUtil.getLengthInBits(gd.getMode(),ed)),gd.write(sd)}let ad=0;for(let pd=0;pd<od.length;pd+=1)ad+=od[pd].dataCount;if(sd.getLengthInBits()>ad*8)throw"code length overflow. ("+sd.getLengthInBits()+">"+ad*8+")";for(sd.getLengthInBits()+4<=ad*8&&sd.put(0,4);sd.getLengthInBits()%8!=0;)sd.putBit(!1);for(;!(sd.getLengthInBits()>=ad*8||(sd.put(236,8),sd.getLengthInBits()>=ad*8));)sd.put(17,8);return Ku(sd,od)};Bu.addData=function(ed,td){td=td||"Byte";let nd=null;switch(td){case"Numeric":nd=qrNumber(ed);break;case"Alphanumeric":nd=qrAlphaNum(ed);break;case"Byte":nd=qr8BitByte(ed);break;case"Kanji":nd=qrKanji(ed);break;default:throw"mode:"+td}Lu.push(nd),Du=null},Bu.isDark=function(ed,td){if(ed<0||Mu<=ed||td<0||Mu<=td)throw ed+","+td;return Ou[ed][td]},Bu.getModuleCount=function(){return Mu},Bu.make=function(){if(Iu<1){let ed=1;for(;ed<40;ed++){const td=QRRSBlock.getRSBlocks(ed,Pu),nd=qrBitBuffer();for(let sd=0;sd<Lu.length;sd++){const ad=Lu[sd];nd.put(ad.getMode(),4),nd.put(ad.getLength(),QRUtil.getLengthInBits(ad.getMode(),ed)),ad.write(nd)}let od=0;for(let sd=0;sd<td.length;sd++)od+=td[sd].dataCount;if(nd.getLengthInBits()<=od*8)break}Iu=ed}ju(!1,zu())},Bu.createTableTag=function(ed,td){ed=ed||2,td=typeof td>"u"?ed*4:td;let nd="";nd+='<table style="',nd+=" border-width: 0px; border-style: none;",nd+=" border-collapse: collapse;",nd+=" padding: 0px; margin: "+td+"px;",nd+='">',nd+="<tbody>";for(let od=0;od<Bu.getModuleCount();od+=1){nd+="<tr>";for(let sd=0;sd<Bu.getModuleCount();sd+=1)nd+='<td style="',nd+=" border-width: 0px; border-style: none;",nd+=" border-collapse: collapse;",nd+=" padding: 0px; margin: 0px;",nd+=" width: "+ed+"px;",nd+=" height: "+ed+"px;",nd+=" background-color: ",nd+=Bu.isDark(od,sd)?"#000000":"#ffffff",nd+=";",nd+='"/>';nd+="</tr>"}return nd+="</tbody>",nd+="</table>",nd},Bu.createSvgTag=function(ed,td,nd,od){let sd={};typeof arguments[0]=="object"&&(sd=arguments[0],ed=sd.cellSize,td=sd.margin,nd=sd.alt,od=sd.title),ed=ed||2,td=typeof td>"u"?ed*4:td,nd=typeof nd=="string"?{text:nd}:nd||{},nd.text=nd.text||null,nd.id=nd.text?nd.id||"qrcode-description":null,od=typeof od=="string"?{text:od}:od||{},od.text=od.text||null,od.id=od.text?od.id||"qrcode-title":null;const ad=Bu.getModuleCount()*ed+td*2;let pd,gd,yd,_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="',yd=0;yd<Bu.getModuleCount();yd+=1)for(_d=yd*ed+td,pd=0;pd<Bu.getModuleCount();pd+=1)Bu.isDark(yd,pd)&&(gd=pd*ed+td,bd+="M"+gd+","+_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 gd=Math.floor((ad-od)/ed),yd=Math.floor((pd-od)/ed);return Bu.isDark(yd,gd)?0:1}else return 1})},Bu.createImgTag=function(ed,td,nd){ed=ed||2,td=typeof td>"u"?ed*4:td;const od=Bu.getModuleCount()*ed+td*2;let sd="";return sd+="<img",sd+=' src="',sd+=Bu.createDataURL(ed,td),sd+='"',sd+=' width="',sd+=od,sd+='"',sd+=' height="',sd+=od,sd+='"',nd&&(sd+=' alt="',sd+=Yu(nd),sd+='"'),sd+="/>",sd};const Yu=function(ed){let td="";for(let nd=0;nd<ed.length;nd+=1){const od=ed.charAt(nd);switch(od){case"<":td+="<";break;case">":td+=">";break;case"&":td+="&";break;case'"':td+=""";break;default:td+=od;break}}return td},Xu=function(ed){ed=typeof ed>"u"?2:ed;const nd=Bu.getModuleCount()*1+ed*2,od=ed,sd=nd-ed;let ad,pd,gd,yd,_d;const bd={"██":"█","█ ":"▀"," █":"▄"," ":" "},wd={"██":"▀","█ ":"▀"," █":" "," ":" "};let Ed="";for(ad=0;ad<nd;ad+=2){for(gd=Math.floor((ad-od)/1),yd=Math.floor((ad+1-od)/1),pd=0;pd<nd;pd+=1)_d="█",od<=pd&&pd<sd&&od<=ad&&ad<sd&&Bu.isDark(gd,Math.floor((pd-od)/1))&&(_d=" "),od<=pd&&pd<sd&&od<=ad+1&&ad+1<sd&&Bu.isDark(yd,Math.floor((pd-od)/1))?_d+=" ":_d+="█",Ed+=ed<1&&ad+1>=sd?wd[_d]:bd[_d];Ed+=`
|
|
3861
3861
|
`}return nd%2&&ed>0?Ed.substring(0,Ed.length-nd-1)+Array(nd+1).join("▀"):Ed.substring(0,Ed.length-1)};return Bu.createASCII=function(ed,td){if(ed=ed||1,ed<2)return Xu(td);ed-=1,td=typeof td>"u"?ed*2:td;const nd=Bu.getModuleCount()*ed+td*2,od=td,sd=nd-td;let ad,pd,gd,yd;const _d=Array(ed+1).join("██"),bd=Array(ed+1).join(" ");let wd="",Ed="";for(ad=0;ad<nd;ad+=1){for(gd=Math.floor((ad-od)/ed),Ed="",pd=0;pd<nd;pd+=1)yd=1,od<=pd&&pd<sd&&od<=ad&&ad<sd&&Bu.isDark(gd,Math.floor((pd-od)/ed))&&(yd=0),Ed+=yd?_d:bd;for(gd=0;gd<ed;gd+=1)wd+=Ed+`
|
|
3862
|
-
`}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 zu=new BroadcastChannel(PAP_SIGN_IN_CHANNEL);return zu.onmessage=Uu=>{const Hu=signInReturnOf(Uu.data,Lu);Hu&&(Mu(Hu),zu.close())},()=>zu.close()},[Lu]),reactExports.useEffect(()=>{Ou==="signed_in"&&lo&&!Iu&&Pu(lo(PAP_SIGN_IN_WORDS.checkMessage(Lu)))},[Ou,lo,Iu,Lu]),!Du)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Au.defaultUI});if("refused"in Du)return jsxRuntimeExports.jsx(Flash,{variant:"danger",role:"alert",sx:{my:2},children:Du.refused});const Bu=async()=>{try{await navigator.clipboard.writeText(Du.code??""),Ru(!0)}catch{Ru(!1)}},ju=Du.company??Du.host,Fu=Du.mode==="mediated"?PAP_SIGN_IN_WORDS.mediatedTitle(Du.host):PAP_SIGN_IN_WORDS.title(ju);return jsxRuntimeExports.jsxs(Box,{as:"section","aria-label":Fu,my:2,p:3,border:"1px solid",borderColor:"border.default",borderRadius:2,bg:"canvas.subtle",maxWidth:480,children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:2,mb:1},children:Fu}),jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{mt:0,mb:2,color:"fg.muted",fontSize:1},children:Du.mode==="device"?PAP_SIGN_IN_WORDS.device:Du.mode==="mediated"?PAP_SIGN_IN_WORDS.mediated:PAP_SIGN_IN_WORDS.direct}),Du.needs?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{mt:0,mb:2,fontSize:1},children:PAP_SIGN_IN_WORDS.needs(Du.needs)}):null,Du.sentTo?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{mt:0,mb:2,fontSize:1},children:PAP_SIGN_IN_WORDS.sentTo(Du.sentTo)}):null,Du.code?jsxRuntimeExports.jsxs(Box,{display:"flex",gap:3,alignItems:"center",flexWrap:"wrap",mb:2,children:[jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{as:"div",sx:{fontSize:0,color:"fg.muted"},children:PAP_SIGN_IN_WORDS.code}),jsxRuntimeExports.jsx(Text$3,{as:"div","aria-live":"polite",sx:{fontFamily:"mono",fontSize:5,fontWeight:"bold",letterSpacing:"0.15em"},children:Du.code}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",leadingVisual:CopyIcon,onClick:()=>{Bu()},children:$u?PAP_SIGN_IN_WORDS.copied:PAP_SIGN_IN_WORDS.copy})]}),jsxRuntimeExports.jsx(Box,{bg:"#ffffff",p:2,borderRadius:2,lineHeight:0,children:jsxRuntimeExports.jsx(QRCode,{value:Du.open,size:112,title:PAP_SIGN_IN_WORDS.qr(Du.host)})})]}):null,jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,flexWrap:"wrap",alignItems:"center",children:[jsxRuntimeExports.jsx(ButtonComponent,{as:"a",href:Du.open,target:"_blank",rel:"noopener noreferrer",variant:"primary",trailingVisual:LinkExternalIcon,children:PAP_SIGN_IN_WORDS.open(ju)}),lo?jsxRuntimeExports.jsx(ButtonComponent,{disabled:Iu,onClick:()=>Pu(lo(PAP_SIGN_IN_WORDS.checkMessage(ju))),children:PAP_SIGN_IN_WORDS.checkAgain}):null]}),Ou?jsxRuntimeExports.jsx(Text$3,{as:"p",role:"status",sx:{mt:2,mb:0,fontSize:1},children:PAP_SIGN_IN_WORDS.returned[Ou](ju)}):null,Du.expiresAt?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{mt:2,mb:0,fontSize:0,color:"fg.muted"},children:PAP_SIGN_IN_WORDS.until(Du.expiresAt)}):null,lo?null:jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{mt:1,mb:0,fontSize:1},children:PAP_SIGN_IN_WORDS.tellMe})]})}const PAP_SIGN_IN_PLUGIN_NAME="@datalayer/loop-plugin-pap-sign-in",PAP_SIGN_IN_TYPE="application/vnd.datalayer.pap.sign-in+json";function resultOf(Au,lo){const $u=Au.data??{};return"toolName"in $u?lo?.result:{status:"waiting_for_the_person",...$u}}function createPapSignInPlugin(){let Au;const lo=Pu=>Au?!Au(Pu):!1;function $u({workspace:Pu}){const Ou=Pu?.viewControls.send;return reactExports.useEffect(()=>(Au=Ou,()=>{Au===Ou&&(Au=void 0)}),[Ou]),null}function Ru({display:Pu,context:Ou}){const Mu=resultOf(Pu,Ou);return reactExports.createElement(PapSignInCard,{key:Pu.id,context:Ou?{...Ou,result:Mu}:{toolCallId:Pu.id,toolName:"pap_sign_in",name:"pap_sign_in",args:{},status:"complete",result:Mu},send:Au?lo:void 0})}return{name:PAP_SIGN_IN_PLUGIN_NAME,displayName:"Sign in at a company",description:"The company’s page, the code and until when, where the agent asks the person to sign in.",octicon:"sign-in",emoji:"🔑",contributes:[contribution(Renderers,defineRenderer({type:PAP_SIGN_IN_TYPE,component:Ru}),{id:"pap-sign-in"}),contribution(ToolBindings,{tool:PAP_SIGN_IN_TOOL,type:PAP_SIGN_IN_TYPE},{id:"pap-sign-in"})],build(){return{components:[{slot:LoopSlots.chatHeader,id:"pap-sign-in",Component:$u}]}}}}const PapSignInPlugin=createPapSignInPlugin(),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=`
|
|
3862
|
+
`}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(),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=`
|
|
3863
3863
|
/*
|
|
3864
3864
|
* Colours live on the panel as variables with light defaults, and the dark
|
|
3865
3865
|
* values are applied by whichever signal the host actually uses:
|