@datalayer/agent-runtimes 1.5.88 → 1.5.89

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.
@@ -482,7 +482,7 @@ ${$u.comment}`:$u.comment}this.doc.range[2]=$u.offset;break}default:this.errors.
482
482
  `,$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(`
483
483
  `)[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(ud=>[ud.name,ud])),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,Zu=new Set;let Ju=new Set;function Yu(){if(!(Uu>0)){zu+=1;for(const ud of Bu)ud()}}function Xu(ud){Uu+=1;try{return ud()}finally{Uu-=1,Uu===0&&Yu()}}for(const ud of Ou){const hd=mergeWithDefaults(ud,Du.get(ud.name)??{});Lu.set(ud.name,{plugin:ud,config:hd,enabled:!0,activated:!1,extension:Iu.get(ud.name),lazy:Ru.get(ud.name),loaded:!Ru.has(ud.name)})}for(const ud of Ou){for(const hd of ud.conflictsWith??[])if(Mu.has(hd))throw new Error(`Plugin ${ud.name} conflicts with ${hd}`);for(const hd of ud.peerDependencies??[])if(!hd.optional&&!Mu.has(hd.name)&&lo.strictPeerDependencies)throw new Error(`Missing required peer dependency ${hd.name} for ${ud.name}`)}function ed(ud){const hd=[];for(const md of Ou){const Ed=Lu.get(md.name);!Ed||Ed.activated||matchesActivation(Ed.plugin.activationEvents,ud)&&hd.push(md.name)}return hd}function td(ud){if(!Wu.has(ud.id)){Wu.add(ud.id);const hd=onContributionPoint(ud);ed(hd).length>0&&Promise.resolve().then(()=>_d(hd))}return ju.get(ud)}const nd={hasPlugin(ud){return Lu.has(ud)},getOutput(ud){return Lu.get(ud)?.outputValue},getRequiredBackendPlugins(ud){return Lu.get(ud)?.plugin.requiredBackendPlugins??[]},getOptionalBackendPlugins(ud){return Lu.get(ud)?.plugin.optionalBackendPlugins??[]},getManifest(ud){const hd=Lu.get(ud);if(!hd)return;const{plugin:md}=hd;return{name:md.name,version:md.version,displayName:md.displayName??md.name,description:md.description,octicon:md.octicon,emoji:md.emoji,extension:hd.extension,requiredBackendPlugins:md.requiredBackendPlugins??[],optionalBackendPlugins:md.optionalBackendPlugins??[],loaded:hd.loaded,lazy:!!hd.lazy,activated:hd.activated,disabledBy:hd.enabled?void 0:hd.disabledBy??"user",loadError:hd.loadError?.message,activationEvents:md.activationEvents??[ON_STARTUP],deactivationEvents:md.deactivationEvents??[],contributionPoints:(md.contributionPoints??[]).map(Ed=>Ed.id),contributesTo:[...new Set((md.contributes??[]).map(Ed=>Ed.point.id))]}},isEnabled(ud){return Lu.get(ud)?.enabled??!1},getContributions(ud){return td(ud)},checkGate(ud,hd){return resolveGate(td(ud),hd)}};function od(ud,hd){return{plugin:hd.plugin,config:hd.config,state:{getConfig:()=>hd.config,getInit:()=>hd.initValue,getOutput:()=>hd.outputValue},reactor:nd,contribute(md,Ed,Td){const Rd=ju.add(ud,md,Ed,Td);Yu();let jd=!1;return()=>{jd||(jd=!0,Rd(),Yu())}},registerCommand(md){const Ed=Fu.add(ud,md);Yu();let Td=!1;return()=>{Td||(Td=!0,Ed(),Yu())}}}}function sd(ud){const hd=Lu.get(ud);if(!hd)throw new Error(`Unknown plugin ${ud}`);if(!hd.loaded)return;const md=od(ud,hd);hd.initValue=hd.plugin.init?.(md),hd.outputValue=hd.plugin.build?.(md)}function ad(ud){const hd=Lu.get(ud);if(!hd||!hd.enabled||!hd.loaded)return;const md=od(ud,hd);for(const Ed of hd.plugin.contributes??[])ju.add(ud,Ed.point,Ed.value,Ed.options);for(const Ed of hd.plugin.commands??[])Fu.add(ud,Ed);Yu(),hd.registerDispose=hd.plugin.register?.(md)??void 0,hd.afterDispose=hd.plugin.afterRegistration?.(md)??void 0}function pd(ud){const hd=Lu.get(ud);!hd||hd.activated||!hd.loaded||(hd.activated=!0,Xu(()=>{hd.enabled&&(hd.plugin.preserveOutput&&hd.outputValue!==void 0||sd(ud),ad(ud))}))}async function vd(ud){const hd=Lu.get(ud);if(!(!hd?.lazy||hd.loaded)){hd.loading??=Promise.resolve().then(()=>hd.lazy.load());try{const md=await hd.loading;if(hd.loaded)return;const Ed=md.default??md;if(!Ed||typeof Ed!="object"||!Ed.name)throw new Error(`Lazy plugin ${ud} did not resolve to a plugin`);hd.plugin=mergeLoaded(hd.lazy,Ed),hd.config=mergeWithDefaults(hd.plugin,Du.get(ud)??{}),hd.loaded=!0}catch(md){hd.loadError=md instanceof Error?md:new Error(String(md)),Yu()}}}function Sd(ud){const hd=Lu.get(ud);if(!hd||hd.activated)return Promise.resolve();const md=Gu.get(ud);if(md)return md;const Ed=(async()=>{for(const Td of hd.plugin.dependencies??[])await Sd(asConfigured(Td).plugin.name);hd.lazy&&!hd.loaded&&await vd(ud),pd(ud),Zu.delete(ud)})().finally(()=>{Gu.delete(ud)});return Gu.set(ud,Ed),Ed}async function _d(ud){const hd=ed(ud);if(hd.length===0)return[];for(const md of hd){const Ed=Lu.get(md);Ed?.lazy&&!Ed.loaded&&(Ed.loading??=Promise.resolve().then(()=>Ed.lazy.load()))}for(const md of hd)await Sd(md);return hd.filter(md=>Lu.get(md)?.activated)}function bd(ud){const hd=new Set([ud]);for(const md of Ou)(md.dependencies??[]).some(Td=>hd.has(asConfigured(Td).plugin.name))&&hd.add(md.name);return hd.delete(ud),Ou.map(md=>md.name).filter(md=>hd.has(md)).reverse()}function wd(ud){return(Lu.get(ud)?.plugin?.dependencies??[]).every(md=>Lu.get(asConfigured(md).plugin.name)?.enabled??!0)}function Ad(ud){const hd=Lu.get(ud);if(!hd||hd.enabled||(hd.enabled=!0,hd.disabledBy=void 0,!hd.loaded||!hd.activated))return;hd.plugin.preserveOutput&&hd.outputValue!==void 0||sd(ud),ad(ud)}function gd(ud,hd="other"){const md=Lu.get(ud);if(!md)throw new Error(`Unknown plugin ${ud}`);if(hd==="other"&&Zu.delete(ud),!md.activated)return[];const Ed=[];if(Xu(()=>{for(const Td of bd(ud)){const Rd=Lu.get(Td);Rd?.activated&&(ld(Td),Rd.activated=!1,dd(Td),Ed.push(Td))}ld(ud),md.activated=!1,dd(ud),Ed.push(ud)}),hd==="other")for(const Td of Ed)Zu.delete(Td);return Ed}function dd(ud){const hd=Lu.get(ud)?.plugin.activationEvents??[];for(const md of hd)md.startsWith("onContributionPoint:")&&Wu.delete(md.slice(20))}function yd(ud){const hd=[];for(const md of Ou){const Ed=Lu.get(md.name);Ed?.activated&&matchesDeactivation(Ed.plugin.deactivationEvents,ud)&&hd.push(...gd(md.name))}return hd}function ld(ud){const hd=Lu.get(ud);hd&&(hd.afterDispose?.(),hd.afterDispose=void 0,hd.registerDispose?.(),hd.registerDispose=void 0,ju.disposePlugin(ud),Fu.disposePlugin(ud))}return{...nd,start(){Vu=!0,Xu(()=>{const ud=Ou.filter(hd=>{const md=Lu.get(hd.name);return md&&md.loaded&&!md.activated&&activatesAtStartup(md.plugin.activationEvents)});for(const hd of ud)Lu.get(hd.name).activated=!0,sd(hd.name);for(const hd of ud)ad(hd.name)}),Hu=_d(ON_STARTUP).then(()=>{})},whenReady(){return Hu??Promise.resolve()},async fire(ud){const hd=yd(ud),md=await _d(ud);return{deactivated:hd,activated:md}},deactivate(ud){gd(ud)},async setBackendPlugins(ud){Ju=new Set(ud);const hd=Td=>(Lu.get(Td)?.plugin.requiredBackendPlugins??[]).every(Rd=>Ju.has(Rd)),md=[];for(const Td of Ou){if(!Lu.get(Td.name)?.activated||hd(Td.name))continue;const jd=gd(Td.name,"backend");for(const Cd of jd)Zu.add(Cd);md.push(...jd)}const Ed=[];for(const Td of Ou){const Rd=Td.name;!Zu.has(Rd)||!hd(Rd)||!Lu.get(Rd)?.enabled||(Zu.delete(Rd),await Sd(Rd),Lu.get(Rd)?.activated&&Ed.push(Rd))}return{deactivated:md,activated:Ed}},async install(ud){const hd=normalizePlugins([ud]),md=hd.plugins.filter(jd=>!Lu.has(jd.name));if(md.length===0)return[];for(const jd of md)for(const Cd of jd.conflictsWith??[])if(Mu.has(Cd)||md.some($d=>$d.name===Cd))throw new Error(`Plugin ${jd.name} conflicts with ${Cd}`);for(const[jd,Cd]of hd.lazyByName)Ru.set(jd,Cd);for(const[jd,Cd]of hd.extensionOf)Iu.set(jd,Cd);for(const[jd,Cd]of hd.extensions)Pu.set(jd,Cd);const Ed=collectOverrides([ud]);for(const jd of md)Mu.set(jd.name,jd),Lu.set(jd.name,{plugin:jd,config:mergeWithDefaults(jd,Ed.get(jd.name)??{}),enabled:!0,activated:!1,extension:Iu.get(jd.name),lazy:Ru.get(jd.name),loaded:!Ru.has(jd.name)});const Td=topoSort([...Ou,...md]);if(Ou.splice(0,Ou.length,...Td),Yu(),!Vu)return md.map(jd=>jd.name);const Rd=[];for(const jd of Td)md.some(Cd=>Cd.name===jd.name)&&(Rd.push(jd.name),activatesAtStartup(jd.activationEvents)&&await Sd(jd.name));return Rd},stop(){Vu=!1,Xu(()=>{for(const ud of[...Ou].reverse()){ld(ud.name);const hd=Lu.get(ud.name);hd&&(hd.activated=!1)}Wu.clear()})},enable(ud){const hd=Lu.get(ud);if(!hd)throw new Error(`Unknown plugin ${ud}`);hd.enabled||Xu(()=>{Ad(ud);for(const md of[...bd(ud)].reverse()){const Ed=Lu.get(md);!Ed||Ed.enabled||Ed.disabledBy==="dependency"&&wd(md)&&Ad(md)}})},disable(ud){const hd=Lu.get(ud);if(!hd)throw new Error(`Unknown plugin ${ud}`);hd.enabled&&Xu(()=>{for(const md of bd(ud)){const Ed=Lu.get(md);Ed?.enabled&&(Ed.enabled=!1,Ed.disabledBy="dependency",ld(md))}hd.enabled=!1,hd.disabledBy="user",ld(ud)})},subscribe(ud){return Bu.add(ud),()=>{Bu.delete(ud)}},listPlugins(){return Ou.map(ud=>ud.name)},listExtensions(){return[...Pu.keys()]},getExtensionManifest(ud){const hd=Pu.get(ud);if(hd)return{name:hd.name,version:hd.version,displayName:hd.displayName??hd.name,description:hd.description,octicon:hd.octicon,emoji:hd.emoji,plugins:Ou.filter(md=>Iu.get(md.name)===ud).map(md=>md.name)}},getConfig(ud){return Lu.get(ud)?.config},describeContributions(){return ju.describe()},listCommands(){return Fu.list()},getCommand(ud){return Fu.get(ud)},executeCommand(ud,hd){return Fu.execute(ud,hd)},getDependencies(ud){return(Lu.get(ud)?.plugin.dependencies??[]).map(hd=>asConfigured(hd).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 vd=(nd+pd)%sd;if(ed[vd]===td)return vd}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 vd=(nd-pd+sd)%sd;if(ed[vd]===td)return vd}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 vd=(nd+pd)%sd;if(td(ed[vd],vd))return vd}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 vd=(nd-pd+sd)%sd;if(td(ed[vd],vd))return vd}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,vd=sd-od+1;for(;vd>0;){let Sd=vd>>1,_d=pd+Sd;nd(ed[_d],td)<0?(pd=_d+1,vd-=Sd+1):vd=Sd}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,vd=sd-od+1;for(;vd>0;){let Sd=vd>>1,_d=pd+Sd;nd(ed[_d],td)>0?vd=Sd:(pd=_d+1,vd-=Sd+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 vd=[];for(let Sd=0;Sd<pd;++Sd)vd[Sd]=ed[nd+Sd*sd];return vd}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 Zu(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=Zu;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(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,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,Zu)=>{const Ju=Du.get(Zu);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,Zu,Ju){Ju=Ju||void 0;let Yu=Du.get(Wu.sender);if(Yu||(Yu=[],Du.set(Wu.sender,Yu)),Fu(Yu,Wu,Zu,Ju))return!1;let Xu=Ju||Zu,ed=Lu.get(Xu);ed||(ed=[],Lu.set(Xu,ed));let td={signal:Wu,slot:Zu,thisArg:Ju};return Yu.push(td),ed.push(td),!0}Au.connect=lo;function $u(Wu,Zu,Ju){Ju=Ju||void 0;let Yu=Du.get(Wu.sender);if(!Yu||Yu.length===0)return!1;let Xu=Fu(Yu,Wu,Zu,Ju);if(!Xu)return!1;let ed=Ju||Zu,td=Lu.get(ed);return Xu.signal=null,Uu(Yu),Uu(td),!0}Au.disconnect=$u;function Ru(Wu,Zu){let Ju=Du.get(Wu);if(!Ju||Ju.length===0)return;let Yu=Lu.get(Zu);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 Zu=Du.get(Wu);if(!(!Zu||Zu.length===0)){for(const Ju of Zu){if(!Ju.signal)continue;let Yu=Ju.thisArg||Ju.slot;Ju.signal=null,Uu(Lu.get(Yu))}Uu(Zu)}}Au.disconnectSender=Iu;function Pu(Wu){let Zu=Lu.get(Wu);if(!(!Zu||Zu.length===0)){for(const Ju of Zu){if(!Ju.signal)continue;let Yu=Ju.signal.sender;Ju.signal=null,Uu(Du.get(Yu))}Uu(Zu)}}Au.disconnectReceiver=Pu;function Ou(Wu){Iu(Wu),Pu(Wu)}Au.disconnectAll=Ou;function Mu(Wu,Zu){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,Zu)}}Au.emit=Mu;const Du=new WeakMap,Lu=new WeakMap,Bu=new Set,ju=typeof requestAnimationFrame=="function"?requestAnimationFrame:setImmediate;function Fu(Wu,Zu,Ju,Yu){return find$3(Wu,Xu=>Xu.signal===Zu&&Xu.slot===Ju&&Xu.thisArg===Yu)}function zu(Wu,Zu){let{signal:Ju,slot:Yu,thisArg:Xu}=Wu;try{Yu.call(Xu,Ju.sender,Zu)}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$1(){}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$7($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$7(Au)&&isPlainObject$7(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$7(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,Zu)=>{Pu=Wu,Ou=Zu});Mu.catch(noop$1);const Du=()=>Iu!=="pending",Lu=Wu=>{if(!Du()){const Zu=new CancelledError(Wu);Hu(Zu),Au.onCancel?.(Zu)}},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(Zu=>{Ru=Ju=>{(Du()||Wu())&&Zu(Ju)},Au.onPause?.()}).then(()=>{Ru=void 0,Du()||Au.onContinue?.()}),Gu=()=>{if(Du())return;let Wu;const Zu=$u===0?Au.initialPromise:void 0;try{Wu=Zu??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})(),Zu=await Fu(Wu),{maxPages:Ju}=lo.options,Yu=Vu?addToStart:addToEnd;return{pages:Yu(Uu.pages,Zu,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$1).catch(noop$1):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$1)),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",Zu=Gu&&Vu,Ju=ju!==void 0;return{status:Uu,fetchStatus:Lu.fetchStatus,isPending:Gu,isSuccess:Uu==="success",isError:Wu,isInitialLoading:Zu,isLoading:Zu,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$1))))}};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$1).catch(noop$1)}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$1)),Iu.state.fetchStatus==="paused"?Promise.resolve():Pu}));return Promise.all(Ru).then(noop$1)}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$1).catch(noop$1)}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$1).catch(noop$1)}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$1;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$1)},[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(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(),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$2=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$2;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(`
484
484
  `),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+`
485
- `);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$1=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$1)})(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)?Zu(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 Zu(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 Zu=this._services.get(Wu);return Zu?this._plugins.get(Zu).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 Zu,Ju,Yu,Xu;this._activated=!1,this._promise=null,this._service=null,this.id=Wu.id,this.description=(Zu=Wu.description)!==null&&Zu!==void 0?Zu:"",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,Zu){const Ju=[...Gu.requires,...Gu.optional],Yu=ed=>{if(ed===Gu.provides)return!0;const td=Zu.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,Zu){const Ju=new Array,Yu=od=>{const sd=Wu.get(od),ad=[...sd.requires,...sd.optional];Ju.push(...ad.reduce((pd,vd)=>{const Sd=Zu.get(vd);return Sd&&pd.push([od,Sd]),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 Zu=new Set;for(const Ju of Gu.keys())Gu.get(Ju).autoStart===!0&&Zu.add(Ju);if(Wu.startPlugins)for(const Ju of Wu.startPlugins)Zu.add(Ju);if(Wu.ignorePlugins)for(const Ju of Wu.ignorePlugins)Zu.delete(Ju);return Array.from(Zu)}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 Zu=Wu[2];Pu.bools[Vu]&&(Zu=Zu!=="false"),Fu(Vu,Zu,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(Zu,Ju){return Fu(Ju.protocol)?Zu.replace(/\\/g,"/"):Zu},["/","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 Zu;typeof window<"u"?Zu=window:typeof globalThis<"u"?Zu=globalThis:typeof self<"u"?Zu=self:Zu={};var Ju=Zu.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,Zu){Wu=Du(Wu),Wu=Wu.replace(Ru,""),Zu=Zu||{};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(Zu.protocol)&&(nd=Ju[4]),{protocol:Yu,slashes:Xu||Fu(Yu),slashesCount:td,rest:nd}}function Uu(Wu,Zu){if(Wu==="")return Zu;for(var Ju=(Zu||"/").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,Zu,Ju){if(Wu=Du(Wu),Wu=Wu.replace(Ru,""),!(this instanceof Hu))return new Hu(Wu,Zu,Ju);var Yu,Xu,ed,td,nd,od,sd=Lu.slice(),ad=typeof Zu,pd=this,vd=0;for(ad!=="object"&&ad!=="string"&&(Ju=Zu,Zu=null),Ju&&typeof Ju!="function"&&(Ju=lo.parse),Zu=ju(Zu),Xu=zu(Wu||"",Zu),Yu=!Xu.protocol&&!Xu.slashes,pd.slashes=Xu.slashes||Yu&&Zu.slashes,pd.protocol=Xu.protocol||Zu.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"]);vd<sd.length;vd++){if(td=sd[vd],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]&&Zu[od]||"",td[4]&&(pd[od]=pd[od].toLowerCase())}Ju&&(pd.query=Ju(pd.query)),Yu&&Zu.slashes&&pd.pathname.charAt(0)!=="/"&&(pd.pathname!==""||Zu.pathname!=="")&&(pd.pathname=Uu(pd.pathname,Zu.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,Zu,Ju){var Yu=this;switch(Wu){case"query":typeof Zu=="string"&&Zu.length&&(Zu=(Ju||lo.parse)(Zu)),Yu[Wu]=Zu;break;case"port":Yu[Wu]=Zu,Au(Zu,Yu.protocol)?Zu&&(Yu.host=Yu.hostname+":"+Zu):(Yu.host=Yu.hostname,Yu[Wu]="");break;case"hostname":Yu[Wu]=Zu,Yu.port&&(Zu+=":"+Yu.port),Yu.host=Zu;break;case"host":Yu[Wu]=Zu,Pu.test(Zu)?(Zu=Zu.split(":"),Yu.port=Zu.pop(),Yu.hostname=Zu.join(":")):(Yu.hostname=Zu,Yu.port="");break;case"protocol":Yu.protocol=Zu.toLowerCase(),Yu.slashes=!Ju;break;case"pathname":case"hash":if(Zu){var Xu=Wu==="pathname"?"/":"#";Yu[Wu]=Zu.charAt(0)!==Xu?Xu+Zu:Zu}else Yu[Wu]=Zu;break;case"username":case"password":Yu[Wu]=encodeURIComponent(Zu);break;case"auth":var ed=Zu.indexOf(":");~ed?(Yu.username=Zu.slice(0,ed),Yu.username=encodeURIComponent(decodeURIComponent(Yu.username)),Yu.password=Zu.slice(ed+1),Yu.password=encodeURIComponent(decodeURIComponent(Yu.password))):Yu.username=encodeURIComponent(decodeURIComponent(Zu))}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 Zu,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,Zu=typeof Ju.query=="object"?Wu(Ju.query):Ju.query,Zu&&(ed+=Zu.charAt(0)!=="?"?"?"+Zu:Zu),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 isFormDataBody(Au){if(!Au||typeof Au!="object")return!1;if(typeof FormData<"u"&&Au instanceof FormData||Object.prototype.toString.call(Au)==="[object FormData]")return!0;const $u=Au;return typeof $u.append=="function"&&typeof $u.get=="function"&&typeof $u.has=="function"&&typeof $u.entries=="function"}class RunResponseError extends Error{static async create(lo){try{const $u=await lo.json(),{message:Ru,errors:Iu,warnings:Pu,traceback:Ou,exception:Mu,detail:Du}=$u,Lu=Ru??(typeof Du=="string"?Du:Du&&typeof Du=="object"&&"message"in Du?String(Du.message):void 0);return Ou&&console.error(Ou),new RunResponseError(lo,Lu??RunResponseError._defaultMessage(lo),Pu,Iu,Mu,Ou??"",Du)}catch($u){return console.debug($u),new RunResponseError(lo)}}constructor(lo,$u=RunResponseError._defaultMessage(lo),Ru=void 0,Iu=void 0,Pu=void 0,Ou="",Mu=void 0){super($u),this.name="RunResponseError",this.warnings=Ru??[],this.errors=Iu??[],this.response=lo,this.exceptionMessage=Pu,this.traceback=Ou,this.detail=Mu}warnings;errors;response;exceptionMessage;traceback;detail;static _defaultMessage(lo){return`Invalid response: ${lo.status} ${lo.statusText}`}}class NetworkError extends TypeError{constructor(lo){super(lo.message),this.name="NetworkError",this.stack=lo.stack}}class TokenExpiredError extends Error{expiredAt;url;constructor(lo,$u){super(`The Datalayer token expired at ${new Date($u).toISOString()}; not sending the request to ${lo}.`),this.name="TokenExpiredError",this.expiredAt=$u,this.url=lo,Object.setPrototypeOf(this,TokenExpiredError.prototype)}}function throwIfTokenExpired(Au,lo,$u){if(!(Au!==401||!lo||!isJwtExpired(lo)))throw new TokenExpiredError($u,getJwtExpiryMs(lo)??Date.now())}function isRawBody(Au){return typeof Au=="string"||typeof Blob<"u"&&Au instanceof Blob||Au instanceof ArrayBuffer||ArrayBuffer.isView(Au)||typeof URLSearchParams<"u"&&Au instanceof URLSearchParams||typeof ReadableStream<"u"&&Au instanceof ReadableStream}function headersToRecord(Au){const lo={};return Au.forEach(($u,Ru)=>{lo[Ru]=$u}),lo}async function readBody(Au,lo){switch(lo){case"text":return Au.text();case"blob":return Au.blob();case"arraybuffer":return Au.arrayBuffer();case"stream":return Au.body;default:{const $u=await Au.text();try{return JSON.parse($u)}catch{return $u}}}}async function send(Au,lo,$u){let Ru;try{Ru=await fetch(Au,lo)}catch(Iu){throw Iu?.name==="AbortError"?Iu:new NetworkError(Iu instanceof Error?Iu:new TypeError(String(Iu)))}if(!Ru.ok)throw throwIfTokenExpired(Ru.status,$u,Au),await RunResponseError.create(Ru);return Ru}async function requestDatalayerAPIWithResponse({url:Au,method:lo,body:$u,token:Ru,signal:Iu,responseType:Pu,headers:Ou={}}){const Mu=lo??"GET",Du=new Headers(Ou);Mu==="GET"&&(Du.has("Cache-Control")||Du.set("Cache-Control","no-store, no-cache, must-revalidate"),Du.has("Pragma")||Du.set("Pragma","no-cache")),Ru&&Du.set("Authorization",`Bearer ${Ru}`),Du.has("Accept")||Du.set("Accept","application/json");let Lu;isFormDataBody($u)?Lu=$u:(Du.has("Content-Type")||Du.set("Content-Type","application/json"),$u===void 0?Lu=void 0:isRawBody($u)?Lu=$u:Lu=JSON.stringify($u));const Bu={method:Mu,headers:Du,body:Lu,credentials:"include",signal:Iu};let ju=await send(Au,Bu,Ru);return ju.status===202&&ju.headers.get("location")&&(ju=await followAsyncRedirect(ju,Bu,Au,Ru)),{data:await readBody(ju,Pu),status:ju.status,statusText:ju.statusText,headers:headersToRecord(ju.headers)}}async function requestDatalayerAPI(Au){return(await requestDatalayerAPIWithResponse(Au)).data}function resolveLocation(Au,lo){const $u=Au.replace(/^([a-z][a-z0-9+.-]*):\/(?!\/)/i,"$1://");try{const Ru=new URL($u,lo),Iu=new URL(lo,typeof window<"u"?window.location.origin:void 0);return Iu.protocol==="https:"&&Ru.protocol==="http:"&&Ru.hostname===Iu.hostname&&(Ru.protocol="https:",Ru.port==="80"&&(Ru.port="")),Ru.toString()}catch{const Ru=libExports$5.URLExt.parse(lo),Iu=Ru.protocol+"//"+Ru.hostname;return libExports$5.URLExt.join(Iu,$u)}}async function followAsyncRedirect(Au,lo,$u,Ru){const Iu=resolveLocation(Au.headers.get("location"),$u),Pu={...lo,method:"GET",body:void 0};let Ou=1e3;for(;Au.status===202;)await sleep$1(Ou),Ou*=2,Au=await send(Iu,Pu,Ru);return Au}const userToProfile=Au=>Au?{id:Au.id,uid:Au.uid,handle:Au.handle,email:Au.email,firstName:Au.firstName,lastName:Au.lastName,displayName:Au.displayName,initials:Au.initials,avatarUrl:Au.avatarUrl,avatarIcon:Au.avatarIcon,banner:Au.banner,showOrbits:Au.showOrbits,origin:Au.origin,roles:Au.roles}:void 0,profileStore=createStore$1(Au=>({profile:void 0,setProfile:lo=>Au({profile:lo}),updateProfile:lo=>Au($u=>({profile:{...$u.profile,...lo}})),setProfileFromUser:lo=>Au($u=>{const Ru=userToProfile(lo);if(!Ru)return $u;const Iu={...$u.profile};for(const[Pu,Ou]of Object.entries(Ru))Ou!==void 0&&(Iu[Pu]=Ou);return{profile:Iu}}),clearProfile:()=>Au({profile:void 0})}));function useProfileStore(Au){return useStore$1(profileStore,Au)}const useProfile=()=>useProfileStore(Au=>Au.profile),SESSION_COOKIES=["datalayer-space-context","datalayer-principal-context","datalayer-billing-entity-uid","otel_sql_history"],SESSION_LOCAL_STORAGE_KEYS=["datalayer-principal","datalayer-billing-entity","datalayer-simple-auth"],SESSION_OWNER_KEY="datalayer-session-owner",registrations=new Set,registerSessionState=Au=>(registrations.add(Au),()=>{registrations.delete(Au)}),storageOf=Au=>{try{return typeof window>"u"?void 0:window[Au]}catch{return}},removeFrom=(Au,lo)=>{try{Au?.removeItem(lo)}catch{}},deleteCookie=Au=>{typeof document>"u"||(document.cookie=`${Au}=; path=/; max-age=0; SameSite=Lax`)},readCookie$1=Au=>{if(typeof document>"u")return;const lo=`${Au}=`,$u=document.cookie.split(";").map(Ru=>Ru.trim()).find(Ru=>Ru.startsWith(lo));return $u?$u.slice(lo.length):void 0},forgetSessionState=()=>{const Au=new Set(SESSION_COOKIES),lo=new Set([...SESSION_LOCAL_STORAGE_KEYS,SESSION_OWNER_KEY]),$u=new Set;for(const Pu of registrations){try{Pu.forget?.()}catch(Ou){console.warn("A session state could not be reset.",Ou)}Pu.cookies?.forEach(Ou=>Au.add(Ou)),Pu.localStorageKeys?.forEach(Ou=>lo.add(Ou)),Pu.sessionStorageKeys?.forEach(Ou=>$u.add(Ou))}Au.forEach(deleteCookie);const Ru=storageOf("localStorage");lo.forEach(Pu=>removeFrom(Ru,Pu));const Iu=storageOf("sessionStorage");$u.forEach(Pu=>removeFrom(Iu,Pu))},personalPrincipalInCookie=()=>{const Au=readCookie$1("datalayer-principal-context");if(Au)try{const lo=JSON.parse(decodeURIComponent(Au));return lo?.selectedPrincipalKind==="personal"&&String(lo?.selectedPrincipalUid??"").trim()||void 0}catch{return}},claimSessionState=Au=>{const lo=String(Au??"").trim();if(!lo)return;const $u=storageOf("localStorage");let Ru;try{Ru=$u?.getItem(SESSION_OWNER_KEY)??null}catch{Ru=null}const Iu=personalPrincipalInCookie();(Ru&&Ru!==lo||!Ru&&Iu&&Iu!==lo)&&forgetSessionState();try{$u?.setItem(SESSION_OWNER_KEY,lo)}catch{}},RESERVATION_WARNING_TIME_MS=5*6e4,iamStore=createStore$1((Au,lo)=>({credits:void 0,creditsReservations:[],externalToken:loadRefreshTokenFromCookie()??void 0,user:getStoredUser(),token:getStoredToken(),iamUrl:coreStore.getState().configuration?.iamUrl,iamProvidersAuthorizationURL:{},version:"",isLoginInProgress:!1,addIAMProviderAuthorizationURL:($u,Ru)=>{Au(Iu=>({iamProvidersAuthorizationURL:{...Iu.iamProvidersAuthorizationURL,[$u]:Ru}}))},login:async $u=>{const{refreshUserByToken:Ru,iamUrl:Iu,logout:Pu}=lo();Au({isLoginInProgress:!0});try{const Ou=await requestDatalayerAPI({url:`${Iu}/api/iam/v1/login`,method:"POST",body:{token:$u}});if(Ou.success&&Ou.token)await Ru(Ou.token);else throw new Error("Invalid Token.")}catch(Ou){throw console.debug("Failed to login.",Ou),Ou.name==="RunResponseError"&&Ou.response.status===401&&(console.debug("Received 401 error - Logging out."),Pu()),Ou}finally{Au({isLoginInProgress:!1})}},logout:()=>{storeUser(),storeToken(),profileStore.getState().clearProfile(),forgetSessionState(),Au({credits:void 0,creditsReservations:[],user:ANONYMOUS_USER,token:ANONYMOUS_USER_TOKEN})},checkIAMToken:async $u=>{lo().token!==$u&&await lo().refreshUserByToken($u)},setIAMProviderAccessToken:($u,Ru)=>{const{user:Iu}=lo();if(!Iu)throw Error("You need to be authenticated to set an Access Token for an IAM provider.");const Pu=IAMProvidersSpecs.getProvider($u);Ru?setCookie(Pu.accessTokenCookieName(Iu),Ru):deleteCookie$1(Pu.accessTokenCookieName(Iu))},getIAMProviderAccessToken:($u,Ru)=>{const Pu=IAMProvidersSpecs.getProvider(Ru).accessTokenCookieName($u);return getCookie$1(Pu)},updateUser:$u=>Au(Ru=>{const Iu={user:{...Ru.user,...$u}};return profileStore.getState().setProfileFromUser(Iu.user),Iu}),refreshCredits:async()=>{const{externalToken:$u,token:Ru,iamUrl:Iu,logout:Pu}=lo();if(Ru)try{const Ou=await requestDatalayerAPI({url:`${Iu}/api/iam/v1/usage/credits`,token:Ru,headers:$u?{"X-External-Token":$u}:void 0}),{credits:Mu,reservations:Du=[]}=Ou;Au({credits:{...Mu,available:availableCredits(Mu,Du)},creditsReservations:Du})}catch(Ou){throw console.error("Failed to refresh user credits.",Ou),Ou.name==="RunResponseError"&&Ou.response.status===401&&(console.error("Received 401, logging out."),Pu()),Ou}else Au({credits:void 0})},refreshUser:async()=>{const{token:$u,refreshUserByToken:Ru,logout:Iu}=lo();$u?await Ru($u):Iu()},refreshUserByTokenStored:async()=>{const $u=getStoredToken();$u?await lo().refreshUserByToken($u):lo().logout()},refreshUserByToken:async $u=>{const{iamUrl:Ru,logout:Iu,isLoginInProgress:Pu}=lo();try{const Ou=await requestDatalayerAPI({url:`${Ru}/api/iam/v1/whoami`,token:$u}),Mu=asUser(Ou.profile);claimSessionState(Mu?.id??Mu?.uid),storeUser(Mu),storeToken($u),Au(()=>({user:Mu,token:$u}))}catch(Ou){Ou.name==="RunResponseError"&&Ou.response.status===401?console.debug("Invalid token - Received 401 error."):console.debug("Failed to fetch user identity.",Ou),Pu||Iu()}},setExternalToken:$u=>Au(Ru=>({externalToken:$u})),setLogin:($u,Ru)=>Au(Iu=>(claimSessionState($u?.id??$u?.uid),storeUser($u),storeToken(Ru),profileStore.getState().setProfileFromUser($u),{user:$u,token:Ru})),setVersion:$u=>{$u&&!lo().version&&Au(Ru=>({version:$u}))}}));function useIAMStore(Au){return useStore$1(iamStore,Au)}const creditsPoll=new Poll({name:"@datalayer/ui:credits-refresh",factory:()=>iamStore.getState().refreshCredits(),auto:!1,frequency:{interval:60*1e3,backoff:!0,max:600*1e3},standby:()=>iamStore.getState().user?.id?"when-hidden":!0});iamStore.getState().refreshUserByTokenStored().catch(Au=>{console.error("Failed to refresh to validate the stored token.",Au)}).finally(()=>{const{externalToken:Au,iamUrl:lo,checkIAMToken:$u,token:Ru}=iamStore.getState();!Ru&&Au&&(console.debug("Can not login with token - Trying with the external token."),requestDatalayerAPI({url:`${lo}/api/iam/v1/login`,method:"POST",body:{token:Au}}).then(Pu=>{Pu.token&&$u(Pu.token)}).catch(Pu=>{console.debug("Can not login with token.",Ru,Pu)})),Ru?console.log("Logged in with token and external token."):console.debug("Failed to login with token and no external token available."),creditsPoll.start(),(()=>{if(typeof window>"u")return;const Pu=window.document;if(!Pu||typeof Pu.addEventListener!="function")return;const Ou=()=>{!Pu.hidden&&iamStore.getState().user?.id&&creditsPoll.refresh()};Pu.addEventListener("visibilitychange",Ou)})()});coreStore.subscribe((Au,lo)=>{if(Au.configuration?.iamUrl&&Au.configuration.iamUrl!==lo.configuration?.iamUrl){const $u=Au.configuration.iamUrl;console.log("Updating iamUrl with new value",$u),iamStore.setState({iamUrl:$u}),iamStore.getState().externalToken?iamStore.getState().login(iamStore.getState().externalToken).catch(Ru=>{console.error("Failed to refresh the user after updating the IAM RUN URL.",Ru)}):iamStore.getState().refreshUser().catch(Ru=>{console.error("Failed to refresh the user after updating the IAM server URL.",Ru)})}});function emojiKey(Au){return Array.from(Au.trim()).map(lo=>lo.codePointAt(0)??0).filter(lo=>lo!==65039).map(lo=>lo.toString(16)).join("-")}const scriptRel=(function Au(){const lo=typeof document<"u"&&document.createElement("link").relList;return lo&&lo.supports&&lo.supports("modulepreload")?"modulepreload":"preload"})(),assetsURL=function(Au,lo){return new URL(Au,lo).href},seen={},__vitePreload=function Au(lo,$u,Ru){let Iu=Promise.resolve();if($u&&$u.length>0){let Lu=function(Bu){return Promise.all(Bu.map(ju=>Promise.resolve(ju).then(Fu=>({status:"fulfilled",value:Fu}),Fu=>({status:"rejected",reason:Fu}))))};const Ou=document.getElementsByTagName("link"),Mu=document.querySelector("meta[property=csp-nonce]"),Du=Mu?.nonce||Mu?.getAttribute("nonce");Iu=Lu($u.map(Bu=>{if(Bu=assetsURL(Bu,Ru),Bu in seen)return;seen[Bu]=!0;const ju=Bu.endsWith(".css"),Fu=ju?'[rel="stylesheet"]':"";if(Ru)for(let Uu=Ou.length-1;Uu>=0;Uu--){const Hu=Ou[Uu];if(Hu.href===Bu&&(!ju||Hu.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${Bu}"]${Fu}`))return;const zu=document.createElement("link");if(zu.rel=ju?"stylesheet":scriptRel,ju||(zu.as="script"),zu.crossOrigin="",zu.href=Bu,Du&&zu.setAttribute("nonce",Du),document.head.appendChild(zu),ju)return new Promise((Uu,Hu)=>{zu.addEventListener("load",Uu),zu.addEventListener("error",()=>Hu(new Error(`Unable to preload CSS for ${Bu}`)))})}))}function Pu(Ou){const Mu=new Event("vite:preloadError",{cancelable:!0});if(Mu.payload=Ou,window.dispatchEvent(Mu),!Mu.defaultPrevented)throw Ou}return Iu.then(Ou=>{for(const Mu of Ou||[])Mu.status==="rejected"&&Pu(Mu.reason);return lo().catch(Pu)})},FLUENT_EMOJI_LOADERS={"1f440":()=>__vitePreload(()=>import("./chunks/1f440-p4rvIPef.js"),[],import.meta.url),"1f4d1":()=>__vitePreload(()=>import("./chunks/1f4d1-2yeMP7i5.js"),[],import.meta.url),"1f399":()=>__vitePreload(()=>import("./chunks/1f399-GX_7MVl_.js"),[],import.meta.url),"1f6a2":()=>__vitePreload(()=>import("./chunks/1f6a2-gL6kUzw5.js"),[],import.meta.url),"1f69a":()=>__vitePreload(()=>import("./chunks/1f69a-CbAMmMYx.js"),[],import.meta.url),"1f50e":()=>__vitePreload(()=>import("./chunks/1f50e-CNC8yd3r.js"),[],import.meta.url),"1f4ec":()=>__vitePreload(()=>import("./chunks/1f4ec-e7JJiuI4.js"),[],import.meta.url),"1f4c8":()=>__vitePreload(()=>import("./chunks/1f4c8-CNuFlfRg.js"),[],import.meta.url),"1f9f9":()=>__vitePreload(()=>import("./chunks/1f9f9-DNoxae13.js"),[],import.meta.url),"1f9e0":()=>__vitePreload(()=>import("./chunks/1f9e0-7eqXrAdK.js"),[],import.meta.url),"1f6df":()=>__vitePreload(()=>import("./chunks/1f6df-DcnntiKi.js"),[],import.meta.url),"1f9ee":()=>__vitePreload(()=>import("./chunks/1f9ee-BuIxmQEW.js"),[],import.meta.url),"1f47e":()=>__vitePreload(()=>import("./chunks/1f47e-CVrptMZb.js"),[],import.meta.url),"1f47d":()=>__vitePreload(()=>import("./chunks/1f47d-DKGX1RHr.js"),[],import.meta.url),"1f9d1-200d-1f680":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f680-C9wxDlc0.js"),[],import.meta.url),"269b":()=>__vitePreload(()=>import("./chunks/269b-CIDlSWpG.js"),[],import.meta.url),"1f3e6":()=>__vitePreload(()=>import("./chunks/1f3e6-LRmfNoyK.js"),[],import.meta.url),2712:()=>__vitePreload(()=>import("./chunks/2712-5PLssGP2.js"),[],import.meta.url),"1f4bc":()=>__vitePreload(()=>import("./chunks/1f4bc-DPph9Yum.js"),[],import.meta.url),"1f3db":()=>__vitePreload(()=>import("./chunks/1f3db-D8W2ZDGL.js"),[],import.meta.url),"1f3d7":()=>__vitePreload(()=>import("./chunks/1f3d7-BCgsEYI1.js"),[],import.meta.url),"1f3e2":()=>__vitePreload(()=>import("./chunks/1f3e2-Ck-pGqVC.js"),[],import.meta.url),"1f3af":()=>__vitePreload(()=>import("./chunks/1f3af-BjGhox67.js"),[],import.meta.url),2601:()=>__vitePreload(()=>import("./chunks/2601-BxBuW0c5.js"),[],import.meta.url),"1f6a7":()=>__vitePreload(()=>import("./chunks/1f6a7-Bf7dX4bM.js"),[],import.meta.url),"1f477":()=>__vitePreload(()=>import("./chunks/1f477--ZfEh0BR.js"),[],import.meta.url),"1f920":()=>__vitePreload(()=>import("./chunks/1f920-DdqVzdU_.js"),[],import.meta.url),"1f9ec":()=>__vitePreload(()=>import("./chunks/1f9ec-BiccuNAi.js"),[],import.meta.url),"1f432":()=>__vitePreload(()=>import("./chunks/1f432-BBBxgCDF.js"),[],import.meta.url),"1f409":()=>__vitePreload(()=>import("./chunks/1f409-B-A-r5OE.js"),[],import.meta.url),"1f9dd":()=>__vitePreload(()=>import("./chunks/1f9dd-Bjlh5f8S.js"),[],import.meta.url),"1f525":()=>__vitePreload(()=>import("./chunks/1f525-DugGj6UX.js"),[],import.meta.url),"1f386":()=>__vitePreload(()=>import("./chunks/1f386-D1j06612.js"),[],import.meta.url),"1f6f8":()=>__vitePreload(()=>import("./chunks/1f6f8-CzpZp4fr.js"),[],import.meta.url),"1f340":()=>__vitePreload(()=>import("./chunks/1f340-B2CJ9tGB.js"),[],import.meta.url),"1f393":()=>__vitePreload(()=>import("./chunks/1f393-Cule2ZWh.js"),[],import.meta.url),"1f600":()=>__vitePreload(()=>import("./chunks/1f600-DHzS58-a.js"),[],import.meta.url),"1f3e0":()=>__vitePreload(()=>import("./chunks/1f3e0-Dvy0EpCV.js"),[],import.meta.url),"1f98e":()=>__vitePreload(()=>import("./chunks/1f98e-BRdu0IxY.js"),[],import.meta.url),"1fa84":()=>__vitePreload(()=>import("./chunks/1fa84-C7Zz9Ttn.js"),[],import.meta.url),"1f9d1-200d-1f4bc":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f4bc-FkyMuHj6.js"),[],import.meta.url),"1f9d1-200d-1f4bb":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f4bb-Bxh01EAD.js"),[],import.meta.url),"1f3b5":()=>__vitePreload(()=>import("./chunks/1f3b5-BdjcFmdt.js"),[],import.meta.url),"1f977":()=>__vitePreload(()=>import("./chunks/1f977-g-J1jf1x.js"),[],import.meta.url),"1f450":()=>__vitePreload(()=>import("./chunks/1f450-CbtsXspW.js"),[],import.meta.url),"1f58a":()=>__vitePreload(()=>import("./chunks/1f58a-mulZ-CFH.js"),[],import.meta.url),"1f427":()=>__vitePreload(()=>import("./chunks/1f427-DglaWI4D.js"),[],import.meta.url),"1f3c4":()=>__vitePreload(()=>import("./chunks/1f3c4-BhpD29zf.js"),[],import.meta.url),"1f3ca":()=>__vitePreload(()=>import("./chunks/1f3ca-gIlr1kJ5.js"),[],import.meta.url),"1f5bc":()=>__vitePreload(()=>import("./chunks/1f5bc-MigptVzH.js"),[],import.meta.url),"1f304":()=>__vitePreload(()=>import("./chunks/1f304-aDc2qDui.js"),[],import.meta.url),"1f6eb":()=>__vitePreload(()=>import("./chunks/1f6eb-lf0G-q-a.js"),[],import.meta.url),"1fa90":()=>__vitePreload(()=>import("./chunks/1fa90-Ccp91l-o.js"),[],import.meta.url),"1f916":()=>__vitePreload(()=>import("./chunks/1f916-BqoYgu9n.js"),[],import.meta.url),"1f680":()=>__vitePreload(()=>import("./chunks/1f680-dnPjZK4l.js"),[],import.meta.url),"1f385":()=>__vitePreload(()=>import("./chunks/1f385-Dt5AZfN7.js"),[],import.meta.url),"1f6f0":()=>__vitePreload(()=>import("./chunks/1f6f0-DiDzAbox.js"),[],import.meta.url),"1f9d1-200d-1f52c":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f52c-DIXbDrbI.js"),[],import.meta.url),"1f988":()=>__vitePreload(()=>import("./chunks/1f988-wqhZ7Rxe.js"),[],import.meta.url),2603:()=>__vitePreload(()=>import("./chunks/2603-DNj-gj-j.js"),[],import.meta.url),"1f387":()=>__vitePreload(()=>import("./chunks/1f387-D0SVWvyW.js"),[],import.meta.url),"2b50":()=>__vitePreload(()=>import("./chunks/2b50-DgcciXHA.js"),[],import.meta.url),"1f9d1-200d-1f393":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f393-DhlpNrMG.js"),[],import.meta.url),2600:()=>__vitePreload(()=>import("./chunks/2600-DZnZtR2D.js"),[],import.meta.url),"1f44b":()=>__vitePreload(()=>import("./chunks/1f44b-CDEzsnIT.js"),[],import.meta.url),"1f433":()=>__vitePreload(()=>import("./chunks/1f433-BGsjKcaL.js"),[],import.meta.url),"1f381":()=>__vitePreload(()=>import("./chunks/1f381-NG1UoP_K.js"),[],import.meta.url),"270d":()=>__vitePreload(()=>import("./chunks/270d-DAjo8CgW.js"),[],import.meta.url),"262f":()=>__vitePreload(()=>import("./chunks/262f-BHwzZDRR.js"),[],import.meta.url),"1f4ca":()=>__vitePreload(()=>import("./chunks/1f4ca-DwUKcdqA.js"),[],import.meta.url),"1f4dd":()=>__vitePreload(()=>import("./chunks/1f4dd-CjeXE9pk.js"),[],import.meta.url),"1f4c5":()=>__vitePreload(()=>import("./chunks/1f4c5-BuR_5gXZ.js"),[],import.meta.url),"1f5d3":()=>__vitePreload(()=>import("./chunks/1f5d3-CD7YTnlH.js"),[],import.meta.url),"1f4da":()=>__vitePreload(()=>import("./chunks/1f4da-T00kbbB7.js"),[],import.meta.url),"1f4a1":()=>__vitePreload(()=>import("./chunks/1f4a1-DuAncIYW.js"),[],import.meta.url),"1f527":()=>__vitePreload(()=>import("./chunks/1f527-DGFX9oVv.js"),[],import.meta.url),"1f6e0":()=>__vitePreload(()=>import("./chunks/1f6e0-BN_iAibr.js"),[],import.meta.url),"1f9f0":()=>__vitePreload(()=>import("./chunks/1f9f0-NjV-EBzJ.js"),[],import.meta.url),2699:()=>__vitePreload(()=>import("./chunks/2699-DHeK1la1.js"),[],import.meta.url),"1f9ea":()=>__vitePreload(()=>import("./chunks/1f9ea-Dn-cjqlg.js"),[],import.meta.url),"1f52c":()=>__vitePreload(()=>import("./chunks/1f52c-PWG_VsFe.js"),[],import.meta.url),"1f5c2":()=>__vitePreload(()=>import("./chunks/1f5c2-BwHVJFvn.js"),[],import.meta.url),"1f4e6":()=>__vitePreload(()=>import("./chunks/1f4e6-iVURZ5lW.js"),[],import.meta.url),"1f6d2":()=>__vitePreload(()=>import("./chunks/1f6d2-C4PVtG90.js"),[],import.meta.url),"1f6b2":()=>__vitePreload(()=>import("./chunks/1f6b2-BvodiaEs.js"),[],import.meta.url),"1f4ac":()=>__vitePreload(()=>import("./chunks/1f4ac-B0hyiBGy.js"),[],import.meta.url),"1f4e3":()=>__vitePreload(()=>import("./chunks/1f4e3-BCLpfdwX.js"),[],import.meta.url),"1f9fe":()=>__vitePreload(()=>import("./chunks/1f9fe-vjnIOB6Q.js"),[],import.meta.url),"1f4b0":()=>__vitePreload(()=>import("./chunks/1f4b0-Bgl_9Qt3.js"),[],import.meta.url),"1f4b3":()=>__vitePreload(()=>import("./chunks/1f4b3-C3bg4q6a.js"),[],import.meta.url),"1f30d":()=>__vitePreload(()=>import("./chunks/1f30d-RKwL3Nsg.js"),[],import.meta.url),"1f512":()=>__vitePreload(()=>import("./chunks/1f512-CfUiEAwd.js"),[],import.meta.url),"1f511":()=>__vitePreload(()=>import("./chunks/1f511-n1Y90TZn.js"),[],import.meta.url),"1f6e1":()=>__vitePreload(()=>import("./chunks/1f6e1-Cu0Gi0Ok.js"),[],import.meta.url),"1f9ed":()=>__vitePreload(()=>import("./chunks/1f9ed-BdM-tuKc.js"),[],import.meta.url),"1f5fa":()=>__vitePreload(()=>import("./chunks/1f5fa-BbhAXfOC.js"),[],import.meta.url),"1f4f0":()=>__vitePreload(()=>import("./chunks/1f4f0-BqBFK1vM.js"),[],import.meta.url),2709:()=>__vitePreload(()=>import("./chunks/2709-R2m2qaPB.js"),[],import.meta.url),"1f4de":()=>__vitePreload(()=>import("./chunks/1f4de-DMKOmTcC.js"),[],import.meta.url),"1f91d":()=>__vitePreload(()=>import("./chunks/1f91d-BLSo-qgX.js"),[],import.meta.url),"1f3e5":()=>__vitePreload(()=>import("./chunks/1f3e5-BZAbo425.js"),[],import.meta.url),2696:()=>__vitePreload(()=>import("./chunks/2696-DCPh-ddG.js"),[],import.meta.url),"1f3a8":()=>__vitePreload(()=>import("./chunks/1f3a8-BVDoGacX.js"),[],import.meta.url),"1f3ac":()=>__vitePreload(()=>import("./chunks/1f3ac-D8k4rvLe.js"),[],import.meta.url),"1f4f7":()=>__vitePreload(()=>import("./chunks/1f4f7-BwaVsOpm.js"),[],import.meta.url),"1f9d1-200d-1f3eb":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f3eb-CMaKZADj.js"),[],import.meta.url),"1f9d1-200d-2695":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-2695-DCucKT0e.js"),[],import.meta.url),"1f9d1-200d-1f373":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f373-DvkX_q7n.js"),[],import.meta.url),"1f9d1-200d-1f33e":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f33e-C1GbmRM7.js"),[],import.meta.url),"1f331":()=>__vitePreload(()=>import("./chunks/1f331-_RrI1iL2.js"),[],import.meta.url),"1f41d":()=>__vitePreload(()=>import("./chunks/1f41d-BFxQMyWe.js"),[],import.meta.url),"1f989":()=>__vitePreload(()=>import("./chunks/1f989-BnANhNFy.js"),[],import.meta.url),"1f98a":()=>__vitePreload(()=>import("./chunks/1f98a-D9FmXaXZ.js"),[],import.meta.url),"1f419":()=>__vitePreload(()=>import("./chunks/1f419-5WEpY3Qm.js"),[],import.meta.url),2764:()=>__vitePreload(()=>import("./chunks/2764-BqnS842k.js"),[],import.meta.url),2705:()=>__vitePreload(()=>import("./chunks/2705-C2znzsf2.js"),[],import.meta.url),"23f0":()=>__vitePreload(()=>import("./chunks/23f0-dWLnhjSv.js"),[],import.meta.url),"1f514":()=>__vitePreload(()=>import("./chunks/1f514-B1X39g06.js"),[],import.meta.url),"1f9e9":()=>__vitePreload(()=>import("./chunks/1f9e9-i_U9-xN7.js"),[],import.meta.url),"1f3f7":()=>__vitePreload(()=>import("./chunks/1f3f7-CcKaOA8W.js"),[],import.meta.url),"1f4cb":()=>__vitePreload(()=>import("./chunks/1f4cb-oUiKe7zE.js"),[],import.meta.url),"1f4cc":()=>__vitePreload(()=>import("./chunks/1f4cc-CBUTvGMt.js"),[],import.meta.url),"1f50d":()=>__vitePreload(()=>import("./chunks/1f50d-1bvZKHvT.js"),[],import.meta.url),"1f642":()=>__vitePreload(()=>import("./chunks/1f642-C6Qm_-ba.js"),[],import.meta.url),"1f913":()=>__vitePreload(()=>import("./chunks/1f913-hQT-pf0C.js"),[],import.meta.url),"1f9d0":()=>__vitePreload(()=>import("./chunks/1f9d0-Bg0qtSKU.js"),[],import.meta.url),"1f60e":()=>__vitePreload(()=>import("./chunks/1f60e-Dxrd05Jo.js"),[],import.meta.url),"1f984":()=>__vitePreload(()=>import("./chunks/1f984-DOK3uNT7.js"),[],import.meta.url),"1f436":()=>__vitePreload(()=>import("./chunks/1f436-CfGEu66M.js"),[],import.meta.url),"1f431":()=>__vitePreload(()=>import("./chunks/1f431-Cy-L3DQS.js"),[],import.meta.url),"1f308":()=>__vitePreload(()=>import("./chunks/1f308-DAQVzKND.js"),[],import.meta.url),"1f31f":()=>__vitePreload(()=>import("./chunks/1f31f-BV2d8NX3.js"),[],import.meta.url),"26a1":()=>__vitePreload(()=>import("./chunks/26a1-Cpmzv_rj.js"),[],import.meta.url),"1f355":()=>__vitePreload(()=>import("./chunks/1f355-C-u8bPC3.js"),[],import.meta.url),2615:()=>__vitePreload(()=>import("./chunks/2615-CoDRCZkH.js"),[],import.meta.url),"1f389":()=>__vitePreload(()=>import("./chunks/1f389-B6nBX5We.js"),[],import.meta.url),"1f3c6":()=>__vitePreload(()=>import("./chunks/1f3c6-PZd-tUlI.js"),[],import.meta.url),"23f3":()=>__vitePreload(()=>import("./chunks/23f3-ASjqFsbT.js"),[],import.meta.url),2611:()=>__vitePreload(()=>import("./chunks/2611-BnnmLm-K.js"),[],import.meta.url),2702:()=>__vitePreload(()=>import("./chunks/2702-CfLyp35r.js"),[],import.meta.url),"1f30a":()=>__vitePreload(()=>import("./chunks/1f30a-DxwAt2Ba.js"),[],import.meta.url),"1f327":()=>__vitePreload(()=>import("./chunks/1f327-Ie-nQBNO.js"),[],import.meta.url),"1f33e":()=>__vitePreload(()=>import("./chunks/1f33e-Cfl2WM63.js"),[],import.meta.url),"1f3ab":()=>__vitePreload(()=>import("./chunks/1f3ab-BUCNQHz1.js"),[],import.meta.url),"1f4be":()=>__vitePreload(()=>import("./chunks/1f4be-DPAcAU4R.js"),[],import.meta.url),"1f4d3":()=>__vitePreload(()=>import("./chunks/1f4d3-GTxRgjv7.js"),[],import.meta.url),"1f4d6":()=>__vitePreload(()=>import("./chunks/1f4d6-COOZY-Q_.js"),[],import.meta.url),"1f4e2":()=>__vitePreload(()=>import("./chunks/1f4e2-DsStZsI-.js"),[],import.meta.url),"1f504":()=>__vitePreload(()=>import("./chunks/1f504-BYIHMoDP.js"),[],import.meta.url),"1f465":()=>__vitePreload(()=>import("./chunks/1f465-CPle6Hjq.js"),[],import.meta.url),"270f":()=>__vitePreload(()=>import("./chunks/270f-CLwo30mk.js"),[],import.meta.url),2728:()=>__vitePreload(()=>import("./chunks/2728-Qg6be-6p.js"),[],import.meta.url),"2b1c":()=>__vitePreload(()=>import("./chunks/2b1c-Uc1aRwAf.js"),[],import.meta.url),"1f310":()=>__vitePreload(()=>import("./chunks/1f310-AqUM9a8q.js"),[],import.meta.url),"1f324":()=>__vitePreload(()=>import("./chunks/1f324-8MHLOhTj.js"),[],import.meta.url),"1f372":()=>__vitePreload(()=>import("./chunks/1f372-3XLDlXkE.js"),[],import.meta.url),"1f373":()=>__vitePreload(()=>import("./chunks/1f373-BPUJt2bp.js"),[],import.meta.url),"1f39b":()=>__vitePreload(()=>import("./chunks/1f39b-CSNtbAXr.js"),[],import.meta.url),"1f41b":()=>__vitePreload(()=>import("./chunks/1f41b-Dre1z0gP.js"),[],import.meta.url),"1f4c2":()=>__vitePreload(()=>import("./chunks/1f4c2-Dx7BKmLO.js"),[],import.meta.url),"1f4c4":()=>__vitePreload(()=>import("./chunks/1f4c4-CNvjvC5k.js"),[],import.meta.url),"1f4dc":()=>__vitePreload(()=>import("./chunks/1f4dc-BhoW4cjD.js"),[],import.meta.url),"1f4e1":()=>__vitePreload(()=>import("./chunks/1f4e1-DezU8ow-.js"),[],import.meta.url),"1f500":()=>__vitePreload(()=>import("./chunks/1f500-D9xRo-IT.js"),[],import.meta.url),"1f501":()=>__vitePreload(()=>import("./chunks/1f501-CzKeDPcw.js"),[],import.meta.url),"1f52d":()=>__vitePreload(()=>import("./chunks/1f52d-2QxCLKhU.js"),[],import.meta.url),"1f552":()=>__vitePreload(()=>import("./chunks/1f552-4d0Y0kn7.js"),[],import.meta.url),"1f58b":()=>__vitePreload(()=>import("./chunks/1f58b-Cp8F_HBg.js"),[],import.meta.url),"1f5b2":()=>__vitePreload(()=>import("./chunks/1f5b2-D6BUULuh.js"),[],import.meta.url),"1f5c3":()=>__vitePreload(()=>import("./chunks/1f5c3-DjkgJLaz.js"),[],import.meta.url),"1f5d1":()=>__vitePreload(()=>import("./chunks/1f5d1-C4Kpe4HL.js"),[],import.meta.url),"1f5dc":()=>__vitePreload(()=>import("./chunks/1f5dc-DyLO7aB9.js"),[],import.meta.url),"1f9d1-200d-2696":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-2696-D9eSB-0q.js"),[],import.meta.url),"1fa79":()=>__vitePreload(()=>import("./chunks/1fa79-DHhIZbWB.js"),[],import.meta.url),"1fa9d":()=>__vitePreload(()=>import("./chunks/1fa9d-DUI9e77m.js"),[],import.meta.url),"1fa9f":()=>__vitePreload(()=>import("./chunks/1fa9f-10ALsMaD.js"),[],import.meta.url),"1f441":()=>__vitePreload(()=>import("./chunks/1f441-D8yah4C4.js"),[],import.meta.url),"1f604":()=>__vitePreload(()=>import("./chunks/1f604-CEekcaYE.js"),[],import.meta.url),"1f326":()=>__vitePreload(()=>import("./chunks/1f326-YSBr3aXI.js"),[],import.meta.url),"1f4b9":()=>__vitePreload(()=>import("./chunks/1f4b9-aacFyckt.js"),[],import.meta.url),"1f4c1":()=>__vitePreload(()=>import("./chunks/1f4c1-Ch6aJ0cj.js"),[],import.meta.url),"1f4e7":()=>__vitePreload(()=>import("./chunks/1f4e7-BBi7c_zx.js"),[],import.meta.url),"1f917":()=>__vitePreload(()=>import("./chunks/1f917-CyyS9fgf.js"),[],import.meta.url)},DRAWN=new Map;function hasFluentEmoji(Au){return!!Au&&Object.prototype.hasOwnProperty.call(FLUENT_EMOJI_LOADERS,emojiKey(Au))}async function loadFluentEmoji(Au){const lo=emojiKey(Au),$u=DRAWN.get(lo);if($u)return $u;if(!Object.prototype.hasOwnProperty.call(FLUENT_EMOJI_LOADERS,lo))return;const Ru=(await FLUENT_EMOJI_LOADERS[lo]()).default,Iu=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(Ru)}`;return DRAWN.set(lo,Iu),Iu}function FluentEmoji({emoji:Au,size:lo,label:$u,className:Ru,style:Iu}){const Pu=emojiKey(Au),Ou=hasFluentEmoji(Au),[Mu,Du]=reactExports.useState(()=>DRAWN.get(Pu));reactExports.useEffect(()=>{let ju=!0;return Du(DRAWN.get(Pu)),Ou&&!DRAWN.has(Pu)&&loadFluentEmoji(Au).then(Fu=>ju&&Du(Fu),()=>{}),()=>{ju=!1}},[Pu,Ou,Au]);const Lu=$u??Au,Bu={display:"inline-flex",alignItems:"center",justifyContent:"center",flex:"none",width:lo,height:lo,...Iu};return Ou?Mu?jsxRuntimeExports.jsx("img",{className:Ru,src:Mu,alt:Lu,"aria-hidden":Lu?void 0:!0,width:lo,height:lo,draggable:!1,"data-emoji":"fluent",style:{...Bu,display:"inline-block"}}):jsxRuntimeExports.jsx("span",{className:Ru,"aria-hidden":"true","data-emoji":"loading",style:Bu}):jsxRuntimeExports.jsx("span",{className:Ru,role:Lu?"img":void 0,"aria-label":Lu||void 0,"aria-hidden":Lu?void 0:!0,"data-emoji":"system",style:{...Bu,fontSize:Math.round(lo*.85),lineHeight:1},children:Au})}function generateMessageId(){return`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function createUserMessage(Au,lo){return{id:generateMessageId(),role:"user",content:Au,createdAt:new Date,metadata:lo}}function createAssistantMessage(Au,lo){return{id:generateMessageId(),role:"assistant",content:Au,createdAt:new Date,agentName:lo?.agentName,toolCalls:lo?.toolCalls,metadata:lo?.metadata}}const createStoreImpl=Au=>{let lo;const $u=new Set,Ru=(Lu,Bu)=>{const ju=typeof Lu=="function"?Lu(lo):Lu;if(!Object.is(ju,lo)){const Fu=lo;lo=Bu??(typeof ju!="object"||ju===null)?ju:Object.assign({},lo,ju),$u.forEach(zu=>zu(lo,Fu))}},Iu=()=>lo,Mu={setState:Ru,getState:Iu,getInitialState:()=>Du,subscribe:Lu=>($u.add(Lu),()=>$u.delete(Lu))},Du=lo=Au(Ru,Iu,Mu);return Mu},createStore=(Au=>Au?createStoreImpl(Au):createStoreImpl),identity=Au=>Au;function useStore(Au,lo=identity){const $u=vM.useSyncExternalStore(Au.subscribe,vM.useCallback(()=>lo(Au.getState()),[Au,lo]),()=>lo(Au.getInitialState()));return vM.useDebugValue($u),$u}const createImpl=Au=>{const lo=createStore(Au),$u=Ru=>useStore(lo,Ru);return Object.assign($u,lo),$u},create$e=(Au=>Au?createImpl(Au):createImpl),useReactorStore=create$e(()=>({reactor:null,isBackendPluginAvailable:()=>!1})),unavailableBackendPlugin=()=>!1;function registerReactor(Au,lo=unavailableBackendPlugin){useReactorStore.setState({reactor:Au,isBackendPluginAvailable:lo})}function useReactor(Au,lo={}){const{autoStart:$u=!0,availableBackendPlugins:Ru,isBackendPluginAvailable:Iu}=lo,Pu=reactExports.useMemo(()=>{if(Iu)return Iu;const Ou=new Set(Ru??[]);return Mu=>Ou.has(Mu)},[Iu,Ru]);return reactExports.useState(()=>(registerReactor(Au,Pu),null)),reactExports.useEffect(()=>(registerReactor(Au,Pu),()=>{useReactorStore.getState().reactor===Au&&registerReactor(null,unavailableBackendPlugin)}),[Au,Pu]),reactExports.useEffect(()=>{if($u)return Au.start(),()=>{Au.stop()}},[$u,Au]),Au}const NO_SUBSCRIPTION$1=()=>()=>{};function useOptionalReactorPlatform(){return useReactorStore(Au=>Au.reactor)}function useReactorPlatform(){const Au=useReactorStore(lo=>lo.reactor);if(!Au)throw new Error("useReactorPlatform: no reactor store registered. Call useReactor(reactor) (or registerReactor) before using reactor hooks.");return Au}function useSignalValue$1(Au){return reactExports.useSyncExternalStore(lo=>{let $u=!1;return effect$1(()=>{Au.value,$u?lo():$u=!0})},()=>Au.peek(),()=>Au.peek())}function useBackendPluginAvailability(){return useReactorStore(Au=>Au.isBackendPluginAvailable)}function useBackendPluginStream(Au,lo={}){const{pollMs:$u=5e3,onState:Ru}=lo,Iu=Au?.replace(/\/+$/,""),Pu=useReactorStore(Mu=>Mu.reactor),Ou=reactExports.useRef(Ru);Ou.current=Ru,reactExports.useEffect(()=>{if(!Iu||!Pu)return;let Mu=!1,Du=-1;const Lu=zu=>{Mu||zu.revision===Du||(Du=zu.revision,Ou.current?.(zu),Pu.setBackendPlugins(zu.plugins.filter(Uu=>Uu.enabled).map(Uu=>Uu.name)))},Bu=()=>fetch(`${Iu}/plugins/state`).then(zu=>zu.ok?zu.json():void 0).then(zu=>zu&&Lu(zu)).catch(()=>{});if(Bu(),typeof EventSource>"u"){const zu=setInterval(Bu,$u);return()=>{Mu=!0,clearInterval(zu)}}const ju=new EventSource(`${Iu}/events/stream`);ju.onmessage=zu=>{try{Lu(JSON.parse(zu.data))}catch{}};const Fu=setInterval(Bu,$u);return()=>{Mu=!0,clearInterval(Fu),ju.close()}},[Iu,Pu,$u])}function useReactorEvent(Au){const lo=useReactorPlatform();reactExports.useEffect(()=>{Au&&lo.fire(Au)},[lo,Au])}function useOptionalSlotComponents(Au){const lo=useOptionalReactorPlatform();return useSlotComponentsFrom(lo,Au)}function useSlotComponents(Au){const lo=useReactorPlatform();return useSlotComponentsFrom(lo,Au)}function useSlotComponentsFrom(Au,lo){const $u=useBackendPluginAvailability(),Ru=reactExports.useSyncExternalStore(Au?Au.subscribe:NO_SUBSCRIPTION$1,()=>Au?Au.getRevision():-1);return reactExports.useMemo(()=>{const Iu=[];if(!Au)return Iu;function Pu(Ou){return Ou.every(Mu=>$u(Mu))}for(const Ou of Au.listPlugins()){if(!Au.isEnabled(Ou))continue;const Mu=Au.getRequiredBackendPlugins(Ou);if(!Pu(Mu))continue;const Du=Au.getOutput(Ou);for(const Lu of Du?.components??[]){const Bu=Lu.requiredBackendPlugins??[];Lu.slot===lo&&Pu(Bu)&&Iu.push(Lu)}}return Iu.map((Ou,Mu)=>({component:Ou,index:Mu})).sort((Ou,Mu)=>(Ou.component.order??0)-(Mu.component.order??0)||Ou.index-Mu.index).map(Ou=>Ou.component)},[Au,lo,Ru,$u])}function ReactorSlot({slot:Au,props:lo={}}){const $u=useOptionalSlotComponents(Au);return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:$u.map(Ru=>{const Iu=Ru.Component;return jsxRuntimeExports.jsx(Iu,{...lo},`${Ru.slot}:${Ru.id}`)})})}function useGate(Au,lo){const $u=useContributions(Au);return reactExports.useMemo(()=>resolveGate($u,lo),[$u,lo])}function useContributions(Au){const lo=useReactorPlatform(),$u=reactExports.useSyncExternalStore(lo.subscribe,()=>lo.getRevision());return reactExports.useMemo(()=>lo.getContributions(Au),[lo,Au,$u])}function useCommands(){const Au=useReactorPlatform(),lo=reactExports.useSyncExternalStore(Au.subscribe,()=>Au.getRevision());return reactExports.useMemo(()=>Au.listCommands(),[Au,lo])}class LazyErrorBoundary extends reactExports.Component{state={error:null};static getDerivedStateFromError(lo){return{error:lo}}componentDidUpdate(lo){lo.resetKey!==this.props.resetKey&&this.state.error&&this.setState({error:null})}render(){return this.state.error?this.props.fallback(this.state.error):this.props.children}}const lazyComponents=new WeakMap;function lazyFor(Au){const lo=lazyComponents.get(Au);if(lo)return lo;const $u=vM.lazy(Au);return lazyComponents.set(Au,$u),$u}function ReactorLazy({load:Au,props:lo,fallback:$u=null,errorFallback:Ru}){const Iu=reactExports.useMemo(()=>lazyFor(Au),[Au]),Pu=Ru??(Ou=>jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:`Failed to load view: ${Ou.message}`}));return jsxRuntimeExports.jsx(LazyErrorBoundary,{fallback:Pu,resetKey:Au,children:jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:$u,children:jsxRuntimeExports.jsx(Iu,{...lo??{}})})})}function defaultResolve(Au){const lo=Au;if(lo&&typeof lo.load=="function")return{load:lo.load};if(lo&&typeof lo.Component=="function")return{Component:lo.Component}}function ReactorViewHost({point:Au,active:lo,props:$u,fallback:Ru=null,empty:Iu=null,errorFallback:Pu,resolve:Ou=defaultResolve,render:Mu}){const Du=useContributions(Au),Lu=reactExports.useMemo(()=>lo===void 0?void 0:Du.find(Fu=>Fu.id===lo),[Du,lo]);if(!Lu)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Iu});if(Mu)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Mu(Lu)});const Bu=Ou(Lu.value);if(!Bu)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Iu});if(Bu.load)return jsxRuntimeExports.jsx(ReactorLazy,{load:Bu.load,props:$u,fallback:Ru,errorFallback:Pu});const ju=Bu.Component;return jsxRuntimeExports.jsx(ju,{...$u??{}})}const UI_WIRE_VERSION=1,DISPLAY_META_KEY$1="reactor.ui/display",ANSWER_ACTION="reactor.answer",UI_OP_NAMES=["show","patch","append","remove","state","ask","window","meta"];function isRecord$6(Au){return typeof Au=="object"&&Au!==null&&!Array.isArray(Au)}function isOptional$1(Au,lo){return Au==null||lo(Au)}function isString$3(Au){return typeof Au=="string"}function isActionOffer(Au){return isRecord$6(Au)&&isString$3(Au.name)&&isString$3(Au.token)&&isOptional$1(Au.label,isString$3)}function isDisplay(Au){return isRecord$6(Au)&&isString$3(Au.type)&&isString$3(Au.id)&&isString$3(Au.text)&&(Au.version===void 0||Number.isInteger(Au.version))&&(Au.data===void 0||isRecord$6(Au.data))&&(Au.actions===void 0||Array.isArray(Au.actions)&&Au.actions.every(isActionOffer))}function isPatchOperation(Au){if(!isRecord$6(Au)||!isString$3(Au.path))return!1;switch(Au.op){case"add":case"replace":case"test":return"value"in Au;case"remove":return!0;case"move":case"copy":return isString$3(Au.from);default:return!1}}function isPatch(Au){return Array.isArray(Au)&&Au.every(isPatchOperation)}const OP_SHAPES={show:Au=>isDisplay(Au.body),ask:Au=>isDisplay(Au.body),patch:Au=>isString$3(Au.id)&&isPatch(Au.body),append:Au=>isString$3(Au.id)&&isRecord$6(Au.body)&&isString$3(Au.body.path),remove:Au=>isString$3(Au.id)&&(Au.body===void 0||Au.body===null),state:Au=>isPatch(Au.body),window:Au=>isRecord$6(Au.body)&&isString$3(Au.body.name)&&(Au.body.args===void 0||isRecord$6(Au.body.args)),meta:Au=>isRecord$6(Au.body)};function isUiOp(Au){return isRecord$6(Au)&&Au.v===UI_WIRE_VERSION&&isString$3(Au.scope)&&isOptional$1(Au.id,isString$3)&&UI_OP_NAMES.includes(Au.op)&&OP_SHAPES[Au.op](Au)}function isSeq(Au,lo){return Number.isInteger(Au)&&Au>=lo}function hasKeys(Au,lo,$u=[]){const Ru=Object.keys(Au);return lo.every(Iu=>Iu in Au)&&Ru.every(Iu=>lo.includes(Iu)||$u.includes(Iu))}function isDownFrame(Au){if(!isRecord$6(Au))return!1;switch(Au.t){case"welcome":return hasKeys(Au,["t","scope","seq"],["v"])&&(Au.v===void 0||Au.v===UI_WIRE_VERSION)&&isString$3(Au.scope)&&isSeq(Au.seq,0);case"op":return hasKeys(Au,["t","seq","op"])&&isSeq(Au.seq,1)&&isUiOp(Au.op);case"result":return hasKeys(Au,["t","ref","ok","status"],["detail","value"])&&isString$3(Au.ref)&&typeof Au.ok=="boolean"&&Number.isInteger(Au.status)&&isOptional$1(Au.detail,isString$3);case"ping":case"pong":return hasKeys(Au,["t"]);default:return!1}}const Renderers=defineContributionPoint("reactor.ui.renderer"),ToolBindings=defineContributionPoint("reactor.ui.toolBinding");function versionInRange(Au,lo){return lo?(lo.min===void 0||Au>=lo.min)&&(lo.max===void 0||Au<=lo.max):!0}function pickRenderer(Au,lo){const $u=lo.version??1;let Ru;for(const Iu of Au)Iu.value.type!==lo.type||!versionInRange($u,Iu.value.versions)||(!Ru||(Iu.value.rank??0)>(Ru.value.rank??0))&&(Ru=Iu);return Ru}function parsedObject(Au){if(typeof Au!="string")return Au;const lo=Au.trimStart();if(!lo.startsWith("{"))return Au;try{return JSON.parse(lo)}catch{return Au}}function embeddedDisplay(Au){const lo=parsedObject(Au);if(typeof lo!="object"||lo===null)return;const $u=lo._meta;if(typeof $u!="object"||$u===null)return;const Ru=$u[DISPLAY_META_KEY$1];return isDisplay(Ru)?Ru:void 0}function bindingMatches(Au,lo){return typeof Au.tool=="string"?Au.tool===lo:(Au.tool.lastIndex=0,Au.tool.test(lo))}function textOf(Au){if(Au==null)return"";if(typeof Au=="string")return Au;try{return JSON.stringify(Au)??String(Au)}catch{return String(Au)}}function resolveToolResult(Au,lo){const $u=embeddedDisplay(lo.result);if($u)return $u;const Ru=Au.getContributions(ToolBindings).find(Iu=>bindingMatches(Iu.value,lo.toolName));if(Ru)return{type:Ru.value.type,version:Ru.value.version??1,id:lo.toolCallId??lo.toolName,text:textOf(lo.result),data:{toolName:lo.toolName,result:lo.result}}}function emptyUiModel(){return{displays:{},order:[],asks:[],state:{},meta:{}}}function clone$2(Au){return Au===void 0?Au:JSON.parse(JSON.stringify(Au))}function parsePointer(Au){if(Au==="")return[];if(!Au.startsWith("/"))throw new Error(`A JSON pointer starts with '/': ${Au}`);return Au.slice(1).split("/").map(lo=>lo.replace(/~1/g,"/").replace(/~0/g,"~")).map(lo=>{if(FORBIDDEN_TOKENS.has(lo))throw new Error(`${Au}: '${lo}' is never a path token`);return lo})}const FORBIDDEN_TOKENS=new Set(["__proto__","constructor","prototype"]);function hasOwn(Au,lo){return Object.prototype.hasOwnProperty.call(Au,lo)}function walk(Au,lo,$u){let Ru=Au;for(const Iu of lo)if(Array.isArray(Ru))Ru=Ru[arrayIndex(Ru,Iu,$u,!1)];else if(typeof Ru=="object"&&Ru!==null&&hasOwn(Ru,Iu))Ru=Ru[Iu];else throw new Error(`No value at ${$u}`);if(typeof Ru!="object"||Ru===null)throw new Error(`${$u} does not lead into an object or an array`);return Ru}function arrayIndex(Au,lo,$u,Ru){if(Ru&&lo==="-")return Au.length;if(!/^(0|[1-9][0-9]*)$/.test(lo))throw new Error(`${$u}: '${lo}' is not an array index`);const Iu=Number(lo);if(Iu>Au.length||!Ru&&Iu===Au.length)throw new Error(`${$u}: index ${Iu} is out of bounds`);return Iu}function read$2(Au,lo){const $u=parsePointer(lo);if($u.length===0)return Au;const Ru=walk(Au,$u.slice(0,-1),lo),Iu=$u[$u.length-1];if(Array.isArray(Ru))return Ru[arrayIndex(Ru,Iu,lo,!1)];if(!hasOwn(Ru,Iu))throw new Error(`No value at ${lo}`);return Ru[Iu]}function add$1(Au,lo,$u){const Ru=parsePointer(lo);if(Ru.length===0)return $u;const Iu=walk(Au,Ru.slice(0,-1),lo),Pu=Ru[Ru.length-1];return Array.isArray(Iu)?Iu.splice(arrayIndex(Iu,Pu,lo,!0),0,$u):Iu[Pu]=$u,Au}function removeAt(Au,lo){const $u=parsePointer(lo);if($u.length===0)return;const Ru=walk(Au,$u.slice(0,-1),lo),Iu=$u[$u.length-1];if(Array.isArray(Ru))Ru.splice(arrayIndex(Ru,Iu,lo,!1),1);else{if(!hasOwn(Ru,Iu))throw new Error(`No value at ${lo}`);delete Ru[Iu]}return Au}function replaceAt(Au,lo,$u){const Ru=parsePointer(lo);if(Ru.length===0)return $u;const Iu=walk(Au,Ru.slice(0,-1),lo),Pu=Ru[Ru.length-1];if(Array.isArray(Iu))Iu[arrayIndex(Iu,Pu,lo,!1)]=$u;else{if(!hasOwn(Iu,Pu))throw new Error(`No value at ${lo}`);Iu[Pu]=$u}return Au}function equal$1(Au,lo){if(Au===lo)return!0;if(Array.isArray(Au)||Array.isArray(lo))return Array.isArray(Au)&&Array.isArray(lo)&&Au.length===lo.length&&Au.every((Pu,Ou)=>equal$1(Pu,lo[Ou]));if(typeof Au!="object"||typeof lo!="object"||Au===null||lo===null)return!1;const $u=Au,Ru=lo,Iu=Object.keys($u);return Iu.length===Object.keys(Ru).length&&Iu.every(Pu=>hasOwn(Ru,Pu)&&equal$1($u[Pu],Ru[Pu]))}function applyPatch$1(Au,lo){let $u=clone$2(Au);for(const Ru of lo)switch(Ru.op){case"add":$u=add$1($u,Ru.path,clone$2(Ru.value));break;case"remove":$u=removeAt($u,Ru.path);break;case"replace":$u=replaceAt($u,Ru.path,clone$2(Ru.value));break;case"move":{const Iu=requireFrom(Ru),Pu=read$2($u,Iu);$u=add$1(removeAt($u,Iu),Ru.path,Pu);break}case"copy":$u=add$1($u,Ru.path,clone$2(read$2($u,requireFrom(Ru))));break;case"test":if(!equal$1(read$2($u,Ru.path),Ru.value))throw new Error(`test failed at ${Ru.path}`);break;default:throw new Error(`Unknown patch op ${Ru.op}`)}return $u}function requireFrom(Au){if(typeof Au.from!="string")throw new Error(`'${Au.op}' at ${Au.path} needs 'from'`);return Au.from}function displayOf(Au,lo){const $u=Au.displays[lo.id];if(!$u)throw new Error(`'${lo.op}' for display '${lo.id}', which was never shown`);return $u}function shown(Au,lo){const $u=lo.id in Au.displays;return{...Au,displays:{...Au.displays,[lo.id]:lo},order:$u?Au.order:[...Au.order,lo.id]}}function applyUiOp(Au,lo){if(lo.v!==UI_WIRE_VERSION)throw new Error(`reactor.ui wire v${String(lo.v)} is not v${UI_WIRE_VERSION}`);switch(lo.op){case"show":return shown(Au,lo.body);case"ask":{const $u=shown(Au,lo.body);return $u.asks.includes(lo.body.id)?$u:{...$u,asks:[...$u.asks,lo.body.id]}}case"patch":{const $u=applyPatch$1(displayOf(Au,lo),lo.body);return{...Au,displays:{...Au.displays,[lo.id]:{...$u,id:lo.id}}}}case"append":{const $u=displayOf(Au,lo),Ru=applyPatch$1($u,[{op:"add",path:`${lo.body.path}/-`,value:lo.body.value}]);return{...Au,displays:{...Au.displays,[lo.id]:Ru}}}case"remove":{if(!(lo.id in Au.displays))return Au;const $u={...Au.displays};return delete $u[lo.id],{...Au,displays:$u,order:Au.order.filter(Ru=>Ru!==lo.id),asks:Au.asks.filter(Ru=>Ru!==lo.id)}}case"state":return{...Au,state:applyPatch$1(Au.state,lo.body)};case"meta":return{...Au,meta:{...Au.meta,...lo.body}};case"window":return Au;default:throw new Error(`Unknown reactor.ui op '${lo.op}'`)}}const AGUI_NAME="reactor.ui",UI_FILE_SCOPE_HEADER="X-Reactor-Scope",UI_FILE_NAME_HEADER="X-Reactor-File-Name";class UiFileRefused extends Error{status;constructor(lo,$u){super($u),this.status=lo,this.name="UiFileRefused"}}async function uploadFile(Au,lo){const $u=await(lo.fetcher??fetch)(lo.url,{method:"POST",headers:{"Content-Type":Au.type||"application/octet-stream",[UI_FILE_SCOPE_HEADER]:lo.scope,[UI_FILE_NAME_HEADER]:encodeURIComponent(Au.name),...lo.token?{Authorization:`Bearer ${lo.token}`}:{}},body:Au});if(!$u.ok){let Iu="";try{const Pu=await $u.json();Iu=typeof Pu.detail=="string"?Pu.detail:""}catch{}throw new UiFileRefused($u.status,Iu||`${Au.name} was refused (${$u.status}).`)}const Ru=await $u.json();if(typeof Ru.ref!="string"||typeof Ru.name!="string"||typeof Ru.media_type!="string")throw new UiFileRefused($u.status,`The host kept ${Au.name} under no ref.`);return Ru}function isFileRef(Au){const lo=Au;return typeof lo=="object"&&lo!==null&&typeof lo.ref=="string"&&typeof lo.name=="string"&&typeof lo.media_type=="string"}const UI_WS_PROTOCOL="reactor.ui.v1",UI_WS_CLOSE={refused:4400,unauthorized:4401,forbidden:4403,timeout:4408,gone:4410};class UiSocketStopped extends Error{status;reason;constructor(lo,$u){super(`reactor.ui socket ${lo}: ${$u}`),this.status=lo,this.reason=$u}}const FINAL_CLOSES={[UI_WS_CLOSE.refused]:"refused",[UI_WS_CLOSE.unauthorized]:"refused",[UI_WS_CLOSE.forbidden]:"refused",[UI_WS_CLOSE.gone]:"gone"};function randomId(){const Au=globalThis.crypto;return Au?.randomUUID?Au.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}class UiSocket{lastSeq;status="connecting";ws=null;welcomed=!1;historyUpTo=0;resumable;stopped=!1;attempt=0;heard=0;beat=null;retry=null;pending=new Map;options;constructor(lo){this.options={heartbeatMs:2e4,timeoutMs:6e4,backoffMs:[250,1e3,2e3,5e3],maxPending:64,newId:randomId,...lo},this.lastSeq=lo.since??0,this.resumable=lo.since!==void 0}connect(){if(this.stopped||this.ws)return;this.setStatus(this.attempt===0&&!this.resumable?"connecting":"reconnecting");const $u=(this.options.open??((Ru,Iu)=>new globalThis.WebSocket(Ru,Iu)))(this.options.url,[UI_WS_PROTOCOL]);this.ws=$u,this.welcomed=!1,$u.onopen=()=>{this.hello($u)},$u.onmessage=Ru=>this.receive($u,Ru.data),$u.onclose=Ru=>this.closed($u,Ru.code,Ru.reason),$u.onerror=()=>{}}act(lo){const $u={...lo,idempotency_id:lo.idempotency_id??this.options.newId()};return this.request({t:"action",ref:this.options.newId(),action:$u})}state(lo){return this.request({t:"state",ref:this.options.newId(),body:lo})}close(){this.stop("closed","closed by the page",1e3)}request(lo){return this.stopped?Promise.reject(new UiSocketStopped(this.status,"the socket is stopped")):this.pending.size>=this.options.maxPending?Promise.reject(new Error(`${this.pending.size} presses are waiting for their result`)):new Promise(($u,Ru)=>{this.pending.set(lo.ref,{frame:lo,resolve:$u,reject:Ru}),this.welcomed&&this.send(lo)})}async hello(lo){let $u;try{$u=await this.options.token()}catch(Ru){this.stop("refused",`no credential: ${String(Ru)}`,1e3);return}lo===this.ws&&(this.heard=Date.now(),this.send({t:"hello",v:UI_WIRE_VERSION,token:$u,scope:this.options.scope,since:this.resumable?this.lastSeq:null}),this.beat=setInterval(()=>this.heartbeat(lo),this.options.heartbeatMs))}heartbeat(lo){if(lo===this.ws){if(Date.now()-this.heard>this.options.timeoutMs){lo.close(UI_WS_CLOSE.timeout,"nothing heard"),this.closed(lo,UI_WS_CLOSE.timeout,"nothing heard");return}this.send({t:"ping"})}}receive(lo,$u){if(lo!==this.ws)return;let Ru;try{Ru=typeof $u=="string"?JSON.parse($u):void 0}catch{Ru=void 0}if(!isDownFrame(Ru)){this.stop("refused","the host sent a frame that is not the schema’s",UI_WS_CLOSE.refused);return}this.heard=Date.now(),this.handle(lo,Ru)}handle(lo,$u){switch($u.t){case"welcome":if($u.scope!==this.options.scope){this.stop("refused",`welcomed to ${$u.scope}, not ${this.options.scope}`,UI_WS_CLOSE.refused);return}if(this.resumable&&$u.seq<this.lastSeq){this.stop("gone",`the host is at op ${$u.seq}, the page at ${this.lastSeq}`,1e3);return}this.resumable||(this.historyUpTo=$u.seq),this.welcomed=!0,this.attempt=0,this.setStatus("open");for(const Ru of this.pending.values())this.send(Ru.frame);return;case"op":if(!this.welcomed){this.stop("refused","an op before the welcome",UI_WS_CLOSE.refused);return}if($u.seq<=this.lastSeq)return;if($u.seq!==this.lastSeq+1){lo.close(1e3,`op ${$u.seq} after ${this.lastSeq}`),this.closed(lo,1e3,"a gap");return}this.lastSeq=$u.seq,this.resumable=!0,this.options.onOp($u.op,$u.seq,$u.seq<=this.historyUpTo);return;case"result":{const Ru=this.pending.get($u.ref);Ru&&(this.pending.delete($u.ref),Ru.resolve({ok:$u.ok,status:$u.status,detail:$u.detail,value:$u.value}));return}case"ping":this.send({t:"pong"});return;case"pong":return}}closed(lo,$u,Ru){if(lo!==this.ws||(this.ws=null,this.welcomed=!1,this.clearBeat(),this.stopped))return;const Iu=FINAL_CLOSES[$u];if(Iu){this.stop(Iu,Ru||`closed with ${$u}`);return}this.resumable=this.resumable||this.lastSeq>0;const Pu=this.options.backoffMs,Ou=Pu[Math.min(this.attempt,Pu.length-1)]??1e3;this.attempt+=1,this.setStatus("reconnecting",Ru),this.retry=setTimeout(()=>{this.retry=null,this.connect()},Ou)}stop(lo,$u,Ru){if(this.stopped)return;this.stopped=!0,this.clearBeat(),this.retry&&(clearTimeout(this.retry),this.retry=null);const Iu=this.ws;this.ws=null,Iu&&Ru!==void 0&&Iu.close(Ru,$u.slice(0,120));for(const Pu of this.pending.values())Pu.reject(new UiSocketStopped(lo,$u));this.pending.clear(),this.setStatus(lo,$u)}send(lo){this.ws?.send(JSON.stringify(lo))}clearBeat(){this.beat&&(clearInterval(this.beat),this.beat=null)}setStatus(lo,$u){this.status=lo,this.options.onStatus?.(lo,$u)}}var lib$b={},basemanager={},serverconnection={},serialize$3={},messages$1={},hasRequiredMessages;function requireMessages(){if(hasRequiredMessages)return messages$1;hasRequiredMessages=1,Object.defineProperty(messages$1,"__esModule",{value:!0}),messages$1.supportedKernelWebSocketProtocols=void 0,messages$1.createMessage=lo,messages$1.isStreamMsg=$u,messages$1.isDisplayDataMsg=Ru,messages$1.isUpdateDisplayDataMsg=Iu,messages$1.isExecuteInputMsg=Pu,messages$1.isExecuteResultMsg=Ou,messages$1.isErrorMsg=Mu,messages$1.isStatusMsg=Du,messages$1.isClearOutputMsg=Lu,messages$1.isDebugEventMsg=Bu,messages$1.isCommOpenMsg=ju,messages$1.isCommCloseMsg=Fu,messages$1.isCommMsgMsg=zu,messages$1.isInfoRequestMsg=Uu,messages$1.isExecuteReplyMsg=Hu,messages$1.isDebugRequestMsg=Vu,messages$1.isDebugReplyMsg=Gu,messages$1.isInputRequestMsg=Wu,messages$1.isInputReplyMsg=Zu;const Au=requireDist();function lo(Yu){var Xu,ed,td,nd,od,sd;return{buffers:(Xu=Yu.buffers)!==null&&Xu!==void 0?Xu:[],channel:Yu.channel,content:Yu.content,header:{date:new Date().toISOString(),msg_id:(ed=Yu.msgId)!==null&&ed!==void 0?ed:Au.UUID.uuid4(),msg_type:Yu.msgType,session:Yu.session,username:(td=Yu.username)!==null&&td!==void 0?td:"",subshell_id:(nd=Yu.subshellId)!==null&&nd!==void 0?nd:null,version:"5.2"},metadata:(od=Yu.metadata)!==null&&od!==void 0?od:{},parent_header:(sd=Yu.parentHeader)!==null&&sd!==void 0?sd:{}}}function $u(Yu){return Yu.header.msg_type==="stream"}function Ru(Yu){return Yu.header.msg_type==="display_data"}function Iu(Yu){return Yu.header.msg_type==="update_display_data"}function Pu(Yu){return Yu.header.msg_type==="execute_input"}function Ou(Yu){return Yu.header.msg_type==="execute_result"}function Mu(Yu){return Yu.header.msg_type==="error"}function Du(Yu){return Yu.header.msg_type==="status"}function Lu(Yu){return Yu.header.msg_type==="clear_output"}function Bu(Yu){return Yu.header.msg_type==="debug_event"}function ju(Yu){return Yu.header.msg_type==="comm_open"}function Fu(Yu){return Yu.header.msg_type==="comm_close"}function zu(Yu){return Yu.header.msg_type==="comm_msg"}function Uu(Yu){return Yu.header.msg_type==="kernel_info_request"}function Hu(Yu){return Yu.header.msg_type==="execute_reply"}function Vu(Yu){return Yu.header.msg_type==="debug_request"}function Gu(Yu){return Yu.header.msg_type==="debug_reply"}function Wu(Yu){return Yu.header.msg_type==="input_request"}function Zu(Yu){return Yu.header.msg_type==="input_reply"}var Ju;return(function(Yu){Yu.v1KernelWebsocketJupyterOrg="v1.kernel.websocket.jupyter.org"})(Ju||(messages$1.supportedKernelWebSocketProtocols=Ju={})),messages$1}var hasRequiredSerialize;function requireSerialize(){if(hasRequiredSerialize)return serialize$3;hasRequiredSerialize=1;var Au=serialize$3&&serialize$3.__createBinding||(Object.create?(function(Mu,Du,Lu,Bu){Bu===void 0&&(Bu=Lu);var ju=Object.getOwnPropertyDescriptor(Du,Lu);(!ju||("get"in ju?!Du.__esModule:ju.writable||ju.configurable))&&(ju={enumerable:!0,get:function(){return Du[Lu]}}),Object.defineProperty(Mu,Bu,ju)}):(function(Mu,Du,Lu,Bu){Bu===void 0&&(Bu=Lu),Mu[Bu]=Du[Lu]})),lo=serialize$3&&serialize$3.__setModuleDefault||(Object.create?(function(Mu,Du){Object.defineProperty(Mu,"default",{enumerable:!0,value:Du})}):function(Mu,Du){Mu.default=Du}),$u=serialize$3&&serialize$3.__importStar||(function(){var Mu=function(Du){return Mu=Object.getOwnPropertyNames||function(Lu){var Bu=[];for(var ju in Lu)Object.prototype.hasOwnProperty.call(Lu,ju)&&(Bu[Bu.length]=ju);return Bu},Mu(Du)};return function(Du){if(Du&&Du.__esModule)return Du;var Lu={};if(Du!=null)for(var Bu=Mu(Du),ju=0;ju<Bu.length;ju++)Bu[ju]!=="default"&&Au(Lu,Du,Bu[ju]);return lo(Lu,Du),Lu}})();Object.defineProperty(serialize$3,"__esModule",{value:!0}),serialize$3.serialize=Iu,serialize$3.deserialize=Pu;const Ru=$u(requireMessages());function Iu(Mu,Du=""){return Du===Ru.supportedKernelWebSocketProtocols.v1KernelWebsocketJupyterOrg?Ou.serializeV1KernelWebsocketJupyterOrg(Mu):Ou.serializeDefault(Mu)}function Pu(Mu,Du=""){return Du===Ru.supportedKernelWebSocketProtocols.v1KernelWebsocketJupyterOrg?Ou.deserializeV1KernelWebsocketJupyterOrg(Mu):Ou.deserializeDefault(Mu)}var Ou;return(function(Mu){function Du(Uu){let Hu;const Vu=new DataView(Uu),Gu=Number(Vu.getBigUint64(0,!0));let Wu=[];for(let od=0;od<Gu;od++)Wu.push(Number(Vu.getBigUint64(8*(od+1),!0)));const Zu=new TextDecoder("utf8"),Ju=Zu.decode(Uu.slice(Wu[0],Wu[1])),Yu=JSON.parse(Zu.decode(Uu.slice(Wu[1],Wu[2]))),Xu=JSON.parse(Zu.decode(Uu.slice(Wu[2],Wu[3]))),ed=JSON.parse(Zu.decode(Uu.slice(Wu[3],Wu[4]))),td=JSON.parse(Zu.decode(Uu.slice(Wu[4],Wu[5])));let nd=[];for(let od=5;od<Wu.length-1;od++)nd.push(new DataView(Uu.slice(Wu[od],Wu[od+1])));return Hu={channel:Ju,header:Yu,parent_header:Xu,metadata:ed,content:td,buffers:nd},Hu}Mu.deserializeV1KernelWebsocketJupyterOrg=Du;function Lu(Uu){const Hu=JSON.stringify(Uu.header),Vu=Uu.parent_header==null?"{}":JSON.stringify(Uu.parent_header),Gu=JSON.stringify(Uu.metadata),Wu=JSON.stringify(Uu.content),Zu=Uu.buffers!==void 0?Uu.buffers:[],Ju=5+Zu.length+1;let Yu=[];Yu.push(8*(1+Ju)),Yu.push(Uu.channel.length+Yu[Yu.length-1]);const Xu=new TextEncoder,ed=Xu.encode(Uu.channel),td=Xu.encode(Hu),nd=Xu.encode(Vu),od=Xu.encode(Gu),sd=Xu.encode(Wu),ad=new Uint8Array(ed.length+td.length+nd.length+od.length+sd.length);ad.set(ed),ad.set(td,ed.length),ad.set(nd,ed.length+td.length),ad.set(od,ed.length+td.length+nd.length),ad.set(sd,ed.length+td.length+nd.length+od.length);for(let bd of[td.length,nd.length,od.length,sd.length])Yu.push(bd+Yu[Yu.length-1]);let pd=0;for(let bd of Zu){let wd=bd.byteLength;Yu.push(wd+Yu[Yu.length-1]),pd+=wd}const vd=new Uint8Array(8*(1+Ju)+ad.byteLength+pd),Sd=new ArrayBuffer(8),_d=new DataView(Sd);_d.setBigUint64(0,BigInt(Ju),!0),vd.set(new Uint8Array(Sd),0);for(let bd=0;bd<Yu.length;bd++)_d.setBigUint64(0,BigInt(Yu[bd]),!0),vd.set(new Uint8Array(Sd),8*(bd+1));vd.set(ad,Yu[0]);for(let bd=0;bd<Zu.length;bd++){const wd=Zu[bd];vd.set(new Uint8Array(ArrayBuffer.isView(wd)?wd.buffer:wd),Yu[5+bd])}return vd.buffer}Mu.serializeV1KernelWebsocketJupyterOrg=Lu;function Bu(Uu){let Hu;return typeof Uu=="string"?Hu=JSON.parse(Uu):Hu=Fu(Uu),Hu}Mu.deserializeDefault=Bu;function ju(Uu){var Hu;let Vu;return!((Hu=Uu.buffers)===null||Hu===void 0)&&Hu.length?Vu=zu(Uu):Vu=JSON.stringify(Uu),Vu}Mu.serializeDefault=ju;function Fu(Uu){const Hu=new DataView(Uu),Vu=Hu.getUint32(0),Gu=[];if(Vu<2)throw new Error("Invalid incoming Kernel Message");for(let Ju=1;Ju<=Vu;Ju++)Gu.push(Hu.getUint32(Ju*4));const Wu=new Uint8Array(Uu.slice(Gu[0],Gu[1])),Zu=JSON.parse(new TextDecoder("utf8").decode(Wu));Zu.buffers=[];for(let Ju=1;Ju<Vu;Ju++){const Yu=Gu[Ju],Xu=Gu[Ju+1]||Uu.byteLength;Zu.buffers.push(new DataView(Uu.slice(Yu,Xu)))}return Zu}function zu(Uu){const Hu=[],Vu=[],Gu=new TextEncoder;let Wu=[];Uu.buffers!==void 0&&(Wu=Uu.buffers,delete Uu.buffers);const Zu=Gu.encode(JSON.stringify(Uu));Vu.push(Zu.buffer);for(let ed=0;ed<Wu.length;ed++){const td=Wu[ed];Vu.push(ArrayBuffer.isView(td)?td.buffer:td)}const Ju=Vu.length;Hu.push(4*(Ju+1));for(let ed=0;ed+1<Vu.length;ed++)Hu.push(Hu[Hu.length-1]+Vu[ed].byteLength);const Yu=new Uint8Array(Hu[Hu.length-1]+Vu[Vu.length-1].byteLength),Xu=new DataView(Yu.buffer);Xu.setUint32(0,Ju);for(let ed=0;ed<Hu.length;ed++)Xu.setUint32(4*(ed+1),Hu[ed]);for(let ed=0;ed<Vu.length;ed++)Yu.set(new Uint8Array(Vu[ed]),Hu[ed]);return Yu.buffer}})(Ou||(Ou={})),serialize$3}var ws$1={},hasRequiredWs;function requireWs(){return hasRequiredWs||(hasRequiredWs=1,Object.defineProperty(ws$1,"__esModule",{value:!0}),ws$1.default=WebSocket),ws$1}var hasRequiredServerconnection;function requireServerconnection(){if(hasRequiredServerconnection)return serverconnection;hasRequiredServerconnection=1;var Au={};Object.defineProperty(serverconnection,"__esModule",{value:!0}),serverconnection.ServerConnection=void 0;const lo=requireLib$b(),$u=requireSerialize();let Ru;typeof window>"u"?Ru=requireWs():Ru=WebSocket;var Iu;(function(Ou){function Mu(ju){return Pu.makeSettings(ju)}Ou.makeSettings=Mu;function Du(ju,Fu,zu){return Pu.handleRequest(ju,Fu,zu)}Ou.makeRequest=Du;class Lu extends Error{static async create(Fu){try{const zu=await Fu.json(),{message:Uu,traceback:Hu}=zu;return Hu&&console.error(Hu),new Lu(Fu,Uu??Lu._defaultMessage(Fu),Hu??"")}catch(zu){return console.debug(zu),new Lu(Fu)}}constructor(Fu,zu=Lu._defaultMessage(Fu),Uu=""){super(zu),this.response=Fu,this.traceback=Uu}static _defaultMessage(Fu){return`Invalid response: ${Fu.status} ${Fu.statusText}`}}Ou.ResponseError=Lu;class Bu extends TypeError{constructor(Fu){super(Fu.message),this.stack=Fu.stack}}Ou.NetworkError=Bu})(Iu||(serverconnection.ServerConnection=Iu={}));var Pu;return(function(Ou){function Mu(Bu={}){var ju;const Fu=lo.PageConfig.getBaseUrl(),zu=lo.PageConfig.getWsUrl(),Uu=lo.URLExt.normalize(Bu.baseUrl)||Fu;let Hu=Bu.wsUrl;!Hu&&Uu===Fu&&(Hu=zu),!Hu&&Uu.indexOf("http")===0&&(Hu="ws"+Uu.slice(4)),Hu=Hu??zu;const Vu=lo.PageConfig.getOption("appendToken").toLowerCase();let Gu;return Vu===""?Gu=typeof window>"u"||typeof process<"u"&&((ju=process==null?void 0:Au)===null||ju===void 0?void 0:ju.JEST_WORKER_ID)!==void 0||lo.URLExt.getHostName(Fu)!==lo.URLExt.getHostName(Hu):Gu=Vu==="true",{init:{cache:"no-store",credentials:"same-origin"},fetch,Headers,Request,WebSocket:Ru,token:lo.PageConfig.getToken(),appUrl:lo.PageConfig.getOption("appUrl"),appendToken:Gu,serializer:{serialize:$u.serialize,deserialize:$u.deserialize},...Bu,baseUrl:Uu,wsUrl:Hu}}Ou.makeSettings=Mu;function Du(Bu,ju,Fu){var zu;if(Bu.indexOf(Fu.baseUrl)!==0)throw new Error("Can only be used for notebook server requests");((zu=ju.cache)!==null&&zu!==void 0?zu:Fu.init.cache)==="no-store"&&(Bu+=(/\?/.test(Bu)?"&":"?")+new Date().getTime());const Hu=new Fu.Request(Bu,{...Fu.init,...ju});let Vu=!1;if(Fu.token&&(Vu=!0,Hu.headers.append("Authorization",`token ${Fu.token}`)),typeof document<"u"){const Gu=Lu("_xsrf");Gu!==void 0&&(Vu=!0,Hu.headers.append("X-XSRFToken",Gu))}return!Hu.headers.has("Content-Type")&&Vu&&Hu.headers.set("Content-Type","application/json"),Fu.fetch.call(null,Hu).catch(Gu=>{throw new Iu.NetworkError(Gu)})}Ou.handleRequest=Du;function Lu(Bu){let ju="";try{ju=document.cookie}catch{return}const Fu=Bu+"=";let zu;for(const Uu of ju.split(";")){const Hu=Uu.trim();Hu.startsWith(Fu)&&(zu=Hu.substring(Fu.length))}return zu}})(Pu||(Pu={})),serverconnection}var hasRequiredBasemanager;function requireBasemanager(){if(hasRequiredBasemanager)return basemanager;hasRequiredBasemanager=1,Object.defineProperty(basemanager,"__esModule",{value:!0}),basemanager.BaseManager=void 0;const Au=require$$0$2,lo=requireServerconnection();class $u{constructor(Iu){var Pu;this._isDisposed=!1,this._disposed=new Au.Signal(this),this.serverSettings=(Pu=Iu.serverSettings)!==null&&Pu!==void 0?Pu:lo.ServerConnection.makeSettings()}get disposed(){return this._disposed}get isDisposed(){return this._isDisposed}get isActive(){return!0}dispose(){this.isDisposed||(this._isDisposed=!0,this._disposed.emit(void 0),Au.Signal.clearData(this))}}return basemanager.BaseManager=$u,basemanager}var config$4={},hasRequiredConfig;function requireConfig(){if(hasRequiredConfig)return config$4;hasRequiredConfig=1,Object.defineProperty(config$4,"__esModule",{value:!0}),config$4.ConfigWithDefaults=config$4.ConfigSection=config$4.ConfigSectionManager=void 0;const Au=requireLib$b(),lo=requireLib$8(),$u="api/config";class Ru{constructor(Du){var Lu;this.serverSettings=(Lu=Du.serverSettings)!==null&&Lu!==void 0?Lu:lo.ServerConnection.makeSettings()}async create(Du){const Lu=new Pu({...Du,serverSettings:this.serverSettings});return await Lu.load(),Lu}}config$4.ConfigSectionManager=Ru;var Iu;(function(Mu){async function Du(ju){if(!Lu){const zu=new Pu(ju);return await zu.load(),zu}return await Lu.create(ju)}Mu.create=Du;let Lu;function Bu(ju){if(Lu)throw new Error("ConfigSectionManager already set. If you would like to create a config section, use the `IConfigSectionManager` token in a plugin.");Lu=ju}Mu._setConfigSectionManager=Bu})(Iu||(config$4.ConfigSection=Iu={}));class Pu{constructor(Du){var Lu;this.serverSettings=(Lu=Du.serverSettings)!==null&&Lu!==void 0?Lu:lo.ServerConnection.makeSettings(),this._name=Du.name}get data(){return this._data}async load(){const Du=await lo.ServerConnection.makeRequest(this._url,{},this.serverSettings);if(Du.status!==200)throw await lo.ServerConnection.ResponseError.create(Du);this._data=await Du.json()}async update(Du){this._data={...this._data,...Du};const Lu={method:"PATCH",body:JSON.stringify(Du)},Bu=await lo.ServerConnection.makeRequest(this._url,Lu,this.serverSettings);if(Bu.status!==200)throw await lo.ServerConnection.ResponseError.create(Bu);return this._data=await Bu.json(),this._data}get _url(){return Au.URLExt.join(this.serverSettings.baseUrl,$u,encodeURIComponent(this._name))}}class Ou{constructor(Du){var Lu,Bu;this._className="",this._section=Du.section,this._defaults=(Lu=Du.defaults)!==null&&Lu!==void 0?Lu:{},this._className=(Bu=Du.className)!==null&&Bu!==void 0?Bu:""}get(Du){const Lu=this._classData();return Du in Lu?Lu[Du]:this._defaults[Du]}set(Du,Lu){const Bu={};if(Bu[Du]=Lu,this._className){const ju={};return ju[this._className]=Bu,this._section.update(ju)}else return this._section.update(Bu)}_classData(){const Du=this._section.data;return this._className&&this._className in Du?Du[this._className]:Du}}return config$4.ConfigWithDefaults=Ou,config$4}var connectionstatus={},hasRequiredConnectionstatus;function requireConnectionstatus(){if(hasRequiredConnectionstatus)return connectionstatus;hasRequiredConnectionstatus=1,Object.defineProperty(connectionstatus,"__esModule",{value:!0}),connectionstatus.ConnectionStatus=void 0;class Au{constructor(){this.isConnected=!0}}return connectionstatus.ConnectionStatus=Au,connectionstatus}var contents={};class DisposableDelegate{constructor(lo){this._fn=lo}get isDisposed(){return!this._fn}dispose(){if(!this._fn)return;let lo=this._fn;this._fn=null,lo()}}class ObservableDisposableDelegate extends DisposableDelegate{constructor(){super(...arguments),this._disposed=new Signal(this)}get disposed(){return this._disposed}dispose(){this.isDisposed||(super.dispose(),this._disposed.emit(void 0),Signal.clearData(this))}}class DisposableSet{constructor(){this._isDisposed=!1,this._items=new Set}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,this._items.forEach(lo=>{lo.dispose()}),this._items.clear())}contains(lo){return this._items.has(lo)}add(lo){this._items.add(lo)}remove(lo){this._items.delete(lo)}clear(){this._items.clear()}}(function(Au){function lo($u){let Ru=new Au;for(const Iu of $u)Ru.add(Iu);return Ru}Au.from=lo})(DisposableSet||(DisposableSet={}));class ObservableDisposableSet extends DisposableSet{constructor(){super(...arguments),this._disposed=new Signal(this)}get disposed(){return this._disposed}dispose(){this.isDisposed||(super.dispose(),this._disposed.emit(void 0),Signal.clearData(this))}}(function(Au){function lo($u){let Ru=new Au;for(const Iu of $u)Ru.add(Iu);return Ru}Au.from=lo})(ObservableDisposableSet||(ObservableDisposableSet={}));const index_es6$1=Object.freeze(Object.defineProperty({__proto__:null,DisposableDelegate,get DisposableSet(){return DisposableSet},ObservableDisposableDelegate,get ObservableDisposableSet(){return ObservableDisposableSet}},Symbol.toStringTag,{value:"Module"})),require$$1$2=getAugmentedNamespace(index_es6$1);var validate$7={},validate$6={},hasRequiredValidate$5;function requireValidate$5(){if(hasRequiredValidate$5)return validate$6;hasRequiredValidate$5=1,Object.defineProperty(validate$6,"__esModule",{value:!0}),validate$6.validateProperty=Au;function Au(lo,$u,Ru,Iu=[]){if(!lo.hasOwnProperty($u))throw Error(`Missing property '${$u}'`);const Pu=lo[$u];if(Ru!==void 0){let Ou;switch(Ru){case"array":Ou=Array.isArray(Pu);break;case"object":Ou=typeof Pu<"u";break;default:Ou=typeof Pu===Ru}if(!Ou)throw new Error(`Property '${$u}' is not of type '${Ru}'`);if(Iu.length>0){let Mu;switch(Ru){case"string":case"number":case"boolean":Mu=Iu.includes(Pu);break;default:Mu=Iu.findIndex(Du=>Du===Pu)>=0;break}if(!Mu)throw new Error(`Property '${$u}' is not one of the valid values ${JSON.stringify(Iu)}`)}}}return validate$6}var hasRequiredValidate$4;function requireValidate$4(){if(hasRequiredValidate$4)return validate$7;hasRequiredValidate$4=1,Object.defineProperty(validate$7,"__esModule",{value:!0}),validate$7.validateContentsModel=lo,validate$7.validateCheckpointModel=$u;const Au=requireValidate$5();function lo(Ru){(0,Au.validateProperty)(Ru,"name","string"),(0,Au.validateProperty)(Ru,"path","string"),(0,Au.validateProperty)(Ru,"type","string"),(0,Au.validateProperty)(Ru,"created","string"),(0,Au.validateProperty)(Ru,"last_modified","string"),(0,Au.validateProperty)(Ru,"mimetype","object"),(0,Au.validateProperty)(Ru,"content","object"),(0,Au.validateProperty)(Ru,"format","object")}function $u(Ru){(0,Au.validateProperty)(Ru,"id","string"),(0,Au.validateProperty)(Ru,"last_modified","string")}return validate$7}var hasRequiredContents;function requireContents(){if(hasRequiredContents)return contents;hasRequiredContents=1;var Au=contents&&contents.__createBinding||(Object.create?(function(Gu,Wu,Zu,Ju){Ju===void 0&&(Ju=Zu);var Yu=Object.getOwnPropertyDescriptor(Wu,Zu);(!Yu||("get"in Yu?!Wu.__esModule:Yu.writable||Yu.configurable))&&(Yu={enumerable:!0,get:function(){return Wu[Zu]}}),Object.defineProperty(Gu,Ju,Yu)}):(function(Gu,Wu,Zu,Ju){Ju===void 0&&(Ju=Zu),Gu[Ju]=Wu[Zu]})),lo=contents&&contents.__setModuleDefault||(Object.create?(function(Gu,Wu){Object.defineProperty(Gu,"default",{enumerable:!0,value:Wu})}):function(Gu,Wu){Gu.default=Wu}),$u=contents&&contents.__importStar||(function(){var Gu=function(Wu){return Gu=Object.getOwnPropertyNames||function(Zu){var Ju=[];for(var Yu in Zu)Object.prototype.hasOwnProperty.call(Zu,Yu)&&(Ju[Ju.length]=Yu);return Ju},Gu(Wu)};return function(Wu){if(Wu&&Wu.__esModule)return Wu;var Zu={};if(Wu!=null)for(var Ju=Gu(Wu),Yu=0;Yu<Ju.length;Yu++)Ju[Yu]!=="default"&&Au(Zu,Wu,Ju[Yu]);return lo(Zu,Wu),Zu}})();Object.defineProperty(contents,"__esModule",{value:!0}),contents.RestContentProvider=contents.ContentProviderRegistry=contents.Drive=contents.ContentsManager=contents.Contents=void 0;const Ru=requireLib$b(),Iu=requireDist(),Pu=require$$1$2,Ou=require$$0$2,Mu=requireLib$8(),Du=$u(requireValidate$4()),Lu="api/contents",Bu="files";var ju;(function(Gu){function Wu(Ju){Du.validateContentsModel(Ju)}Gu.validateContentsModel=Wu;function Zu(Ju){Du.validateCheckpointModel(Ju)}Gu.validateCheckpointModel=Zu})(ju||(contents.Contents=ju={}));class Fu{constructor(Wu={}){var Zu,Ju;this._isDisposed=!1,this._additionalDrives=new Map,this._fileChanged=new Ou.Signal(this);const Yu=this.serverSettings=(Zu=Wu.serverSettings)!==null&&Zu!==void 0?Zu:Mu.ServerConnection.makeSettings();this._defaultDrive=(Ju=Wu.defaultDrive)!==null&&Ju!==void 0?Ju:new zu({serverSettings:Yu}),this._defaultDrive.fileChanged.connect(this._onFileChanged,this)}get defaultDrive(){return this._defaultDrive}get fileChanged(){return this._fileChanged}get isDisposed(){return this._isDisposed}dispose(){this.isDisposed||(this._isDisposed=!0,Ou.Signal.clearData(this))}addDrive(Wu){this._additionalDrives.set(Wu.name,Wu),Wu.fileChanged.connect(this._onFileChanged,this)}getSharedModelFactory(Wu,Zu){var Ju,Yu;const[Xu]=this._driveForPath(Wu),ed=(Ju=Xu.contentProviderRegistry)===null||Ju===void 0?void 0:Ju.getProvider(Zu?.contentProviderId);return ed?.sharedModelFactory?ed.sharedModelFactory:(Yu=Xu.sharedModelFactory)!==null&&Yu!==void 0?Yu:null}localPath(Wu){const Zu=Wu.split("/"),Ju=Zu[0].split(":");return Ju.length===1||!this._additionalDrives.has(Ju[0])?Ru.PathExt.removeSlash(Wu):Ru.PathExt.join(Ju.slice(1).join(":"),...Zu.slice(1))}normalize(Wu){const Zu=Wu.split(":");return Zu.length===1?Ru.PathExt.normalize(Wu):`${Zu[0]}:${Ru.PathExt.normalize(Zu.slice(1).join(":"))}`}resolvePath(Wu,Zu){const Ju=this.driveName(Wu),Yu=this.localPath(Wu),Xu=Ru.PathExt.resolve("/",Yu,Zu);return Ju?`${Ju}:${Xu}`:Xu}driveName(Wu){const Ju=Wu.split("/")[0].split(":");return Ju.length===1?"":this._additionalDrives.has(Ju[0])?Ju[0]:""}get(Wu,Zu){const[Ju,Yu]=this._driveForPath(Wu);return Ju.get(Yu,Zu).then(Xu=>{const ed=[];if(Xu.type==="directory"&&Xu.content){for(const td of Xu.content)ed.push({...td,path:this._toGlobalPath(Ju,td.path)});return{...Xu,path:this._toGlobalPath(Ju,Yu),content:ed,serverPath:Xu.path}}else return{...Xu,path:this._toGlobalPath(Ju,Yu),serverPath:Xu.path}})}getDownloadUrl(Wu){const[Zu,Ju]=this._driveForPath(Wu);return Zu.getDownloadUrl(Ju)}newUntitled(Wu={}){if(Wu.path){const Zu=this.normalize(Wu.path),[Ju,Yu]=this._driveForPath(Zu);return Ju.newUntitled({...Wu,path:Yu}).then(Xu=>({...Xu,path:Ru.PathExt.join(Zu,Xu.name),serverPath:Xu.path}))}else return this._defaultDrive.newUntitled(Wu)}delete(Wu){const[Zu,Ju]=this._driveForPath(Wu);return Zu.delete(Ju)}rename(Wu,Zu){const[Ju,Yu]=this._driveForPath(Wu),[Xu,ed]=this._driveForPath(Zu);if(Ju!==Xu)throw Error("ContentsManager: renaming files must occur within a Drive");return Ju.rename(Yu,ed).then(td=>({...td,path:this._toGlobalPath(Ju,ed),serverPath:td.path}))}async overwrite(Wu,Zu){const Ju=`${Zu}.${Iu.UUID.uuid4()}`;return await this.rename(Wu,Ju),await this.delete(Zu),await this.rename(Ju,Zu)}save(Wu,Zu={}){const Ju=this.normalize(Wu),[Yu,Xu]=this._driveForPath(Wu);return Yu.save(Xu,{...Zu,path:Xu}).then(ed=>({...ed,path:Ju,serverPath:ed.path}))}copy(Wu,Zu){const[Ju,Yu]=this._driveForPath(Wu),[Xu,ed]=this._driveForPath(Zu);if(Ju===Xu)return Ju.copy(Yu,ed).then(td=>({...td,path:this._toGlobalPath(Ju,td.path),serverPath:td.path}));throw Error("Copying files between drives is not currently implemented")}createCheckpoint(Wu){const[Zu,Ju]=this._driveForPath(Wu);return Zu.createCheckpoint(Ju)}listCheckpoints(Wu){const[Zu,Ju]=this._driveForPath(Wu);return Zu.listCheckpoints(Ju)}restoreCheckpoint(Wu,Zu){const[Ju,Yu]=this._driveForPath(Wu);return Ju.restoreCheckpoint(Yu,Zu)}deleteCheckpoint(Wu,Zu){const[Ju,Yu]=this._driveForPath(Wu);return Ju.deleteCheckpoint(Yu,Zu)}_toGlobalPath(Wu,Zu){return Wu===this._defaultDrive?Ru.PathExt.removeSlash(Zu):`${Wu.name}:${Ru.PathExt.removeSlash(Zu)}`}_driveForPath(Wu){const Zu=this.driveName(Wu),Ju=this.localPath(Wu);return Zu?[this._additionalDrives.get(Zu),Ju]:[this._defaultDrive,Ju]}_onFileChanged(Wu,Zu){var Ju,Yu;if(Wu===this._defaultDrive)this._fileChanged.emit(Zu);else{let Xu=null,ed=null;!((Ju=Zu.newValue)===null||Ju===void 0)&&Ju.path&&(Xu={...Zu.newValue,path:this._toGlobalPath(Wu,Zu.newValue.path)}),!((Yu=Zu.oldValue)===null||Yu===void 0)&&Yu.path&&(ed={...Zu.oldValue,path:this._toGlobalPath(Wu,Zu.oldValue.path)}),this._fileChanged.emit({type:Zu.type,newValue:Xu,oldValue:ed})}}}contents.ContentsManager=Fu;class zu{constructor(Wu={}){var Zu,Ju,Yu;this._isDisposed=!1,this._fileChanged=new Ou.Signal(this),this.name=(Zu=Wu.name)!==null&&Zu!==void 0?Zu:"Default",this._apiEndpoint=(Ju=Wu.apiEndpoint)!==null&&Ju!==void 0?Ju:Lu,this.serverSettings=(Yu=Wu.serverSettings)!==null&&Yu!==void 0?Yu:Mu.ServerConnection.makeSettings(),this._restContentProvider=new Vu({...Wu,apiEndpoint:this._apiEndpoint,serverSettings:this.serverSettings}),Wu.defaultContentProvider?this.contentProviderRegistry=new Hu({defaultProvider:Wu.defaultContentProvider}):this.contentProviderRegistry=new Hu,this.contentProviderRegistry.fileChanged.connect((Xu,ed)=>{this._fileChanged.emit(ed)})}get fileChanged(){return this._fileChanged}get isDisposed(){return this._isDisposed}dispose(){this.isDisposed||(this._isDisposed=!0,Ou.Signal.clearData(this))}async get(Wu,Zu){const Ju=this.contentProviderRegistry.getProvider(Zu?.contentProviderId);return Ju?Ju.get(Wu,Zu):await this._restContentProvider.get(Wu,Zu)}getDownloadUrl(Wu){const Zu=this.serverSettings.baseUrl;let Ju=Ru.URLExt.join(Zu,Bu,Ru.URLExt.encodeParts(Wu)),Yu="";try{Yu=document.cookie}catch{}const Xu=Yu.match("\\b_xsrf=([^;]*)\\b");if(Xu){const ed=new URL(Ju);ed.searchParams.append("_xsrf",Xu[1]),Ju=ed.toString()}return Promise.resolve(Ju)}async newUntitled(Wu={}){var Zu;let Ju="{}";Wu&&(Wu.ext&&(Wu.ext=Uu.normalizeExtension(Wu.ext)),Ju=JSON.stringify(Wu));const Yu=this.serverSettings,Xu=this._getUrl((Zu=Wu.path)!==null&&Zu!==void 0?Zu:""),ed={method:"POST",body:Ju},td=await Mu.ServerConnection.makeRequest(Xu,ed,Yu);if(td.status!==201)throw await Mu.ServerConnection.ResponseError.create(td);const nd=await td.json();return Du.validateContentsModel(nd),this._fileChanged.emit({type:"new",oldValue:null,newValue:nd}),nd}async delete(Wu){const Zu=this._getUrl(Wu),Ju=this.serverSettings,Yu={method:"DELETE"},Xu=await Mu.ServerConnection.makeRequest(Zu,Yu,Ju);if(Xu.status!==204)throw await Mu.ServerConnection.ResponseError.create(Xu);this._fileChanged.emit({type:"delete",oldValue:{path:Wu},newValue:null})}async rename(Wu,Zu){const Ju=this.serverSettings,Yu=this._getUrl(Wu),Xu={method:"PATCH",body:JSON.stringify({path:Zu})},ed=await Mu.ServerConnection.makeRequest(Yu,Xu,Ju);if(ed.status!==200)throw await Mu.ServerConnection.ResponseError.create(ed);const td=await ed.json();return Du.validateContentsModel(td),this._fileChanged.emit({type:"rename",oldValue:{path:Wu},newValue:td}),td}async save(Wu,Zu={}){const Ju=this.contentProviderRegistry.getProvider(Zu?.contentProviderId);let Yu;return Ju?Yu=await Ju.save(Wu,Zu):Yu=await this._restContentProvider.save(Wu,Zu),this._fileChanged.emit({type:"save",oldValue:null,newValue:Yu}),Yu}async copy(Wu,Zu){const Ju=this.serverSettings,Yu=this._getUrl(Zu),Xu={method:"POST",body:JSON.stringify({copy_from:Wu})},ed=await Mu.ServerConnection.makeRequest(Yu,Xu,Ju);if(ed.status!==201)throw await Mu.ServerConnection.ResponseError.create(ed);const td=await ed.json();return Du.validateContentsModel(td),this._fileChanged.emit({type:"new",oldValue:null,newValue:td}),td}async createCheckpoint(Wu){const Zu=this._getUrl(Wu,"checkpoints"),Ju={method:"POST"},Yu=await Mu.ServerConnection.makeRequest(Zu,Ju,this.serverSettings);if(Yu.status!==201)throw await Mu.ServerConnection.ResponseError.create(Yu);const Xu=await Yu.json();return Du.validateCheckpointModel(Xu),Xu}async listCheckpoints(Wu){const Zu=this._getUrl(Wu,"checkpoints"),Ju=await Mu.ServerConnection.makeRequest(Zu,{},this.serverSettings);if(Ju.status!==200)throw await Mu.ServerConnection.ResponseError.create(Ju);const Yu=await Ju.json();if(!Array.isArray(Yu))throw new Error("Invalid Checkpoint list");for(let Xu=0;Xu<Yu.length;Xu++)Du.validateCheckpointModel(Yu[Xu]);return Yu}async restoreCheckpoint(Wu,Zu){const Ju=this._getUrl(Wu,"checkpoints",Zu),Yu={method:"POST"},Xu=await Mu.ServerConnection.makeRequest(Ju,Yu,this.serverSettings);if(Xu.status!==204)throw await Mu.ServerConnection.ResponseError.create(Xu)}async deleteCheckpoint(Wu,Zu){const Ju=this._getUrl(Wu,"checkpoints",Zu),Yu={method:"DELETE"},Xu=await Mu.ServerConnection.makeRequest(Ju,Yu,this.serverSettings);if(Xu.status!==204)throw await Mu.ServerConnection.ResponseError.create(Xu)}_getUrl(...Wu){const Zu=Wu.map(Yu=>Ru.URLExt.encodeParts(Yu)),Ju=this.serverSettings.baseUrl;return Ru.URLExt.join(Ju,this._apiEndpoint,...Zu)}}contents.Drive=zu;var Uu;(function(Gu){function Wu(Zu){return Zu.length>0&&Zu.indexOf(".")!==0&&(Zu=`.${Zu}`),Zu}Gu.normalizeExtension=Wu})(Uu||(Uu={}));class Hu{constructor(Wu){this._providers=new Map,this._fileChanged=new Ou.Signal(this),Wu?.defaultProvider&&this.register("default",Wu.defaultProvider)}register(Wu,Zu){if(this._providers.has(Wu))throw Error(`Provider with ${Wu} identifier was already registered on this drive`);this._providers.set(Wu,Zu);const Ju=(Yu,Xu)=>{this._fileChanged.emit(Xu)};return Zu.fileChanged&&Zu.fileChanged.connect(Ju),new Pu.DisposableDelegate(()=>{Zu.fileChanged&&Zu.fileChanged.disconnect(Ju),this._providers.has(Wu)&&this._providers.delete(Wu)})}getProvider(Wu){if(!Wu)return null;const Zu=this._providers.get(Wu);if(!Zu)throw Error(`Provider ${Wu} is not registered`);return Zu}get fileChanged(){return this._fileChanged}}contents.ContentProviderRegistry=Hu;class Vu{constructor(Wu){this._options=Wu}async get(Wu,Zu){let Ju=this._getUrl(Wu);if(Zu){Zu.type==="notebook"&&delete Zu.format;const td=Zu.content?"1":"0",nd=Zu.hash?"1":"0",od={...Zu,content:td,hash:nd};Ju+=Ru.URLExt.objectToQueryString(od)}const Yu=this._options.serverSettings,Xu=await Mu.ServerConnection.makeRequest(Ju,{},Yu);if(Xu.status!==200)throw await Mu.ServerConnection.ResponseError.create(Xu);const ed=await Xu.json();return Du.validateContentsModel(ed),ed}async save(Wu,Zu={}){const Ju=this._options.serverSettings,Yu=this._getUrl(Wu),ed={method:"PUT",body:new File([JSON.stringify(Zu)],"data.json",{type:"application/json"})},td=await Mu.ServerConnection.makeRequest(Yu,ed,Ju);if(td.status!==200&&td.status!==201)throw await Mu.ServerConnection.ResponseError.create(td);const nd=await td.json();return Du.validateContentsModel(nd),nd}_getUrl(...Wu){const Zu=Wu.map(Yu=>Ru.URLExt.encodeParts(Yu)),Ju=this._options.serverSettings.baseUrl;return Ru.URLExt.join(Ju,this._options.apiEndpoint,...Zu)}}return contents.RestContentProvider=Vu,contents}var event={};const require$$1$1=getAugmentedNamespace(index_es6$2);var hasRequiredEvent;function requireEvent(){if(hasRequiredEvent)return event;hasRequiredEvent=1,Object.defineProperty(event,"__esModule",{value:!0}),event.EventManager=void 0;const Au=requireLib$b(),lo=require$$1$1,$u=require$$0$2,Ru=requireServerconnection(),Iu="api/events";class Pu{constructor(Mu={}){var Du,Lu;this._socket=null,this.serverSettings=(Du=Mu.serverSettings)!==null&&Du!==void 0?Du:Ru.ServerConnection.makeSettings(),this._poll=new lo.Poll({factory:()=>this._subscribe(),standby:(Lu=Mu.standby)!==null&&Lu!==void 0?Lu:"when-hidden"}),this._stream=new $u.Stream(this),this._poll.start()}get isDisposed(){return this._poll.isDisposed}get stream(){return this._stream}dispose(){if(this.isDisposed)return;this._poll.dispose();const Mu=this._socket;Mu&&(this._socket=null,Mu.onopen=()=>{},Mu.onerror=()=>{},Mu.onmessage=()=>{},Mu.onclose=()=>{},Mu.close()),$u.Signal.clearData(this),this._stream.stop()}async emit(Mu){const{serverSettings:Du}=this,{baseUrl:Lu}=Du,{makeRequest:Bu,ResponseError:ju}=Ru.ServerConnection,Fu=Au.URLExt.join(Lu,Iu),zu={body:JSON.stringify(Mu),method:"POST"},Uu=await Bu(Fu,zu,Du);if(Uu.status!==204)throw new ju(Uu)}_subscribe(){return new Promise((Mu,Du)=>{if(this.isDisposed)return;const{appendToken:Lu,token:Bu,WebSocket:ju,wsUrl:Fu}=this.serverSettings;let zu=Au.URLExt.join(Fu,Iu,"subscribe");Lu&&Bu!==""&&(zu+=`?token=${encodeURIComponent(Bu)}`);const Uu=this._socket=new ju(zu),Hu=this._stream;Uu.onclose=()=>Du(new Error("EventManager socket closed")),Uu.onmessage=Vu=>Vu.data&&Hu.emit(JSON.parse(Vu.data))})}}return event.EventManager=Pu,event}var kernel$1={},comm={},hasRequiredComm;function requireComm(){if(hasRequiredComm)return comm;hasRequiredComm=1;var Au=comm&&comm.__createBinding||(Object.create?(function(Du,Lu,Bu,ju){ju===void 0&&(ju=Bu);var Fu=Object.getOwnPropertyDescriptor(Lu,Bu);(!Fu||("get"in Fu?!Lu.__esModule:Fu.writable||Fu.configurable))&&(Fu={enumerable:!0,get:function(){return Lu[Bu]}}),Object.defineProperty(Du,ju,Fu)}):(function(Du,Lu,Bu,ju){ju===void 0&&(ju=Bu),Du[ju]=Lu[Bu]})),lo=comm&&comm.__setModuleDefault||(Object.create?(function(Du,Lu){Object.defineProperty(Du,"default",{enumerable:!0,value:Lu})}):function(Du,Lu){Du.default=Lu}),$u=comm&&comm.__importStar||(function(){var Du=function(Lu){return Du=Object.getOwnPropertyNames||function(Bu){var ju=[];for(var Fu in Bu)Object.prototype.hasOwnProperty.call(Bu,Fu)&&(ju[ju.length]=Fu);return ju},Du(Lu)};return function(Lu){if(Lu&&Lu.__esModule)return Lu;var Bu={};if(Lu!=null)for(var ju=Du(Lu),Fu=0;Fu<ju.length;Fu++)ju[Fu]!=="default"&&Au(Bu,Lu,ju[Fu]);return lo(Bu,Lu),Bu}})();Object.defineProperty(comm,"__esModule",{value:!0}),comm.CommHandler=comm.CommsOverSubshells=void 0;const Ru=requireDist(),Iu=require$$1$2,Pu=$u(requireMessages());var Ou;(function(Du){Du.Disabled="disabled",Du.PerComm="perComm",Du.PerCommTarget="perCommTarget"})(Ou||(comm.CommsOverSubshells=Ou={}));class Mu extends Iu.DisposableDelegate{constructor(Lu,Bu,ju,Fu,zu){super(Fu),this._subshellStarted=new Ru.PromiseDelegate,this._subshellId=null,this._target="",this._id="",this._id=Bu,this._target=Lu,this._kernel=ju,this._kernel.statusChanged.connect(()=>{this._kernel.status==="restarting"&&this._cleanSubshells()}),this.commsOverSubshells=zu??Ou.PerCommTarget}get commId(){return this._id}get targetName(){return this._target}get subshellId(){return this._subshellId}get subshellStarted(){return this._subshellStarted.promise}get commsOverSubshells(){return this._commsOverSubshells}set commsOverSubshells(Lu){if(Lu===this._commsOverSubshells)return;const Bu=this._maybeCloseSubshell(this._commsOverSubshells);this._commsOverSubshells=Lu,Bu.then(()=>{this._commsOverSubshells!==Ou.Disabled&&this._maybeStartSubshell()}).catch(console.warn)}get onClose(){return this._onClose}set onClose(Lu){this._onClose=Lu}get onMsg(){return this._onMsg}set onMsg(Lu){this._onMsg=Lu}open(Lu,Bu,ju=[]){if(this.isDisposed||this._kernel.isDisposed)throw new Error("Cannot open");const Fu=Pu.createMessage({msgType:"comm_open",channel:"shell",username:this._kernel.username,session:this._kernel.clientId,subshellId:this._subshellId||this._kernel.subshellId,content:{comm_id:this._id,target_name:this._target,data:Lu??{}},metadata:Bu,buffers:ju});return this._kernel.sendShellMessage(Fu,!1,!0)}send(Lu,Bu,ju=[],Fu=!0){if(this.isDisposed||this._kernel.isDisposed)throw new Error("Cannot send");const zu=Pu.createMessage({msgType:"comm_msg",channel:"shell",username:this._kernel.username,session:this._kernel.clientId,subshellId:this._subshellId||this._kernel.subshellId,content:{comm_id:this._id,data:Lu},metadata:Bu,buffers:ju});return this._kernel.sendShellMessage(zu,!1,Fu)}close(Lu,Bu,ju=[]){if(this.isDisposed||this._kernel.isDisposed)throw new Error("Cannot close");const Fu=Pu.createMessage({msgType:"comm_close",channel:"shell",username:this._kernel.username,session:this._kernel.clientId,subshellId:this._subshellId||this._kernel.subshellId,content:{comm_id:this._id,data:Lu??{}},metadata:Bu,buffers:ju}),zu=this._kernel.sendShellMessage(Fu,!1,!0),Uu=this._onClose;if(Uu){const Hu=Pu.createMessage({msgType:"comm_close",channel:"iopub",username:this._kernel.username,session:this._kernel.clientId,subshellId:this._subshellId||this._kernel.subshellId,content:{comm_id:this._id,data:Lu??{}},metadata:Bu,buffers:ju});Uu(Hu)}return this.dispose(),zu}dispose(){this._maybeCloseSubshell(this._commsOverSubshells),super.dispose()}_cleanSubshells(){const Lu=this._kernel.id;Mu._commTargetSubShellsId.hasOwnProperty(Lu)&&delete Mu._commTargetSubShellsId[Lu]}async _maybeStartSubshell(){if(await this._kernel.info,!this._kernel.supportsSubshells)return;if(this._commsOverSubshells===Ou.PerComm){const Uu=await this._kernel.requestCreateSubshell({}).done;this._subshellId=Uu.content.subshell_id,this._subshellStarted.resolve();return}const Lu=this._subshellStarted,Bu=this._kernel.id;Mu._commTargetSubShellsId.hasOwnProperty(Bu)||(Mu._commTargetSubShellsId[Bu]={});const ju=Mu._commTargetSubShellsId[Bu],Fu=ju[this._target];if(Fu){Fu.referenceCount+=1;try{this._subshellId=await Fu.subshellId,Lu.resolve()}catch(Uu){await this._closePerCommTargetSubshell(!1),Lu.reject(`Per comm-target subshell creation failed: ${Uu}`)}return}const zu={subshellId:this._kernel.requestCreateSubshell({}).done.then(Uu=>Uu.content.subshell_id),referenceCount:1};ju[this._target]=zu;try{this._subshellId=await zu.subshellId,Lu.resolve()}catch(Uu){await this._closePerCommTargetSubshell(!1),Lu.reject(`Per comm-target subshell creation failed: ${Uu}`)}}async _closePerCommTargetSubshell(Lu=!0){const Bu=this._kernel.id,ju=this._target;if(Mu._commTargetSubShellsId.hasOwnProperty(Bu)){const Fu=Mu._commTargetSubShellsId[Bu],zu=Fu[ju];if(zu&&(zu.referenceCount-=1,zu.referenceCount<=0)){if(Lu){let Uu=null;try{Uu=await zu.subshellId}catch(Hu){console.warn(`Subshell identifier not available in the closeout sequence, will not request deletion: ${Hu}`)}Uu!==null&&this._kernel.requestDeleteSubshell({subshell_id:Uu},!0)}delete Fu[ju]}Object.keys(Fu).length===0&&delete Mu._commTargetSubShellsId[Bu],this._subshellId=null}this._subshellStarted=new Ru.PromiseDelegate}async _maybeCloseSubshell(Lu){if(this._kernel.status!=="dead")switch(Lu){case Ou.PerComm:{this._subshellId&&(this._kernel.requestDeleteSubshell({subshell_id:this._subshellId},!0),this._subshellId=null),this._subshellStarted=new Ru.PromiseDelegate;break}case Ou.PerCommTarget:{await this._closePerCommTargetSubshell();break}case Ou.Disabled:break}}}return comm.CommHandler=Mu,Mu._commTargetSubShellsId={},comm}var kernel={},hasRequiredKernel$1;function requireKernel$1(){return hasRequiredKernel$1||(hasRequiredKernel$1=1,Object.defineProperty(kernel,"__esModule",{value:!0})),kernel}var restapi$4={},validate$5={},hasRequiredValidate$3;function requireValidate$3(){if(hasRequiredValidate$3)return validate$5;hasRequiredValidate$3=1,Object.defineProperty(validate$5,"__esModule",{value:!0}),validate$5.validateMessage=Iu,validate$5.validateModel=Ou,validate$5.validateModels=Mu;const Au=requireValidate$5(),lo=["username","version","session","msg_id","msg_type"],$u={stream:{name:"string",text:"string"},display_data:{data:"object",metadata:"object"},execute_input:{code:"string",execution_count:"number"},execute_result:{execution_count:"number",data:"object",metadata:"object"},error:{ename:"string",evalue:"string",traceback:"object"},status:{execution_state:["string",["starting","idle","busy","restarting","dead"]]},clear_output:{wait:"boolean"},comm_open:{comm_id:"string",target_name:"string",data:"object"},comm_msg:{comm_id:"string",data:"object"},comm_close:{comm_id:"string"},shutdown_reply:{restart:"boolean"}};function Ru(Du){for(let Lu=0;Lu<lo.length;Lu++)(0,Au.validateProperty)(Du,lo[Lu],"string")}function Iu(Du){(0,Au.validateProperty)(Du,"metadata","object"),(0,Au.validateProperty)(Du,"content","object"),(0,Au.validateProperty)(Du,"channel","string"),Ru(Du.header),Du.channel==="iopub"&&Pu(Du)}function Pu(Du){if(Du.channel==="iopub"){const Lu=$u[Du.header.msg_type];if(Lu===void 0)return;const Bu=Object.keys(Lu),ju=Du.content;for(let Fu=0;Fu<Bu.length;Fu++){let zu=Lu[Bu[Fu]];Array.isArray(zu)||(zu=[zu]),(0,Au.validateProperty)(ju,Bu[Fu],...zu)}}}function Ou(Du){(0,Au.validateProperty)(Du,"name","string"),(0,Au.validateProperty)(Du,"id","string")}function Mu(Du){if(!Array.isArray(Du))throw new Error("Invalid kernel list");Du.forEach(Lu=>Ou(Lu))}return validate$5}var hasRequiredRestapi$4;function requireRestapi$4(){return hasRequiredRestapi$4||(hasRequiredRestapi$4=1,(function(Au){Object.defineProperty(Au,"__esModule",{value:!0}),Au.KernelAPIClient=Au.KERNEL_SERVICE_URL=void 0,Au.listRunning=Iu,Au.startNew=Pu,Au.restartKernel=Ou,Au.interruptKernel=Mu,Au.shutdownKernel=Du,Au.getKernelModel=Lu;const lo=requireServerconnection(),$u=requireLib$b(),Ru=requireValidate$3();Au.KERNEL_SERVICE_URL="api/kernels";async function Iu(ju=lo.ServerConnection.makeSettings()){const Fu=$u.URLExt.join(ju.baseUrl,Au.KERNEL_SERVICE_URL),zu=await lo.ServerConnection.makeRequest(Fu,{},ju);if(zu.status!==200)throw await lo.ServerConnection.ResponseError.create(zu);const Uu=await zu.json();return(0,Ru.validateModels)(Uu),Uu}async function Pu(ju={},Fu=lo.ServerConnection.makeSettings()){const zu=$u.URLExt.join(Fu.baseUrl,Au.KERNEL_SERVICE_URL),Uu={method:"POST",body:JSON.stringify(ju)},Hu=await lo.ServerConnection.makeRequest(zu,Uu,Fu);if(Hu.status!==201)throw await lo.ServerConnection.ResponseError.create(Hu);const Vu=await Hu.json();return(0,Ru.validateModel)(Vu),Vu}async function Ou(ju,Fu=lo.ServerConnection.makeSettings()){const zu=$u.URLExt.join(Fu.baseUrl,Au.KERNEL_SERVICE_URL,encodeURIComponent(ju),"restart"),Uu={method:"POST"},Hu=await lo.ServerConnection.makeRequest(zu,Uu,Fu);if(Hu.status!==200)throw await lo.ServerConnection.ResponseError.create(Hu);const Vu=await Hu.json();(0,Ru.validateModel)(Vu)}async function Mu(ju,Fu=lo.ServerConnection.makeSettings()){const zu=$u.URLExt.join(Fu.baseUrl,Au.KERNEL_SERVICE_URL,encodeURIComponent(ju),"interrupt"),Uu={method:"POST"},Hu=await lo.ServerConnection.makeRequest(zu,Uu,Fu);if(Hu.status!==204)throw await lo.ServerConnection.ResponseError.create(Hu)}async function Du(ju,Fu=lo.ServerConnection.makeSettings()){const zu=$u.URLExt.join(Fu.baseUrl,Au.KERNEL_SERVICE_URL,encodeURIComponent(ju)),Uu={method:"DELETE"},Hu=await lo.ServerConnection.makeRequest(zu,Uu,Fu);if(Hu.status===404){const Vu=`The kernel "${ju}" does not exist on the server`;console.warn(Vu)}else if(Hu.status!==204)throw await lo.ServerConnection.ResponseError.create(Hu)}async function Lu(ju,Fu=lo.ServerConnection.makeSettings()){const zu=$u.URLExt.join(Fu.baseUrl,Au.KERNEL_SERVICE_URL,encodeURIComponent(ju)),Uu=await lo.ServerConnection.makeRequest(zu,{},Fu);if(Uu.status===404)return;if(Uu.status!==200)throw await lo.ServerConnection.ResponseError.create(Uu);const Hu=await Uu.json();return(0,Ru.validateModel)(Hu),Hu}class Bu{constructor(Fu={}){var zu;this.serverSettings=(zu=Fu.serverSettings)!==null&&zu!==void 0?zu:lo.ServerConnection.makeSettings()}async listRunning(){return Iu(this.serverSettings)}async getModel(Fu){return Lu(Fu,this.serverSettings)}async startNew(Fu={}){return Pu(Fu,this.serverSettings)}async restart(Fu){return Ou(Fu,this.serverSettings)}async interrupt(Fu){return Mu(Fu,this.serverSettings)}async shutdown(Fu){return Du(Fu,this.serverSettings)}}Au.KernelAPIClient=Bu})(restapi$4)),restapi$4}var _default$3={},future={},hasRequiredFuture;function requireFuture(){if(hasRequiredFuture)return future;hasRequiredFuture=1;var Au=future&&future.__createBinding||(Object.create?(function(Bu,ju,Fu,zu){zu===void 0&&(zu=Fu);var Uu=Object.getOwnPropertyDescriptor(ju,Fu);(!Uu||("get"in Uu?!ju.__esModule:Uu.writable||Uu.configurable))&&(Uu={enumerable:!0,get:function(){return ju[Fu]}}),Object.defineProperty(Bu,zu,Uu)}):(function(Bu,ju,Fu,zu){zu===void 0&&(zu=Fu),Bu[zu]=ju[Fu]})),lo=future&&future.__setModuleDefault||(Object.create?(function(Bu,ju){Object.defineProperty(Bu,"default",{enumerable:!0,value:ju})}):function(Bu,ju){Bu.default=ju}),$u=future&&future.__importStar||(function(){var Bu=function(ju){return Bu=Object.getOwnPropertyNames||function(Fu){var zu=[];for(var Uu in Fu)Object.prototype.hasOwnProperty.call(Fu,Uu)&&(zu[zu.length]=Uu);return zu},Bu(ju)};return function(ju){if(ju&&ju.__esModule)return ju;var Fu={};if(ju!=null)for(var zu=Bu(ju),Uu=0;Uu<zu.length;Uu++)zu[Uu]!=="default"&&Au(Fu,ju,zu[Uu]);return lo(Fu,ju),Fu}})();Object.defineProperty(future,"__esModule",{value:!0}),future.KernelShellFutureHandler=future.KernelControlFutureHandler=future.KernelFutureHandler=void 0;const Ru=requireDist(),Iu=require$$1$2,Pu=$u(requireMessages());class Ou extends Iu.DisposableDelegate{constructor(ju,Fu,zu,Uu,Hu){super(ju),this._status=0,this._stdin=Lu.noOp,this._iopub=Lu.noOp,this._reply=Lu.noOp,this._done=new Ru.PromiseDelegate,this._hooks=new Lu.HookList,this._disposeOnDone=!0,this._msg=Fu,zu||this._setFlag(Lu.KernelFutureFlag.GotReply),this._disposeOnDone=Uu,this._kernel=Hu}get msg(){return this._msg}get done(){return this._done.promise}get onReply(){return this._reply}set onReply(ju){this._reply=ju}get onIOPub(){return this._iopub}set onIOPub(ju){this._iopub=ju}get onStdin(){return this._stdin}set onStdin(ju){this._stdin=ju}registerMessageHook(ju){if(this.isDisposed)throw new Error("Kernel future is disposed");this._hooks.add(ju)}removeMessageHook(ju){this.isDisposed||this._hooks.remove(ju)}sendInputReply(ju,Fu){this._kernel.sendInputReply(ju,Fu)}dispose(){this._stdin=Lu.noOp,this._iopub=Lu.noOp,this._reply=Lu.noOp,this._hooks=null,this._testFlag(Lu.KernelFutureFlag.IsDone)||(this._done.promise.catch(()=>{}),this._done.reject(new Error(`Canceled future for ${this.msg.header.msg_type} message before replies were done`))),super.dispose()}async handleMsg(ju){switch(ju.channel){case"control":case"shell":ju.channel===this.msg.channel&&ju.parent_header.msg_id===this.msg.header.msg_id&&await this._handleReply(ju);break;case"stdin":await this._handleStdin(ju);break;case"iopub":await this._handleIOPub(ju);break}}async _handleReply(ju){const Fu=this._reply;Fu&&await Fu(ju),this._replyMsg=ju,this._setFlag(Lu.KernelFutureFlag.GotReply),this._testFlag(Lu.KernelFutureFlag.GotIdle)&&this._handleDone()}async _handleStdin(ju){this._kernel.hasPendingInput=!0;const Fu=this._stdin;Fu&&await Fu(ju)}async _handleIOPub(ju){const Fu=await this._hooks.process(ju),zu=this._iopub;Fu&&zu&&await zu(ju),Pu.isStatusMsg(ju)&&ju.content.execution_state==="idle"&&(this._setFlag(Lu.KernelFutureFlag.GotIdle),this._testFlag(Lu.KernelFutureFlag.GotReply)&&this._handleDone())}_handleDone(){this._testFlag(Lu.KernelFutureFlag.IsDone)||(this._setFlag(Lu.KernelFutureFlag.IsDone),this._done.resolve(this._replyMsg),this._disposeOnDone&&this.dispose())}_testFlag(ju){return(this._status&ju)!==0}_setFlag(ju){this._status|=ju}}future.KernelFutureHandler=Ou;class Mu extends Ou{}future.KernelControlFutureHandler=Mu;class Du extends Ou{}future.KernelShellFutureHandler=Du;var Lu;return(function(Bu){Bu.noOp=()=>{};const ju=typeof requestAnimationFrame=="function"?requestAnimationFrame:setImmediate;class Fu{constructor(){this._hooks=[]}add(Uu){this.remove(Uu),this._hooks.push(Uu)}remove(Uu){const Hu=this._hooks.indexOf(Uu);Hu>=0&&(this._hooks[Hu]=null,this._scheduleCompact())}async process(Uu){await this._processing;const Hu=new Ru.PromiseDelegate;this._processing=Hu.promise;let Vu;for(let Gu=this._hooks.length-1;Gu>=0;Gu--){const Wu=this._hooks[Gu];if(Wu!==null){try{Vu=await Wu(Uu)}catch(Zu){Vu=!0,console.error(Zu)}if(Vu===!1)return Hu.resolve(void 0),!1}}return Hu.resolve(void 0),!0}_scheduleCompact(){this._compactScheduled||(this._compactScheduled=!0,ju(()=>{this._processing=this._processing.then(()=>{this._compactScheduled=!1,this._compact()})}))}_compact(){let Uu=0;for(let Hu=0,Vu=this._hooks.length;Hu<Vu;Hu++){const Gu=this._hooks[Hu];this._hooks[Hu]===null?Uu++:this._hooks[Hu-Uu]=Gu}this._hooks.length-=Uu}}Bu.HookList=Fu,(function(zu){zu[zu.GotReply=1]="GotReply",zu[zu.GotIdle=2]="GotIdle",zu[zu.IsDone=4]="IsDone",zu[zu.DisposeOnDone=8]="DisposeOnDone"})(Bu.KernelFutureFlag||(Bu.KernelFutureFlag={}))})(Lu||(Lu={})),future}var restapi$3={},validate$4={},hasRequiredValidate$2;function requireValidate$2(){if(hasRequiredValidate$2)return validate$4;hasRequiredValidate$2=1,Object.defineProperty(validate$4,"__esModule",{value:!0}),validate$4.validateSpecModel=lo,validate$4.validateSpecModels=$u;const Au=requireValidate$5();function lo(Ru){const Iu=Ru.spec;if(!Iu)throw new Error("Invalid kernel spec");(0,Au.validateProperty)(Ru,"name","string"),(0,Au.validateProperty)(Ru,"resources","object"),(0,Au.validateProperty)(Iu,"language","string"),(0,Au.validateProperty)(Iu,"display_name","string"),(0,Au.validateProperty)(Iu,"argv","array");let Pu=null;Iu.hasOwnProperty("metadata")&&((0,Au.validateProperty)(Iu,"metadata","object"),Pu=Iu.metadata);let Ou=null;return Iu.hasOwnProperty("env")&&((0,Au.validateProperty)(Iu,"env","object"),Ou=Iu.env),Iu.hasOwnProperty("interrupt_mode")&&((0,Au.validateProperty)(Iu,"interrupt_mode","string"),Ou=Iu.env),{name:Ru.name,resources:Ru.resources,language:Iu.language,display_name:Iu.display_name,argv:Iu.argv,metadata:Pu,env:Ou}}function $u(Ru){if(!Ru.hasOwnProperty("kernelspecs"))throw new Error("No kernelspecs found");let Iu=Object.keys(Ru.kernelspecs);const Pu=Object.create(null);let Ou=Ru.default;for(let Mu=0;Mu<Iu.length;Mu++){const Du=Ru.kernelspecs[Iu[Mu]];try{Pu[Iu[Mu]]=lo(Du)}catch{console.warn(`Removing errant kernel spec: ${Iu[Mu]}`)}}if(Iu=Object.keys(Pu),!Iu.length)throw new Error("No valid kernelspecs found");return(!Ou||typeof Ou!="string"||!(Ou in Pu))&&(Ou=Iu[0],console.warn(`Default kernel not found, using '${Iu[0]}'`)),{default:Ou,kernelspecs:Pu}}return validate$4}var hasRequiredRestapi$3;function requireRestapi$3(){if(hasRequiredRestapi$3)return restapi$3;hasRequiredRestapi$3=1,Object.defineProperty(restapi$3,"__esModule",{value:!0}),restapi$3.KernelSpecAPIClient=void 0,restapi$3.getSpecs=Iu;const Au=requireServerconnection(),lo=requireValidate$2(),$u=requireLib$b(),Ru="api/kernelspecs";async function Iu(Ou=Au.ServerConnection.makeSettings()){const Mu=$u.URLExt.join(Ou.baseUrl,Ru),Du=await Au.ServerConnection.makeRequest(Mu,{},Ou);if(Du.status!==200)throw await Au.ServerConnection.ResponseError.create(Du);const Lu=await Du.json();return(0,lo.validateSpecModels)(Lu)}class Pu{constructor(Mu={}){var Du;this.serverSettings=(Du=Mu.serverSettings)!==null&&Du!==void 0?Du:Au.ServerConnection.makeSettings()}async get(){return Iu(this.serverSettings)}}return restapi$3.KernelSpecAPIClient=Pu,restapi$3}var hasRequired_default$2;function require_default$2(){return hasRequired_default$2||(hasRequired_default$2=1,(function(Au){var lo=_default$3&&_default$3.__createBinding||(Object.create?(function(Wu,Zu,Ju,Yu){Yu===void 0&&(Yu=Ju);var Xu=Object.getOwnPropertyDescriptor(Zu,Ju);(!Xu||("get"in Xu?!Zu.__esModule:Xu.writable||Xu.configurable))&&(Xu={enumerable:!0,get:function(){return Zu[Ju]}}),Object.defineProperty(Wu,Yu,Xu)}):(function(Wu,Zu,Ju,Yu){Yu===void 0&&(Yu=Ju),Wu[Yu]=Zu[Ju]})),$u=_default$3&&_default$3.__setModuleDefault||(Object.create?(function(Wu,Zu){Object.defineProperty(Wu,"default",{enumerable:!0,value:Zu})}):function(Wu,Zu){Wu.default=Zu}),Ru=_default$3&&_default$3.__importStar||(function(){var Wu=function(Zu){return Wu=Object.getOwnPropertyNames||function(Ju){var Yu=[];for(var Xu in Ju)Object.prototype.hasOwnProperty.call(Ju,Xu)&&(Yu[Yu.length]=Xu);return Yu},Wu(Zu)};return function(Zu){if(Zu&&Zu.__esModule)return Zu;var Ju={};if(Zu!=null)for(var Yu=Wu(Zu),Xu=0;Xu<Yu.length;Xu++)Yu[Xu]!=="default"&&lo(Ju,Zu,Yu[Xu]);return $u(Ju,Zu),Ju}})();Object.defineProperty(Au,"__esModule",{value:!0}),Au.KernelConnection=Au.DEFAULT_KERNEL_INFO_TIMEOUT=void 0;const Iu=requireLib$b(),Pu=requireDist(),Ou=require$$0$2,Mu=requireLib$8(),Du=requireComm(),Lu=Ru(requireMessages()),Bu=requireFuture(),ju=Ru(requireValidate$3()),Fu=requireRestapi$4(),zu=requireRestapi$3(),Uu=requireLib$b();Au.DEFAULT_KERNEL_INFO_TIMEOUT=3e3;const Hu="";class Vu{constructor(Zu){var Ju,Yu,Xu,ed,td,nd,od,sd,ad;this._createSocket=(pd=!0)=>{this._errorIfDisposed(),this._clearSocket(),this._updateConnectionStatus("connecting");const vd=this.serverSettings,Sd=Iu.URLExt.join(vd.wsUrl,Fu.KERNEL_SERVICE_URL,encodeURIComponent(this._id)),_d=Sd.replace(/^((?:\w+:)?\/\/)[^@/]+@/,"$1");console.debug(`Starting WebSocket: ${_d}`);let bd=Iu.URLExt.join(Sd,"channels?session_id="+encodeURIComponent(this._clientId));const wd=vd.token;vd.appendToken&&wd!==""&&(bd=bd+`&token=${encodeURIComponent(wd)}`);const Ad=pd?this._supportedProtocols:[];this._ws=new vd.WebSocket(bd,Ad),this._ws.binaryType="arraybuffer";let gd=!1;const dd=async ld=>{var ud,hd;if(!this._isDisposed){this._reason="",this._model=void 0;try{const md=await this._kernelAPIClient.getModel(this._id);this._model=md,md?.execution_state==="dead"?this._updateStatus("dead"):this._onWSClose(ld)}catch(md){if(md instanceof Mu.ServerConnection.NetworkError||((ud=md.response)===null||ud===void 0?void 0:ud.status)===503||((hd=md.response)===null||hd===void 0?void 0:hd.status)===424){const Ed=Gu.getRandomIntInclusive(10,30)*1e3;setTimeout(dd,Ed,ld)}else this._reason="Kernel died unexpectedly",this._updateStatus("dead")}}},yd=async ld=>{gd||(gd=!0,await dd(ld))};this._ws.onmessage=this._onWSMessage,this._ws.onopen=this._onWSOpen,this._ws.onclose=yd,this._ws.onerror=yd},this._onWSOpen=pd=>{if(this._ws.protocol!==""&&!this._supportedProtocols.includes(this._ws.protocol))throw console.log("Server selected unknown kernel wire protocol:",this._ws.protocol),this._updateStatus("dead"),new Error(`Unknown kernel wire protocol: ${this._ws.protocol}`);this._selectedProtocol=this._ws.protocol,this._ws.onclose=this._onWSClose,this._ws.onerror=this._onWSClose,this._updateConnectionStatus("connected")},this._onWSMessage=pd=>{let vd;try{vd=this.serverSettings.serializer.deserialize(pd.data,this._ws.protocol),ju.validateMessage(vd)}catch(Sd){throw Sd.message=`Kernel message validation error: ${Sd.message}`,Sd}this._kernelSession=vd.header.session,this._msgChain=this._msgChain.then(()=>this._handleMessage(vd)).catch(Sd=>{Sd.message.startsWith("Canceled future for ")&&console.error(Sd)}),this._anyMessage.emit({msg:vd,direction:"recv"})},this._onWSClose=pd=>{if(!this.isDisposed){if("code"in pd&&(pd.code===1e3||pd.code===1001)){this._updateConnectionStatus("disconnected");return}this._reconnect()}},this._id="",this._name="",this._status="unknown",this._connectionStatus="connecting",this._kernelSession="",this._isRestarting=!1,this._isDisposed=!1,this._ws=null,this._username="",this._reconnectLimit=7,this._reconnectAttempt=0,this._reconnectTimeout=null,this._supportedProtocols=Object.values(Lu.supportedKernelWebSocketProtocols),this._selectedProtocol="",this._commsOverSubshells=Mu.CommsOverSubshells.PerCommTarget,this._futures=new Map,this._comms=new Map,this._targetRegistry=Object.create(null),this._info=new Pu.PromiseDelegate,this._pendingMessages=[],this._statusChanged=new Ou.Signal(this),this._connectionStatusChanged=new Ou.Signal(this),this._disposed=new Ou.Signal(this),this._iopubMessage=new Ou.Signal(this),this._anyMessage=new Ou.Signal(this),this._pendingInput=new Ou.Signal(this),this._unhandledMessage=new Ou.Signal(this),this._displayIdToParentIds=new Map,this._msgIdToDisplayIds=new Map,this._msgChain=Promise.resolve(),this._hasPendingInput=!1,this._reason="",this._noOp=()=>{},this._supportsSubshells=!1,this._kernelInfoTimeout=Au.DEFAULT_KERNEL_INFO_TIMEOUT,this._name=Zu.model.name,this._id=Zu.model.id,this.serverSettings=(Ju=Zu.serverSettings)!==null&&Ju!==void 0?Ju:Mu.ServerConnection.makeSettings(),this._kernelAPIClient=(Yu=Zu.kernelAPIClient)!==null&&Yu!==void 0?Yu:new Fu.KernelAPIClient({serverSettings:this.serverSettings}),this._kernelSpecAPIClient=(Xu=Zu.kernelSpecAPIClient)!==null&&Xu!==void 0?Xu:new zu.KernelSpecAPIClient({serverSettings:this.serverSettings}),this._clientId=(ed=Zu.clientId)!==null&&ed!==void 0?ed:Pu.UUID.uuid4(),this._username=(td=Zu.username)!==null&&td!==void 0?td:"",this.handleComms=(nd=Zu.handleComms)!==null&&nd!==void 0?nd:!0,this._commsOverSubshells=(od=Zu.commsOverSubshells)!==null&&od!==void 0?od:Mu.CommsOverSubshells.PerCommTarget,this._subshellId=(sd=Zu.subshellId)!==null&&sd!==void 0?sd:null,this._createSocket(),this._kernelInfoTimeout=(ad=Zu?.kernelInfoTimeout)!==null&&ad!==void 0?ad:Au.DEFAULT_KERNEL_INFO_TIMEOUT}get disposed(){return this._disposed}get commsOverSubshells(){return this._commsOverSubshells}set commsOverSubshells(Zu){this._commsOverSubshells=Zu;for(const[Ju,Yu]of this._comms)Yu.commsOverSubshells=Zu}get statusChanged(){return this._statusChanged}get connectionStatusChanged(){return this._connectionStatusChanged}get iopubMessage(){return this._iopubMessage}get unhandledMessage(){return this._unhandledMessage}get model(){return this._model||{id:this.id,name:this.name,reason:this._reason}}get anyMessage(){return this._anyMessage}get pendingInput(){return this._pendingInput}get id(){return this._id}get name(){return this._name}get username(){return this._username}get clientId(){return this._clientId}get subshellId(){return this._subshellId}set subshellId(Zu){this._subshellId=Zu}get status(){return this._status}get connectionStatus(){return this._connectionStatus}get isDisposed(){return this._isDisposed}get info(){return this._info.promise}get spec(){return this._specPromise?this._specPromise:(this._specPromise=this._kernelSpecAPIClient.get().then(Zu=>Zu.kernelspecs[this._name]),this._specPromise)}get supportsSubshells(){return this._supportsSubshells}clone(Zu={}){return new Vu({model:this.model,username:this.username,serverSettings:this.serverSettings,handleComms:!1,kernelAPIClient:this._kernelAPIClient,commsOverSubshells:Mu.CommsOverSubshells.Disabled,kernelInfoTimeout:this._kernelInfoTimeout,...Zu})}dispose(){if(this.isDisposed)return;const Zu=()=>{this._isDisposed=!0,this._disposed.emit(),this._updateConnectionStatus("disconnected"),this._clearKernelState(),this._pendingMessages=[],this._clearSocket(),Ou.Signal.clearData(this)};if(this._subshellId!==null){const Ju=this.requestDeleteSubshell({subshell_id:this._subshellId},!0);Ju.onReply=Yu=>{Zu()}}else Zu()}sendShellMessage(Zu,Ju=!1,Yu=!0){return this._sendKernelShellControl(Bu.KernelShellFutureHandler,Zu,Ju,Yu)}sendControlMessage(Zu,Ju=!1,Yu=!0){return this._sendKernelShellControl(Bu.KernelControlFutureHandler,Zu,Ju,Yu)}_sendKernelShellControl(Zu,Ju,Yu=!1,Xu=!0){this._sendMessage(Ju),this._anyMessage.emit({msg:Ju,direction:"send"});const ed=new Zu(()=>{const td=Ju.header.msg_id;this._futures.delete(td);const nd=this._msgIdToDisplayIds.get(td);nd&&(nd.forEach(od=>{const sd=this._displayIdToParentIds.get(od);if(sd){const ad=sd.indexOf(td);if(ad===-1)return;sd.length===1?this._displayIdToParentIds.delete(od):(sd.splice(ad,1),this._displayIdToParentIds.set(od,sd))}}),this._msgIdToDisplayIds.delete(td))},Ju,Yu,Xu,this);return this._futures.set(Ju.header.msg_id,ed),ed}_sendMessage(Zu,Ju=!0){if(this.status==="dead")throw new Error("Kernel is dead");if((this._kernelSession===Hu||this._isRestarting)&&Lu.isInfoRequestMsg(Zu))if(this.connectionStatus==="connected"){this._ws.send(this.serverSettings.serializer.serialize(Zu,this._ws.protocol));return}else throw new Error("Could not send message: status is not connected");if(Ju&&this._pendingMessages.length>0){this._pendingMessages.push(Zu);return}if(this.connectionStatus==="connected"&&!this._isRestarting)this._ws.send(this.serverSettings.serializer.serialize(Zu,this._ws.protocol));else if(Ju)this._pendingMessages.push(Zu);else throw new Error("Could not send message")}async interrupt(){if(this.hasPendingInput=!1,this.status==="dead")throw new Error("Kernel is dead");return this._kernelAPIClient.interrupt(this.id)}async restart(){if(this.status==="dead")throw new Error("Kernel is dead");this._updateStatus("restarting"),this._clearKernelState(),this._isRestarting=!0;try{await this._kernelAPIClient.restart(this.id),await this.reconnect()}catch(Zu){throw this._isRestarting=!1,Zu}this.hasPendingInput=!1}reconnect(){this._errorIfDisposed();const Zu=new Pu.PromiseDelegate,Ju=(Yu,Xu)=>{Xu==="connected"?(Zu.resolve(),this.connectionStatusChanged.disconnect(Ju,this)):Xu==="disconnected"&&(Zu.reject(new Error("Kernel connection disconnected")),this.connectionStatusChanged.disconnect(Ju,this))};return this.connectionStatusChanged.connect(Ju,this),this._reconnectAttempt=0,this._reconnect(),Zu.promise}async shutdown(){this.status!=="dead"&&await this._kernelAPIClient.shutdown(this.id),this.handleShutdown()}handleShutdown(){this._updateStatus("dead"),this.dispose()}async requestKernelInfo(){const Zu=Lu.createMessage({msgType:"kernel_info_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:{}});let Ju;try{Ju=await Gu.handleShellMessage(this,Zu)}catch(Xu){if(this.isDisposed)return;throw Xu}if(this._errorIfDisposed(),!Ju)return;if(Ju.content.status===void 0&&(Ju.content.status="ok"),Ju.content.status!=="ok")return this._info.reject("Kernel info reply errored"),Ju;this._info.resolve(Ju.content),this._kernelSession=Ju.header.session;const Yu=Ju.content.supported_features;return this._supportsSubshells=Yu!==void 0&&Yu.includes("kernel subshells"),Ju}requestComplete(Zu){const Ju=Lu.createMessage({msgType:"complete_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:Zu});return Gu.handleShellMessage(this,Ju)}requestInspect(Zu){const Ju=Lu.createMessage({msgType:"inspect_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:Zu});return Gu.handleShellMessage(this,Ju)}requestHistory(Zu){const Ju=Lu.createMessage({msgType:"history_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:Zu});return Gu.handleShellMessage(this,Ju)}requestExecute(Zu,Ju=!0,Yu){const Xu={silent:!1,store_history:!0,user_expressions:{},allow_stdin:!0,stop_on_error:!1},ed=Lu.createMessage({msgType:"execute_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:{...Xu,...Zu},metadata:Yu});return this.sendShellMessage(ed,!0,Ju)}requestDebug(Zu,Ju=!0){const Yu=Lu.createMessage({msgType:"debug_request",channel:"control",username:this._username,session:this._clientId,content:Zu});return this.sendControlMessage(Yu,!0,Ju)}requestCreateSubshell(Zu,Ju=!0){if(!this.supportsSubshells)throw new Error("Kernel subshells are not supported");const Yu=Lu.createMessage({msgType:"create_subshell_request",channel:"control",username:this._username,session:this._clientId,content:Zu});return this.sendControlMessage(Yu,!0,Ju)}requestDeleteSubshell(Zu,Ju=!0){if(!this.supportsSubshells)throw new Error("Kernel subshells are not supported");const Yu=Lu.createMessage({msgType:"delete_subshell_request",channel:"control",username:this._username,session:this._clientId,content:Zu});return this.sendControlMessage(Yu,!0,Ju)}requestListSubshell(Zu,Ju=!0){if(!this.supportsSubshells)throw new Error("Kernel subshells are not supported");const Yu=Lu.createMessage({msgType:"list_subshell_request",channel:"control",username:this._username,session:this._clientId,content:Zu});return this.sendControlMessage(Yu,!0,Ju)}requestIsComplete(Zu){const Ju=Lu.createMessage({msgType:"is_complete_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:Zu});return Gu.handleShellMessage(this,Ju)}requestCommInfo(Zu){const Ju=Lu.createMessage({msgType:"comm_info_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:Zu});return Gu.handleShellMessage(this,Ju)}sendInputReply(Zu,Ju){const Yu=Lu.createMessage({msgType:"input_reply",channel:"stdin",username:this._username,session:this._clientId,content:Zu});Yu.parent_header=Ju,this._sendMessage(Yu),this._anyMessage.emit({msg:Yu,direction:"send"}),this.hasPendingInput=!1}createComm(Zu,Ju=Pu.UUID.uuid4()){if(!this.handleComms)throw new Error("Comms are disabled on this kernel connection");if(this._comms.has(Ju))throw new Error("Comm is already created");const Yu=new Du.CommHandler(Zu,Ju,this,()=>{this._unregisterComm(Ju)},this._commsOverSubshells);return this._comms.set(Ju,Yu),Yu}hasComm(Zu){return this._comms.has(Zu)}registerCommTarget(Zu,Ju){this.handleComms&&(this._targetRegistry[Zu]=Ju)}removeCommTarget(Zu,Ju){this.handleComms&&!this.isDisposed&&this._targetRegistry[Zu]===Ju&&delete this._targetRegistry[Zu]}registerMessageHook(Zu,Ju){var Yu;const Xu=(Yu=this._futures)===null||Yu===void 0?void 0:Yu.get(Zu);Xu&&Xu.registerMessageHook(Ju)}removeMessageHook(Zu,Ju){var Yu;const Xu=(Yu=this._futures)===null||Yu===void 0?void 0:Yu.get(Zu);Xu&&Xu.removeMessageHook(Ju)}removeInputGuard(){this.hasPendingInput=!1}async _handleDisplayId(Zu,Ju){var Yu,Xu;const ed=Ju.parent_header.msg_id;let td=this._displayIdToParentIds.get(Zu);if(td){const od={header:Pu.JSONExt.deepCopy(Ju.header),parent_header:Pu.JSONExt.deepCopy(Ju.parent_header),metadata:Pu.JSONExt.deepCopy(Ju.metadata),content:Pu.JSONExt.deepCopy(Ju.content),channel:Ju.channel,buffers:Ju.buffers?Ju.buffers.slice():[]};od.header.msg_type="update_display_data",await Promise.all(td.map(async sd=>{const ad=this._futures&&this._futures.get(sd);ad&&await ad.handleMsg(od)}))}if(Ju.header.msg_type==="update_display_data")return!0;td=(Yu=this._displayIdToParentIds.get(Zu))!==null&&Yu!==void 0?Yu:[],td.indexOf(ed)===-1&&td.push(ed),this._displayIdToParentIds.set(Zu,td);const nd=(Xu=this._msgIdToDisplayIds.get(ed))!==null&&Xu!==void 0?Xu:[];return nd.indexOf(ed)===-1&&nd.push(ed),this._msgIdToDisplayIds.set(ed,nd),!1}_clearSocket(){this._ws!==null&&(this._ws.onopen=this._noOp,this._ws.onclose=this._noOp,this._ws.onerror=this._noOp,this._ws.onmessage=this._noOp,this._ws.close(),this._ws=null)}_updateStatus(Zu){this._status===Zu||this._status==="dead"||(this._status=Zu,Gu.logKernelStatus(this),this._statusChanged.emit(Zu),Zu==="dead"&&this.dispose())}_sendPending(){for(;this.connectionStatus==="connected"&&!this._isRestarting&&this._pendingMessages.length>0;)this._sendMessage(this._pendingMessages[0],!1),this._pendingMessages.shift()}_clearKernelState(){this._kernelSession="",this._pendingMessages=[],this._futures.forEach(Zu=>{Zu.dispose()}),this._comms.forEach(Zu=>{Zu.dispose()}),this._msgChain=Promise.resolve(),this._futures=new Map,this._comms=new Map,this._displayIdToParentIds.clear(),this._msgIdToDisplayIds.clear()}_assertCurrentMessage(Zu){if(this._errorIfDisposed(),Zu.header.session!==this._kernelSession)throw new Error(`Canceling handling of old message: ${Zu.header.msg_type}`)}async _handleCommOpen(Zu){this._assertCurrentMessage(Zu);const Ju=Zu.content,Yu=new Du.CommHandler(Ju.target_name,Ju.comm_id,this,()=>{this._unregisterComm(Ju.comm_id)},this.commsOverSubshells);this._comms.set(Ju.comm_id,Yu);try{await(await Gu.loadObject(Ju.target_name,Ju.target_module,this._targetRegistry))(Yu,Zu)}catch(Xu){throw Yu.close(),console.error("Exception opening new comm"),Xu}}async _handleCommClose(Zu){this._assertCurrentMessage(Zu);const Ju=Zu.content,Yu=this._comms.get(Ju.comm_id);if(!Yu){console.error("Comm not found for comm id "+Ju.comm_id);return}this._unregisterComm(Yu.commId);const Xu=Yu.onClose;Xu&&await Xu(Zu),Yu.dispose()}async _handleCommMsg(Zu){this._assertCurrentMessage(Zu);const Ju=Zu.content,Yu=this._comms.get(Ju.comm_id);if(!Yu)return;const Xu=Yu.onMsg;Xu&&await Xu(Zu)}_unregisterComm(Zu){this._comms.delete(Zu)}_updateConnectionStatus(Zu){if(this._connectionStatus!==Zu){if(this._connectionStatus=Zu,Zu!=="connecting"&&(this._reconnectAttempt=0,clearTimeout(this._reconnectTimeout)),this.status!=="dead")if(Zu==="connected"){let Ju=this._isRestarting,Yu=this.requestKernelInfo(),Xu=!1,ed=()=>{Xu||(Xu=!0,Ju&&this._isRestarting&&(this._isRestarting=!1,this._kernelSession=""),clearTimeout(td),this._pendingMessages.length>0&&this._sendPending())};Yu.then(()=>{Ju&&(this._isRestarting=!1),ed()});let td=setTimeout(ed,this._kernelInfoTimeout)}else this._updateStatus("unknown");this._connectionStatusChanged.emit(Zu)}}async _handleMessage(Zu){var Ju,Yu;let Xu=!1;if(Zu.parent_header&&Zu.channel==="iopub"&&(Lu.isDisplayDataMsg(Zu)||Lu.isUpdateDisplayDataMsg(Zu)||Lu.isExecuteResultMsg(Zu))){const td=((Ju=Zu.content.transient)!==null&&Ju!==void 0?Ju:{}).display_id;td&&(Xu=await this._handleDisplayId(td,Zu),this._assertCurrentMessage(Zu))}if(!Xu&&Zu.parent_header){const ed=Zu.parent_header,td=(Yu=this._futures)===null||Yu===void 0?void 0:Yu.get(ed.msg_id);if(td)await td.handleMsg(Zu),this._assertCurrentMessage(Zu);else{const nd=ed.session===this.clientId;Zu.channel!=="iopub"&&nd&&this._unhandledMessage.emit(Zu)}}if(Zu.channel==="iopub"){switch(Zu.header.msg_type){case"status":{const ed=Uu.PageConfig.getOption("untracked_message_types");if(JSON.parse(ed||"[]").includes(Zu.parent_header.msg_type))break;const nd=Zu.content.execution_state;nd==="restarting"&&Promise.resolve().then(async()=>{this._updateStatus("autorestarting"),this._clearKernelState(),await this.reconnect()}),this._updateStatus(nd);break}case"comm_open":this.handleComms&&await this._handleCommOpen(Zu);break;case"comm_msg":this.handleComms&&await this._handleCommMsg(Zu);break;case"comm_close":this.handleComms&&await this._handleCommClose(Zu);break}this.isDisposed||(this._assertCurrentMessage(Zu),this._iopubMessage.emit(Zu))}}_reconnect(){if(this._errorIfDisposed(),clearTimeout(this._reconnectTimeout),this._reconnectAttempt<this._reconnectLimit){this._updateConnectionStatus("connecting");const Zu=Gu.getRandomIntInclusive(0,1e3*(Math.pow(2,this._reconnectAttempt)-1));console.warn(`Connection lost, reconnecting in ${Math.floor(Zu/1e3)} seconds.`);const Ju=this._selectedProtocol!=="";this._reconnectTimeout=setTimeout(this._createSocket,Zu,Ju),this._reconnectAttempt+=1}else this._updateConnectionStatus("disconnected");this._clearSocket()}_errorIfDisposed(){if(this.isDisposed)throw new Error("Kernel connection is disposed")}get hasPendingInput(){return this._hasPendingInput}set hasPendingInput(Zu){this._hasPendingInput=Zu,this._pendingInput.emit(Zu)}}Au.KernelConnection=Vu;var Gu;(function(Wu){function Zu(ed){switch(ed.status){case"idle":case"busy":case"unknown":return;default:console.debug(`Kernel: ${ed.status} (${ed.id})`);break}}Wu.logKernelStatus=Zu;async function Ju(ed,td){return ed.sendShellMessage(td,!0).done}Wu.handleShellMessage=Ju;function Yu(ed,td,nd){return new Promise((od,sd)=>{if(td){if(typeof requirejs>"u")throw new Error("requirejs not found");requirejs([td],ad=>{if(ad[ed]===void 0){const pd=`Object '${ed}' not found in module '${td}'`;sd(new Error(pd))}else od(ad[ed])},sd)}else nd?.[ed]?od(nd[ed]):sd(new Error(`Object '${ed}' not found in registry`))})}Wu.loadObject=Yu;function Xu(ed,td){return ed=Math.ceil(ed),td=Math.floor(td),Math.floor(Math.random()*(td-ed+1))+ed}Wu.getRandomIntInclusive=Xu})(Gu||(Gu={}))})(_default$3)),_default$3}var manager$5={},hasRequiredManager$5;function requireManager$5(){if(hasRequiredManager$5)return manager$5;hasRequiredManager$5=1,Object.defineProperty(manager$5,"__esModule",{value:!0}),manager$5.KernelManager=void 0;const Au=require$$1$1,lo=require$$0$2,$u=requireLib$8(),Ru=requireBasemanager(),Iu=requireRestapi$4(),Pu=require_default$2(),Ou=requireRestapi$3();class Mu extends Ru.BaseManager{constructor(Lu={}){var Bu,ju,Fu;super(Lu),this._commsOverSubshells=$u.CommsOverSubshells.PerCommTarget,this._isReady=!1,this._kernelConnections=new Set,this._models=new Map,this._runningChanged=new lo.Signal(this),this._connectionFailure=new lo.Signal(this),this._kernelInfoTimeout=Pu.DEFAULT_KERNEL_INFO_TIMEOUT,this._kernelAPIClient=(Bu=Lu.kernelAPIClient)!==null&&Bu!==void 0?Bu:new Iu.KernelAPIClient({serverSettings:this.serverSettings}),this._kernelSpecAPIClient=(ju=Lu.kernelSpecAPIClient)!==null&&ju!==void 0?ju:new Ou.KernelSpecAPIClient({serverSettings:this.serverSettings}),this._pollModels=new Au.Poll({auto:!1,factory:()=>this.requestRunning(),frequency:{interval:10*1e3,backoff:!0,max:300*1e3},name:"@jupyterlab/services:KernelManager#models",standby:(Fu=Lu.standby)!==null&&Fu!==void 0?Fu:"when-hidden"}),this._ready=(async()=>{await this._pollModels.start(),await this._pollModels.tick,this._isReady=!0})()}get isReady(){return this._isReady}get ready(){return this._ready}get runningChanged(){return this._runningChanged}get connectionFailure(){return this._connectionFailure}get kernelInfoTimeout(){return this._kernelInfoTimeout}set kernelInfoTimeout(Lu){this._kernelInfoTimeout=Lu}dispose(){this.isDisposed||(this._models.clear(),this._kernelConnections.forEach(Lu=>Lu.dispose()),this._pollModels.dispose(),super.dispose())}connectTo(Lu){var Bu,ju;const{id:Fu}=Lu.model;let zu=(Bu=Lu.handleComms)!==null&&Bu!==void 0?Bu:!0;if(Lu.handleComms===void 0){for(const Hu of this._kernelConnections)if(Hu.id===Fu&&Hu.handleComms){zu=!1;break}}const Uu=new Pu.KernelConnection({handleComms:zu,...Lu,commsOverSubshells:(ju=Lu.commsOverSubshells)!==null&&ju!==void 0?ju:this._commsOverSubshells,serverSettings:this.serverSettings,kernelAPIClient:this._kernelAPIClient,kernelSpecAPIClient:this._kernelSpecAPIClient,kernelInfoTimeout:this._kernelInfoTimeout});return this._onStarted(Uu),this._models.has(Fu)||this.refreshRunning().catch(()=>{}),Uu}running(){return this._models.values()}get runningCount(){return this._models.size}get commsOverSubshells(){return this._commsOverSubshells}set commsOverSubshells(Lu){this._commsOverSubshells=Lu;for(const Bu of this._kernelConnections)Bu.commsOverSubshells=Lu}async refreshRunning(){await this._pollModels.refresh(),await this._pollModels.tick}async startNew(Lu={},Bu={}){const ju=await this._kernelAPIClient.startNew(Lu);return this.connectTo({...Bu,model:ju})}async shutdown(Lu){await this._kernelAPIClient.shutdown(Lu),await this.refreshRunning()}async shutdownAll(){await this.refreshRunning(),await Promise.all([...this._models.keys()].map(Lu=>this._kernelAPIClient.shutdown(Lu))),await this.refreshRunning()}async findById(Lu){return this._models.has(Lu)?this._models.get(Lu):(await this.refreshRunning(),this._models.get(Lu))}async requestRunning(){var Lu,Bu;let ju;try{ju=await this._kernelAPIClient.listRunning()}catch(Fu){throw(Fu instanceof $u.ServerConnection.NetworkError||((Lu=Fu.response)===null||Lu===void 0?void 0:Lu.status)===503||((Bu=Fu.response)===null||Bu===void 0?void 0:Bu.status)===424)&&this._connectionFailure.emit(Fu),Fu}this.isDisposed||this._models.size===ju.length&&ju.every(Fu=>{const zu=this._models.get(Fu.id);return zu?zu.connections===Fu.connections&&zu.execution_state===Fu.execution_state&&zu.last_activity===Fu.last_activity&&zu.name===Fu.name&&zu.reason===Fu.reason&&zu.traceback===Fu.traceback:!1})||(this._models=new Map(ju.map(Fu=>[Fu.id,Fu])),this._kernelConnections.forEach(Fu=>{this._models.has(Fu.id)||Fu.handleShutdown()}),this._runningChanged.emit(ju))}_onStarted(Lu){this._kernelConnections.add(Lu),Lu.statusChanged.connect(this._onStatusChanged,this),Lu.disposed.connect(this._onDisposed,this)}_onDisposed(Lu){this._kernelConnections.delete(Lu),this.refreshRunning().catch(()=>{})}_onStatusChanged(Lu,Bu){Bu==="dead"&&this.refreshRunning().catch(()=>{})}}return manager$5.KernelManager=Mu,(function(Du){class Lu extends Du{constructor(){super(...arguments),this._readyPromise=new Promise(()=>{})}get isActive(){return!1}get parentReady(){return super.ready}async startNew(ju={},Fu={}){return Promise.reject(new Error("Not implemented in no-op Kernel Manager"))}connectTo(ju){throw new Error("Not implemented in no-op Kernel Manager")}async shutdown(ju){return Promise.reject(new Error("Not implemented in no-op Kernel Manager"))}get ready(){return this.parentReady.then(()=>this._readyPromise)}async requestRunning(){return Promise.resolve()}}Du.NoopManager=Lu})(Mu||(manager$5.KernelManager=Mu={})),manager$5}var hasRequiredKernel;function requireKernel(){return hasRequiredKernel||(hasRequiredKernel=1,(function(Au){var lo=kernel$1&&kernel$1.__createBinding||(Object.create?(function(Bu,ju,Fu,zu){zu===void 0&&(zu=Fu);var Uu=Object.getOwnPropertyDescriptor(ju,Fu);(!Uu||("get"in Uu?!ju.__esModule:Uu.writable||Uu.configurable))&&(Uu={enumerable:!0,get:function(){return ju[Fu]}}),Object.defineProperty(Bu,zu,Uu)}):(function(Bu,ju,Fu,zu){zu===void 0&&(zu=Fu),Bu[zu]=ju[Fu]})),$u=kernel$1&&kernel$1.__setModuleDefault||(Object.create?(function(Bu,ju){Object.defineProperty(Bu,"default",{enumerable:!0,value:ju})}):function(Bu,ju){Bu.default=ju}),Ru=kernel$1&&kernel$1.__importStar||(function(){var Bu=function(ju){return Bu=Object.getOwnPropertyNames||function(Fu){var zu=[];for(var Uu in Fu)Object.prototype.hasOwnProperty.call(Fu,Uu)&&(zu[zu.length]=Uu);return zu},Bu(ju)};return function(ju){if(ju&&ju.__esModule)return ju;var Fu={};if(ju!=null)for(var zu=Bu(ju),Uu=0;Uu<zu.length;Uu++)zu[Uu]!=="default"&&lo(Fu,ju,zu[Uu]);return $u(Fu,ju),Fu}})(),Iu=kernel$1&&kernel$1.__exportStar||function(Bu,ju){for(var Fu in Bu)Fu!=="default"&&!Object.prototype.hasOwnProperty.call(ju,Fu)&&lo(ju,Bu,Fu)};Object.defineProperty(Au,"__esModule",{value:!0}),Au.CommsOverSubshells=Au.KernelConnection=Au.KernelAPI=Au.KernelMessage=Au.Kernel=void 0;const Pu=requireComm();Object.defineProperty(Au,"CommsOverSubshells",{enumerable:!0,get:function(){return Pu.CommsOverSubshells}});const Ou=Ru(requireKernel$1());Au.Kernel=Ou;const Mu=Ru(requireMessages());Au.KernelMessage=Mu;const Du=Ru(requireRestapi$4());Au.KernelAPI=Du;const Lu=require_default$2();Object.defineProperty(Au,"KernelConnection",{enumerable:!0,get:function(){return Lu.KernelConnection}}),Iu(requireManager$5(),Au)})(kernel$1)),kernel$1}var kernelspec$1={},kernelspec={},hasRequiredKernelspec$1;function requireKernelspec$1(){return hasRequiredKernelspec$1||(hasRequiredKernelspec$1=1,Object.defineProperty(kernelspec,"__esModule",{value:!0})),kernelspec}var manager$4={},hasRequiredManager$4;function requireManager$4(){if(hasRequiredManager$4)return manager$4;hasRequiredManager$4=1,Object.defineProperty(manager$4,"__esModule",{value:!0}),manager$4.KernelSpecManager=void 0;const Au=requireDist(),lo=require$$1$1,$u=require$$0$2,Ru=requireBasemanager(),Iu=requireRestapi$3();class Pu extends Ru.BaseManager{constructor(Mu={}){var Du,Lu;super(Mu),this._isReady=!1,this._connectionFailure=new $u.Signal(this),this._specs=null,this._specsChanged=new $u.Signal(this),this._kernelSpecAPIClient=(Du=Mu.kernelSpecAPIClient)!==null&&Du!==void 0?Du:new Iu.KernelSpecAPIClient({serverSettings:this.serverSettings}),this._ready=Promise.all([this.requestSpecs()]).then(Bu=>{}).catch(Bu=>{}).then(()=>{this.isDisposed||(this._isReady=!0)}),this._pollSpecs=new lo.Poll({auto:!1,factory:()=>this.requestSpecs(),frequency:{interval:61*1e3,backoff:!0,max:300*1e3},name:"@jupyterlab/services:KernelSpecManager#specs",standby:(Lu=Mu.standby)!==null&&Lu!==void 0?Lu:"when-hidden"}),this.ready.then(()=>{this._pollSpecs.start()})}get isReady(){return this._isReady}get ready(){return this._ready}get specs(){return this._specs}get specsChanged(){return this._specsChanged}get connectionFailure(){return this._connectionFailure}dispose(){this._pollSpecs.dispose(),super.dispose()}async refreshSpecs(){await this._pollSpecs.refresh(),await this._pollSpecs.tick}async requestSpecs(){const Mu=await this._kernelSpecAPIClient.get();this.isDisposed||Au.JSONExt.deepEqual(Mu,this._specs)||(this._specs=Mu,this._specsChanged.emit(Mu))}}return manager$4.KernelSpecManager=Pu,manager$4}var hasRequiredKernelspec;function requireKernelspec(){return hasRequiredKernelspec||(hasRequiredKernelspec=1,(function(Au){var lo=kernelspec$1&&kernelspec$1.__createBinding||(Object.create?(function(Mu,Du,Lu,Bu){Bu===void 0&&(Bu=Lu);var ju=Object.getOwnPropertyDescriptor(Du,Lu);(!ju||("get"in ju?!Du.__esModule:ju.writable||ju.configurable))&&(ju={enumerable:!0,get:function(){return Du[Lu]}}),Object.defineProperty(Mu,Bu,ju)}):(function(Mu,Du,Lu,Bu){Bu===void 0&&(Bu=Lu),Mu[Bu]=Du[Lu]})),$u=kernelspec$1&&kernelspec$1.__setModuleDefault||(Object.create?(function(Mu,Du){Object.defineProperty(Mu,"default",{enumerable:!0,value:Du})}):function(Mu,Du){Mu.default=Du}),Ru=kernelspec$1&&kernelspec$1.__importStar||(function(){var Mu=function(Du){return Mu=Object.getOwnPropertyNames||function(Lu){var Bu=[];for(var ju in Lu)Object.prototype.hasOwnProperty.call(Lu,ju)&&(Bu[Bu.length]=ju);return Bu},Mu(Du)};return function(Du){if(Du&&Du.__esModule)return Du;var Lu={};if(Du!=null)for(var Bu=Mu(Du),ju=0;ju<Bu.length;ju++)Bu[ju]!=="default"&&lo(Lu,Du,Bu[ju]);return $u(Lu,Du),Lu}})(),Iu=kernelspec$1&&kernelspec$1.__exportStar||function(Mu,Du){for(var Lu in Mu)Lu!=="default"&&!Object.prototype.hasOwnProperty.call(Du,Lu)&&lo(Du,Mu,Lu)};Object.defineProperty(Au,"__esModule",{value:!0}),Au.KernelSpecAPI=Au.KernelSpec=void 0;const Pu=Ru(requireKernelspec$1());Au.KernelSpec=Pu;const Ou=Ru(requireRestapi$3());Au.KernelSpecAPI=Ou,Iu(requireManager$4(),Au)})(kernelspec$1)),kernelspec$1}var manager$3={},builder={},hasRequiredBuilder;function requireBuilder(){if(hasRequiredBuilder)return builder;hasRequiredBuilder=1,Object.defineProperty(builder,"__esModule",{value:!0}),builder.BuildManager=void 0;const Au=requireLib$b(),lo=requireServerconnection(),$u="api/build";class Ru{constructor(Pu={}){var Ou;this.serverSettings=(Ou=Pu.serverSettings)!==null&&Ou!==void 0?Ou:lo.ServerConnection.makeSettings()}get isAvailable(){return Au.PageConfig.getOption("buildAvailable").toLowerCase()==="true"}get shouldCheck(){return Au.PageConfig.getOption("buildCheck").toLowerCase()==="true"}getStatus(){const{_url:Pu,serverSettings:Ou}=this;return lo.ServerConnection.makeRequest(Pu,{},Ou).then(Du=>{if(Du.status!==200)throw new lo.ServerConnection.ResponseError(Du);return Du.json()}).then(Du=>{if(typeof Du.status!="string")throw new Error("Invalid data");if(typeof Du.message!="string")throw new Error("Invalid data");return Du})}build(){const{_url:Pu,serverSettings:Ou}=this,Mu={method:"POST"};return lo.ServerConnection.makeRequest(Pu,Mu,Ou).then(Lu=>{if(Lu.status===400)throw new lo.ServerConnection.ResponseError(Lu,"Build aborted");if(Lu.status!==200){const Bu=`Build failed with ${Lu.status}.
485
+ `);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$1=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$1)})(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)?Zu(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 Zu(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 Zu=this._services.get(Wu);return Zu?this._plugins.get(Zu).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 Zu,Ju,Yu,Xu;this._activated=!1,this._promise=null,this._service=null,this.id=Wu.id,this.description=(Zu=Wu.description)!==null&&Zu!==void 0?Zu:"",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,Zu){const Ju=[...Gu.requires,...Gu.optional],Yu=ed=>{if(ed===Gu.provides)return!0;const td=Zu.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,Zu){const Ju=new Array,Yu=od=>{const sd=Wu.get(od),ad=[...sd.requires,...sd.optional];Ju.push(...ad.reduce((pd,vd)=>{const Sd=Zu.get(vd);return Sd&&pd.push([od,Sd]),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 Zu=new Set;for(const Ju of Gu.keys())Gu.get(Ju).autoStart===!0&&Zu.add(Ju);if(Wu.startPlugins)for(const Ju of Wu.startPlugins)Zu.add(Ju);if(Wu.ignorePlugins)for(const Ju of Wu.ignorePlugins)Zu.delete(Ju);return Array.from(Zu)}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 Zu=Wu[2];Pu.bools[Vu]&&(Zu=Zu!=="false"),Fu(Vu,Zu,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(Zu,Ju){return Fu(Ju.protocol)?Zu.replace(/\\/g,"/"):Zu},["/","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 Zu;typeof window<"u"?Zu=window:typeof globalThis<"u"?Zu=globalThis:typeof self<"u"?Zu=self:Zu={};var Ju=Zu.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,Zu){Wu=Du(Wu),Wu=Wu.replace(Ru,""),Zu=Zu||{};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(Zu.protocol)&&(nd=Ju[4]),{protocol:Yu,slashes:Xu||Fu(Yu),slashesCount:td,rest:nd}}function Uu(Wu,Zu){if(Wu==="")return Zu;for(var Ju=(Zu||"/").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,Zu,Ju){if(Wu=Du(Wu),Wu=Wu.replace(Ru,""),!(this instanceof Hu))return new Hu(Wu,Zu,Ju);var Yu,Xu,ed,td,nd,od,sd=Lu.slice(),ad=typeof Zu,pd=this,vd=0;for(ad!=="object"&&ad!=="string"&&(Ju=Zu,Zu=null),Ju&&typeof Ju!="function"&&(Ju=lo.parse),Zu=ju(Zu),Xu=zu(Wu||"",Zu),Yu=!Xu.protocol&&!Xu.slashes,pd.slashes=Xu.slashes||Yu&&Zu.slashes,pd.protocol=Xu.protocol||Zu.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"]);vd<sd.length;vd++){if(td=sd[vd],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]&&Zu[od]||"",td[4]&&(pd[od]=pd[od].toLowerCase())}Ju&&(pd.query=Ju(pd.query)),Yu&&Zu.slashes&&pd.pathname.charAt(0)!=="/"&&(pd.pathname!==""||Zu.pathname!=="")&&(pd.pathname=Uu(pd.pathname,Zu.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,Zu,Ju){var Yu=this;switch(Wu){case"query":typeof Zu=="string"&&Zu.length&&(Zu=(Ju||lo.parse)(Zu)),Yu[Wu]=Zu;break;case"port":Yu[Wu]=Zu,Au(Zu,Yu.protocol)?Zu&&(Yu.host=Yu.hostname+":"+Zu):(Yu.host=Yu.hostname,Yu[Wu]="");break;case"hostname":Yu[Wu]=Zu,Yu.port&&(Zu+=":"+Yu.port),Yu.host=Zu;break;case"host":Yu[Wu]=Zu,Pu.test(Zu)?(Zu=Zu.split(":"),Yu.port=Zu.pop(),Yu.hostname=Zu.join(":")):(Yu.hostname=Zu,Yu.port="");break;case"protocol":Yu.protocol=Zu.toLowerCase(),Yu.slashes=!Ju;break;case"pathname":case"hash":if(Zu){var Xu=Wu==="pathname"?"/":"#";Yu[Wu]=Zu.charAt(0)!==Xu?Xu+Zu:Zu}else Yu[Wu]=Zu;break;case"username":case"password":Yu[Wu]=encodeURIComponent(Zu);break;case"auth":var ed=Zu.indexOf(":");~ed?(Yu.username=Zu.slice(0,ed),Yu.username=encodeURIComponent(decodeURIComponent(Yu.username)),Yu.password=Zu.slice(ed+1),Yu.password=encodeURIComponent(decodeURIComponent(Yu.password))):Yu.username=encodeURIComponent(decodeURIComponent(Zu))}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 Zu,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,Zu=typeof Ju.query=="object"?Wu(Ju.query):Ju.query,Zu&&(ed+=Zu.charAt(0)!=="?"?"?"+Zu:Zu),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 isFormDataBody(Au){if(!Au||typeof Au!="object")return!1;if(typeof FormData<"u"&&Au instanceof FormData||Object.prototype.toString.call(Au)==="[object FormData]")return!0;const $u=Au;return typeof $u.append=="function"&&typeof $u.get=="function"&&typeof $u.has=="function"&&typeof $u.entries=="function"}class RunResponseError extends Error{static async create(lo){try{const $u=await lo.json(),{message:Ru,errors:Iu,warnings:Pu,traceback:Ou,exception:Mu,detail:Du}=$u,Lu=Ru??(typeof Du=="string"?Du:Du&&typeof Du=="object"&&"message"in Du?String(Du.message):void 0);return Ou&&console.error(Ou),new RunResponseError(lo,Lu??RunResponseError._defaultMessage(lo),Pu,Iu,Mu,Ou??"",Du)}catch($u){return console.debug($u),new RunResponseError(lo)}}constructor(lo,$u=RunResponseError._defaultMessage(lo),Ru=void 0,Iu=void 0,Pu=void 0,Ou="",Mu=void 0){super($u),this.name="RunResponseError",this.warnings=Ru??[],this.errors=Iu??[],this.response=lo,this.exceptionMessage=Pu,this.traceback=Ou,this.detail=Mu}warnings;errors;response;exceptionMessage;traceback;detail;static _defaultMessage(lo){return`Invalid response: ${lo.status} ${lo.statusText}`}}class NetworkError extends TypeError{constructor(lo){super(lo.message),this.name="NetworkError",this.stack=lo.stack}}class TokenExpiredError extends Error{expiredAt;url;constructor(lo,$u){super(`The Datalayer token expired at ${new Date($u).toISOString()}; not sending the request to ${lo}.`),this.name="TokenExpiredError",this.expiredAt=$u,this.url=lo,Object.setPrototypeOf(this,TokenExpiredError.prototype)}}function throwIfTokenExpired(Au,lo,$u){if(!(Au!==401||!lo||!isJwtExpired(lo)))throw new TokenExpiredError($u,getJwtExpiryMs(lo)??Date.now())}function isRawBody(Au){return typeof Au=="string"||typeof Blob<"u"&&Au instanceof Blob||Au instanceof ArrayBuffer||ArrayBuffer.isView(Au)||typeof URLSearchParams<"u"&&Au instanceof URLSearchParams||typeof ReadableStream<"u"&&Au instanceof ReadableStream}function headersToRecord(Au){const lo={};return Au.forEach(($u,Ru)=>{lo[Ru]=$u}),lo}async function readBody(Au,lo){switch(lo){case"text":return Au.text();case"blob":return Au.blob();case"arraybuffer":return Au.arrayBuffer();case"stream":return Au.body;default:{const $u=await Au.text();try{return JSON.parse($u)}catch{return $u}}}}async function send(Au,lo,$u){let Ru;try{Ru=await fetch(Au,lo)}catch(Iu){throw Iu?.name==="AbortError"?Iu:new NetworkError(Iu instanceof Error?Iu:new TypeError(String(Iu)))}if(!Ru.ok)throw throwIfTokenExpired(Ru.status,$u,Au),await RunResponseError.create(Ru);return Ru}async function requestDatalayerAPIWithResponse({url:Au,method:lo,body:$u,token:Ru,signal:Iu,responseType:Pu,headers:Ou={}}){const Mu=lo??"GET",Du=new Headers(Ou);Mu==="GET"&&(Du.has("Cache-Control")||Du.set("Cache-Control","no-store, no-cache, must-revalidate"),Du.has("Pragma")||Du.set("Pragma","no-cache")),Ru&&Du.set("Authorization",`Bearer ${Ru}`),Du.has("Accept")||Du.set("Accept","application/json");let Lu;isFormDataBody($u)?Lu=$u:(Du.has("Content-Type")||Du.set("Content-Type","application/json"),$u===void 0?Lu=void 0:isRawBody($u)?Lu=$u:Lu=JSON.stringify($u));const Bu={method:Mu,headers:Du,body:Lu,credentials:"include",signal:Iu};let ju=await send(Au,Bu,Ru);return ju.status===202&&ju.headers.get("location")&&(ju=await followAsyncRedirect(ju,Bu,Au,Ru)),{data:await readBody(ju,Pu),status:ju.status,statusText:ju.statusText,headers:headersToRecord(ju.headers)}}async function requestDatalayerAPI(Au){return(await requestDatalayerAPIWithResponse(Au)).data}function resolveLocation(Au,lo){const $u=Au.replace(/^([a-z][a-z0-9+.-]*):\/(?!\/)/i,"$1://");try{const Ru=new URL($u,lo),Iu=new URL(lo,typeof window<"u"?window.location.origin:void 0);return Iu.protocol==="https:"&&Ru.protocol==="http:"&&Ru.hostname===Iu.hostname&&(Ru.protocol="https:",Ru.port==="80"&&(Ru.port="")),Ru.toString()}catch{const Ru=libExports$5.URLExt.parse(lo),Iu=Ru.protocol+"//"+Ru.hostname;return libExports$5.URLExt.join(Iu,$u)}}async function followAsyncRedirect(Au,lo,$u,Ru){const Iu=resolveLocation(Au.headers.get("location"),$u),Pu={...lo,method:"GET",body:void 0};let Ou=1e3;for(;Au.status===202;)await sleep$1(Ou),Ou*=2,Au=await send(Iu,Pu,Ru);return Au}const userToProfile=Au=>Au?{id:Au.id,uid:Au.uid,handle:Au.handle,email:Au.email,firstName:Au.firstName,lastName:Au.lastName,displayName:Au.displayName,initials:Au.initials,avatarUrl:Au.avatarUrl,avatarIcon:Au.avatarIcon,banner:Au.banner,showOrbits:Au.showOrbits,origin:Au.origin,roles:Au.roles}:void 0,profileStore=createStore$1(Au=>({profile:void 0,setProfile:lo=>Au({profile:lo}),updateProfile:lo=>Au($u=>({profile:{...$u.profile,...lo}})),setProfileFromUser:lo=>Au($u=>{const Ru=userToProfile(lo);if(!Ru)return $u;const Iu={...$u.profile};for(const[Pu,Ou]of Object.entries(Ru))Ou!==void 0&&(Iu[Pu]=Ou);return{profile:Iu}}),clearProfile:()=>Au({profile:void 0})}));function useProfileStore(Au){return useStore$1(profileStore,Au)}const useProfile=()=>useProfileStore(Au=>Au.profile),SESSION_COOKIES=["datalayer-space-context","datalayer-principal-context","datalayer-billing-entity-uid","otel_sql_history"],SESSION_LOCAL_STORAGE_KEYS=["datalayer-principal","datalayer-billing-entity","datalayer-simple-auth"],SESSION_OWNER_KEY="datalayer-session-owner",registrations=new Set,registerSessionState=Au=>(registrations.add(Au),()=>{registrations.delete(Au)}),storageOf=Au=>{try{return typeof window>"u"?void 0:window[Au]}catch{return}},removeFrom=(Au,lo)=>{try{Au?.removeItem(lo)}catch{}},deleteCookie=Au=>{typeof document>"u"||(document.cookie=`${Au}=; path=/; max-age=0; SameSite=Lax`)},readCookie$1=Au=>{if(typeof document>"u")return;const lo=`${Au}=`,$u=document.cookie.split(";").map(Ru=>Ru.trim()).find(Ru=>Ru.startsWith(lo));return $u?$u.slice(lo.length):void 0},forgetSessionState=()=>{const Au=new Set(SESSION_COOKIES),lo=new Set([...SESSION_LOCAL_STORAGE_KEYS,SESSION_OWNER_KEY]),$u=new Set;for(const Pu of registrations){try{Pu.forget?.()}catch(Ou){console.warn("A session state could not be reset.",Ou)}Pu.cookies?.forEach(Ou=>Au.add(Ou)),Pu.localStorageKeys?.forEach(Ou=>lo.add(Ou)),Pu.sessionStorageKeys?.forEach(Ou=>$u.add(Ou))}Au.forEach(deleteCookie);const Ru=storageOf("localStorage");lo.forEach(Pu=>removeFrom(Ru,Pu));const Iu=storageOf("sessionStorage");$u.forEach(Pu=>removeFrom(Iu,Pu))},personalPrincipalInCookie=()=>{const Au=readCookie$1("datalayer-principal-context");if(Au)try{const lo=JSON.parse(decodeURIComponent(Au));return lo?.selectedPrincipalKind==="personal"&&String(lo?.selectedPrincipalUid??"").trim()||void 0}catch{return}},claimSessionState=Au=>{const lo=String(Au??"").trim();if(!lo)return;const $u=storageOf("localStorage");let Ru;try{Ru=$u?.getItem(SESSION_OWNER_KEY)??null}catch{Ru=null}const Iu=personalPrincipalInCookie();(Ru&&Ru!==lo||!Ru&&Iu&&Iu!==lo)&&forgetSessionState();try{$u?.setItem(SESSION_OWNER_KEY,lo)}catch{}},RESERVATION_WARNING_TIME_MS=5*6e4,iamStore=createStore$1((Au,lo)=>({credits:void 0,creditsReservations:[],externalToken:loadRefreshTokenFromCookie()??void 0,user:getStoredUser(),token:getStoredToken(),iamUrl:coreStore.getState().configuration?.iamUrl,iamProvidersAuthorizationURL:{},version:"",isLoginInProgress:!1,addIAMProviderAuthorizationURL:($u,Ru)=>{Au(Iu=>({iamProvidersAuthorizationURL:{...Iu.iamProvidersAuthorizationURL,[$u]:Ru}}))},login:async $u=>{const{refreshUserByToken:Ru,iamUrl:Iu,logout:Pu}=lo();Au({isLoginInProgress:!0});try{const Ou=await requestDatalayerAPI({url:`${Iu}/api/iam/v1/login`,method:"POST",body:{token:$u}});if(Ou.success&&Ou.token)await Ru(Ou.token);else throw new Error("Invalid Token.")}catch(Ou){throw console.debug("Failed to login.",Ou),Ou.name==="RunResponseError"&&Ou.response.status===401&&(console.debug("Received 401 error - Logging out."),Pu()),Ou}finally{Au({isLoginInProgress:!1})}},logout:()=>{storeUser(),storeToken(),profileStore.getState().clearProfile(),forgetSessionState(),Au({credits:void 0,creditsReservations:[],user:ANONYMOUS_USER,token:ANONYMOUS_USER_TOKEN})},checkIAMToken:async $u=>{lo().token!==$u&&await lo().refreshUserByToken($u)},setIAMProviderAccessToken:($u,Ru)=>{const{user:Iu}=lo();if(!Iu)throw Error("You need to be authenticated to set an Access Token for an IAM provider.");const Pu=IAMProvidersSpecs.getProvider($u);Ru?setCookie(Pu.accessTokenCookieName(Iu),Ru):deleteCookie$1(Pu.accessTokenCookieName(Iu))},getIAMProviderAccessToken:($u,Ru)=>{const Pu=IAMProvidersSpecs.getProvider(Ru).accessTokenCookieName($u);return getCookie$1(Pu)},updateUser:$u=>Au(Ru=>{const Iu={user:{...Ru.user,...$u}};return profileStore.getState().setProfileFromUser(Iu.user),Iu}),refreshCredits:async()=>{const{externalToken:$u,token:Ru,iamUrl:Iu,logout:Pu}=lo();if(Ru)try{const Ou=await requestDatalayerAPI({url:`${Iu}/api/iam/v1/usage/credits`,token:Ru,headers:$u?{"X-External-Token":$u}:void 0}),{credits:Mu,reservations:Du=[]}=Ou;Au({credits:{...Mu,available:availableCredits(Mu,Du)},creditsReservations:Du})}catch(Ou){throw console.error("Failed to refresh user credits.",Ou),Ou.name==="RunResponseError"&&Ou.response.status===401&&(console.error("Received 401, logging out."),Pu()),Ou}else Au({credits:void 0})},refreshUser:async()=>{const{token:$u,refreshUserByToken:Ru,logout:Iu}=lo();$u?await Ru($u):Iu()},refreshUserByTokenStored:async()=>{const $u=getStoredToken();$u?await lo().refreshUserByToken($u):lo().logout()},refreshUserByToken:async $u=>{const{iamUrl:Ru,logout:Iu,isLoginInProgress:Pu}=lo();try{const Ou=await requestDatalayerAPI({url:`${Ru}/api/iam/v1/whoami`,token:$u}),Mu=asUser(Ou.profile);claimSessionState(Mu?.id??Mu?.uid),storeUser(Mu),storeToken($u),Au(()=>({user:Mu,token:$u}))}catch(Ou){Ou.name==="RunResponseError"&&Ou.response.status===401?console.debug("Invalid token - Received 401 error."):console.debug("Failed to fetch user identity.",Ou),Pu||Iu()}},setExternalToken:$u=>Au(Ru=>({externalToken:$u})),setLogin:($u,Ru)=>Au(Iu=>(claimSessionState($u?.id??$u?.uid),storeUser($u),storeToken(Ru),profileStore.getState().setProfileFromUser($u),{user:$u,token:Ru})),setVersion:$u=>{$u&&!lo().version&&Au(Ru=>({version:$u}))}}));function useIAMStore(Au){return useStore$1(iamStore,Au)}const creditsPoll=new Poll({name:"@datalayer/ui:credits-refresh",factory:()=>iamStore.getState().refreshCredits(),auto:!1,frequency:{interval:60*1e3,backoff:!0,max:600*1e3},standby:()=>iamStore.getState().user?.id?"when-hidden":!0});iamStore.getState().refreshUserByTokenStored().catch(Au=>{console.error("Failed to refresh to validate the stored token.",Au)}).finally(()=>{const{externalToken:Au,iamUrl:lo,checkIAMToken:$u,token:Ru}=iamStore.getState();!Ru&&Au&&(console.debug("Can not login with token - Trying with the external token."),requestDatalayerAPI({url:`${lo}/api/iam/v1/login`,method:"POST",body:{token:Au}}).then(Pu=>{Pu.token&&$u(Pu.token)}).catch(Pu=>{console.debug("Can not login with token.",Ru,Pu)})),Ru?console.log("Logged in with token and external token."):console.debug("Failed to login with token and no external token available."),creditsPoll.start(),(()=>{if(typeof window>"u")return;const Pu=window.document;if(!Pu||typeof Pu.addEventListener!="function")return;const Ou=()=>{!Pu.hidden&&iamStore.getState().user?.id&&creditsPoll.refresh()};Pu.addEventListener("visibilitychange",Ou)})()});coreStore.subscribe((Au,lo)=>{if(Au.configuration?.iamUrl&&Au.configuration.iamUrl!==lo.configuration?.iamUrl){const $u=Au.configuration.iamUrl;console.log("Updating iamUrl with new value",$u),iamStore.setState({iamUrl:$u}),iamStore.getState().externalToken?iamStore.getState().login(iamStore.getState().externalToken).catch(Ru=>{console.error("Failed to refresh the user after updating the IAM RUN URL.",Ru)}):iamStore.getState().refreshUser().catch(Ru=>{console.error("Failed to refresh the user after updating the IAM server URL.",Ru)})}});function emojiKey(Au){return Array.from(Au.trim()).map(lo=>lo.codePointAt(0)??0).filter(lo=>lo!==65039).map(lo=>lo.toString(16)).join("-")}const scriptRel=(function Au(){const lo=typeof document<"u"&&document.createElement("link").relList;return lo&&lo.supports&&lo.supports("modulepreload")?"modulepreload":"preload"})(),assetsURL=function(Au,lo){return new URL(Au,lo).href},seen={},__vitePreload=function Au(lo,$u,Ru){let Iu=Promise.resolve();if($u&&$u.length>0){let Lu=function(Bu){return Promise.all(Bu.map(ju=>Promise.resolve(ju).then(Fu=>({status:"fulfilled",value:Fu}),Fu=>({status:"rejected",reason:Fu}))))};const Ou=document.getElementsByTagName("link"),Mu=document.querySelector("meta[property=csp-nonce]"),Du=Mu?.nonce||Mu?.getAttribute("nonce");Iu=Lu($u.map(Bu=>{if(Bu=assetsURL(Bu,Ru),Bu in seen)return;seen[Bu]=!0;const ju=Bu.endsWith(".css"),Fu=ju?'[rel="stylesheet"]':"";if(Ru)for(let Uu=Ou.length-1;Uu>=0;Uu--){const Hu=Ou[Uu];if(Hu.href===Bu&&(!ju||Hu.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${Bu}"]${Fu}`))return;const zu=document.createElement("link");if(zu.rel=ju?"stylesheet":scriptRel,ju||(zu.as="script"),zu.crossOrigin="",zu.href=Bu,Du&&zu.setAttribute("nonce",Du),document.head.appendChild(zu),ju)return new Promise((Uu,Hu)=>{zu.addEventListener("load",Uu),zu.addEventListener("error",()=>Hu(new Error(`Unable to preload CSS for ${Bu}`)))})}))}function Pu(Ou){const Mu=new Event("vite:preloadError",{cancelable:!0});if(Mu.payload=Ou,window.dispatchEvent(Mu),!Mu.defaultPrevented)throw Ou}return Iu.then(Ou=>{for(const Mu of Ou||[])Mu.status==="rejected"&&Pu(Mu.reason);return lo().catch(Pu)})},FLUENT_EMOJI_LOADERS={"1f440":()=>__vitePreload(()=>import("./chunks/1f440-p4rvIPef.js"),[],import.meta.url),"1f4d1":()=>__vitePreload(()=>import("./chunks/1f4d1-2yeMP7i5.js"),[],import.meta.url),"1f399":()=>__vitePreload(()=>import("./chunks/1f399-GX_7MVl_.js"),[],import.meta.url),"1f6a2":()=>__vitePreload(()=>import("./chunks/1f6a2-gL6kUzw5.js"),[],import.meta.url),"1f69a":()=>__vitePreload(()=>import("./chunks/1f69a-CbAMmMYx.js"),[],import.meta.url),"1f50e":()=>__vitePreload(()=>import("./chunks/1f50e-CNC8yd3r.js"),[],import.meta.url),"1f4ec":()=>__vitePreload(()=>import("./chunks/1f4ec-e7JJiuI4.js"),[],import.meta.url),"1f4c8":()=>__vitePreload(()=>import("./chunks/1f4c8-CNuFlfRg.js"),[],import.meta.url),"1f9f9":()=>__vitePreload(()=>import("./chunks/1f9f9-DNoxae13.js"),[],import.meta.url),"1f9e0":()=>__vitePreload(()=>import("./chunks/1f9e0-7eqXrAdK.js"),[],import.meta.url),"1f6df":()=>__vitePreload(()=>import("./chunks/1f6df-DcnntiKi.js"),[],import.meta.url),"1f9ee":()=>__vitePreload(()=>import("./chunks/1f9ee-BuIxmQEW.js"),[],import.meta.url),"1f47e":()=>__vitePreload(()=>import("./chunks/1f47e-CVrptMZb.js"),[],import.meta.url),"1f47d":()=>__vitePreload(()=>import("./chunks/1f47d-DKGX1RHr.js"),[],import.meta.url),"1f9d1-200d-1f680":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f680-C9wxDlc0.js"),[],import.meta.url),"269b":()=>__vitePreload(()=>import("./chunks/269b-CIDlSWpG.js"),[],import.meta.url),"1f3e6":()=>__vitePreload(()=>import("./chunks/1f3e6-LRmfNoyK.js"),[],import.meta.url),2712:()=>__vitePreload(()=>import("./chunks/2712-5PLssGP2.js"),[],import.meta.url),"1f4bc":()=>__vitePreload(()=>import("./chunks/1f4bc-DPph9Yum.js"),[],import.meta.url),"1f3db":()=>__vitePreload(()=>import("./chunks/1f3db-D8W2ZDGL.js"),[],import.meta.url),"1f3d7":()=>__vitePreload(()=>import("./chunks/1f3d7-BCgsEYI1.js"),[],import.meta.url),"1f3e2":()=>__vitePreload(()=>import("./chunks/1f3e2-Ck-pGqVC.js"),[],import.meta.url),"1f3af":()=>__vitePreload(()=>import("./chunks/1f3af-BjGhox67.js"),[],import.meta.url),2601:()=>__vitePreload(()=>import("./chunks/2601-BxBuW0c5.js"),[],import.meta.url),"1f6a7":()=>__vitePreload(()=>import("./chunks/1f6a7-Bf7dX4bM.js"),[],import.meta.url),"1f477":()=>__vitePreload(()=>import("./chunks/1f477--ZfEh0BR.js"),[],import.meta.url),"1f920":()=>__vitePreload(()=>import("./chunks/1f920-DdqVzdU_.js"),[],import.meta.url),"1f9ec":()=>__vitePreload(()=>import("./chunks/1f9ec-BiccuNAi.js"),[],import.meta.url),"1f432":()=>__vitePreload(()=>import("./chunks/1f432-BBBxgCDF.js"),[],import.meta.url),"1f409":()=>__vitePreload(()=>import("./chunks/1f409-B-A-r5OE.js"),[],import.meta.url),"1f9dd":()=>__vitePreload(()=>import("./chunks/1f9dd-Bjlh5f8S.js"),[],import.meta.url),"1f525":()=>__vitePreload(()=>import("./chunks/1f525-DugGj6UX.js"),[],import.meta.url),"1f386":()=>__vitePreload(()=>import("./chunks/1f386-D1j06612.js"),[],import.meta.url),"1f6f8":()=>__vitePreload(()=>import("./chunks/1f6f8-CzpZp4fr.js"),[],import.meta.url),"1f340":()=>__vitePreload(()=>import("./chunks/1f340-B2CJ9tGB.js"),[],import.meta.url),"1f393":()=>__vitePreload(()=>import("./chunks/1f393-Cule2ZWh.js"),[],import.meta.url),"1f600":()=>__vitePreload(()=>import("./chunks/1f600-DHzS58-a.js"),[],import.meta.url),"1f3e0":()=>__vitePreload(()=>import("./chunks/1f3e0-Dvy0EpCV.js"),[],import.meta.url),"1f98e":()=>__vitePreload(()=>import("./chunks/1f98e-BRdu0IxY.js"),[],import.meta.url),"1fa84":()=>__vitePreload(()=>import("./chunks/1fa84-C7Zz9Ttn.js"),[],import.meta.url),"1f9d1-200d-1f4bc":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f4bc-FkyMuHj6.js"),[],import.meta.url),"1f9d1-200d-1f4bb":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f4bb-Bxh01EAD.js"),[],import.meta.url),"1f3b5":()=>__vitePreload(()=>import("./chunks/1f3b5-BdjcFmdt.js"),[],import.meta.url),"1f977":()=>__vitePreload(()=>import("./chunks/1f977-g-J1jf1x.js"),[],import.meta.url),"1f450":()=>__vitePreload(()=>import("./chunks/1f450-CbtsXspW.js"),[],import.meta.url),"1f58a":()=>__vitePreload(()=>import("./chunks/1f58a-mulZ-CFH.js"),[],import.meta.url),"1f427":()=>__vitePreload(()=>import("./chunks/1f427-DglaWI4D.js"),[],import.meta.url),"1f3c4":()=>__vitePreload(()=>import("./chunks/1f3c4-BhpD29zf.js"),[],import.meta.url),"1f3ca":()=>__vitePreload(()=>import("./chunks/1f3ca-gIlr1kJ5.js"),[],import.meta.url),"1f5bc":()=>__vitePreload(()=>import("./chunks/1f5bc-MigptVzH.js"),[],import.meta.url),"1f304":()=>__vitePreload(()=>import("./chunks/1f304-aDc2qDui.js"),[],import.meta.url),"1f6eb":()=>__vitePreload(()=>import("./chunks/1f6eb-lf0G-q-a.js"),[],import.meta.url),"1fa90":()=>__vitePreload(()=>import("./chunks/1fa90-Ccp91l-o.js"),[],import.meta.url),"1f916":()=>__vitePreload(()=>import("./chunks/1f916-BqoYgu9n.js"),[],import.meta.url),"1f680":()=>__vitePreload(()=>import("./chunks/1f680-dnPjZK4l.js"),[],import.meta.url),"1f385":()=>__vitePreload(()=>import("./chunks/1f385-Dt5AZfN7.js"),[],import.meta.url),"1f6f0":()=>__vitePreload(()=>import("./chunks/1f6f0-DiDzAbox.js"),[],import.meta.url),"1f9d1-200d-1f52c":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f52c-DIXbDrbI.js"),[],import.meta.url),"1f988":()=>__vitePreload(()=>import("./chunks/1f988-wqhZ7Rxe.js"),[],import.meta.url),2603:()=>__vitePreload(()=>import("./chunks/2603-DNj-gj-j.js"),[],import.meta.url),"1f387":()=>__vitePreload(()=>import("./chunks/1f387-D0SVWvyW.js"),[],import.meta.url),"2b50":()=>__vitePreload(()=>import("./chunks/2b50-DgcciXHA.js"),[],import.meta.url),"1f9d1-200d-1f393":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f393-DhlpNrMG.js"),[],import.meta.url),2600:()=>__vitePreload(()=>import("./chunks/2600-DZnZtR2D.js"),[],import.meta.url),"1f44b":()=>__vitePreload(()=>import("./chunks/1f44b-CDEzsnIT.js"),[],import.meta.url),"1f433":()=>__vitePreload(()=>import("./chunks/1f433-BGsjKcaL.js"),[],import.meta.url),"1f381":()=>__vitePreload(()=>import("./chunks/1f381-NG1UoP_K.js"),[],import.meta.url),"270d":()=>__vitePreload(()=>import("./chunks/270d-DAjo8CgW.js"),[],import.meta.url),"262f":()=>__vitePreload(()=>import("./chunks/262f-BHwzZDRR.js"),[],import.meta.url),"1f4ca":()=>__vitePreload(()=>import("./chunks/1f4ca-DwUKcdqA.js"),[],import.meta.url),"1f4dd":()=>__vitePreload(()=>import("./chunks/1f4dd-CjeXE9pk.js"),[],import.meta.url),"1f4c5":()=>__vitePreload(()=>import("./chunks/1f4c5-BuR_5gXZ.js"),[],import.meta.url),"1f5d3":()=>__vitePreload(()=>import("./chunks/1f5d3-CD7YTnlH.js"),[],import.meta.url),"1f4da":()=>__vitePreload(()=>import("./chunks/1f4da-T00kbbB7.js"),[],import.meta.url),"1f4a1":()=>__vitePreload(()=>import("./chunks/1f4a1-DuAncIYW.js"),[],import.meta.url),"1f527":()=>__vitePreload(()=>import("./chunks/1f527-DGFX9oVv.js"),[],import.meta.url),"1f6e0":()=>__vitePreload(()=>import("./chunks/1f6e0-BN_iAibr.js"),[],import.meta.url),"1f9f0":()=>__vitePreload(()=>import("./chunks/1f9f0-NjV-EBzJ.js"),[],import.meta.url),2699:()=>__vitePreload(()=>import("./chunks/2699-DHeK1la1.js"),[],import.meta.url),"1f9ea":()=>__vitePreload(()=>import("./chunks/1f9ea-Dn-cjqlg.js"),[],import.meta.url),"1f52c":()=>__vitePreload(()=>import("./chunks/1f52c-PWG_VsFe.js"),[],import.meta.url),"1f5c2":()=>__vitePreload(()=>import("./chunks/1f5c2-BwHVJFvn.js"),[],import.meta.url),"1f4e6":()=>__vitePreload(()=>import("./chunks/1f4e6-iVURZ5lW.js"),[],import.meta.url),"1f6d2":()=>__vitePreload(()=>import("./chunks/1f6d2-C4PVtG90.js"),[],import.meta.url),"1f6b2":()=>__vitePreload(()=>import("./chunks/1f6b2-BvodiaEs.js"),[],import.meta.url),"1f4ac":()=>__vitePreload(()=>import("./chunks/1f4ac-B0hyiBGy.js"),[],import.meta.url),"1f4e3":()=>__vitePreload(()=>import("./chunks/1f4e3-BCLpfdwX.js"),[],import.meta.url),"1f9fe":()=>__vitePreload(()=>import("./chunks/1f9fe-vjnIOB6Q.js"),[],import.meta.url),"1f4b0":()=>__vitePreload(()=>import("./chunks/1f4b0-Bgl_9Qt3.js"),[],import.meta.url),"1f4b3":()=>__vitePreload(()=>import("./chunks/1f4b3-C3bg4q6a.js"),[],import.meta.url),"1f30d":()=>__vitePreload(()=>import("./chunks/1f30d-RKwL3Nsg.js"),[],import.meta.url),"1f512":()=>__vitePreload(()=>import("./chunks/1f512-CfUiEAwd.js"),[],import.meta.url),"1f511":()=>__vitePreload(()=>import("./chunks/1f511-n1Y90TZn.js"),[],import.meta.url),"1f6e1":()=>__vitePreload(()=>import("./chunks/1f6e1-Cu0Gi0Ok.js"),[],import.meta.url),"1f9ed":()=>__vitePreload(()=>import("./chunks/1f9ed-BdM-tuKc.js"),[],import.meta.url),"1f5fa":()=>__vitePreload(()=>import("./chunks/1f5fa-BbhAXfOC.js"),[],import.meta.url),"1f4f0":()=>__vitePreload(()=>import("./chunks/1f4f0-BqBFK1vM.js"),[],import.meta.url),2709:()=>__vitePreload(()=>import("./chunks/2709-R2m2qaPB.js"),[],import.meta.url),"1f4de":()=>__vitePreload(()=>import("./chunks/1f4de-DMKOmTcC.js"),[],import.meta.url),"1f91d":()=>__vitePreload(()=>import("./chunks/1f91d-BLSo-qgX.js"),[],import.meta.url),"1f3e5":()=>__vitePreload(()=>import("./chunks/1f3e5-BZAbo425.js"),[],import.meta.url),2696:()=>__vitePreload(()=>import("./chunks/2696-DCPh-ddG.js"),[],import.meta.url),"1f3a8":()=>__vitePreload(()=>import("./chunks/1f3a8-BVDoGacX.js"),[],import.meta.url),"1f3ac":()=>__vitePreload(()=>import("./chunks/1f3ac-D8k4rvLe.js"),[],import.meta.url),"1f4f7":()=>__vitePreload(()=>import("./chunks/1f4f7-BwaVsOpm.js"),[],import.meta.url),"1f9d1-200d-1f3eb":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f3eb-CMaKZADj.js"),[],import.meta.url),"1f9d1-200d-2695":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-2695-DCucKT0e.js"),[],import.meta.url),"1f9d1-200d-1f373":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f373-DvkX_q7n.js"),[],import.meta.url),"1f9d1-200d-1f33e":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-1f33e-C1GbmRM7.js"),[],import.meta.url),"1f331":()=>__vitePreload(()=>import("./chunks/1f331-_RrI1iL2.js"),[],import.meta.url),"1f41d":()=>__vitePreload(()=>import("./chunks/1f41d-BFxQMyWe.js"),[],import.meta.url),"1f989":()=>__vitePreload(()=>import("./chunks/1f989-BnANhNFy.js"),[],import.meta.url),"1f98a":()=>__vitePreload(()=>import("./chunks/1f98a-D9FmXaXZ.js"),[],import.meta.url),"1f419":()=>__vitePreload(()=>import("./chunks/1f419-5WEpY3Qm.js"),[],import.meta.url),2764:()=>__vitePreload(()=>import("./chunks/2764-BqnS842k.js"),[],import.meta.url),2705:()=>__vitePreload(()=>import("./chunks/2705-C2znzsf2.js"),[],import.meta.url),"23f0":()=>__vitePreload(()=>import("./chunks/23f0-dWLnhjSv.js"),[],import.meta.url),"1f514":()=>__vitePreload(()=>import("./chunks/1f514-B1X39g06.js"),[],import.meta.url),"1f9e9":()=>__vitePreload(()=>import("./chunks/1f9e9-i_U9-xN7.js"),[],import.meta.url),"1f3f7":()=>__vitePreload(()=>import("./chunks/1f3f7-CcKaOA8W.js"),[],import.meta.url),"1f4cb":()=>__vitePreload(()=>import("./chunks/1f4cb-oUiKe7zE.js"),[],import.meta.url),"1f4cc":()=>__vitePreload(()=>import("./chunks/1f4cc-CBUTvGMt.js"),[],import.meta.url),"1f50d":()=>__vitePreload(()=>import("./chunks/1f50d-1bvZKHvT.js"),[],import.meta.url),"1f642":()=>__vitePreload(()=>import("./chunks/1f642-C6Qm_-ba.js"),[],import.meta.url),"1f913":()=>__vitePreload(()=>import("./chunks/1f913-hQT-pf0C.js"),[],import.meta.url),"1f9d0":()=>__vitePreload(()=>import("./chunks/1f9d0-Bg0qtSKU.js"),[],import.meta.url),"1f60e":()=>__vitePreload(()=>import("./chunks/1f60e-Dxrd05Jo.js"),[],import.meta.url),"1f984":()=>__vitePreload(()=>import("./chunks/1f984-DOK3uNT7.js"),[],import.meta.url),"1f436":()=>__vitePreload(()=>import("./chunks/1f436-CfGEu66M.js"),[],import.meta.url),"1f431":()=>__vitePreload(()=>import("./chunks/1f431-Cy-L3DQS.js"),[],import.meta.url),"1f308":()=>__vitePreload(()=>import("./chunks/1f308-DAQVzKND.js"),[],import.meta.url),"1f31f":()=>__vitePreload(()=>import("./chunks/1f31f-BV2d8NX3.js"),[],import.meta.url),"26a1":()=>__vitePreload(()=>import("./chunks/26a1-Cpmzv_rj.js"),[],import.meta.url),"1f355":()=>__vitePreload(()=>import("./chunks/1f355-C-u8bPC3.js"),[],import.meta.url),2615:()=>__vitePreload(()=>import("./chunks/2615-CoDRCZkH.js"),[],import.meta.url),"1f389":()=>__vitePreload(()=>import("./chunks/1f389-B6nBX5We.js"),[],import.meta.url),"1f3c6":()=>__vitePreload(()=>import("./chunks/1f3c6-PZd-tUlI.js"),[],import.meta.url),"23f3":()=>__vitePreload(()=>import("./chunks/23f3-ASjqFsbT.js"),[],import.meta.url),2611:()=>__vitePreload(()=>import("./chunks/2611-BnnmLm-K.js"),[],import.meta.url),2702:()=>__vitePreload(()=>import("./chunks/2702-CfLyp35r.js"),[],import.meta.url),"1f30a":()=>__vitePreload(()=>import("./chunks/1f30a-DxwAt2Ba.js"),[],import.meta.url),"1f327":()=>__vitePreload(()=>import("./chunks/1f327-Ie-nQBNO.js"),[],import.meta.url),"1f33e":()=>__vitePreload(()=>import("./chunks/1f33e-Cfl2WM63.js"),[],import.meta.url),"1f3ab":()=>__vitePreload(()=>import("./chunks/1f3ab-BUCNQHz1.js"),[],import.meta.url),"1f4be":()=>__vitePreload(()=>import("./chunks/1f4be-DPAcAU4R.js"),[],import.meta.url),"1f4d3":()=>__vitePreload(()=>import("./chunks/1f4d3-GTxRgjv7.js"),[],import.meta.url),"1f4d6":()=>__vitePreload(()=>import("./chunks/1f4d6-COOZY-Q_.js"),[],import.meta.url),"1f4e2":()=>__vitePreload(()=>import("./chunks/1f4e2-DsStZsI-.js"),[],import.meta.url),"1f504":()=>__vitePreload(()=>import("./chunks/1f504-BYIHMoDP.js"),[],import.meta.url),"1f465":()=>__vitePreload(()=>import("./chunks/1f465-CPle6Hjq.js"),[],import.meta.url),"270f":()=>__vitePreload(()=>import("./chunks/270f-CLwo30mk.js"),[],import.meta.url),2728:()=>__vitePreload(()=>import("./chunks/2728-Qg6be-6p.js"),[],import.meta.url),"2b1c":()=>__vitePreload(()=>import("./chunks/2b1c-Uc1aRwAf.js"),[],import.meta.url),"1f310":()=>__vitePreload(()=>import("./chunks/1f310-AqUM9a8q.js"),[],import.meta.url),"1f324":()=>__vitePreload(()=>import("./chunks/1f324-8MHLOhTj.js"),[],import.meta.url),"1f372":()=>__vitePreload(()=>import("./chunks/1f372-3XLDlXkE.js"),[],import.meta.url),"1f373":()=>__vitePreload(()=>import("./chunks/1f373-BPUJt2bp.js"),[],import.meta.url),"1f39b":()=>__vitePreload(()=>import("./chunks/1f39b-CSNtbAXr.js"),[],import.meta.url),"1f41b":()=>__vitePreload(()=>import("./chunks/1f41b-Dre1z0gP.js"),[],import.meta.url),"1f4c2":()=>__vitePreload(()=>import("./chunks/1f4c2-Dx7BKmLO.js"),[],import.meta.url),"1f4c4":()=>__vitePreload(()=>import("./chunks/1f4c4-CNvjvC5k.js"),[],import.meta.url),"1f4dc":()=>__vitePreload(()=>import("./chunks/1f4dc-BhoW4cjD.js"),[],import.meta.url),"1f4e1":()=>__vitePreload(()=>import("./chunks/1f4e1-DezU8ow-.js"),[],import.meta.url),"1f500":()=>__vitePreload(()=>import("./chunks/1f500-D9xRo-IT.js"),[],import.meta.url),"1f501":()=>__vitePreload(()=>import("./chunks/1f501-CzKeDPcw.js"),[],import.meta.url),"1f52d":()=>__vitePreload(()=>import("./chunks/1f52d-2QxCLKhU.js"),[],import.meta.url),"1f552":()=>__vitePreload(()=>import("./chunks/1f552-4d0Y0kn7.js"),[],import.meta.url),"1f58b":()=>__vitePreload(()=>import("./chunks/1f58b-Cp8F_HBg.js"),[],import.meta.url),"1f5b2":()=>__vitePreload(()=>import("./chunks/1f5b2-D6BUULuh.js"),[],import.meta.url),"1f5c3":()=>__vitePreload(()=>import("./chunks/1f5c3-DjkgJLaz.js"),[],import.meta.url),"1f5d1":()=>__vitePreload(()=>import("./chunks/1f5d1-C4Kpe4HL.js"),[],import.meta.url),"1f5dc":()=>__vitePreload(()=>import("./chunks/1f5dc-DyLO7aB9.js"),[],import.meta.url),"1f9d1-200d-2696":()=>__vitePreload(()=>import("./chunks/1f9d1-200d-2696-D9eSB-0q.js"),[],import.meta.url),"1fa79":()=>__vitePreload(()=>import("./chunks/1fa79-DHhIZbWB.js"),[],import.meta.url),"1fa9d":()=>__vitePreload(()=>import("./chunks/1fa9d-DUI9e77m.js"),[],import.meta.url),"1fa9f":()=>__vitePreload(()=>import("./chunks/1fa9f-10ALsMaD.js"),[],import.meta.url),"1f441":()=>__vitePreload(()=>import("./chunks/1f441-D8yah4C4.js"),[],import.meta.url),"1f604":()=>__vitePreload(()=>import("./chunks/1f604-CEekcaYE.js"),[],import.meta.url),"1f326":()=>__vitePreload(()=>import("./chunks/1f326-YSBr3aXI.js"),[],import.meta.url),"1f4b9":()=>__vitePreload(()=>import("./chunks/1f4b9-aacFyckt.js"),[],import.meta.url),"1f4c1":()=>__vitePreload(()=>import("./chunks/1f4c1-Ch6aJ0cj.js"),[],import.meta.url),"1f4e7":()=>__vitePreload(()=>import("./chunks/1f4e7-BBi7c_zx.js"),[],import.meta.url),"1f917":()=>__vitePreload(()=>import("./chunks/1f917-CyyS9fgf.js"),[],import.meta.url)},DRAWN=new Map;function hasFluentEmoji(Au){return!!Au&&Object.prototype.hasOwnProperty.call(FLUENT_EMOJI_LOADERS,emojiKey(Au))}async function loadFluentEmoji(Au){const lo=emojiKey(Au),$u=DRAWN.get(lo);if($u)return $u;if(!Object.prototype.hasOwnProperty.call(FLUENT_EMOJI_LOADERS,lo))return;const Ru=(await FLUENT_EMOJI_LOADERS[lo]()).default,Iu=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(Ru)}`;return DRAWN.set(lo,Iu),Iu}function FluentEmoji({emoji:Au,size:lo,label:$u,className:Ru,style:Iu}){const Pu=emojiKey(Au),Ou=hasFluentEmoji(Au),[Mu,Du]=reactExports.useState(()=>DRAWN.get(Pu));reactExports.useEffect(()=>{let ju=!0;return Du(DRAWN.get(Pu)),Ou&&!DRAWN.has(Pu)&&loadFluentEmoji(Au).then(Fu=>ju&&Du(Fu),()=>{}),()=>{ju=!1}},[Pu,Ou,Au]);const Lu=$u??Au,Bu={display:"inline-flex",alignItems:"center",justifyContent:"center",flex:"none",width:lo,height:lo,...Iu};return Ou?Mu?jsxRuntimeExports.jsx("img",{className:Ru,src:Mu,alt:Lu,"aria-hidden":Lu?void 0:!0,width:lo,height:lo,draggable:!1,"data-emoji":"fluent",style:{...Bu,display:"inline-block"}}):jsxRuntimeExports.jsx("span",{className:Ru,"aria-hidden":"true","data-emoji":"loading",style:Bu}):jsxRuntimeExports.jsx("span",{className:Ru,role:Lu?"img":void 0,"aria-label":Lu||void 0,"aria-hidden":Lu?void 0:!0,"data-emoji":"system",style:{...Bu,fontSize:Math.round(lo*.85),lineHeight:1},children:Au})}function generateMessageId(){return`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function createUserMessage(Au,lo){return{id:generateMessageId(),role:"user",content:Au,createdAt:new Date,metadata:lo}}function createAssistantMessage(Au,lo){return{id:generateMessageId(),role:"assistant",content:Au,createdAt:new Date,agentName:lo?.agentName,toolCalls:lo?.toolCalls,metadata:lo?.metadata}}const createStoreImpl=Au=>{let lo;const $u=new Set,Ru=(Lu,Bu)=>{const ju=typeof Lu=="function"?Lu(lo):Lu;if(!Object.is(ju,lo)){const Fu=lo;lo=Bu??(typeof ju!="object"||ju===null)?ju:Object.assign({},lo,ju),$u.forEach(zu=>zu(lo,Fu))}},Iu=()=>lo,Mu={setState:Ru,getState:Iu,getInitialState:()=>Du,subscribe:Lu=>($u.add(Lu),()=>$u.delete(Lu))},Du=lo=Au(Ru,Iu,Mu);return Mu},createStore=(Au=>Au?createStoreImpl(Au):createStoreImpl),identity=Au=>Au;function useStore(Au,lo=identity){const $u=vM.useSyncExternalStore(Au.subscribe,vM.useCallback(()=>lo(Au.getState()),[Au,lo]),()=>lo(Au.getInitialState()));return vM.useDebugValue($u),$u}const createImpl=Au=>{const lo=createStore(Au),$u=Ru=>useStore(lo,Ru);return Object.assign($u,lo),$u},create$e=(Au=>Au?createImpl(Au):createImpl),useReactorStore=create$e(()=>({reactor:null,isBackendPluginAvailable:()=>!1})),unavailableBackendPlugin=()=>!1;function registerReactor(Au,lo=unavailableBackendPlugin){useReactorStore.setState({reactor:Au,isBackendPluginAvailable:lo})}function useReactor(Au,lo={}){const{autoStart:$u=!0,availableBackendPlugins:Ru,isBackendPluginAvailable:Iu}=lo,Pu=reactExports.useMemo(()=>{if(Iu)return Iu;const Ou=new Set(Ru??[]);return Mu=>Ou.has(Mu)},[Iu,Ru]);return reactExports.useState(()=>(registerReactor(Au,Pu),null)),reactExports.useEffect(()=>(registerReactor(Au,Pu),()=>{useReactorStore.getState().reactor===Au&&registerReactor(null,unavailableBackendPlugin)}),[Au,Pu]),reactExports.useEffect(()=>{if($u)return Au.start(),()=>{Au.stop()}},[$u,Au]),Au}const NO_SUBSCRIPTION$2=()=>()=>{};function useOptionalReactorPlatform(){return useReactorStore(Au=>Au.reactor)}function useReactorPlatform(){const Au=useReactorStore(lo=>lo.reactor);if(!Au)throw new Error("useReactorPlatform: no reactor store registered. Call useReactor(reactor) (or registerReactor) before using reactor hooks.");return Au}function useSignalValue$1(Au){return reactExports.useSyncExternalStore(lo=>{let $u=!1;return effect$1(()=>{Au.value,$u?lo():$u=!0})},()=>Au.peek(),()=>Au.peek())}function useBackendPluginAvailability(){return useReactorStore(Au=>Au.isBackendPluginAvailable)}function useBackendPluginStream(Au,lo={}){const{pollMs:$u=5e3,onState:Ru}=lo,Iu=Au?.replace(/\/+$/,""),Pu=useReactorStore(Mu=>Mu.reactor),Ou=reactExports.useRef(Ru);Ou.current=Ru,reactExports.useEffect(()=>{if(!Iu||!Pu)return;let Mu=!1,Du=-1;const Lu=zu=>{Mu||zu.revision===Du||(Du=zu.revision,Ou.current?.(zu),Pu.setBackendPlugins(zu.plugins.filter(Uu=>Uu.enabled).map(Uu=>Uu.name)))},Bu=()=>fetch(`${Iu}/plugins/state`).then(zu=>zu.ok?zu.json():void 0).then(zu=>zu&&Lu(zu)).catch(()=>{});if(Bu(),typeof EventSource>"u"){const zu=setInterval(Bu,$u);return()=>{Mu=!0,clearInterval(zu)}}const ju=new EventSource(`${Iu}/events/stream`);ju.onmessage=zu=>{try{Lu(JSON.parse(zu.data))}catch{}};const Fu=setInterval(Bu,$u);return()=>{Mu=!0,clearInterval(Fu),ju.close()}},[Iu,Pu,$u])}function useReactorEvent(Au){const lo=useReactorPlatform();reactExports.useEffect(()=>{Au&&lo.fire(Au)},[lo,Au])}function useOptionalSlotComponents(Au){const lo=useOptionalReactorPlatform();return useSlotComponentsFrom(lo,Au)}function useSlotComponents(Au){const lo=useReactorPlatform();return useSlotComponentsFrom(lo,Au)}function useSlotComponentsFrom(Au,lo){const $u=useBackendPluginAvailability(),Ru=reactExports.useSyncExternalStore(Au?Au.subscribe:NO_SUBSCRIPTION$2,()=>Au?Au.getRevision():-1);return reactExports.useMemo(()=>{const Iu=[];if(!Au)return Iu;function Pu(Ou){return Ou.every(Mu=>$u(Mu))}for(const Ou of Au.listPlugins()){if(!Au.isEnabled(Ou))continue;const Mu=Au.getRequiredBackendPlugins(Ou);if(!Pu(Mu))continue;const Du=Au.getOutput(Ou);for(const Lu of Du?.components??[]){const Bu=Lu.requiredBackendPlugins??[];Lu.slot===lo&&Pu(Bu)&&Iu.push(Lu)}}return Iu.map((Ou,Mu)=>({component:Ou,index:Mu})).sort((Ou,Mu)=>(Ou.component.order??0)-(Mu.component.order??0)||Ou.index-Mu.index).map(Ou=>Ou.component)},[Au,lo,Ru,$u])}function ReactorSlot({slot:Au,props:lo={}}){const $u=useOptionalSlotComponents(Au);return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:$u.map(Ru=>{const Iu=Ru.Component;return jsxRuntimeExports.jsx(Iu,{...lo},`${Ru.slot}:${Ru.id}`)})})}function useGate(Au,lo){const $u=useContributions(Au);return reactExports.useMemo(()=>resolveGate($u,lo),[$u,lo])}function useContributions(Au){const lo=useReactorPlatform(),$u=reactExports.useSyncExternalStore(lo.subscribe,()=>lo.getRevision());return reactExports.useMemo(()=>lo.getContributions(Au),[lo,Au,$u])}function useCommands(){const Au=useReactorPlatform(),lo=reactExports.useSyncExternalStore(Au.subscribe,()=>Au.getRevision());return reactExports.useMemo(()=>Au.listCommands(),[Au,lo])}class LazyErrorBoundary extends reactExports.Component{state={error:null};static getDerivedStateFromError(lo){return{error:lo}}componentDidUpdate(lo){lo.resetKey!==this.props.resetKey&&this.state.error&&this.setState({error:null})}render(){return this.state.error?this.props.fallback(this.state.error):this.props.children}}const lazyComponents=new WeakMap;function lazyFor(Au){const lo=lazyComponents.get(Au);if(lo)return lo;const $u=vM.lazy(Au);return lazyComponents.set(Au,$u),$u}function ReactorLazy({load:Au,props:lo,fallback:$u=null,errorFallback:Ru}){const Iu=reactExports.useMemo(()=>lazyFor(Au),[Au]),Pu=Ru??(Ou=>jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:`Failed to load view: ${Ou.message}`}));return jsxRuntimeExports.jsx(LazyErrorBoundary,{fallback:Pu,resetKey:Au,children:jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:$u,children:jsxRuntimeExports.jsx(Iu,{...lo??{}})})})}function defaultResolve(Au){const lo=Au;if(lo&&typeof lo.load=="function")return{load:lo.load};if(lo&&typeof lo.Component=="function")return{Component:lo.Component}}function ReactorViewHost({point:Au,active:lo,props:$u,fallback:Ru=null,empty:Iu=null,errorFallback:Pu,resolve:Ou=defaultResolve,render:Mu}){const Du=useContributions(Au),Lu=reactExports.useMemo(()=>lo===void 0?void 0:Du.find(Fu=>Fu.id===lo),[Du,lo]);if(!Lu)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Iu});if(Mu)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Mu(Lu)});const Bu=Ou(Lu.value);if(!Bu)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Iu});if(Bu.load)return jsxRuntimeExports.jsx(ReactorLazy,{load:Bu.load,props:$u,fallback:Ru,errorFallback:Pu});const ju=Bu.Component;return jsxRuntimeExports.jsx(ju,{...$u??{}})}const UI_WIRE_VERSION=1,DISPLAY_META_KEY$1="reactor.ui/display",ANSWER_ACTION="reactor.answer",UI_OP_NAMES=["show","patch","append","remove","state","ask","window","meta"];function isRecord$6(Au){return typeof Au=="object"&&Au!==null&&!Array.isArray(Au)}function isOptional$1(Au,lo){return Au==null||lo(Au)}function isString$3(Au){return typeof Au=="string"}function isActionOffer(Au){return isRecord$6(Au)&&isString$3(Au.name)&&isString$3(Au.token)&&isOptional$1(Au.label,isString$3)}function isDisplay(Au){return isRecord$6(Au)&&isString$3(Au.type)&&isString$3(Au.id)&&isString$3(Au.text)&&(Au.version===void 0||Number.isInteger(Au.version))&&(Au.data===void 0||isRecord$6(Au.data))&&(Au.actions===void 0||Array.isArray(Au.actions)&&Au.actions.every(isActionOffer))}function isPatchOperation(Au){if(!isRecord$6(Au)||!isString$3(Au.path))return!1;switch(Au.op){case"add":case"replace":case"test":return"value"in Au;case"remove":return!0;case"move":case"copy":return isString$3(Au.from);default:return!1}}function isPatch(Au){return Array.isArray(Au)&&Au.every(isPatchOperation)}const OP_SHAPES={show:Au=>isDisplay(Au.body),ask:Au=>isDisplay(Au.body),patch:Au=>isString$3(Au.id)&&isPatch(Au.body),append:Au=>isString$3(Au.id)&&isRecord$6(Au.body)&&isString$3(Au.body.path),remove:Au=>isString$3(Au.id)&&(Au.body===void 0||Au.body===null),state:Au=>isPatch(Au.body),window:Au=>isRecord$6(Au.body)&&isString$3(Au.body.name)&&(Au.body.args===void 0||isRecord$6(Au.body.args)),meta:Au=>isRecord$6(Au.body)};function isUiOp(Au){return isRecord$6(Au)&&Au.v===UI_WIRE_VERSION&&isString$3(Au.scope)&&isOptional$1(Au.id,isString$3)&&UI_OP_NAMES.includes(Au.op)&&OP_SHAPES[Au.op](Au)}function isSeq(Au,lo){return Number.isInteger(Au)&&Au>=lo}function hasKeys(Au,lo,$u=[]){const Ru=Object.keys(Au);return lo.every(Iu=>Iu in Au)&&Ru.every(Iu=>lo.includes(Iu)||$u.includes(Iu))}function isDownFrame(Au){if(!isRecord$6(Au))return!1;switch(Au.t){case"welcome":return hasKeys(Au,["t","scope","seq"],["v"])&&(Au.v===void 0||Au.v===UI_WIRE_VERSION)&&isString$3(Au.scope)&&isSeq(Au.seq,0);case"op":return hasKeys(Au,["t","seq","op"])&&isSeq(Au.seq,1)&&isUiOp(Au.op);case"result":return hasKeys(Au,["t","ref","ok","status"],["detail","value"])&&isString$3(Au.ref)&&typeof Au.ok=="boolean"&&Number.isInteger(Au.status)&&isOptional$1(Au.detail,isString$3);case"ping":case"pong":return hasKeys(Au,["t"]);default:return!1}}const Renderers=defineContributionPoint("reactor.ui.renderer"),ToolBindings=defineContributionPoint("reactor.ui.toolBinding");function versionInRange(Au,lo){return lo?(lo.min===void 0||Au>=lo.min)&&(lo.max===void 0||Au<=lo.max):!0}function pickRenderer(Au,lo){const $u=lo.version??1;let Ru;for(const Iu of Au)Iu.value.type!==lo.type||!versionInRange($u,Iu.value.versions)||(!Ru||(Iu.value.rank??0)>(Ru.value.rank??0))&&(Ru=Iu);return Ru}function parsedObject(Au){if(typeof Au!="string")return Au;const lo=Au.trimStart();if(!lo.startsWith("{"))return Au;try{return JSON.parse(lo)}catch{return Au}}function embeddedDisplay(Au){const lo=parsedObject(Au);if(typeof lo!="object"||lo===null)return;const $u=lo._meta;if(typeof $u!="object"||$u===null)return;const Ru=$u[DISPLAY_META_KEY$1];return isDisplay(Ru)?Ru:void 0}function bindingMatches(Au,lo){return typeof Au.tool=="string"?Au.tool===lo:(Au.tool.lastIndex=0,Au.tool.test(lo))}function textOf$1(Au){if(Au==null)return"";if(typeof Au=="string")return Au;try{return JSON.stringify(Au)??String(Au)}catch{return String(Au)}}function resolveToolResult(Au,lo){const $u=embeddedDisplay(lo.result);if($u)return $u;const Ru=Au.getContributions(ToolBindings).find(Iu=>bindingMatches(Iu.value,lo.toolName));if(Ru)return{type:Ru.value.type,version:Ru.value.version??1,id:lo.toolCallId??lo.toolName,text:textOf$1(lo.result),data:{toolName:lo.toolName,result:lo.result}}}function emptyUiModel(){return{displays:{},order:[],asks:[],state:{},meta:{}}}function clone$2(Au){return Au===void 0?Au:JSON.parse(JSON.stringify(Au))}function parsePointer(Au){if(Au==="")return[];if(!Au.startsWith("/"))throw new Error(`A JSON pointer starts with '/': ${Au}`);return Au.slice(1).split("/").map(lo=>lo.replace(/~1/g,"/").replace(/~0/g,"~")).map(lo=>{if(FORBIDDEN_TOKENS.has(lo))throw new Error(`${Au}: '${lo}' is never a path token`);return lo})}const FORBIDDEN_TOKENS=new Set(["__proto__","constructor","prototype"]);function hasOwn(Au,lo){return Object.prototype.hasOwnProperty.call(Au,lo)}function walk(Au,lo,$u){let Ru=Au;for(const Iu of lo)if(Array.isArray(Ru))Ru=Ru[arrayIndex(Ru,Iu,$u,!1)];else if(typeof Ru=="object"&&Ru!==null&&hasOwn(Ru,Iu))Ru=Ru[Iu];else throw new Error(`No value at ${$u}`);if(typeof Ru!="object"||Ru===null)throw new Error(`${$u} does not lead into an object or an array`);return Ru}function arrayIndex(Au,lo,$u,Ru){if(Ru&&lo==="-")return Au.length;if(!/^(0|[1-9][0-9]*)$/.test(lo))throw new Error(`${$u}: '${lo}' is not an array index`);const Iu=Number(lo);if(Iu>Au.length||!Ru&&Iu===Au.length)throw new Error(`${$u}: index ${Iu} is out of bounds`);return Iu}function read$2(Au,lo){const $u=parsePointer(lo);if($u.length===0)return Au;const Ru=walk(Au,$u.slice(0,-1),lo),Iu=$u[$u.length-1];if(Array.isArray(Ru))return Ru[arrayIndex(Ru,Iu,lo,!1)];if(!hasOwn(Ru,Iu))throw new Error(`No value at ${lo}`);return Ru[Iu]}function add$1(Au,lo,$u){const Ru=parsePointer(lo);if(Ru.length===0)return $u;const Iu=walk(Au,Ru.slice(0,-1),lo),Pu=Ru[Ru.length-1];return Array.isArray(Iu)?Iu.splice(arrayIndex(Iu,Pu,lo,!0),0,$u):Iu[Pu]=$u,Au}function removeAt(Au,lo){const $u=parsePointer(lo);if($u.length===0)return;const Ru=walk(Au,$u.slice(0,-1),lo),Iu=$u[$u.length-1];if(Array.isArray(Ru))Ru.splice(arrayIndex(Ru,Iu,lo,!1),1);else{if(!hasOwn(Ru,Iu))throw new Error(`No value at ${lo}`);delete Ru[Iu]}return Au}function replaceAt(Au,lo,$u){const Ru=parsePointer(lo);if(Ru.length===0)return $u;const Iu=walk(Au,Ru.slice(0,-1),lo),Pu=Ru[Ru.length-1];if(Array.isArray(Iu))Iu[arrayIndex(Iu,Pu,lo,!1)]=$u;else{if(!hasOwn(Iu,Pu))throw new Error(`No value at ${lo}`);Iu[Pu]=$u}return Au}function equal$1(Au,lo){if(Au===lo)return!0;if(Array.isArray(Au)||Array.isArray(lo))return Array.isArray(Au)&&Array.isArray(lo)&&Au.length===lo.length&&Au.every((Pu,Ou)=>equal$1(Pu,lo[Ou]));if(typeof Au!="object"||typeof lo!="object"||Au===null||lo===null)return!1;const $u=Au,Ru=lo,Iu=Object.keys($u);return Iu.length===Object.keys(Ru).length&&Iu.every(Pu=>hasOwn(Ru,Pu)&&equal$1($u[Pu],Ru[Pu]))}function applyPatch$1(Au,lo){let $u=clone$2(Au);for(const Ru of lo)switch(Ru.op){case"add":$u=add$1($u,Ru.path,clone$2(Ru.value));break;case"remove":$u=removeAt($u,Ru.path);break;case"replace":$u=replaceAt($u,Ru.path,clone$2(Ru.value));break;case"move":{const Iu=requireFrom(Ru),Pu=read$2($u,Iu);$u=add$1(removeAt($u,Iu),Ru.path,Pu);break}case"copy":$u=add$1($u,Ru.path,clone$2(read$2($u,requireFrom(Ru))));break;case"test":if(!equal$1(read$2($u,Ru.path),Ru.value))throw new Error(`test failed at ${Ru.path}`);break;default:throw new Error(`Unknown patch op ${Ru.op}`)}return $u}function requireFrom(Au){if(typeof Au.from!="string")throw new Error(`'${Au.op}' at ${Au.path} needs 'from'`);return Au.from}function displayOf(Au,lo){const $u=Au.displays[lo.id];if(!$u)throw new Error(`'${lo.op}' for display '${lo.id}', which was never shown`);return $u}function shown(Au,lo){const $u=lo.id in Au.displays;return{...Au,displays:{...Au.displays,[lo.id]:lo},order:$u?Au.order:[...Au.order,lo.id]}}function applyUiOp(Au,lo){if(lo.v!==UI_WIRE_VERSION)throw new Error(`reactor.ui wire v${String(lo.v)} is not v${UI_WIRE_VERSION}`);switch(lo.op){case"show":return shown(Au,lo.body);case"ask":{const $u=shown(Au,lo.body);return $u.asks.includes(lo.body.id)?$u:{...$u,asks:[...$u.asks,lo.body.id]}}case"patch":{const $u=applyPatch$1(displayOf(Au,lo),lo.body);return{...Au,displays:{...Au.displays,[lo.id]:{...$u,id:lo.id}}}}case"append":{const $u=displayOf(Au,lo),Ru=applyPatch$1($u,[{op:"add",path:`${lo.body.path}/-`,value:lo.body.value}]);return{...Au,displays:{...Au.displays,[lo.id]:Ru}}}case"remove":{if(!(lo.id in Au.displays))return Au;const $u={...Au.displays};return delete $u[lo.id],{...Au,displays:$u,order:Au.order.filter(Ru=>Ru!==lo.id),asks:Au.asks.filter(Ru=>Ru!==lo.id)}}case"state":return{...Au,state:applyPatch$1(Au.state,lo.body)};case"meta":return{...Au,meta:{...Au.meta,...lo.body}};case"window":return Au;default:throw new Error(`Unknown reactor.ui op '${lo.op}'`)}}const AGUI_NAME="reactor.ui",UI_FILE_SCOPE_HEADER="X-Reactor-Scope",UI_FILE_NAME_HEADER="X-Reactor-File-Name";class UiFileRefused extends Error{status;constructor(lo,$u){super($u),this.status=lo,this.name="UiFileRefused"}}async function uploadFile(Au,lo){const $u=await(lo.fetcher??fetch)(lo.url,{method:"POST",headers:{"Content-Type":Au.type||"application/octet-stream",[UI_FILE_SCOPE_HEADER]:lo.scope,[UI_FILE_NAME_HEADER]:encodeURIComponent(Au.name),...lo.token?{Authorization:`Bearer ${lo.token}`}:{}},body:Au});if(!$u.ok){let Iu="";try{const Pu=await $u.json();Iu=typeof Pu.detail=="string"?Pu.detail:""}catch{}throw new UiFileRefused($u.status,Iu||`${Au.name} was refused (${$u.status}).`)}const Ru=await $u.json();if(typeof Ru.ref!="string"||typeof Ru.name!="string"||typeof Ru.media_type!="string")throw new UiFileRefused($u.status,`The host kept ${Au.name} under no ref.`);return Ru}function isFileRef(Au){const lo=Au;return typeof lo=="object"&&lo!==null&&typeof lo.ref=="string"&&typeof lo.name=="string"&&typeof lo.media_type=="string"}const UI_WS_PROTOCOL="reactor.ui.v1",UI_WS_CLOSE={refused:4400,unauthorized:4401,forbidden:4403,timeout:4408,gone:4410};class UiSocketStopped extends Error{status;reason;constructor(lo,$u){super(`reactor.ui socket ${lo}: ${$u}`),this.status=lo,this.reason=$u}}const FINAL_CLOSES={[UI_WS_CLOSE.refused]:"refused",[UI_WS_CLOSE.unauthorized]:"refused",[UI_WS_CLOSE.forbidden]:"refused",[UI_WS_CLOSE.gone]:"gone"};function randomId(){const Au=globalThis.crypto;return Au?.randomUUID?Au.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}class UiSocket{lastSeq;status="connecting";ws=null;welcomed=!1;historyUpTo=0;resumable;stopped=!1;attempt=0;heard=0;beat=null;retry=null;pending=new Map;options;constructor(lo){this.options={heartbeatMs:2e4,timeoutMs:6e4,backoffMs:[250,1e3,2e3,5e3],maxPending:64,newId:randomId,...lo},this.lastSeq=lo.since??0,this.resumable=lo.since!==void 0}connect(){if(this.stopped||this.ws)return;this.setStatus(this.attempt===0&&!this.resumable?"connecting":"reconnecting");const $u=(this.options.open??((Ru,Iu)=>new globalThis.WebSocket(Ru,Iu)))(this.options.url,[UI_WS_PROTOCOL]);this.ws=$u,this.welcomed=!1,$u.onopen=()=>{this.hello($u)},$u.onmessage=Ru=>this.receive($u,Ru.data),$u.onclose=Ru=>this.closed($u,Ru.code,Ru.reason),$u.onerror=()=>{}}act(lo){const $u={...lo,idempotency_id:lo.idempotency_id??this.options.newId()};return this.request({t:"action",ref:this.options.newId(),action:$u})}state(lo){return this.request({t:"state",ref:this.options.newId(),body:lo})}close(){this.stop("closed","closed by the page",1e3)}request(lo){return this.stopped?Promise.reject(new UiSocketStopped(this.status,"the socket is stopped")):this.pending.size>=this.options.maxPending?Promise.reject(new Error(`${this.pending.size} presses are waiting for their result`)):new Promise(($u,Ru)=>{this.pending.set(lo.ref,{frame:lo,resolve:$u,reject:Ru}),this.welcomed&&this.send(lo)})}async hello(lo){let $u;try{$u=await this.options.token()}catch(Ru){this.stop("refused",`no credential: ${String(Ru)}`,1e3);return}lo===this.ws&&(this.heard=Date.now(),this.send({t:"hello",v:UI_WIRE_VERSION,token:$u,scope:this.options.scope,since:this.resumable?this.lastSeq:null}),this.beat=setInterval(()=>this.heartbeat(lo),this.options.heartbeatMs))}heartbeat(lo){if(lo===this.ws){if(Date.now()-this.heard>this.options.timeoutMs){lo.close(UI_WS_CLOSE.timeout,"nothing heard"),this.closed(lo,UI_WS_CLOSE.timeout,"nothing heard");return}this.send({t:"ping"})}}receive(lo,$u){if(lo!==this.ws)return;let Ru;try{Ru=typeof $u=="string"?JSON.parse($u):void 0}catch{Ru=void 0}if(!isDownFrame(Ru)){this.stop("refused","the host sent a frame that is not the schema’s",UI_WS_CLOSE.refused);return}this.heard=Date.now(),this.handle(lo,Ru)}handle(lo,$u){switch($u.t){case"welcome":if($u.scope!==this.options.scope){this.stop("refused",`welcomed to ${$u.scope}, not ${this.options.scope}`,UI_WS_CLOSE.refused);return}if(this.resumable&&$u.seq<this.lastSeq){this.stop("gone",`the host is at op ${$u.seq}, the page at ${this.lastSeq}`,1e3);return}this.resumable||(this.historyUpTo=$u.seq),this.welcomed=!0,this.attempt=0,this.setStatus("open");for(const Ru of this.pending.values())this.send(Ru.frame);return;case"op":if(!this.welcomed){this.stop("refused","an op before the welcome",UI_WS_CLOSE.refused);return}if($u.seq<=this.lastSeq)return;if($u.seq!==this.lastSeq+1){lo.close(1e3,`op ${$u.seq} after ${this.lastSeq}`),this.closed(lo,1e3,"a gap");return}this.lastSeq=$u.seq,this.resumable=!0,this.options.onOp($u.op,$u.seq,$u.seq<=this.historyUpTo);return;case"result":{const Ru=this.pending.get($u.ref);Ru&&(this.pending.delete($u.ref),Ru.resolve({ok:$u.ok,status:$u.status,detail:$u.detail,value:$u.value}));return}case"ping":this.send({t:"pong"});return;case"pong":return}}closed(lo,$u,Ru){if(lo!==this.ws||(this.ws=null,this.welcomed=!1,this.clearBeat(),this.stopped))return;const Iu=FINAL_CLOSES[$u];if(Iu){this.stop(Iu,Ru||`closed with ${$u}`);return}this.resumable=this.resumable||this.lastSeq>0;const Pu=this.options.backoffMs,Ou=Pu[Math.min(this.attempt,Pu.length-1)]??1e3;this.attempt+=1,this.setStatus("reconnecting",Ru),this.retry=setTimeout(()=>{this.retry=null,this.connect()},Ou)}stop(lo,$u,Ru){if(this.stopped)return;this.stopped=!0,this.clearBeat(),this.retry&&(clearTimeout(this.retry),this.retry=null);const Iu=this.ws;this.ws=null,Iu&&Ru!==void 0&&Iu.close(Ru,$u.slice(0,120));for(const Pu of this.pending.values())Pu.reject(new UiSocketStopped(lo,$u));this.pending.clear(),this.setStatus(lo,$u)}send(lo){this.ws?.send(JSON.stringify(lo))}clearBeat(){this.beat&&(clearInterval(this.beat),this.beat=null)}setStatus(lo,$u){this.status=lo,this.options.onStatus?.(lo,$u)}}var lib$b={},basemanager={},serverconnection={},serialize$3={},messages$1={},hasRequiredMessages;function requireMessages(){if(hasRequiredMessages)return messages$1;hasRequiredMessages=1,Object.defineProperty(messages$1,"__esModule",{value:!0}),messages$1.supportedKernelWebSocketProtocols=void 0,messages$1.createMessage=lo,messages$1.isStreamMsg=$u,messages$1.isDisplayDataMsg=Ru,messages$1.isUpdateDisplayDataMsg=Iu,messages$1.isExecuteInputMsg=Pu,messages$1.isExecuteResultMsg=Ou,messages$1.isErrorMsg=Mu,messages$1.isStatusMsg=Du,messages$1.isClearOutputMsg=Lu,messages$1.isDebugEventMsg=Bu,messages$1.isCommOpenMsg=ju,messages$1.isCommCloseMsg=Fu,messages$1.isCommMsgMsg=zu,messages$1.isInfoRequestMsg=Uu,messages$1.isExecuteReplyMsg=Hu,messages$1.isDebugRequestMsg=Vu,messages$1.isDebugReplyMsg=Gu,messages$1.isInputRequestMsg=Wu,messages$1.isInputReplyMsg=Zu;const Au=requireDist();function lo(Yu){var Xu,ed,td,nd,od,sd;return{buffers:(Xu=Yu.buffers)!==null&&Xu!==void 0?Xu:[],channel:Yu.channel,content:Yu.content,header:{date:new Date().toISOString(),msg_id:(ed=Yu.msgId)!==null&&ed!==void 0?ed:Au.UUID.uuid4(),msg_type:Yu.msgType,session:Yu.session,username:(td=Yu.username)!==null&&td!==void 0?td:"",subshell_id:(nd=Yu.subshellId)!==null&&nd!==void 0?nd:null,version:"5.2"},metadata:(od=Yu.metadata)!==null&&od!==void 0?od:{},parent_header:(sd=Yu.parentHeader)!==null&&sd!==void 0?sd:{}}}function $u(Yu){return Yu.header.msg_type==="stream"}function Ru(Yu){return Yu.header.msg_type==="display_data"}function Iu(Yu){return Yu.header.msg_type==="update_display_data"}function Pu(Yu){return Yu.header.msg_type==="execute_input"}function Ou(Yu){return Yu.header.msg_type==="execute_result"}function Mu(Yu){return Yu.header.msg_type==="error"}function Du(Yu){return Yu.header.msg_type==="status"}function Lu(Yu){return Yu.header.msg_type==="clear_output"}function Bu(Yu){return Yu.header.msg_type==="debug_event"}function ju(Yu){return Yu.header.msg_type==="comm_open"}function Fu(Yu){return Yu.header.msg_type==="comm_close"}function zu(Yu){return Yu.header.msg_type==="comm_msg"}function Uu(Yu){return Yu.header.msg_type==="kernel_info_request"}function Hu(Yu){return Yu.header.msg_type==="execute_reply"}function Vu(Yu){return Yu.header.msg_type==="debug_request"}function Gu(Yu){return Yu.header.msg_type==="debug_reply"}function Wu(Yu){return Yu.header.msg_type==="input_request"}function Zu(Yu){return Yu.header.msg_type==="input_reply"}var Ju;return(function(Yu){Yu.v1KernelWebsocketJupyterOrg="v1.kernel.websocket.jupyter.org"})(Ju||(messages$1.supportedKernelWebSocketProtocols=Ju={})),messages$1}var hasRequiredSerialize;function requireSerialize(){if(hasRequiredSerialize)return serialize$3;hasRequiredSerialize=1;var Au=serialize$3&&serialize$3.__createBinding||(Object.create?(function(Mu,Du,Lu,Bu){Bu===void 0&&(Bu=Lu);var ju=Object.getOwnPropertyDescriptor(Du,Lu);(!ju||("get"in ju?!Du.__esModule:ju.writable||ju.configurable))&&(ju={enumerable:!0,get:function(){return Du[Lu]}}),Object.defineProperty(Mu,Bu,ju)}):(function(Mu,Du,Lu,Bu){Bu===void 0&&(Bu=Lu),Mu[Bu]=Du[Lu]})),lo=serialize$3&&serialize$3.__setModuleDefault||(Object.create?(function(Mu,Du){Object.defineProperty(Mu,"default",{enumerable:!0,value:Du})}):function(Mu,Du){Mu.default=Du}),$u=serialize$3&&serialize$3.__importStar||(function(){var Mu=function(Du){return Mu=Object.getOwnPropertyNames||function(Lu){var Bu=[];for(var ju in Lu)Object.prototype.hasOwnProperty.call(Lu,ju)&&(Bu[Bu.length]=ju);return Bu},Mu(Du)};return function(Du){if(Du&&Du.__esModule)return Du;var Lu={};if(Du!=null)for(var Bu=Mu(Du),ju=0;ju<Bu.length;ju++)Bu[ju]!=="default"&&Au(Lu,Du,Bu[ju]);return lo(Lu,Du),Lu}})();Object.defineProperty(serialize$3,"__esModule",{value:!0}),serialize$3.serialize=Iu,serialize$3.deserialize=Pu;const Ru=$u(requireMessages());function Iu(Mu,Du=""){return Du===Ru.supportedKernelWebSocketProtocols.v1KernelWebsocketJupyterOrg?Ou.serializeV1KernelWebsocketJupyterOrg(Mu):Ou.serializeDefault(Mu)}function Pu(Mu,Du=""){return Du===Ru.supportedKernelWebSocketProtocols.v1KernelWebsocketJupyterOrg?Ou.deserializeV1KernelWebsocketJupyterOrg(Mu):Ou.deserializeDefault(Mu)}var Ou;return(function(Mu){function Du(Uu){let Hu;const Vu=new DataView(Uu),Gu=Number(Vu.getBigUint64(0,!0));let Wu=[];for(let od=0;od<Gu;od++)Wu.push(Number(Vu.getBigUint64(8*(od+1),!0)));const Zu=new TextDecoder("utf8"),Ju=Zu.decode(Uu.slice(Wu[0],Wu[1])),Yu=JSON.parse(Zu.decode(Uu.slice(Wu[1],Wu[2]))),Xu=JSON.parse(Zu.decode(Uu.slice(Wu[2],Wu[3]))),ed=JSON.parse(Zu.decode(Uu.slice(Wu[3],Wu[4]))),td=JSON.parse(Zu.decode(Uu.slice(Wu[4],Wu[5])));let nd=[];for(let od=5;od<Wu.length-1;od++)nd.push(new DataView(Uu.slice(Wu[od],Wu[od+1])));return Hu={channel:Ju,header:Yu,parent_header:Xu,metadata:ed,content:td,buffers:nd},Hu}Mu.deserializeV1KernelWebsocketJupyterOrg=Du;function Lu(Uu){const Hu=JSON.stringify(Uu.header),Vu=Uu.parent_header==null?"{}":JSON.stringify(Uu.parent_header),Gu=JSON.stringify(Uu.metadata),Wu=JSON.stringify(Uu.content),Zu=Uu.buffers!==void 0?Uu.buffers:[],Ju=5+Zu.length+1;let Yu=[];Yu.push(8*(1+Ju)),Yu.push(Uu.channel.length+Yu[Yu.length-1]);const Xu=new TextEncoder,ed=Xu.encode(Uu.channel),td=Xu.encode(Hu),nd=Xu.encode(Vu),od=Xu.encode(Gu),sd=Xu.encode(Wu),ad=new Uint8Array(ed.length+td.length+nd.length+od.length+sd.length);ad.set(ed),ad.set(td,ed.length),ad.set(nd,ed.length+td.length),ad.set(od,ed.length+td.length+nd.length),ad.set(sd,ed.length+td.length+nd.length+od.length);for(let bd of[td.length,nd.length,od.length,sd.length])Yu.push(bd+Yu[Yu.length-1]);let pd=0;for(let bd of Zu){let wd=bd.byteLength;Yu.push(wd+Yu[Yu.length-1]),pd+=wd}const vd=new Uint8Array(8*(1+Ju)+ad.byteLength+pd),Sd=new ArrayBuffer(8),_d=new DataView(Sd);_d.setBigUint64(0,BigInt(Ju),!0),vd.set(new Uint8Array(Sd),0);for(let bd=0;bd<Yu.length;bd++)_d.setBigUint64(0,BigInt(Yu[bd]),!0),vd.set(new Uint8Array(Sd),8*(bd+1));vd.set(ad,Yu[0]);for(let bd=0;bd<Zu.length;bd++){const wd=Zu[bd];vd.set(new Uint8Array(ArrayBuffer.isView(wd)?wd.buffer:wd),Yu[5+bd])}return vd.buffer}Mu.serializeV1KernelWebsocketJupyterOrg=Lu;function Bu(Uu){let Hu;return typeof Uu=="string"?Hu=JSON.parse(Uu):Hu=Fu(Uu),Hu}Mu.deserializeDefault=Bu;function ju(Uu){var Hu;let Vu;return!((Hu=Uu.buffers)===null||Hu===void 0)&&Hu.length?Vu=zu(Uu):Vu=JSON.stringify(Uu),Vu}Mu.serializeDefault=ju;function Fu(Uu){const Hu=new DataView(Uu),Vu=Hu.getUint32(0),Gu=[];if(Vu<2)throw new Error("Invalid incoming Kernel Message");for(let Ju=1;Ju<=Vu;Ju++)Gu.push(Hu.getUint32(Ju*4));const Wu=new Uint8Array(Uu.slice(Gu[0],Gu[1])),Zu=JSON.parse(new TextDecoder("utf8").decode(Wu));Zu.buffers=[];for(let Ju=1;Ju<Vu;Ju++){const Yu=Gu[Ju],Xu=Gu[Ju+1]||Uu.byteLength;Zu.buffers.push(new DataView(Uu.slice(Yu,Xu)))}return Zu}function zu(Uu){const Hu=[],Vu=[],Gu=new TextEncoder;let Wu=[];Uu.buffers!==void 0&&(Wu=Uu.buffers,delete Uu.buffers);const Zu=Gu.encode(JSON.stringify(Uu));Vu.push(Zu.buffer);for(let ed=0;ed<Wu.length;ed++){const td=Wu[ed];Vu.push(ArrayBuffer.isView(td)?td.buffer:td)}const Ju=Vu.length;Hu.push(4*(Ju+1));for(let ed=0;ed+1<Vu.length;ed++)Hu.push(Hu[Hu.length-1]+Vu[ed].byteLength);const Yu=new Uint8Array(Hu[Hu.length-1]+Vu[Vu.length-1].byteLength),Xu=new DataView(Yu.buffer);Xu.setUint32(0,Ju);for(let ed=0;ed<Hu.length;ed++)Xu.setUint32(4*(ed+1),Hu[ed]);for(let ed=0;ed<Vu.length;ed++)Yu.set(new Uint8Array(Vu[ed]),Hu[ed]);return Yu.buffer}})(Ou||(Ou={})),serialize$3}var ws$1={},hasRequiredWs;function requireWs(){return hasRequiredWs||(hasRequiredWs=1,Object.defineProperty(ws$1,"__esModule",{value:!0}),ws$1.default=WebSocket),ws$1}var hasRequiredServerconnection;function requireServerconnection(){if(hasRequiredServerconnection)return serverconnection;hasRequiredServerconnection=1;var Au={};Object.defineProperty(serverconnection,"__esModule",{value:!0}),serverconnection.ServerConnection=void 0;const lo=requireLib$b(),$u=requireSerialize();let Ru;typeof window>"u"?Ru=requireWs():Ru=WebSocket;var Iu;(function(Ou){function Mu(ju){return Pu.makeSettings(ju)}Ou.makeSettings=Mu;function Du(ju,Fu,zu){return Pu.handleRequest(ju,Fu,zu)}Ou.makeRequest=Du;class Lu extends Error{static async create(Fu){try{const zu=await Fu.json(),{message:Uu,traceback:Hu}=zu;return Hu&&console.error(Hu),new Lu(Fu,Uu??Lu._defaultMessage(Fu),Hu??"")}catch(zu){return console.debug(zu),new Lu(Fu)}}constructor(Fu,zu=Lu._defaultMessage(Fu),Uu=""){super(zu),this.response=Fu,this.traceback=Uu}static _defaultMessage(Fu){return`Invalid response: ${Fu.status} ${Fu.statusText}`}}Ou.ResponseError=Lu;class Bu extends TypeError{constructor(Fu){super(Fu.message),this.stack=Fu.stack}}Ou.NetworkError=Bu})(Iu||(serverconnection.ServerConnection=Iu={}));var Pu;return(function(Ou){function Mu(Bu={}){var ju;const Fu=lo.PageConfig.getBaseUrl(),zu=lo.PageConfig.getWsUrl(),Uu=lo.URLExt.normalize(Bu.baseUrl)||Fu;let Hu=Bu.wsUrl;!Hu&&Uu===Fu&&(Hu=zu),!Hu&&Uu.indexOf("http")===0&&(Hu="ws"+Uu.slice(4)),Hu=Hu??zu;const Vu=lo.PageConfig.getOption("appendToken").toLowerCase();let Gu;return Vu===""?Gu=typeof window>"u"||typeof process<"u"&&((ju=process==null?void 0:Au)===null||ju===void 0?void 0:ju.JEST_WORKER_ID)!==void 0||lo.URLExt.getHostName(Fu)!==lo.URLExt.getHostName(Hu):Gu=Vu==="true",{init:{cache:"no-store",credentials:"same-origin"},fetch,Headers,Request,WebSocket:Ru,token:lo.PageConfig.getToken(),appUrl:lo.PageConfig.getOption("appUrl"),appendToken:Gu,serializer:{serialize:$u.serialize,deserialize:$u.deserialize},...Bu,baseUrl:Uu,wsUrl:Hu}}Ou.makeSettings=Mu;function Du(Bu,ju,Fu){var zu;if(Bu.indexOf(Fu.baseUrl)!==0)throw new Error("Can only be used for notebook server requests");((zu=ju.cache)!==null&&zu!==void 0?zu:Fu.init.cache)==="no-store"&&(Bu+=(/\?/.test(Bu)?"&":"?")+new Date().getTime());const Hu=new Fu.Request(Bu,{...Fu.init,...ju});let Vu=!1;if(Fu.token&&(Vu=!0,Hu.headers.append("Authorization",`token ${Fu.token}`)),typeof document<"u"){const Gu=Lu("_xsrf");Gu!==void 0&&(Vu=!0,Hu.headers.append("X-XSRFToken",Gu))}return!Hu.headers.has("Content-Type")&&Vu&&Hu.headers.set("Content-Type","application/json"),Fu.fetch.call(null,Hu).catch(Gu=>{throw new Iu.NetworkError(Gu)})}Ou.handleRequest=Du;function Lu(Bu){let ju="";try{ju=document.cookie}catch{return}const Fu=Bu+"=";let zu;for(const Uu of ju.split(";")){const Hu=Uu.trim();Hu.startsWith(Fu)&&(zu=Hu.substring(Fu.length))}return zu}})(Pu||(Pu={})),serverconnection}var hasRequiredBasemanager;function requireBasemanager(){if(hasRequiredBasemanager)return basemanager;hasRequiredBasemanager=1,Object.defineProperty(basemanager,"__esModule",{value:!0}),basemanager.BaseManager=void 0;const Au=require$$0$2,lo=requireServerconnection();class $u{constructor(Iu){var Pu;this._isDisposed=!1,this._disposed=new Au.Signal(this),this.serverSettings=(Pu=Iu.serverSettings)!==null&&Pu!==void 0?Pu:lo.ServerConnection.makeSettings()}get disposed(){return this._disposed}get isDisposed(){return this._isDisposed}get isActive(){return!0}dispose(){this.isDisposed||(this._isDisposed=!0,this._disposed.emit(void 0),Au.Signal.clearData(this))}}return basemanager.BaseManager=$u,basemanager}var config$4={},hasRequiredConfig;function requireConfig(){if(hasRequiredConfig)return config$4;hasRequiredConfig=1,Object.defineProperty(config$4,"__esModule",{value:!0}),config$4.ConfigWithDefaults=config$4.ConfigSection=config$4.ConfigSectionManager=void 0;const Au=requireLib$b(),lo=requireLib$8(),$u="api/config";class Ru{constructor(Du){var Lu;this.serverSettings=(Lu=Du.serverSettings)!==null&&Lu!==void 0?Lu:lo.ServerConnection.makeSettings()}async create(Du){const Lu=new Pu({...Du,serverSettings:this.serverSettings});return await Lu.load(),Lu}}config$4.ConfigSectionManager=Ru;var Iu;(function(Mu){async function Du(ju){if(!Lu){const zu=new Pu(ju);return await zu.load(),zu}return await Lu.create(ju)}Mu.create=Du;let Lu;function Bu(ju){if(Lu)throw new Error("ConfigSectionManager already set. If you would like to create a config section, use the `IConfigSectionManager` token in a plugin.");Lu=ju}Mu._setConfigSectionManager=Bu})(Iu||(config$4.ConfigSection=Iu={}));class Pu{constructor(Du){var Lu;this.serverSettings=(Lu=Du.serverSettings)!==null&&Lu!==void 0?Lu:lo.ServerConnection.makeSettings(),this._name=Du.name}get data(){return this._data}async load(){const Du=await lo.ServerConnection.makeRequest(this._url,{},this.serverSettings);if(Du.status!==200)throw await lo.ServerConnection.ResponseError.create(Du);this._data=await Du.json()}async update(Du){this._data={...this._data,...Du};const Lu={method:"PATCH",body:JSON.stringify(Du)},Bu=await lo.ServerConnection.makeRequest(this._url,Lu,this.serverSettings);if(Bu.status!==200)throw await lo.ServerConnection.ResponseError.create(Bu);return this._data=await Bu.json(),this._data}get _url(){return Au.URLExt.join(this.serverSettings.baseUrl,$u,encodeURIComponent(this._name))}}class Ou{constructor(Du){var Lu,Bu;this._className="",this._section=Du.section,this._defaults=(Lu=Du.defaults)!==null&&Lu!==void 0?Lu:{},this._className=(Bu=Du.className)!==null&&Bu!==void 0?Bu:""}get(Du){const Lu=this._classData();return Du in Lu?Lu[Du]:this._defaults[Du]}set(Du,Lu){const Bu={};if(Bu[Du]=Lu,this._className){const ju={};return ju[this._className]=Bu,this._section.update(ju)}else return this._section.update(Bu)}_classData(){const Du=this._section.data;return this._className&&this._className in Du?Du[this._className]:Du}}return config$4.ConfigWithDefaults=Ou,config$4}var connectionstatus={},hasRequiredConnectionstatus;function requireConnectionstatus(){if(hasRequiredConnectionstatus)return connectionstatus;hasRequiredConnectionstatus=1,Object.defineProperty(connectionstatus,"__esModule",{value:!0}),connectionstatus.ConnectionStatus=void 0;class Au{constructor(){this.isConnected=!0}}return connectionstatus.ConnectionStatus=Au,connectionstatus}var contents={};class DisposableDelegate{constructor(lo){this._fn=lo}get isDisposed(){return!this._fn}dispose(){if(!this._fn)return;let lo=this._fn;this._fn=null,lo()}}class ObservableDisposableDelegate extends DisposableDelegate{constructor(){super(...arguments),this._disposed=new Signal(this)}get disposed(){return this._disposed}dispose(){this.isDisposed||(super.dispose(),this._disposed.emit(void 0),Signal.clearData(this))}}class DisposableSet{constructor(){this._isDisposed=!1,this._items=new Set}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,this._items.forEach(lo=>{lo.dispose()}),this._items.clear())}contains(lo){return this._items.has(lo)}add(lo){this._items.add(lo)}remove(lo){this._items.delete(lo)}clear(){this._items.clear()}}(function(Au){function lo($u){let Ru=new Au;for(const Iu of $u)Ru.add(Iu);return Ru}Au.from=lo})(DisposableSet||(DisposableSet={}));class ObservableDisposableSet extends DisposableSet{constructor(){super(...arguments),this._disposed=new Signal(this)}get disposed(){return this._disposed}dispose(){this.isDisposed||(super.dispose(),this._disposed.emit(void 0),Signal.clearData(this))}}(function(Au){function lo($u){let Ru=new Au;for(const Iu of $u)Ru.add(Iu);return Ru}Au.from=lo})(ObservableDisposableSet||(ObservableDisposableSet={}));const index_es6$1=Object.freeze(Object.defineProperty({__proto__:null,DisposableDelegate,get DisposableSet(){return DisposableSet},ObservableDisposableDelegate,get ObservableDisposableSet(){return ObservableDisposableSet}},Symbol.toStringTag,{value:"Module"})),require$$1$2=getAugmentedNamespace(index_es6$1);var validate$7={},validate$6={},hasRequiredValidate$5;function requireValidate$5(){if(hasRequiredValidate$5)return validate$6;hasRequiredValidate$5=1,Object.defineProperty(validate$6,"__esModule",{value:!0}),validate$6.validateProperty=Au;function Au(lo,$u,Ru,Iu=[]){if(!lo.hasOwnProperty($u))throw Error(`Missing property '${$u}'`);const Pu=lo[$u];if(Ru!==void 0){let Ou;switch(Ru){case"array":Ou=Array.isArray(Pu);break;case"object":Ou=typeof Pu<"u";break;default:Ou=typeof Pu===Ru}if(!Ou)throw new Error(`Property '${$u}' is not of type '${Ru}'`);if(Iu.length>0){let Mu;switch(Ru){case"string":case"number":case"boolean":Mu=Iu.includes(Pu);break;default:Mu=Iu.findIndex(Du=>Du===Pu)>=0;break}if(!Mu)throw new Error(`Property '${$u}' is not one of the valid values ${JSON.stringify(Iu)}`)}}}return validate$6}var hasRequiredValidate$4;function requireValidate$4(){if(hasRequiredValidate$4)return validate$7;hasRequiredValidate$4=1,Object.defineProperty(validate$7,"__esModule",{value:!0}),validate$7.validateContentsModel=lo,validate$7.validateCheckpointModel=$u;const Au=requireValidate$5();function lo(Ru){(0,Au.validateProperty)(Ru,"name","string"),(0,Au.validateProperty)(Ru,"path","string"),(0,Au.validateProperty)(Ru,"type","string"),(0,Au.validateProperty)(Ru,"created","string"),(0,Au.validateProperty)(Ru,"last_modified","string"),(0,Au.validateProperty)(Ru,"mimetype","object"),(0,Au.validateProperty)(Ru,"content","object"),(0,Au.validateProperty)(Ru,"format","object")}function $u(Ru){(0,Au.validateProperty)(Ru,"id","string"),(0,Au.validateProperty)(Ru,"last_modified","string")}return validate$7}var hasRequiredContents;function requireContents(){if(hasRequiredContents)return contents;hasRequiredContents=1;var Au=contents&&contents.__createBinding||(Object.create?(function(Gu,Wu,Zu,Ju){Ju===void 0&&(Ju=Zu);var Yu=Object.getOwnPropertyDescriptor(Wu,Zu);(!Yu||("get"in Yu?!Wu.__esModule:Yu.writable||Yu.configurable))&&(Yu={enumerable:!0,get:function(){return Wu[Zu]}}),Object.defineProperty(Gu,Ju,Yu)}):(function(Gu,Wu,Zu,Ju){Ju===void 0&&(Ju=Zu),Gu[Ju]=Wu[Zu]})),lo=contents&&contents.__setModuleDefault||(Object.create?(function(Gu,Wu){Object.defineProperty(Gu,"default",{enumerable:!0,value:Wu})}):function(Gu,Wu){Gu.default=Wu}),$u=contents&&contents.__importStar||(function(){var Gu=function(Wu){return Gu=Object.getOwnPropertyNames||function(Zu){var Ju=[];for(var Yu in Zu)Object.prototype.hasOwnProperty.call(Zu,Yu)&&(Ju[Ju.length]=Yu);return Ju},Gu(Wu)};return function(Wu){if(Wu&&Wu.__esModule)return Wu;var Zu={};if(Wu!=null)for(var Ju=Gu(Wu),Yu=0;Yu<Ju.length;Yu++)Ju[Yu]!=="default"&&Au(Zu,Wu,Ju[Yu]);return lo(Zu,Wu),Zu}})();Object.defineProperty(contents,"__esModule",{value:!0}),contents.RestContentProvider=contents.ContentProviderRegistry=contents.Drive=contents.ContentsManager=contents.Contents=void 0;const Ru=requireLib$b(),Iu=requireDist(),Pu=require$$1$2,Ou=require$$0$2,Mu=requireLib$8(),Du=$u(requireValidate$4()),Lu="api/contents",Bu="files";var ju;(function(Gu){function Wu(Ju){Du.validateContentsModel(Ju)}Gu.validateContentsModel=Wu;function Zu(Ju){Du.validateCheckpointModel(Ju)}Gu.validateCheckpointModel=Zu})(ju||(contents.Contents=ju={}));class Fu{constructor(Wu={}){var Zu,Ju;this._isDisposed=!1,this._additionalDrives=new Map,this._fileChanged=new Ou.Signal(this);const Yu=this.serverSettings=(Zu=Wu.serverSettings)!==null&&Zu!==void 0?Zu:Mu.ServerConnection.makeSettings();this._defaultDrive=(Ju=Wu.defaultDrive)!==null&&Ju!==void 0?Ju:new zu({serverSettings:Yu}),this._defaultDrive.fileChanged.connect(this._onFileChanged,this)}get defaultDrive(){return this._defaultDrive}get fileChanged(){return this._fileChanged}get isDisposed(){return this._isDisposed}dispose(){this.isDisposed||(this._isDisposed=!0,Ou.Signal.clearData(this))}addDrive(Wu){this._additionalDrives.set(Wu.name,Wu),Wu.fileChanged.connect(this._onFileChanged,this)}getSharedModelFactory(Wu,Zu){var Ju,Yu;const[Xu]=this._driveForPath(Wu),ed=(Ju=Xu.contentProviderRegistry)===null||Ju===void 0?void 0:Ju.getProvider(Zu?.contentProviderId);return ed?.sharedModelFactory?ed.sharedModelFactory:(Yu=Xu.sharedModelFactory)!==null&&Yu!==void 0?Yu:null}localPath(Wu){const Zu=Wu.split("/"),Ju=Zu[0].split(":");return Ju.length===1||!this._additionalDrives.has(Ju[0])?Ru.PathExt.removeSlash(Wu):Ru.PathExt.join(Ju.slice(1).join(":"),...Zu.slice(1))}normalize(Wu){const Zu=Wu.split(":");return Zu.length===1?Ru.PathExt.normalize(Wu):`${Zu[0]}:${Ru.PathExt.normalize(Zu.slice(1).join(":"))}`}resolvePath(Wu,Zu){const Ju=this.driveName(Wu),Yu=this.localPath(Wu),Xu=Ru.PathExt.resolve("/",Yu,Zu);return Ju?`${Ju}:${Xu}`:Xu}driveName(Wu){const Ju=Wu.split("/")[0].split(":");return Ju.length===1?"":this._additionalDrives.has(Ju[0])?Ju[0]:""}get(Wu,Zu){const[Ju,Yu]=this._driveForPath(Wu);return Ju.get(Yu,Zu).then(Xu=>{const ed=[];if(Xu.type==="directory"&&Xu.content){for(const td of Xu.content)ed.push({...td,path:this._toGlobalPath(Ju,td.path)});return{...Xu,path:this._toGlobalPath(Ju,Yu),content:ed,serverPath:Xu.path}}else return{...Xu,path:this._toGlobalPath(Ju,Yu),serverPath:Xu.path}})}getDownloadUrl(Wu){const[Zu,Ju]=this._driveForPath(Wu);return Zu.getDownloadUrl(Ju)}newUntitled(Wu={}){if(Wu.path){const Zu=this.normalize(Wu.path),[Ju,Yu]=this._driveForPath(Zu);return Ju.newUntitled({...Wu,path:Yu}).then(Xu=>({...Xu,path:Ru.PathExt.join(Zu,Xu.name),serverPath:Xu.path}))}else return this._defaultDrive.newUntitled(Wu)}delete(Wu){const[Zu,Ju]=this._driveForPath(Wu);return Zu.delete(Ju)}rename(Wu,Zu){const[Ju,Yu]=this._driveForPath(Wu),[Xu,ed]=this._driveForPath(Zu);if(Ju!==Xu)throw Error("ContentsManager: renaming files must occur within a Drive");return Ju.rename(Yu,ed).then(td=>({...td,path:this._toGlobalPath(Ju,ed),serverPath:td.path}))}async overwrite(Wu,Zu){const Ju=`${Zu}.${Iu.UUID.uuid4()}`;return await this.rename(Wu,Ju),await this.delete(Zu),await this.rename(Ju,Zu)}save(Wu,Zu={}){const Ju=this.normalize(Wu),[Yu,Xu]=this._driveForPath(Wu);return Yu.save(Xu,{...Zu,path:Xu}).then(ed=>({...ed,path:Ju,serverPath:ed.path}))}copy(Wu,Zu){const[Ju,Yu]=this._driveForPath(Wu),[Xu,ed]=this._driveForPath(Zu);if(Ju===Xu)return Ju.copy(Yu,ed).then(td=>({...td,path:this._toGlobalPath(Ju,td.path),serverPath:td.path}));throw Error("Copying files between drives is not currently implemented")}createCheckpoint(Wu){const[Zu,Ju]=this._driveForPath(Wu);return Zu.createCheckpoint(Ju)}listCheckpoints(Wu){const[Zu,Ju]=this._driveForPath(Wu);return Zu.listCheckpoints(Ju)}restoreCheckpoint(Wu,Zu){const[Ju,Yu]=this._driveForPath(Wu);return Ju.restoreCheckpoint(Yu,Zu)}deleteCheckpoint(Wu,Zu){const[Ju,Yu]=this._driveForPath(Wu);return Ju.deleteCheckpoint(Yu,Zu)}_toGlobalPath(Wu,Zu){return Wu===this._defaultDrive?Ru.PathExt.removeSlash(Zu):`${Wu.name}:${Ru.PathExt.removeSlash(Zu)}`}_driveForPath(Wu){const Zu=this.driveName(Wu),Ju=this.localPath(Wu);return Zu?[this._additionalDrives.get(Zu),Ju]:[this._defaultDrive,Ju]}_onFileChanged(Wu,Zu){var Ju,Yu;if(Wu===this._defaultDrive)this._fileChanged.emit(Zu);else{let Xu=null,ed=null;!((Ju=Zu.newValue)===null||Ju===void 0)&&Ju.path&&(Xu={...Zu.newValue,path:this._toGlobalPath(Wu,Zu.newValue.path)}),!((Yu=Zu.oldValue)===null||Yu===void 0)&&Yu.path&&(ed={...Zu.oldValue,path:this._toGlobalPath(Wu,Zu.oldValue.path)}),this._fileChanged.emit({type:Zu.type,newValue:Xu,oldValue:ed})}}}contents.ContentsManager=Fu;class zu{constructor(Wu={}){var Zu,Ju,Yu;this._isDisposed=!1,this._fileChanged=new Ou.Signal(this),this.name=(Zu=Wu.name)!==null&&Zu!==void 0?Zu:"Default",this._apiEndpoint=(Ju=Wu.apiEndpoint)!==null&&Ju!==void 0?Ju:Lu,this.serverSettings=(Yu=Wu.serverSettings)!==null&&Yu!==void 0?Yu:Mu.ServerConnection.makeSettings(),this._restContentProvider=new Vu({...Wu,apiEndpoint:this._apiEndpoint,serverSettings:this.serverSettings}),Wu.defaultContentProvider?this.contentProviderRegistry=new Hu({defaultProvider:Wu.defaultContentProvider}):this.contentProviderRegistry=new Hu,this.contentProviderRegistry.fileChanged.connect((Xu,ed)=>{this._fileChanged.emit(ed)})}get fileChanged(){return this._fileChanged}get isDisposed(){return this._isDisposed}dispose(){this.isDisposed||(this._isDisposed=!0,Ou.Signal.clearData(this))}async get(Wu,Zu){const Ju=this.contentProviderRegistry.getProvider(Zu?.contentProviderId);return Ju?Ju.get(Wu,Zu):await this._restContentProvider.get(Wu,Zu)}getDownloadUrl(Wu){const Zu=this.serverSettings.baseUrl;let Ju=Ru.URLExt.join(Zu,Bu,Ru.URLExt.encodeParts(Wu)),Yu="";try{Yu=document.cookie}catch{}const Xu=Yu.match("\\b_xsrf=([^;]*)\\b");if(Xu){const ed=new URL(Ju);ed.searchParams.append("_xsrf",Xu[1]),Ju=ed.toString()}return Promise.resolve(Ju)}async newUntitled(Wu={}){var Zu;let Ju="{}";Wu&&(Wu.ext&&(Wu.ext=Uu.normalizeExtension(Wu.ext)),Ju=JSON.stringify(Wu));const Yu=this.serverSettings,Xu=this._getUrl((Zu=Wu.path)!==null&&Zu!==void 0?Zu:""),ed={method:"POST",body:Ju},td=await Mu.ServerConnection.makeRequest(Xu,ed,Yu);if(td.status!==201)throw await Mu.ServerConnection.ResponseError.create(td);const nd=await td.json();return Du.validateContentsModel(nd),this._fileChanged.emit({type:"new",oldValue:null,newValue:nd}),nd}async delete(Wu){const Zu=this._getUrl(Wu),Ju=this.serverSettings,Yu={method:"DELETE"},Xu=await Mu.ServerConnection.makeRequest(Zu,Yu,Ju);if(Xu.status!==204)throw await Mu.ServerConnection.ResponseError.create(Xu);this._fileChanged.emit({type:"delete",oldValue:{path:Wu},newValue:null})}async rename(Wu,Zu){const Ju=this.serverSettings,Yu=this._getUrl(Wu),Xu={method:"PATCH",body:JSON.stringify({path:Zu})},ed=await Mu.ServerConnection.makeRequest(Yu,Xu,Ju);if(ed.status!==200)throw await Mu.ServerConnection.ResponseError.create(ed);const td=await ed.json();return Du.validateContentsModel(td),this._fileChanged.emit({type:"rename",oldValue:{path:Wu},newValue:td}),td}async save(Wu,Zu={}){const Ju=this.contentProviderRegistry.getProvider(Zu?.contentProviderId);let Yu;return Ju?Yu=await Ju.save(Wu,Zu):Yu=await this._restContentProvider.save(Wu,Zu),this._fileChanged.emit({type:"save",oldValue:null,newValue:Yu}),Yu}async copy(Wu,Zu){const Ju=this.serverSettings,Yu=this._getUrl(Zu),Xu={method:"POST",body:JSON.stringify({copy_from:Wu})},ed=await Mu.ServerConnection.makeRequest(Yu,Xu,Ju);if(ed.status!==201)throw await Mu.ServerConnection.ResponseError.create(ed);const td=await ed.json();return Du.validateContentsModel(td),this._fileChanged.emit({type:"new",oldValue:null,newValue:td}),td}async createCheckpoint(Wu){const Zu=this._getUrl(Wu,"checkpoints"),Ju={method:"POST"},Yu=await Mu.ServerConnection.makeRequest(Zu,Ju,this.serverSettings);if(Yu.status!==201)throw await Mu.ServerConnection.ResponseError.create(Yu);const Xu=await Yu.json();return Du.validateCheckpointModel(Xu),Xu}async listCheckpoints(Wu){const Zu=this._getUrl(Wu,"checkpoints"),Ju=await Mu.ServerConnection.makeRequest(Zu,{},this.serverSettings);if(Ju.status!==200)throw await Mu.ServerConnection.ResponseError.create(Ju);const Yu=await Ju.json();if(!Array.isArray(Yu))throw new Error("Invalid Checkpoint list");for(let Xu=0;Xu<Yu.length;Xu++)Du.validateCheckpointModel(Yu[Xu]);return Yu}async restoreCheckpoint(Wu,Zu){const Ju=this._getUrl(Wu,"checkpoints",Zu),Yu={method:"POST"},Xu=await Mu.ServerConnection.makeRequest(Ju,Yu,this.serverSettings);if(Xu.status!==204)throw await Mu.ServerConnection.ResponseError.create(Xu)}async deleteCheckpoint(Wu,Zu){const Ju=this._getUrl(Wu,"checkpoints",Zu),Yu={method:"DELETE"},Xu=await Mu.ServerConnection.makeRequest(Ju,Yu,this.serverSettings);if(Xu.status!==204)throw await Mu.ServerConnection.ResponseError.create(Xu)}_getUrl(...Wu){const Zu=Wu.map(Yu=>Ru.URLExt.encodeParts(Yu)),Ju=this.serverSettings.baseUrl;return Ru.URLExt.join(Ju,this._apiEndpoint,...Zu)}}contents.Drive=zu;var Uu;(function(Gu){function Wu(Zu){return Zu.length>0&&Zu.indexOf(".")!==0&&(Zu=`.${Zu}`),Zu}Gu.normalizeExtension=Wu})(Uu||(Uu={}));class Hu{constructor(Wu){this._providers=new Map,this._fileChanged=new Ou.Signal(this),Wu?.defaultProvider&&this.register("default",Wu.defaultProvider)}register(Wu,Zu){if(this._providers.has(Wu))throw Error(`Provider with ${Wu} identifier was already registered on this drive`);this._providers.set(Wu,Zu);const Ju=(Yu,Xu)=>{this._fileChanged.emit(Xu)};return Zu.fileChanged&&Zu.fileChanged.connect(Ju),new Pu.DisposableDelegate(()=>{Zu.fileChanged&&Zu.fileChanged.disconnect(Ju),this._providers.has(Wu)&&this._providers.delete(Wu)})}getProvider(Wu){if(!Wu)return null;const Zu=this._providers.get(Wu);if(!Zu)throw Error(`Provider ${Wu} is not registered`);return Zu}get fileChanged(){return this._fileChanged}}contents.ContentProviderRegistry=Hu;class Vu{constructor(Wu){this._options=Wu}async get(Wu,Zu){let Ju=this._getUrl(Wu);if(Zu){Zu.type==="notebook"&&delete Zu.format;const td=Zu.content?"1":"0",nd=Zu.hash?"1":"0",od={...Zu,content:td,hash:nd};Ju+=Ru.URLExt.objectToQueryString(od)}const Yu=this._options.serverSettings,Xu=await Mu.ServerConnection.makeRequest(Ju,{},Yu);if(Xu.status!==200)throw await Mu.ServerConnection.ResponseError.create(Xu);const ed=await Xu.json();return Du.validateContentsModel(ed),ed}async save(Wu,Zu={}){const Ju=this._options.serverSettings,Yu=this._getUrl(Wu),ed={method:"PUT",body:new File([JSON.stringify(Zu)],"data.json",{type:"application/json"})},td=await Mu.ServerConnection.makeRequest(Yu,ed,Ju);if(td.status!==200&&td.status!==201)throw await Mu.ServerConnection.ResponseError.create(td);const nd=await td.json();return Du.validateContentsModel(nd),nd}_getUrl(...Wu){const Zu=Wu.map(Yu=>Ru.URLExt.encodeParts(Yu)),Ju=this._options.serverSettings.baseUrl;return Ru.URLExt.join(Ju,this._options.apiEndpoint,...Zu)}}return contents.RestContentProvider=Vu,contents}var event={};const require$$1$1=getAugmentedNamespace(index_es6$2);var hasRequiredEvent;function requireEvent(){if(hasRequiredEvent)return event;hasRequiredEvent=1,Object.defineProperty(event,"__esModule",{value:!0}),event.EventManager=void 0;const Au=requireLib$b(),lo=require$$1$1,$u=require$$0$2,Ru=requireServerconnection(),Iu="api/events";class Pu{constructor(Mu={}){var Du,Lu;this._socket=null,this.serverSettings=(Du=Mu.serverSettings)!==null&&Du!==void 0?Du:Ru.ServerConnection.makeSettings(),this._poll=new lo.Poll({factory:()=>this._subscribe(),standby:(Lu=Mu.standby)!==null&&Lu!==void 0?Lu:"when-hidden"}),this._stream=new $u.Stream(this),this._poll.start()}get isDisposed(){return this._poll.isDisposed}get stream(){return this._stream}dispose(){if(this.isDisposed)return;this._poll.dispose();const Mu=this._socket;Mu&&(this._socket=null,Mu.onopen=()=>{},Mu.onerror=()=>{},Mu.onmessage=()=>{},Mu.onclose=()=>{},Mu.close()),$u.Signal.clearData(this),this._stream.stop()}async emit(Mu){const{serverSettings:Du}=this,{baseUrl:Lu}=Du,{makeRequest:Bu,ResponseError:ju}=Ru.ServerConnection,Fu=Au.URLExt.join(Lu,Iu),zu={body:JSON.stringify(Mu),method:"POST"},Uu=await Bu(Fu,zu,Du);if(Uu.status!==204)throw new ju(Uu)}_subscribe(){return new Promise((Mu,Du)=>{if(this.isDisposed)return;const{appendToken:Lu,token:Bu,WebSocket:ju,wsUrl:Fu}=this.serverSettings;let zu=Au.URLExt.join(Fu,Iu,"subscribe");Lu&&Bu!==""&&(zu+=`?token=${encodeURIComponent(Bu)}`);const Uu=this._socket=new ju(zu),Hu=this._stream;Uu.onclose=()=>Du(new Error("EventManager socket closed")),Uu.onmessage=Vu=>Vu.data&&Hu.emit(JSON.parse(Vu.data))})}}return event.EventManager=Pu,event}var kernel$1={},comm={},hasRequiredComm;function requireComm(){if(hasRequiredComm)return comm;hasRequiredComm=1;var Au=comm&&comm.__createBinding||(Object.create?(function(Du,Lu,Bu,ju){ju===void 0&&(ju=Bu);var Fu=Object.getOwnPropertyDescriptor(Lu,Bu);(!Fu||("get"in Fu?!Lu.__esModule:Fu.writable||Fu.configurable))&&(Fu={enumerable:!0,get:function(){return Lu[Bu]}}),Object.defineProperty(Du,ju,Fu)}):(function(Du,Lu,Bu,ju){ju===void 0&&(ju=Bu),Du[ju]=Lu[Bu]})),lo=comm&&comm.__setModuleDefault||(Object.create?(function(Du,Lu){Object.defineProperty(Du,"default",{enumerable:!0,value:Lu})}):function(Du,Lu){Du.default=Lu}),$u=comm&&comm.__importStar||(function(){var Du=function(Lu){return Du=Object.getOwnPropertyNames||function(Bu){var ju=[];for(var Fu in Bu)Object.prototype.hasOwnProperty.call(Bu,Fu)&&(ju[ju.length]=Fu);return ju},Du(Lu)};return function(Lu){if(Lu&&Lu.__esModule)return Lu;var Bu={};if(Lu!=null)for(var ju=Du(Lu),Fu=0;Fu<ju.length;Fu++)ju[Fu]!=="default"&&Au(Bu,Lu,ju[Fu]);return lo(Bu,Lu),Bu}})();Object.defineProperty(comm,"__esModule",{value:!0}),comm.CommHandler=comm.CommsOverSubshells=void 0;const Ru=requireDist(),Iu=require$$1$2,Pu=$u(requireMessages());var Ou;(function(Du){Du.Disabled="disabled",Du.PerComm="perComm",Du.PerCommTarget="perCommTarget"})(Ou||(comm.CommsOverSubshells=Ou={}));class Mu extends Iu.DisposableDelegate{constructor(Lu,Bu,ju,Fu,zu){super(Fu),this._subshellStarted=new Ru.PromiseDelegate,this._subshellId=null,this._target="",this._id="",this._id=Bu,this._target=Lu,this._kernel=ju,this._kernel.statusChanged.connect(()=>{this._kernel.status==="restarting"&&this._cleanSubshells()}),this.commsOverSubshells=zu??Ou.PerCommTarget}get commId(){return this._id}get targetName(){return this._target}get subshellId(){return this._subshellId}get subshellStarted(){return this._subshellStarted.promise}get commsOverSubshells(){return this._commsOverSubshells}set commsOverSubshells(Lu){if(Lu===this._commsOverSubshells)return;const Bu=this._maybeCloseSubshell(this._commsOverSubshells);this._commsOverSubshells=Lu,Bu.then(()=>{this._commsOverSubshells!==Ou.Disabled&&this._maybeStartSubshell()}).catch(console.warn)}get onClose(){return this._onClose}set onClose(Lu){this._onClose=Lu}get onMsg(){return this._onMsg}set onMsg(Lu){this._onMsg=Lu}open(Lu,Bu,ju=[]){if(this.isDisposed||this._kernel.isDisposed)throw new Error("Cannot open");const Fu=Pu.createMessage({msgType:"comm_open",channel:"shell",username:this._kernel.username,session:this._kernel.clientId,subshellId:this._subshellId||this._kernel.subshellId,content:{comm_id:this._id,target_name:this._target,data:Lu??{}},metadata:Bu,buffers:ju});return this._kernel.sendShellMessage(Fu,!1,!0)}send(Lu,Bu,ju=[],Fu=!0){if(this.isDisposed||this._kernel.isDisposed)throw new Error("Cannot send");const zu=Pu.createMessage({msgType:"comm_msg",channel:"shell",username:this._kernel.username,session:this._kernel.clientId,subshellId:this._subshellId||this._kernel.subshellId,content:{comm_id:this._id,data:Lu},metadata:Bu,buffers:ju});return this._kernel.sendShellMessage(zu,!1,Fu)}close(Lu,Bu,ju=[]){if(this.isDisposed||this._kernel.isDisposed)throw new Error("Cannot close");const Fu=Pu.createMessage({msgType:"comm_close",channel:"shell",username:this._kernel.username,session:this._kernel.clientId,subshellId:this._subshellId||this._kernel.subshellId,content:{comm_id:this._id,data:Lu??{}},metadata:Bu,buffers:ju}),zu=this._kernel.sendShellMessage(Fu,!1,!0),Uu=this._onClose;if(Uu){const Hu=Pu.createMessage({msgType:"comm_close",channel:"iopub",username:this._kernel.username,session:this._kernel.clientId,subshellId:this._subshellId||this._kernel.subshellId,content:{comm_id:this._id,data:Lu??{}},metadata:Bu,buffers:ju});Uu(Hu)}return this.dispose(),zu}dispose(){this._maybeCloseSubshell(this._commsOverSubshells),super.dispose()}_cleanSubshells(){const Lu=this._kernel.id;Mu._commTargetSubShellsId.hasOwnProperty(Lu)&&delete Mu._commTargetSubShellsId[Lu]}async _maybeStartSubshell(){if(await this._kernel.info,!this._kernel.supportsSubshells)return;if(this._commsOverSubshells===Ou.PerComm){const Uu=await this._kernel.requestCreateSubshell({}).done;this._subshellId=Uu.content.subshell_id,this._subshellStarted.resolve();return}const Lu=this._subshellStarted,Bu=this._kernel.id;Mu._commTargetSubShellsId.hasOwnProperty(Bu)||(Mu._commTargetSubShellsId[Bu]={});const ju=Mu._commTargetSubShellsId[Bu],Fu=ju[this._target];if(Fu){Fu.referenceCount+=1;try{this._subshellId=await Fu.subshellId,Lu.resolve()}catch(Uu){await this._closePerCommTargetSubshell(!1),Lu.reject(`Per comm-target subshell creation failed: ${Uu}`)}return}const zu={subshellId:this._kernel.requestCreateSubshell({}).done.then(Uu=>Uu.content.subshell_id),referenceCount:1};ju[this._target]=zu;try{this._subshellId=await zu.subshellId,Lu.resolve()}catch(Uu){await this._closePerCommTargetSubshell(!1),Lu.reject(`Per comm-target subshell creation failed: ${Uu}`)}}async _closePerCommTargetSubshell(Lu=!0){const Bu=this._kernel.id,ju=this._target;if(Mu._commTargetSubShellsId.hasOwnProperty(Bu)){const Fu=Mu._commTargetSubShellsId[Bu],zu=Fu[ju];if(zu&&(zu.referenceCount-=1,zu.referenceCount<=0)){if(Lu){let Uu=null;try{Uu=await zu.subshellId}catch(Hu){console.warn(`Subshell identifier not available in the closeout sequence, will not request deletion: ${Hu}`)}Uu!==null&&this._kernel.requestDeleteSubshell({subshell_id:Uu},!0)}delete Fu[ju]}Object.keys(Fu).length===0&&delete Mu._commTargetSubShellsId[Bu],this._subshellId=null}this._subshellStarted=new Ru.PromiseDelegate}async _maybeCloseSubshell(Lu){if(this._kernel.status!=="dead")switch(Lu){case Ou.PerComm:{this._subshellId&&(this._kernel.requestDeleteSubshell({subshell_id:this._subshellId},!0),this._subshellId=null),this._subshellStarted=new Ru.PromiseDelegate;break}case Ou.PerCommTarget:{await this._closePerCommTargetSubshell();break}case Ou.Disabled:break}}}return comm.CommHandler=Mu,Mu._commTargetSubShellsId={},comm}var kernel={},hasRequiredKernel$1;function requireKernel$1(){return hasRequiredKernel$1||(hasRequiredKernel$1=1,Object.defineProperty(kernel,"__esModule",{value:!0})),kernel}var restapi$4={},validate$5={},hasRequiredValidate$3;function requireValidate$3(){if(hasRequiredValidate$3)return validate$5;hasRequiredValidate$3=1,Object.defineProperty(validate$5,"__esModule",{value:!0}),validate$5.validateMessage=Iu,validate$5.validateModel=Ou,validate$5.validateModels=Mu;const Au=requireValidate$5(),lo=["username","version","session","msg_id","msg_type"],$u={stream:{name:"string",text:"string"},display_data:{data:"object",metadata:"object"},execute_input:{code:"string",execution_count:"number"},execute_result:{execution_count:"number",data:"object",metadata:"object"},error:{ename:"string",evalue:"string",traceback:"object"},status:{execution_state:["string",["starting","idle","busy","restarting","dead"]]},clear_output:{wait:"boolean"},comm_open:{comm_id:"string",target_name:"string",data:"object"},comm_msg:{comm_id:"string",data:"object"},comm_close:{comm_id:"string"},shutdown_reply:{restart:"boolean"}};function Ru(Du){for(let Lu=0;Lu<lo.length;Lu++)(0,Au.validateProperty)(Du,lo[Lu],"string")}function Iu(Du){(0,Au.validateProperty)(Du,"metadata","object"),(0,Au.validateProperty)(Du,"content","object"),(0,Au.validateProperty)(Du,"channel","string"),Ru(Du.header),Du.channel==="iopub"&&Pu(Du)}function Pu(Du){if(Du.channel==="iopub"){const Lu=$u[Du.header.msg_type];if(Lu===void 0)return;const Bu=Object.keys(Lu),ju=Du.content;for(let Fu=0;Fu<Bu.length;Fu++){let zu=Lu[Bu[Fu]];Array.isArray(zu)||(zu=[zu]),(0,Au.validateProperty)(ju,Bu[Fu],...zu)}}}function Ou(Du){(0,Au.validateProperty)(Du,"name","string"),(0,Au.validateProperty)(Du,"id","string")}function Mu(Du){if(!Array.isArray(Du))throw new Error("Invalid kernel list");Du.forEach(Lu=>Ou(Lu))}return validate$5}var hasRequiredRestapi$4;function requireRestapi$4(){return hasRequiredRestapi$4||(hasRequiredRestapi$4=1,(function(Au){Object.defineProperty(Au,"__esModule",{value:!0}),Au.KernelAPIClient=Au.KERNEL_SERVICE_URL=void 0,Au.listRunning=Iu,Au.startNew=Pu,Au.restartKernel=Ou,Au.interruptKernel=Mu,Au.shutdownKernel=Du,Au.getKernelModel=Lu;const lo=requireServerconnection(),$u=requireLib$b(),Ru=requireValidate$3();Au.KERNEL_SERVICE_URL="api/kernels";async function Iu(ju=lo.ServerConnection.makeSettings()){const Fu=$u.URLExt.join(ju.baseUrl,Au.KERNEL_SERVICE_URL),zu=await lo.ServerConnection.makeRequest(Fu,{},ju);if(zu.status!==200)throw await lo.ServerConnection.ResponseError.create(zu);const Uu=await zu.json();return(0,Ru.validateModels)(Uu),Uu}async function Pu(ju={},Fu=lo.ServerConnection.makeSettings()){const zu=$u.URLExt.join(Fu.baseUrl,Au.KERNEL_SERVICE_URL),Uu={method:"POST",body:JSON.stringify(ju)},Hu=await lo.ServerConnection.makeRequest(zu,Uu,Fu);if(Hu.status!==201)throw await lo.ServerConnection.ResponseError.create(Hu);const Vu=await Hu.json();return(0,Ru.validateModel)(Vu),Vu}async function Ou(ju,Fu=lo.ServerConnection.makeSettings()){const zu=$u.URLExt.join(Fu.baseUrl,Au.KERNEL_SERVICE_URL,encodeURIComponent(ju),"restart"),Uu={method:"POST"},Hu=await lo.ServerConnection.makeRequest(zu,Uu,Fu);if(Hu.status!==200)throw await lo.ServerConnection.ResponseError.create(Hu);const Vu=await Hu.json();(0,Ru.validateModel)(Vu)}async function Mu(ju,Fu=lo.ServerConnection.makeSettings()){const zu=$u.URLExt.join(Fu.baseUrl,Au.KERNEL_SERVICE_URL,encodeURIComponent(ju),"interrupt"),Uu={method:"POST"},Hu=await lo.ServerConnection.makeRequest(zu,Uu,Fu);if(Hu.status!==204)throw await lo.ServerConnection.ResponseError.create(Hu)}async function Du(ju,Fu=lo.ServerConnection.makeSettings()){const zu=$u.URLExt.join(Fu.baseUrl,Au.KERNEL_SERVICE_URL,encodeURIComponent(ju)),Uu={method:"DELETE"},Hu=await lo.ServerConnection.makeRequest(zu,Uu,Fu);if(Hu.status===404){const Vu=`The kernel "${ju}" does not exist on the server`;console.warn(Vu)}else if(Hu.status!==204)throw await lo.ServerConnection.ResponseError.create(Hu)}async function Lu(ju,Fu=lo.ServerConnection.makeSettings()){const zu=$u.URLExt.join(Fu.baseUrl,Au.KERNEL_SERVICE_URL,encodeURIComponent(ju)),Uu=await lo.ServerConnection.makeRequest(zu,{},Fu);if(Uu.status===404)return;if(Uu.status!==200)throw await lo.ServerConnection.ResponseError.create(Uu);const Hu=await Uu.json();return(0,Ru.validateModel)(Hu),Hu}class Bu{constructor(Fu={}){var zu;this.serverSettings=(zu=Fu.serverSettings)!==null&&zu!==void 0?zu:lo.ServerConnection.makeSettings()}async listRunning(){return Iu(this.serverSettings)}async getModel(Fu){return Lu(Fu,this.serverSettings)}async startNew(Fu={}){return Pu(Fu,this.serverSettings)}async restart(Fu){return Ou(Fu,this.serverSettings)}async interrupt(Fu){return Mu(Fu,this.serverSettings)}async shutdown(Fu){return Du(Fu,this.serverSettings)}}Au.KernelAPIClient=Bu})(restapi$4)),restapi$4}var _default$3={},future={},hasRequiredFuture;function requireFuture(){if(hasRequiredFuture)return future;hasRequiredFuture=1;var Au=future&&future.__createBinding||(Object.create?(function(Bu,ju,Fu,zu){zu===void 0&&(zu=Fu);var Uu=Object.getOwnPropertyDescriptor(ju,Fu);(!Uu||("get"in Uu?!ju.__esModule:Uu.writable||Uu.configurable))&&(Uu={enumerable:!0,get:function(){return ju[Fu]}}),Object.defineProperty(Bu,zu,Uu)}):(function(Bu,ju,Fu,zu){zu===void 0&&(zu=Fu),Bu[zu]=ju[Fu]})),lo=future&&future.__setModuleDefault||(Object.create?(function(Bu,ju){Object.defineProperty(Bu,"default",{enumerable:!0,value:ju})}):function(Bu,ju){Bu.default=ju}),$u=future&&future.__importStar||(function(){var Bu=function(ju){return Bu=Object.getOwnPropertyNames||function(Fu){var zu=[];for(var Uu in Fu)Object.prototype.hasOwnProperty.call(Fu,Uu)&&(zu[zu.length]=Uu);return zu},Bu(ju)};return function(ju){if(ju&&ju.__esModule)return ju;var Fu={};if(ju!=null)for(var zu=Bu(ju),Uu=0;Uu<zu.length;Uu++)zu[Uu]!=="default"&&Au(Fu,ju,zu[Uu]);return lo(Fu,ju),Fu}})();Object.defineProperty(future,"__esModule",{value:!0}),future.KernelShellFutureHandler=future.KernelControlFutureHandler=future.KernelFutureHandler=void 0;const Ru=requireDist(),Iu=require$$1$2,Pu=$u(requireMessages());class Ou extends Iu.DisposableDelegate{constructor(ju,Fu,zu,Uu,Hu){super(ju),this._status=0,this._stdin=Lu.noOp,this._iopub=Lu.noOp,this._reply=Lu.noOp,this._done=new Ru.PromiseDelegate,this._hooks=new Lu.HookList,this._disposeOnDone=!0,this._msg=Fu,zu||this._setFlag(Lu.KernelFutureFlag.GotReply),this._disposeOnDone=Uu,this._kernel=Hu}get msg(){return this._msg}get done(){return this._done.promise}get onReply(){return this._reply}set onReply(ju){this._reply=ju}get onIOPub(){return this._iopub}set onIOPub(ju){this._iopub=ju}get onStdin(){return this._stdin}set onStdin(ju){this._stdin=ju}registerMessageHook(ju){if(this.isDisposed)throw new Error("Kernel future is disposed");this._hooks.add(ju)}removeMessageHook(ju){this.isDisposed||this._hooks.remove(ju)}sendInputReply(ju,Fu){this._kernel.sendInputReply(ju,Fu)}dispose(){this._stdin=Lu.noOp,this._iopub=Lu.noOp,this._reply=Lu.noOp,this._hooks=null,this._testFlag(Lu.KernelFutureFlag.IsDone)||(this._done.promise.catch(()=>{}),this._done.reject(new Error(`Canceled future for ${this.msg.header.msg_type} message before replies were done`))),super.dispose()}async handleMsg(ju){switch(ju.channel){case"control":case"shell":ju.channel===this.msg.channel&&ju.parent_header.msg_id===this.msg.header.msg_id&&await this._handleReply(ju);break;case"stdin":await this._handleStdin(ju);break;case"iopub":await this._handleIOPub(ju);break}}async _handleReply(ju){const Fu=this._reply;Fu&&await Fu(ju),this._replyMsg=ju,this._setFlag(Lu.KernelFutureFlag.GotReply),this._testFlag(Lu.KernelFutureFlag.GotIdle)&&this._handleDone()}async _handleStdin(ju){this._kernel.hasPendingInput=!0;const Fu=this._stdin;Fu&&await Fu(ju)}async _handleIOPub(ju){const Fu=await this._hooks.process(ju),zu=this._iopub;Fu&&zu&&await zu(ju),Pu.isStatusMsg(ju)&&ju.content.execution_state==="idle"&&(this._setFlag(Lu.KernelFutureFlag.GotIdle),this._testFlag(Lu.KernelFutureFlag.GotReply)&&this._handleDone())}_handleDone(){this._testFlag(Lu.KernelFutureFlag.IsDone)||(this._setFlag(Lu.KernelFutureFlag.IsDone),this._done.resolve(this._replyMsg),this._disposeOnDone&&this.dispose())}_testFlag(ju){return(this._status&ju)!==0}_setFlag(ju){this._status|=ju}}future.KernelFutureHandler=Ou;class Mu extends Ou{}future.KernelControlFutureHandler=Mu;class Du extends Ou{}future.KernelShellFutureHandler=Du;var Lu;return(function(Bu){Bu.noOp=()=>{};const ju=typeof requestAnimationFrame=="function"?requestAnimationFrame:setImmediate;class Fu{constructor(){this._hooks=[]}add(Uu){this.remove(Uu),this._hooks.push(Uu)}remove(Uu){const Hu=this._hooks.indexOf(Uu);Hu>=0&&(this._hooks[Hu]=null,this._scheduleCompact())}async process(Uu){await this._processing;const Hu=new Ru.PromiseDelegate;this._processing=Hu.promise;let Vu;for(let Gu=this._hooks.length-1;Gu>=0;Gu--){const Wu=this._hooks[Gu];if(Wu!==null){try{Vu=await Wu(Uu)}catch(Zu){Vu=!0,console.error(Zu)}if(Vu===!1)return Hu.resolve(void 0),!1}}return Hu.resolve(void 0),!0}_scheduleCompact(){this._compactScheduled||(this._compactScheduled=!0,ju(()=>{this._processing=this._processing.then(()=>{this._compactScheduled=!1,this._compact()})}))}_compact(){let Uu=0;for(let Hu=0,Vu=this._hooks.length;Hu<Vu;Hu++){const Gu=this._hooks[Hu];this._hooks[Hu]===null?Uu++:this._hooks[Hu-Uu]=Gu}this._hooks.length-=Uu}}Bu.HookList=Fu,(function(zu){zu[zu.GotReply=1]="GotReply",zu[zu.GotIdle=2]="GotIdle",zu[zu.IsDone=4]="IsDone",zu[zu.DisposeOnDone=8]="DisposeOnDone"})(Bu.KernelFutureFlag||(Bu.KernelFutureFlag={}))})(Lu||(Lu={})),future}var restapi$3={},validate$4={},hasRequiredValidate$2;function requireValidate$2(){if(hasRequiredValidate$2)return validate$4;hasRequiredValidate$2=1,Object.defineProperty(validate$4,"__esModule",{value:!0}),validate$4.validateSpecModel=lo,validate$4.validateSpecModels=$u;const Au=requireValidate$5();function lo(Ru){const Iu=Ru.spec;if(!Iu)throw new Error("Invalid kernel spec");(0,Au.validateProperty)(Ru,"name","string"),(0,Au.validateProperty)(Ru,"resources","object"),(0,Au.validateProperty)(Iu,"language","string"),(0,Au.validateProperty)(Iu,"display_name","string"),(0,Au.validateProperty)(Iu,"argv","array");let Pu=null;Iu.hasOwnProperty("metadata")&&((0,Au.validateProperty)(Iu,"metadata","object"),Pu=Iu.metadata);let Ou=null;return Iu.hasOwnProperty("env")&&((0,Au.validateProperty)(Iu,"env","object"),Ou=Iu.env),Iu.hasOwnProperty("interrupt_mode")&&((0,Au.validateProperty)(Iu,"interrupt_mode","string"),Ou=Iu.env),{name:Ru.name,resources:Ru.resources,language:Iu.language,display_name:Iu.display_name,argv:Iu.argv,metadata:Pu,env:Ou}}function $u(Ru){if(!Ru.hasOwnProperty("kernelspecs"))throw new Error("No kernelspecs found");let Iu=Object.keys(Ru.kernelspecs);const Pu=Object.create(null);let Ou=Ru.default;for(let Mu=0;Mu<Iu.length;Mu++){const Du=Ru.kernelspecs[Iu[Mu]];try{Pu[Iu[Mu]]=lo(Du)}catch{console.warn(`Removing errant kernel spec: ${Iu[Mu]}`)}}if(Iu=Object.keys(Pu),!Iu.length)throw new Error("No valid kernelspecs found");return(!Ou||typeof Ou!="string"||!(Ou in Pu))&&(Ou=Iu[0],console.warn(`Default kernel not found, using '${Iu[0]}'`)),{default:Ou,kernelspecs:Pu}}return validate$4}var hasRequiredRestapi$3;function requireRestapi$3(){if(hasRequiredRestapi$3)return restapi$3;hasRequiredRestapi$3=1,Object.defineProperty(restapi$3,"__esModule",{value:!0}),restapi$3.KernelSpecAPIClient=void 0,restapi$3.getSpecs=Iu;const Au=requireServerconnection(),lo=requireValidate$2(),$u=requireLib$b(),Ru="api/kernelspecs";async function Iu(Ou=Au.ServerConnection.makeSettings()){const Mu=$u.URLExt.join(Ou.baseUrl,Ru),Du=await Au.ServerConnection.makeRequest(Mu,{},Ou);if(Du.status!==200)throw await Au.ServerConnection.ResponseError.create(Du);const Lu=await Du.json();return(0,lo.validateSpecModels)(Lu)}class Pu{constructor(Mu={}){var Du;this.serverSettings=(Du=Mu.serverSettings)!==null&&Du!==void 0?Du:Au.ServerConnection.makeSettings()}async get(){return Iu(this.serverSettings)}}return restapi$3.KernelSpecAPIClient=Pu,restapi$3}var hasRequired_default$2;function require_default$2(){return hasRequired_default$2||(hasRequired_default$2=1,(function(Au){var lo=_default$3&&_default$3.__createBinding||(Object.create?(function(Wu,Zu,Ju,Yu){Yu===void 0&&(Yu=Ju);var Xu=Object.getOwnPropertyDescriptor(Zu,Ju);(!Xu||("get"in Xu?!Zu.__esModule:Xu.writable||Xu.configurable))&&(Xu={enumerable:!0,get:function(){return Zu[Ju]}}),Object.defineProperty(Wu,Yu,Xu)}):(function(Wu,Zu,Ju,Yu){Yu===void 0&&(Yu=Ju),Wu[Yu]=Zu[Ju]})),$u=_default$3&&_default$3.__setModuleDefault||(Object.create?(function(Wu,Zu){Object.defineProperty(Wu,"default",{enumerable:!0,value:Zu})}):function(Wu,Zu){Wu.default=Zu}),Ru=_default$3&&_default$3.__importStar||(function(){var Wu=function(Zu){return Wu=Object.getOwnPropertyNames||function(Ju){var Yu=[];for(var Xu in Ju)Object.prototype.hasOwnProperty.call(Ju,Xu)&&(Yu[Yu.length]=Xu);return Yu},Wu(Zu)};return function(Zu){if(Zu&&Zu.__esModule)return Zu;var Ju={};if(Zu!=null)for(var Yu=Wu(Zu),Xu=0;Xu<Yu.length;Xu++)Yu[Xu]!=="default"&&lo(Ju,Zu,Yu[Xu]);return $u(Ju,Zu),Ju}})();Object.defineProperty(Au,"__esModule",{value:!0}),Au.KernelConnection=Au.DEFAULT_KERNEL_INFO_TIMEOUT=void 0;const Iu=requireLib$b(),Pu=requireDist(),Ou=require$$0$2,Mu=requireLib$8(),Du=requireComm(),Lu=Ru(requireMessages()),Bu=requireFuture(),ju=Ru(requireValidate$3()),Fu=requireRestapi$4(),zu=requireRestapi$3(),Uu=requireLib$b();Au.DEFAULT_KERNEL_INFO_TIMEOUT=3e3;const Hu="";class Vu{constructor(Zu){var Ju,Yu,Xu,ed,td,nd,od,sd,ad;this._createSocket=(pd=!0)=>{this._errorIfDisposed(),this._clearSocket(),this._updateConnectionStatus("connecting");const vd=this.serverSettings,Sd=Iu.URLExt.join(vd.wsUrl,Fu.KERNEL_SERVICE_URL,encodeURIComponent(this._id)),_d=Sd.replace(/^((?:\w+:)?\/\/)[^@/]+@/,"$1");console.debug(`Starting WebSocket: ${_d}`);let bd=Iu.URLExt.join(Sd,"channels?session_id="+encodeURIComponent(this._clientId));const wd=vd.token;vd.appendToken&&wd!==""&&(bd=bd+`&token=${encodeURIComponent(wd)}`);const Ad=pd?this._supportedProtocols:[];this._ws=new vd.WebSocket(bd,Ad),this._ws.binaryType="arraybuffer";let gd=!1;const dd=async ld=>{var ud,hd;if(!this._isDisposed){this._reason="",this._model=void 0;try{const md=await this._kernelAPIClient.getModel(this._id);this._model=md,md?.execution_state==="dead"?this._updateStatus("dead"):this._onWSClose(ld)}catch(md){if(md instanceof Mu.ServerConnection.NetworkError||((ud=md.response)===null||ud===void 0?void 0:ud.status)===503||((hd=md.response)===null||hd===void 0?void 0:hd.status)===424){const Ed=Gu.getRandomIntInclusive(10,30)*1e3;setTimeout(dd,Ed,ld)}else this._reason="Kernel died unexpectedly",this._updateStatus("dead")}}},yd=async ld=>{gd||(gd=!0,await dd(ld))};this._ws.onmessage=this._onWSMessage,this._ws.onopen=this._onWSOpen,this._ws.onclose=yd,this._ws.onerror=yd},this._onWSOpen=pd=>{if(this._ws.protocol!==""&&!this._supportedProtocols.includes(this._ws.protocol))throw console.log("Server selected unknown kernel wire protocol:",this._ws.protocol),this._updateStatus("dead"),new Error(`Unknown kernel wire protocol: ${this._ws.protocol}`);this._selectedProtocol=this._ws.protocol,this._ws.onclose=this._onWSClose,this._ws.onerror=this._onWSClose,this._updateConnectionStatus("connected")},this._onWSMessage=pd=>{let vd;try{vd=this.serverSettings.serializer.deserialize(pd.data,this._ws.protocol),ju.validateMessage(vd)}catch(Sd){throw Sd.message=`Kernel message validation error: ${Sd.message}`,Sd}this._kernelSession=vd.header.session,this._msgChain=this._msgChain.then(()=>this._handleMessage(vd)).catch(Sd=>{Sd.message.startsWith("Canceled future for ")&&console.error(Sd)}),this._anyMessage.emit({msg:vd,direction:"recv"})},this._onWSClose=pd=>{if(!this.isDisposed){if("code"in pd&&(pd.code===1e3||pd.code===1001)){this._updateConnectionStatus("disconnected");return}this._reconnect()}},this._id="",this._name="",this._status="unknown",this._connectionStatus="connecting",this._kernelSession="",this._isRestarting=!1,this._isDisposed=!1,this._ws=null,this._username="",this._reconnectLimit=7,this._reconnectAttempt=0,this._reconnectTimeout=null,this._supportedProtocols=Object.values(Lu.supportedKernelWebSocketProtocols),this._selectedProtocol="",this._commsOverSubshells=Mu.CommsOverSubshells.PerCommTarget,this._futures=new Map,this._comms=new Map,this._targetRegistry=Object.create(null),this._info=new Pu.PromiseDelegate,this._pendingMessages=[],this._statusChanged=new Ou.Signal(this),this._connectionStatusChanged=new Ou.Signal(this),this._disposed=new Ou.Signal(this),this._iopubMessage=new Ou.Signal(this),this._anyMessage=new Ou.Signal(this),this._pendingInput=new Ou.Signal(this),this._unhandledMessage=new Ou.Signal(this),this._displayIdToParentIds=new Map,this._msgIdToDisplayIds=new Map,this._msgChain=Promise.resolve(),this._hasPendingInput=!1,this._reason="",this._noOp=()=>{},this._supportsSubshells=!1,this._kernelInfoTimeout=Au.DEFAULT_KERNEL_INFO_TIMEOUT,this._name=Zu.model.name,this._id=Zu.model.id,this.serverSettings=(Ju=Zu.serverSettings)!==null&&Ju!==void 0?Ju:Mu.ServerConnection.makeSettings(),this._kernelAPIClient=(Yu=Zu.kernelAPIClient)!==null&&Yu!==void 0?Yu:new Fu.KernelAPIClient({serverSettings:this.serverSettings}),this._kernelSpecAPIClient=(Xu=Zu.kernelSpecAPIClient)!==null&&Xu!==void 0?Xu:new zu.KernelSpecAPIClient({serverSettings:this.serverSettings}),this._clientId=(ed=Zu.clientId)!==null&&ed!==void 0?ed:Pu.UUID.uuid4(),this._username=(td=Zu.username)!==null&&td!==void 0?td:"",this.handleComms=(nd=Zu.handleComms)!==null&&nd!==void 0?nd:!0,this._commsOverSubshells=(od=Zu.commsOverSubshells)!==null&&od!==void 0?od:Mu.CommsOverSubshells.PerCommTarget,this._subshellId=(sd=Zu.subshellId)!==null&&sd!==void 0?sd:null,this._createSocket(),this._kernelInfoTimeout=(ad=Zu?.kernelInfoTimeout)!==null&&ad!==void 0?ad:Au.DEFAULT_KERNEL_INFO_TIMEOUT}get disposed(){return this._disposed}get commsOverSubshells(){return this._commsOverSubshells}set commsOverSubshells(Zu){this._commsOverSubshells=Zu;for(const[Ju,Yu]of this._comms)Yu.commsOverSubshells=Zu}get statusChanged(){return this._statusChanged}get connectionStatusChanged(){return this._connectionStatusChanged}get iopubMessage(){return this._iopubMessage}get unhandledMessage(){return this._unhandledMessage}get model(){return this._model||{id:this.id,name:this.name,reason:this._reason}}get anyMessage(){return this._anyMessage}get pendingInput(){return this._pendingInput}get id(){return this._id}get name(){return this._name}get username(){return this._username}get clientId(){return this._clientId}get subshellId(){return this._subshellId}set subshellId(Zu){this._subshellId=Zu}get status(){return this._status}get connectionStatus(){return this._connectionStatus}get isDisposed(){return this._isDisposed}get info(){return this._info.promise}get spec(){return this._specPromise?this._specPromise:(this._specPromise=this._kernelSpecAPIClient.get().then(Zu=>Zu.kernelspecs[this._name]),this._specPromise)}get supportsSubshells(){return this._supportsSubshells}clone(Zu={}){return new Vu({model:this.model,username:this.username,serverSettings:this.serverSettings,handleComms:!1,kernelAPIClient:this._kernelAPIClient,commsOverSubshells:Mu.CommsOverSubshells.Disabled,kernelInfoTimeout:this._kernelInfoTimeout,...Zu})}dispose(){if(this.isDisposed)return;const Zu=()=>{this._isDisposed=!0,this._disposed.emit(),this._updateConnectionStatus("disconnected"),this._clearKernelState(),this._pendingMessages=[],this._clearSocket(),Ou.Signal.clearData(this)};if(this._subshellId!==null){const Ju=this.requestDeleteSubshell({subshell_id:this._subshellId},!0);Ju.onReply=Yu=>{Zu()}}else Zu()}sendShellMessage(Zu,Ju=!1,Yu=!0){return this._sendKernelShellControl(Bu.KernelShellFutureHandler,Zu,Ju,Yu)}sendControlMessage(Zu,Ju=!1,Yu=!0){return this._sendKernelShellControl(Bu.KernelControlFutureHandler,Zu,Ju,Yu)}_sendKernelShellControl(Zu,Ju,Yu=!1,Xu=!0){this._sendMessage(Ju),this._anyMessage.emit({msg:Ju,direction:"send"});const ed=new Zu(()=>{const td=Ju.header.msg_id;this._futures.delete(td);const nd=this._msgIdToDisplayIds.get(td);nd&&(nd.forEach(od=>{const sd=this._displayIdToParentIds.get(od);if(sd){const ad=sd.indexOf(td);if(ad===-1)return;sd.length===1?this._displayIdToParentIds.delete(od):(sd.splice(ad,1),this._displayIdToParentIds.set(od,sd))}}),this._msgIdToDisplayIds.delete(td))},Ju,Yu,Xu,this);return this._futures.set(Ju.header.msg_id,ed),ed}_sendMessage(Zu,Ju=!0){if(this.status==="dead")throw new Error("Kernel is dead");if((this._kernelSession===Hu||this._isRestarting)&&Lu.isInfoRequestMsg(Zu))if(this.connectionStatus==="connected"){this._ws.send(this.serverSettings.serializer.serialize(Zu,this._ws.protocol));return}else throw new Error("Could not send message: status is not connected");if(Ju&&this._pendingMessages.length>0){this._pendingMessages.push(Zu);return}if(this.connectionStatus==="connected"&&!this._isRestarting)this._ws.send(this.serverSettings.serializer.serialize(Zu,this._ws.protocol));else if(Ju)this._pendingMessages.push(Zu);else throw new Error("Could not send message")}async interrupt(){if(this.hasPendingInput=!1,this.status==="dead")throw new Error("Kernel is dead");return this._kernelAPIClient.interrupt(this.id)}async restart(){if(this.status==="dead")throw new Error("Kernel is dead");this._updateStatus("restarting"),this._clearKernelState(),this._isRestarting=!0;try{await this._kernelAPIClient.restart(this.id),await this.reconnect()}catch(Zu){throw this._isRestarting=!1,Zu}this.hasPendingInput=!1}reconnect(){this._errorIfDisposed();const Zu=new Pu.PromiseDelegate,Ju=(Yu,Xu)=>{Xu==="connected"?(Zu.resolve(),this.connectionStatusChanged.disconnect(Ju,this)):Xu==="disconnected"&&(Zu.reject(new Error("Kernel connection disconnected")),this.connectionStatusChanged.disconnect(Ju,this))};return this.connectionStatusChanged.connect(Ju,this),this._reconnectAttempt=0,this._reconnect(),Zu.promise}async shutdown(){this.status!=="dead"&&await this._kernelAPIClient.shutdown(this.id),this.handleShutdown()}handleShutdown(){this._updateStatus("dead"),this.dispose()}async requestKernelInfo(){const Zu=Lu.createMessage({msgType:"kernel_info_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:{}});let Ju;try{Ju=await Gu.handleShellMessage(this,Zu)}catch(Xu){if(this.isDisposed)return;throw Xu}if(this._errorIfDisposed(),!Ju)return;if(Ju.content.status===void 0&&(Ju.content.status="ok"),Ju.content.status!=="ok")return this._info.reject("Kernel info reply errored"),Ju;this._info.resolve(Ju.content),this._kernelSession=Ju.header.session;const Yu=Ju.content.supported_features;return this._supportsSubshells=Yu!==void 0&&Yu.includes("kernel subshells"),Ju}requestComplete(Zu){const Ju=Lu.createMessage({msgType:"complete_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:Zu});return Gu.handleShellMessage(this,Ju)}requestInspect(Zu){const Ju=Lu.createMessage({msgType:"inspect_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:Zu});return Gu.handleShellMessage(this,Ju)}requestHistory(Zu){const Ju=Lu.createMessage({msgType:"history_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:Zu});return Gu.handleShellMessage(this,Ju)}requestExecute(Zu,Ju=!0,Yu){const Xu={silent:!1,store_history:!0,user_expressions:{},allow_stdin:!0,stop_on_error:!1},ed=Lu.createMessage({msgType:"execute_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:{...Xu,...Zu},metadata:Yu});return this.sendShellMessage(ed,!0,Ju)}requestDebug(Zu,Ju=!0){const Yu=Lu.createMessage({msgType:"debug_request",channel:"control",username:this._username,session:this._clientId,content:Zu});return this.sendControlMessage(Yu,!0,Ju)}requestCreateSubshell(Zu,Ju=!0){if(!this.supportsSubshells)throw new Error("Kernel subshells are not supported");const Yu=Lu.createMessage({msgType:"create_subshell_request",channel:"control",username:this._username,session:this._clientId,content:Zu});return this.sendControlMessage(Yu,!0,Ju)}requestDeleteSubshell(Zu,Ju=!0){if(!this.supportsSubshells)throw new Error("Kernel subshells are not supported");const Yu=Lu.createMessage({msgType:"delete_subshell_request",channel:"control",username:this._username,session:this._clientId,content:Zu});return this.sendControlMessage(Yu,!0,Ju)}requestListSubshell(Zu,Ju=!0){if(!this.supportsSubshells)throw new Error("Kernel subshells are not supported");const Yu=Lu.createMessage({msgType:"list_subshell_request",channel:"control",username:this._username,session:this._clientId,content:Zu});return this.sendControlMessage(Yu,!0,Ju)}requestIsComplete(Zu){const Ju=Lu.createMessage({msgType:"is_complete_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:Zu});return Gu.handleShellMessage(this,Ju)}requestCommInfo(Zu){const Ju=Lu.createMessage({msgType:"comm_info_request",channel:"shell",username:this._username,session:this._clientId,subshellId:this._subshellId,content:Zu});return Gu.handleShellMessage(this,Ju)}sendInputReply(Zu,Ju){const Yu=Lu.createMessage({msgType:"input_reply",channel:"stdin",username:this._username,session:this._clientId,content:Zu});Yu.parent_header=Ju,this._sendMessage(Yu),this._anyMessage.emit({msg:Yu,direction:"send"}),this.hasPendingInput=!1}createComm(Zu,Ju=Pu.UUID.uuid4()){if(!this.handleComms)throw new Error("Comms are disabled on this kernel connection");if(this._comms.has(Ju))throw new Error("Comm is already created");const Yu=new Du.CommHandler(Zu,Ju,this,()=>{this._unregisterComm(Ju)},this._commsOverSubshells);return this._comms.set(Ju,Yu),Yu}hasComm(Zu){return this._comms.has(Zu)}registerCommTarget(Zu,Ju){this.handleComms&&(this._targetRegistry[Zu]=Ju)}removeCommTarget(Zu,Ju){this.handleComms&&!this.isDisposed&&this._targetRegistry[Zu]===Ju&&delete this._targetRegistry[Zu]}registerMessageHook(Zu,Ju){var Yu;const Xu=(Yu=this._futures)===null||Yu===void 0?void 0:Yu.get(Zu);Xu&&Xu.registerMessageHook(Ju)}removeMessageHook(Zu,Ju){var Yu;const Xu=(Yu=this._futures)===null||Yu===void 0?void 0:Yu.get(Zu);Xu&&Xu.removeMessageHook(Ju)}removeInputGuard(){this.hasPendingInput=!1}async _handleDisplayId(Zu,Ju){var Yu,Xu;const ed=Ju.parent_header.msg_id;let td=this._displayIdToParentIds.get(Zu);if(td){const od={header:Pu.JSONExt.deepCopy(Ju.header),parent_header:Pu.JSONExt.deepCopy(Ju.parent_header),metadata:Pu.JSONExt.deepCopy(Ju.metadata),content:Pu.JSONExt.deepCopy(Ju.content),channel:Ju.channel,buffers:Ju.buffers?Ju.buffers.slice():[]};od.header.msg_type="update_display_data",await Promise.all(td.map(async sd=>{const ad=this._futures&&this._futures.get(sd);ad&&await ad.handleMsg(od)}))}if(Ju.header.msg_type==="update_display_data")return!0;td=(Yu=this._displayIdToParentIds.get(Zu))!==null&&Yu!==void 0?Yu:[],td.indexOf(ed)===-1&&td.push(ed),this._displayIdToParentIds.set(Zu,td);const nd=(Xu=this._msgIdToDisplayIds.get(ed))!==null&&Xu!==void 0?Xu:[];return nd.indexOf(ed)===-1&&nd.push(ed),this._msgIdToDisplayIds.set(ed,nd),!1}_clearSocket(){this._ws!==null&&(this._ws.onopen=this._noOp,this._ws.onclose=this._noOp,this._ws.onerror=this._noOp,this._ws.onmessage=this._noOp,this._ws.close(),this._ws=null)}_updateStatus(Zu){this._status===Zu||this._status==="dead"||(this._status=Zu,Gu.logKernelStatus(this),this._statusChanged.emit(Zu),Zu==="dead"&&this.dispose())}_sendPending(){for(;this.connectionStatus==="connected"&&!this._isRestarting&&this._pendingMessages.length>0;)this._sendMessage(this._pendingMessages[0],!1),this._pendingMessages.shift()}_clearKernelState(){this._kernelSession="",this._pendingMessages=[],this._futures.forEach(Zu=>{Zu.dispose()}),this._comms.forEach(Zu=>{Zu.dispose()}),this._msgChain=Promise.resolve(),this._futures=new Map,this._comms=new Map,this._displayIdToParentIds.clear(),this._msgIdToDisplayIds.clear()}_assertCurrentMessage(Zu){if(this._errorIfDisposed(),Zu.header.session!==this._kernelSession)throw new Error(`Canceling handling of old message: ${Zu.header.msg_type}`)}async _handleCommOpen(Zu){this._assertCurrentMessage(Zu);const Ju=Zu.content,Yu=new Du.CommHandler(Ju.target_name,Ju.comm_id,this,()=>{this._unregisterComm(Ju.comm_id)},this.commsOverSubshells);this._comms.set(Ju.comm_id,Yu);try{await(await Gu.loadObject(Ju.target_name,Ju.target_module,this._targetRegistry))(Yu,Zu)}catch(Xu){throw Yu.close(),console.error("Exception opening new comm"),Xu}}async _handleCommClose(Zu){this._assertCurrentMessage(Zu);const Ju=Zu.content,Yu=this._comms.get(Ju.comm_id);if(!Yu){console.error("Comm not found for comm id "+Ju.comm_id);return}this._unregisterComm(Yu.commId);const Xu=Yu.onClose;Xu&&await Xu(Zu),Yu.dispose()}async _handleCommMsg(Zu){this._assertCurrentMessage(Zu);const Ju=Zu.content,Yu=this._comms.get(Ju.comm_id);if(!Yu)return;const Xu=Yu.onMsg;Xu&&await Xu(Zu)}_unregisterComm(Zu){this._comms.delete(Zu)}_updateConnectionStatus(Zu){if(this._connectionStatus!==Zu){if(this._connectionStatus=Zu,Zu!=="connecting"&&(this._reconnectAttempt=0,clearTimeout(this._reconnectTimeout)),this.status!=="dead")if(Zu==="connected"){let Ju=this._isRestarting,Yu=this.requestKernelInfo(),Xu=!1,ed=()=>{Xu||(Xu=!0,Ju&&this._isRestarting&&(this._isRestarting=!1,this._kernelSession=""),clearTimeout(td),this._pendingMessages.length>0&&this._sendPending())};Yu.then(()=>{Ju&&(this._isRestarting=!1),ed()});let td=setTimeout(ed,this._kernelInfoTimeout)}else this._updateStatus("unknown");this._connectionStatusChanged.emit(Zu)}}async _handleMessage(Zu){var Ju,Yu;let Xu=!1;if(Zu.parent_header&&Zu.channel==="iopub"&&(Lu.isDisplayDataMsg(Zu)||Lu.isUpdateDisplayDataMsg(Zu)||Lu.isExecuteResultMsg(Zu))){const td=((Ju=Zu.content.transient)!==null&&Ju!==void 0?Ju:{}).display_id;td&&(Xu=await this._handleDisplayId(td,Zu),this._assertCurrentMessage(Zu))}if(!Xu&&Zu.parent_header){const ed=Zu.parent_header,td=(Yu=this._futures)===null||Yu===void 0?void 0:Yu.get(ed.msg_id);if(td)await td.handleMsg(Zu),this._assertCurrentMessage(Zu);else{const nd=ed.session===this.clientId;Zu.channel!=="iopub"&&nd&&this._unhandledMessage.emit(Zu)}}if(Zu.channel==="iopub"){switch(Zu.header.msg_type){case"status":{const ed=Uu.PageConfig.getOption("untracked_message_types");if(JSON.parse(ed||"[]").includes(Zu.parent_header.msg_type))break;const nd=Zu.content.execution_state;nd==="restarting"&&Promise.resolve().then(async()=>{this._updateStatus("autorestarting"),this._clearKernelState(),await this.reconnect()}),this._updateStatus(nd);break}case"comm_open":this.handleComms&&await this._handleCommOpen(Zu);break;case"comm_msg":this.handleComms&&await this._handleCommMsg(Zu);break;case"comm_close":this.handleComms&&await this._handleCommClose(Zu);break}this.isDisposed||(this._assertCurrentMessage(Zu),this._iopubMessage.emit(Zu))}}_reconnect(){if(this._errorIfDisposed(),clearTimeout(this._reconnectTimeout),this._reconnectAttempt<this._reconnectLimit){this._updateConnectionStatus("connecting");const Zu=Gu.getRandomIntInclusive(0,1e3*(Math.pow(2,this._reconnectAttempt)-1));console.warn(`Connection lost, reconnecting in ${Math.floor(Zu/1e3)} seconds.`);const Ju=this._selectedProtocol!=="";this._reconnectTimeout=setTimeout(this._createSocket,Zu,Ju),this._reconnectAttempt+=1}else this._updateConnectionStatus("disconnected");this._clearSocket()}_errorIfDisposed(){if(this.isDisposed)throw new Error("Kernel connection is disposed")}get hasPendingInput(){return this._hasPendingInput}set hasPendingInput(Zu){this._hasPendingInput=Zu,this._pendingInput.emit(Zu)}}Au.KernelConnection=Vu;var Gu;(function(Wu){function Zu(ed){switch(ed.status){case"idle":case"busy":case"unknown":return;default:console.debug(`Kernel: ${ed.status} (${ed.id})`);break}}Wu.logKernelStatus=Zu;async function Ju(ed,td){return ed.sendShellMessage(td,!0).done}Wu.handleShellMessage=Ju;function Yu(ed,td,nd){return new Promise((od,sd)=>{if(td){if(typeof requirejs>"u")throw new Error("requirejs not found");requirejs([td],ad=>{if(ad[ed]===void 0){const pd=`Object '${ed}' not found in module '${td}'`;sd(new Error(pd))}else od(ad[ed])},sd)}else nd?.[ed]?od(nd[ed]):sd(new Error(`Object '${ed}' not found in registry`))})}Wu.loadObject=Yu;function Xu(ed,td){return ed=Math.ceil(ed),td=Math.floor(td),Math.floor(Math.random()*(td-ed+1))+ed}Wu.getRandomIntInclusive=Xu})(Gu||(Gu={}))})(_default$3)),_default$3}var manager$5={},hasRequiredManager$5;function requireManager$5(){if(hasRequiredManager$5)return manager$5;hasRequiredManager$5=1,Object.defineProperty(manager$5,"__esModule",{value:!0}),manager$5.KernelManager=void 0;const Au=require$$1$1,lo=require$$0$2,$u=requireLib$8(),Ru=requireBasemanager(),Iu=requireRestapi$4(),Pu=require_default$2(),Ou=requireRestapi$3();class Mu extends Ru.BaseManager{constructor(Lu={}){var Bu,ju,Fu;super(Lu),this._commsOverSubshells=$u.CommsOverSubshells.PerCommTarget,this._isReady=!1,this._kernelConnections=new Set,this._models=new Map,this._runningChanged=new lo.Signal(this),this._connectionFailure=new lo.Signal(this),this._kernelInfoTimeout=Pu.DEFAULT_KERNEL_INFO_TIMEOUT,this._kernelAPIClient=(Bu=Lu.kernelAPIClient)!==null&&Bu!==void 0?Bu:new Iu.KernelAPIClient({serverSettings:this.serverSettings}),this._kernelSpecAPIClient=(ju=Lu.kernelSpecAPIClient)!==null&&ju!==void 0?ju:new Ou.KernelSpecAPIClient({serverSettings:this.serverSettings}),this._pollModels=new Au.Poll({auto:!1,factory:()=>this.requestRunning(),frequency:{interval:10*1e3,backoff:!0,max:300*1e3},name:"@jupyterlab/services:KernelManager#models",standby:(Fu=Lu.standby)!==null&&Fu!==void 0?Fu:"when-hidden"}),this._ready=(async()=>{await this._pollModels.start(),await this._pollModels.tick,this._isReady=!0})()}get isReady(){return this._isReady}get ready(){return this._ready}get runningChanged(){return this._runningChanged}get connectionFailure(){return this._connectionFailure}get kernelInfoTimeout(){return this._kernelInfoTimeout}set kernelInfoTimeout(Lu){this._kernelInfoTimeout=Lu}dispose(){this.isDisposed||(this._models.clear(),this._kernelConnections.forEach(Lu=>Lu.dispose()),this._pollModels.dispose(),super.dispose())}connectTo(Lu){var Bu,ju;const{id:Fu}=Lu.model;let zu=(Bu=Lu.handleComms)!==null&&Bu!==void 0?Bu:!0;if(Lu.handleComms===void 0){for(const Hu of this._kernelConnections)if(Hu.id===Fu&&Hu.handleComms){zu=!1;break}}const Uu=new Pu.KernelConnection({handleComms:zu,...Lu,commsOverSubshells:(ju=Lu.commsOverSubshells)!==null&&ju!==void 0?ju:this._commsOverSubshells,serverSettings:this.serverSettings,kernelAPIClient:this._kernelAPIClient,kernelSpecAPIClient:this._kernelSpecAPIClient,kernelInfoTimeout:this._kernelInfoTimeout});return this._onStarted(Uu),this._models.has(Fu)||this.refreshRunning().catch(()=>{}),Uu}running(){return this._models.values()}get runningCount(){return this._models.size}get commsOverSubshells(){return this._commsOverSubshells}set commsOverSubshells(Lu){this._commsOverSubshells=Lu;for(const Bu of this._kernelConnections)Bu.commsOverSubshells=Lu}async refreshRunning(){await this._pollModels.refresh(),await this._pollModels.tick}async startNew(Lu={},Bu={}){const ju=await this._kernelAPIClient.startNew(Lu);return this.connectTo({...Bu,model:ju})}async shutdown(Lu){await this._kernelAPIClient.shutdown(Lu),await this.refreshRunning()}async shutdownAll(){await this.refreshRunning(),await Promise.all([...this._models.keys()].map(Lu=>this._kernelAPIClient.shutdown(Lu))),await this.refreshRunning()}async findById(Lu){return this._models.has(Lu)?this._models.get(Lu):(await this.refreshRunning(),this._models.get(Lu))}async requestRunning(){var Lu,Bu;let ju;try{ju=await this._kernelAPIClient.listRunning()}catch(Fu){throw(Fu instanceof $u.ServerConnection.NetworkError||((Lu=Fu.response)===null||Lu===void 0?void 0:Lu.status)===503||((Bu=Fu.response)===null||Bu===void 0?void 0:Bu.status)===424)&&this._connectionFailure.emit(Fu),Fu}this.isDisposed||this._models.size===ju.length&&ju.every(Fu=>{const zu=this._models.get(Fu.id);return zu?zu.connections===Fu.connections&&zu.execution_state===Fu.execution_state&&zu.last_activity===Fu.last_activity&&zu.name===Fu.name&&zu.reason===Fu.reason&&zu.traceback===Fu.traceback:!1})||(this._models=new Map(ju.map(Fu=>[Fu.id,Fu])),this._kernelConnections.forEach(Fu=>{this._models.has(Fu.id)||Fu.handleShutdown()}),this._runningChanged.emit(ju))}_onStarted(Lu){this._kernelConnections.add(Lu),Lu.statusChanged.connect(this._onStatusChanged,this),Lu.disposed.connect(this._onDisposed,this)}_onDisposed(Lu){this._kernelConnections.delete(Lu),this.refreshRunning().catch(()=>{})}_onStatusChanged(Lu,Bu){Bu==="dead"&&this.refreshRunning().catch(()=>{})}}return manager$5.KernelManager=Mu,(function(Du){class Lu extends Du{constructor(){super(...arguments),this._readyPromise=new Promise(()=>{})}get isActive(){return!1}get parentReady(){return super.ready}async startNew(ju={},Fu={}){return Promise.reject(new Error("Not implemented in no-op Kernel Manager"))}connectTo(ju){throw new Error("Not implemented in no-op Kernel Manager")}async shutdown(ju){return Promise.reject(new Error("Not implemented in no-op Kernel Manager"))}get ready(){return this.parentReady.then(()=>this._readyPromise)}async requestRunning(){return Promise.resolve()}}Du.NoopManager=Lu})(Mu||(manager$5.KernelManager=Mu={})),manager$5}var hasRequiredKernel;function requireKernel(){return hasRequiredKernel||(hasRequiredKernel=1,(function(Au){var lo=kernel$1&&kernel$1.__createBinding||(Object.create?(function(Bu,ju,Fu,zu){zu===void 0&&(zu=Fu);var Uu=Object.getOwnPropertyDescriptor(ju,Fu);(!Uu||("get"in Uu?!ju.__esModule:Uu.writable||Uu.configurable))&&(Uu={enumerable:!0,get:function(){return ju[Fu]}}),Object.defineProperty(Bu,zu,Uu)}):(function(Bu,ju,Fu,zu){zu===void 0&&(zu=Fu),Bu[zu]=ju[Fu]})),$u=kernel$1&&kernel$1.__setModuleDefault||(Object.create?(function(Bu,ju){Object.defineProperty(Bu,"default",{enumerable:!0,value:ju})}):function(Bu,ju){Bu.default=ju}),Ru=kernel$1&&kernel$1.__importStar||(function(){var Bu=function(ju){return Bu=Object.getOwnPropertyNames||function(Fu){var zu=[];for(var Uu in Fu)Object.prototype.hasOwnProperty.call(Fu,Uu)&&(zu[zu.length]=Uu);return zu},Bu(ju)};return function(ju){if(ju&&ju.__esModule)return ju;var Fu={};if(ju!=null)for(var zu=Bu(ju),Uu=0;Uu<zu.length;Uu++)zu[Uu]!=="default"&&lo(Fu,ju,zu[Uu]);return $u(Fu,ju),Fu}})(),Iu=kernel$1&&kernel$1.__exportStar||function(Bu,ju){for(var Fu in Bu)Fu!=="default"&&!Object.prototype.hasOwnProperty.call(ju,Fu)&&lo(ju,Bu,Fu)};Object.defineProperty(Au,"__esModule",{value:!0}),Au.CommsOverSubshells=Au.KernelConnection=Au.KernelAPI=Au.KernelMessage=Au.Kernel=void 0;const Pu=requireComm();Object.defineProperty(Au,"CommsOverSubshells",{enumerable:!0,get:function(){return Pu.CommsOverSubshells}});const Ou=Ru(requireKernel$1());Au.Kernel=Ou;const Mu=Ru(requireMessages());Au.KernelMessage=Mu;const Du=Ru(requireRestapi$4());Au.KernelAPI=Du;const Lu=require_default$2();Object.defineProperty(Au,"KernelConnection",{enumerable:!0,get:function(){return Lu.KernelConnection}}),Iu(requireManager$5(),Au)})(kernel$1)),kernel$1}var kernelspec$1={},kernelspec={},hasRequiredKernelspec$1;function requireKernelspec$1(){return hasRequiredKernelspec$1||(hasRequiredKernelspec$1=1,Object.defineProperty(kernelspec,"__esModule",{value:!0})),kernelspec}var manager$4={},hasRequiredManager$4;function requireManager$4(){if(hasRequiredManager$4)return manager$4;hasRequiredManager$4=1,Object.defineProperty(manager$4,"__esModule",{value:!0}),manager$4.KernelSpecManager=void 0;const Au=requireDist(),lo=require$$1$1,$u=require$$0$2,Ru=requireBasemanager(),Iu=requireRestapi$3();class Pu extends Ru.BaseManager{constructor(Mu={}){var Du,Lu;super(Mu),this._isReady=!1,this._connectionFailure=new $u.Signal(this),this._specs=null,this._specsChanged=new $u.Signal(this),this._kernelSpecAPIClient=(Du=Mu.kernelSpecAPIClient)!==null&&Du!==void 0?Du:new Iu.KernelSpecAPIClient({serverSettings:this.serverSettings}),this._ready=Promise.all([this.requestSpecs()]).then(Bu=>{}).catch(Bu=>{}).then(()=>{this.isDisposed||(this._isReady=!0)}),this._pollSpecs=new lo.Poll({auto:!1,factory:()=>this.requestSpecs(),frequency:{interval:61*1e3,backoff:!0,max:300*1e3},name:"@jupyterlab/services:KernelSpecManager#specs",standby:(Lu=Mu.standby)!==null&&Lu!==void 0?Lu:"when-hidden"}),this.ready.then(()=>{this._pollSpecs.start()})}get isReady(){return this._isReady}get ready(){return this._ready}get specs(){return this._specs}get specsChanged(){return this._specsChanged}get connectionFailure(){return this._connectionFailure}dispose(){this._pollSpecs.dispose(),super.dispose()}async refreshSpecs(){await this._pollSpecs.refresh(),await this._pollSpecs.tick}async requestSpecs(){const Mu=await this._kernelSpecAPIClient.get();this.isDisposed||Au.JSONExt.deepEqual(Mu,this._specs)||(this._specs=Mu,this._specsChanged.emit(Mu))}}return manager$4.KernelSpecManager=Pu,manager$4}var hasRequiredKernelspec;function requireKernelspec(){return hasRequiredKernelspec||(hasRequiredKernelspec=1,(function(Au){var lo=kernelspec$1&&kernelspec$1.__createBinding||(Object.create?(function(Mu,Du,Lu,Bu){Bu===void 0&&(Bu=Lu);var ju=Object.getOwnPropertyDescriptor(Du,Lu);(!ju||("get"in ju?!Du.__esModule:ju.writable||ju.configurable))&&(ju={enumerable:!0,get:function(){return Du[Lu]}}),Object.defineProperty(Mu,Bu,ju)}):(function(Mu,Du,Lu,Bu){Bu===void 0&&(Bu=Lu),Mu[Bu]=Du[Lu]})),$u=kernelspec$1&&kernelspec$1.__setModuleDefault||(Object.create?(function(Mu,Du){Object.defineProperty(Mu,"default",{enumerable:!0,value:Du})}):function(Mu,Du){Mu.default=Du}),Ru=kernelspec$1&&kernelspec$1.__importStar||(function(){var Mu=function(Du){return Mu=Object.getOwnPropertyNames||function(Lu){var Bu=[];for(var ju in Lu)Object.prototype.hasOwnProperty.call(Lu,ju)&&(Bu[Bu.length]=ju);return Bu},Mu(Du)};return function(Du){if(Du&&Du.__esModule)return Du;var Lu={};if(Du!=null)for(var Bu=Mu(Du),ju=0;ju<Bu.length;ju++)Bu[ju]!=="default"&&lo(Lu,Du,Bu[ju]);return $u(Lu,Du),Lu}})(),Iu=kernelspec$1&&kernelspec$1.__exportStar||function(Mu,Du){for(var Lu in Mu)Lu!=="default"&&!Object.prototype.hasOwnProperty.call(Du,Lu)&&lo(Du,Mu,Lu)};Object.defineProperty(Au,"__esModule",{value:!0}),Au.KernelSpecAPI=Au.KernelSpec=void 0;const Pu=Ru(requireKernelspec$1());Au.KernelSpec=Pu;const Ou=Ru(requireRestapi$3());Au.KernelSpecAPI=Ou,Iu(requireManager$4(),Au)})(kernelspec$1)),kernelspec$1}var manager$3={},builder={},hasRequiredBuilder;function requireBuilder(){if(hasRequiredBuilder)return builder;hasRequiredBuilder=1,Object.defineProperty(builder,"__esModule",{value:!0}),builder.BuildManager=void 0;const Au=requireLib$b(),lo=requireServerconnection(),$u="api/build";class Ru{constructor(Pu={}){var Ou;this.serverSettings=(Ou=Pu.serverSettings)!==null&&Ou!==void 0?Ou:lo.ServerConnection.makeSettings()}get isAvailable(){return Au.PageConfig.getOption("buildAvailable").toLowerCase()==="true"}get shouldCheck(){return Au.PageConfig.getOption("buildCheck").toLowerCase()==="true"}getStatus(){const{_url:Pu,serverSettings:Ou}=this;return lo.ServerConnection.makeRequest(Pu,{},Ou).then(Du=>{if(Du.status!==200)throw new lo.ServerConnection.ResponseError(Du);return Du.json()}).then(Du=>{if(typeof Du.status!="string")throw new Error("Invalid data");if(typeof Du.message!="string")throw new Error("Invalid data");return Du})}build(){const{_url:Pu,serverSettings:Ou}=this,Mu={method:"POST"};return lo.ServerConnection.makeRequest(Pu,Mu,Ou).then(Lu=>{if(Lu.status===400)throw new lo.ServerConnection.ResponseError(Lu,"Build aborted");if(Lu.status!==200){const Bu=`Build failed with ${Lu.status}.
486
486
 
487
487
  If you are experiencing the build failure after installing an extension (or trying to include previously installed extension after updating JupyterLab) please check the extension repository for new installation instructions as many extensions migrated to the prebuilt extensions system which no longer requires rebuilding JupyterLab (but uses a different installation procedure, typically involving a package manager such as 'pip' or 'conda').
488
488
 
@@ -2419,7 +2419,7 @@ ${lo}:`]}}function getResponseMetadata2({id:Au,model:lo,created:$u}){return{id:A
2419
2419
  `)?1:0),LANGUAGES={py:"python",pyi:"python",ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",mjs:"javascript",json:"json",md:"markdown",mdx:"markdown",yaml:"yaml",yml:"yaml",toml:"toml",sh:"bash",bash:"bash",css:"css",scss:"scss",html:"html",xml:"xml",sql:"sql",rs:"rust",go:"go",java:"java",c:"c",h:"c",cpp:"cpp",rb:"ruby",ipynb:"json",txt:"text"};function languageOf$1(Au){const lo=Au.split("/").pop()??"";if(lo==="Dockerfile"||lo==="Makefile")return lo.toLowerCase();const $u=lo.lastIndexOf(".");return $u>0?LANGUAGES[lo.slice($u+1).toLowerCase()]??"text":"text"}const DIFF_LINES_LIMIT=2e3,lines=Au=>Au===""?[]:Au.replace(/\n$/,"").split(`
2420
2420
  `);function unifiedDiffLines(Au,lo){const $u=Au===null?[]:lines(Au),Ru=lines(lo);if($u.length>DIFF_LINES_LIMIT||Ru.length>DIFF_LINES_LIMIT)return[...$u.map(Du=>({kind:"remove",text:Du})),...Ru.map(Du=>({kind:"add",text:Du}))];const Iu=[];for(let Du=0;Du<=$u.length;Du++)Iu.push(new Uint32Array(Ru.length+1));for(let Du=$u.length-1;Du>=0;Du--)for(let Lu=Ru.length-1;Lu>=0;Lu--)Iu[Du][Lu]=$u[Du]===Ru[Lu]?Iu[Du+1][Lu+1]+1:Math.max(Iu[Du+1][Lu],Iu[Du][Lu+1]);const Pu=[];let Ou=0,Mu=0;for(;Ou<$u.length&&Mu<Ru.length;)$u[Ou]===Ru[Mu]?(Pu.push({kind:"context",text:$u[Ou]}),Ou++,Mu++):Iu[Ou+1][Mu]>=Iu[Ou][Mu+1]?(Pu.push({kind:"remove",text:$u[Ou]}),Ou++):(Pu.push({kind:"add",text:Ru[Mu]}),Mu++);for(;Ou<$u.length;)Pu.push({kind:"remove",text:$u[Ou++]});for(;Mu<Ru.length;)Pu.push({kind:"add",text:Ru[Mu++]});return Pu}const THREAD_WORDS={opening:"Opening your conversation…",notOpened:Au=>`Your conversation could not be opened, so this is a new one: ${Au}`};function messagesOfThread(Au){if(!Array.isArray(Au))return[];const lo=[];for(const $u of Au){if(!$u||typeof $u!="object")continue;const{id:Ru,role:Iu,content:Pu,activityType:Ou}=$u;if(Iu==="activity"&&Ou===REACTOR_UI_NAME)throw new Error(`Activity ${String(Ru)}: what a message showed comes on the ui socket (RU-W)`);(Iu==="user"||Iu==="assistant")&&typeof Ru=="string"&&typeof Pu=="string"&&Pu.trim()&&lo.push({id:Ru,role:Iu,content:Iu==="user"?askedOf(Pu):Pu,createdAt:new Date})}return lo}function snapshotOfStream(Au){let lo;for(const $u of eventsOfStream(Au))$u.type==="MESSAGES_SNAPSHOT"&&Array.isArray($u.messages)&&(lo=$u.messages);return lo}async function detailOf(Au){try{const lo=await Au.json();if(typeof lo.detail=="string"&&lo.detail)return lo.detail}catch{}return`${Au.status}`}async function openThread({agentBaseUrl:Au,agentId:lo,uid:$u,token:Ru,fetcher:Iu=fetch}){const Pu=`${Au.replace(/\/+$/,"")}/api/v1/apps/sessions/${encodeURIComponent($u)}`,Ou=Ru?{Authorization:`Bearer ${Ru}`}:{},Mu=await Iu(`${Pu}/messages`,{headers:Ou});if(Mu.ok){const Bu=await Mu.json();return messagesOfThread(Bu.messages)}if(Mu.status!==404)throw new Error(await detailOf(Mu));const Du=await Iu(`${Pu}/resume`,{method:"POST",headers:{"Content-Type":"application/json",...Ou},body:JSON.stringify({agent:lo})});if(!Du.ok)throw new Error(await detailOf(Du));const Lu=snapshotOfStream(await Du.text());if(!Lu)throw new Error(`The runtime said nothing of session ${$u}.`);return messagesOfThread(Lu)}const ITEM_LIMIT=400,MESSAGE_TEXT_LIMIT=1e5,TOOL_TEXT_LIMIT=4e3,DIAGNOSTIC_LIMIT=50,DEVICE_LIMITS={items:ITEM_LIMIT,messageText:MESSAGE_TEXT_LIMIT,toolText:TOOL_TEXT_LIMIT,diagnostics:DIAGNOSTIC_LIMIT},BROWSER_LIMITS={items:5e3,messageText:1e6,toolText:1e6,diagnostics:DIAGNOSTIC_LIMIT},CUT_MARK="… (cut: too long to keep on this device)",emptyConversation=(Au=DEVICE_LIMITS)=>{for(const[lo,$u]of Object.entries(Au))if(!Number.isInteger($u)||$u<1)throw new Error(`A conversation's ${lo} bound is ${String($u)}: give a whole number of at least 1.`);return{items:[],running:!1,session:null,asking:null,dropped:0,diagnostics:[],turnRows:0,limits:Au}},text$g=Au=>typeof Au=="string"?Au:"",cut=(Au,lo)=>Au.length>lo?`${Au.slice(0,lo)}${CUT_MARK}`:Au,appended=(Au,lo,$u)=>Au.endsWith(CUT_MARK)?Au:cut(Au+lo,$u),isRecord$2=Au=>!!Au&&typeof Au=="object"&&!Array.isArray(Au);function withoutMeta(Au){if(isRecord$2(Au)&&"_meta"in Au){const{_meta:lo,...$u}=Au;return $u}return Au}function said$1(Au){return Au==null?"":typeof Au=="string"?Au:JSON.stringify(Au)}function questionOf$1(Au){if(!Au||typeof Au!="object")return null;const lo=Au,$u=lo.kind;if($u!=="text"&&$u!=="choice"&&$u!=="form"&&$u!=="file")throw new Error(`The application asks something no client knows: ${String($u)}.`);const Ru=Pu=>Array.isArray(Pu)?Pu.filter(Ou=>typeof Ou=="string"):[],Iu=lo.schema;return{kind:$u,prompt:text$g(lo.prompt),options:Ru(lo.options),schema:isRecord$2(Iu)?Iu:null,accept:Ru(lo.accept)}}function withItems(Au,lo,$u=0){const Ru=lo.length-Au.limits.items;return{...Au,items:Ru>0?lo.slice(Ru):lo,dropped:Au.dropped+Math.max(0,Ru),turnRows:Au.turnRows+$u}}function changed$1(Au,lo,$u){const Ru=Au.items.findIndex(Pu=>Pu.id===lo);if(Ru<0)return null;const Iu=Au.items.slice();return Iu[Ru]=$u(Iu[Ru]),{...Au,items:Iu}}function noted(Au,lo){const $u={type:lo.type,name:text$g(lo.name)||text$g(lo.activityType)};return{...Au,diagnostics:[...Au.diagnostics,$u].slice(-Au.limits.diagnostics)}}const HARNESS_TOOL_CALL="datalayer.harness.tool_call";function withRunningDisplay(Au,lo){if(!isRecord$2(lo)||!isRecord$2(lo._meta))return null;const $u=lo._meta[DISPLAY_META_KEY];if($u===void 0)return null;const Ru=protocolDisplayOf($u);if(!Ru)throw new Error(`${HARNESS_TOOL_CALL} of ${text$g(lo.id)} carries a display no client reads.`);return changed$1(Au,text$g(lo.id),Iu=>Iu.kind==="tool"&&Iu.status==="running"?{...Iu,value:{_meta:lo._meta},display:Ru}:Iu)}let rowCount=0;const rowId=Au=>`${Au}-${Date.now().toString(36)}-${rowCount+=1}`;function toolRow(Au,lo){return{kind:"tool",id:Au,name:lo,args:"",input:null,status:"running",awaiting:null,result:"",value:void 0,error:"",executionError:"",codeError:null,exitCode:null,display:null}}function withInput(Au,lo,$u){const Ru=JSON.stringify(lo),Iu=Ru.length<=$u;return{...Au,args:cut(Ru,$u),input:Iu?lo:null}}const asksThePerson=Au=>!!Au&&Array.isArray(Au.steps);function withResult(Au,lo,$u,Ru=!1){const Iu=lo.result,Pu=said$1(withoutMeta(Iu)),Ou=isRecord$2(Iu)?Iu:null,Mu=typeof Ou?.execution_error=="string"?Ou.execution_error:"",Du=isRecord$2(Ou?.code_error)?Ou.code_error:null,Lu=Du?{name:text$g(Du.name)||"Error",value:text$g(Du.value)||"Unknown error",traceback:cut(text$g(Du.traceback),$u)}:null,Bu=Ou&&typeof Ou.exit_code=="number"?Ou.exit_code:null,ju=!lo.success||Mu!==""||Lu!==null||Bu!==null&&Bu!==0||Ou?.execution_ok===!1,Fu=ju||Ru?null:Ou?.pending_approval===!0?"approval":asksThePerson(Au.input)?"person":null;return{...Au,status:ju?"error":Fu?"running":"complete",awaiting:Fu,result:cut(Pu,$u),value:Pu.length<=$u?Iu:void 0,error:lo.error??"",executionError:cut(Mu,$u),codeError:Lu,exitCode:Bu,display:displayOfToolResult(Au.name,Iu,Au.id)}}function rowsOfSnapshot(Au,lo,$u){if(!Array.isArray(Au))throw new Error("A messages snapshot carries no list of messages.");const Ru=[],Iu=new Map;for(const Pu of Au){for(const Ou of messagesOfThread([Pu]))Ru.push({kind:"message",id:Ou.id,role:Ou.role==="user"?"user":"assistant",text:cut(typeof Ou.content=="string"?Ou.content:"",lo.messageText),streaming:!1});if(isRecord$2(Pu)){if(Pu.role==="assistant"&&Pu.toolCalls!==void 0){if(!Array.isArray(Pu.toolCalls))throw new Error(`Message ${String(Pu.id)}'s tool calls are not a list.`);for(const Ou of Pu.toolCalls){const Mu=isRecord$2(Ou)?Ou.function:void 0;if(!isRecord$2(Ou)||typeof Ou.id!="string"||!isRecord$2(Mu))throw new Error(`Message ${String(Pu.id)} holds a tool call without its id and function.`);const Du=text$g(Mu.arguments);let Lu=null;if(Du&&Du.length<=lo.toolText){let Bu;try{Bu=JSON.parse(Du)}catch{Bu=void 0}if(!isRecord$2(Bu))throw new Error(`Tool call ${Ou.id}'s arguments are not a JSON object.`);Lu=Bu}Iu.set(Ou.id,Ru.length),Ru.push({...toolRow(Ou.id,text$g(Mu.name)),args:cut(Du,lo.toolText),input:Du?Lu:{},status:"complete"})}}if(Pu.role==="tool"){const Ou=text$g(Pu.toolCallId),Mu=Iu.get(Ou);if(Mu===void 0){$u.push(Ou||"no call");continue}Ru[Mu]=withResult(Ru[Mu],toolResultOf(Pu.content),lo.toolText,!0)}}}return Ru}function withPrompt(Au,lo,$u){return withItems({...Au,asking:null},[...Au.items,{kind:"message",id:lo,role:"user",text:$u,streaming:!1}])}function withoutItems(Au,lo){const $u=new Set(lo);return{...Au,items:Au.items.filter(Ru=>!$u.has(Ru.id))}}function withTurnEnded(Au,lo){const $u=Au.items.map(Iu=>Iu.kind==="message"&&Iu.streaming?{...Iu,streaming:!1}:Iu.kind==="tool"&&Iu.status==="running"?{...Iu,status:"error",awaiting:null,error:RUN_END_WORDS[lo]}:Iu.kind==="step"&&Iu.status==="running"?{...Iu,status:"complete"}:Iu),Ru={...Au,items:$u,running:!1};return withItems(Ru,[...$u,{kind:"end",id:rowId("end"),end:lo,words:RUN_END_WORDS[lo]}])}function withError(Au,lo){const $u=Au.items.map(Ru=>Ru.kind==="message"&&Ru.streaming?{...Ru,streaming:!1}:Ru.kind==="tool"&&Ru.status==="running"?{...Ru,status:"error",awaiting:null}:Ru.kind==="step"&&Ru.status==="running"?{...Ru,status:"complete"}:Ru);return withItems({...Au,running:!1},[...$u,{kind:"error",id:rowId("error"),text:lo}])}function required(Au,lo){const $u=Au[lo];if(typeof $u!="string"||!$u)throw new Error(`${Au.type} carries no ${lo}.`);return $u}function reduceConversation(Au,lo){const{limits:$u}=Au;switch(lo.type){case"RUN_STARTED":return{...Au,running:!0,asking:null,turnRows:0};case"TEXT_MESSAGE_START":{const Ru=text$g(lo.messageId)||rowId("message");if(Au.items.some(Pu=>Pu.id===Ru))return Au;const Iu=lo.role==="user"?"user":"assistant";return withItems(Au,[...Au.items,{kind:"message",id:Ru,role:Iu,text:"",streaming:!0}],1)}case"TEXT_MESSAGE_CONTENT":case"TEXT_MESSAGE_CHUNK":{const Ru=text$g(lo.delta),Iu=text$g(lo.messageId),Pu=changed$1(Au,Iu,Ou=>Ou.kind==="message"?{...Ou,text:appended(Ou.text,Ru,$u.messageText)}:Ou);return Pu||withItems(Au,[...Au.items,{kind:"message",id:Iu||rowId("message"),role:lo.role==="user"?"user":"assistant",text:cut(Ru,$u.messageText),streaming:lo.type==="TEXT_MESSAGE_CONTENT"}],1)}case"TEXT_MESSAGE_END":return changed$1(Au,text$g(lo.messageId),Ru=>Ru.kind==="message"?{...Ru,streaming:!1}:Ru)??Au;case"MESSAGE_SAID":{const Ru=required(lo,"messageId");if(typeof lo.text!="string")throw new Error(`MESSAGE_SAID of ${Ru} carries no text.`);if(lo.role!=="user"&&lo.role!=="assistant")throw new Error(`MESSAGE_SAID of ${Ru} is said by ${String(lo.role)}: only the person or the assistant speaks here.`);const Iu=lo.role,Pu=cut(lo.text,$u.messageText),Ou=Iu==="assistant"&&lo.streaming!==!1,Mu=Au.items.findIndex(Du=>Du.id===Ru);if(Mu>=0){const Du=Au.items[Mu];if(Du.kind!=="message")throw new Error(`MESSAGE_SAID of ${Ru} names a ${Du.kind} row.`);const Lu=Au.items.slice();return Lu[Mu]={...Du,text:Pu,streaming:Ou},{...Au,items:Lu}}return withItems(Au,[...Au.items,{kind:"message",id:Ru,role:Iu,text:Pu,streaming:Ou}],1)}case"TOOL_CALL_START":{const Ru=text$g(lo.toolCallId)||rowId("tool");return Au.items.some(Iu=>Iu.id===Ru)?Au:withItems(Au,[...Au.items,toolRow(Ru,text$g(lo.toolCallName)||text$g(lo.name))],1)}case"TOOL_CALL_ARGS":return changed$1(Au,text$g(lo.toolCallId),Ru=>Ru.kind==="tool"?{...Ru,args:appended(Ru.args,text$g(lo.delta),$u.toolText)}:Ru)??Au;case"TOOL_CALL_END":return changed$1(Au,text$g(lo.toolCallId),Ru=>{if(Ru.kind!=="tool"||Ru.args.endsWith(CUT_MARK))return Ru;if(!Ru.args)return{...Ru,input:{}};let Iu;try{Iu=JSON.parse(Ru.args)}catch{Iu=void 0}return isRecord$2(Iu)?{...Ru,input:Iu}:{...Ru,status:"error",awaiting:null,error:"Its arguments are not a JSON object."}})??Au;case"TOOL_CALL_SAID":{const Ru=required(lo,"toolCallId"),Iu=required(lo,"toolCallName");if(!isRecord$2(lo.args))throw new Error(`TOOL_CALL_SAID of ${Ru} carries arguments that are not an object.`);const Pu=lo.args,Ou=Au.items.findIndex(Lu=>Lu.id===Ru);if(Ou<0)return withItems(Au,[...Au.items,withInput(toolRow(Ru,Iu),Pu,$u.toolText)],1);const Mu=Au.items[Ou];if(Mu.kind!=="tool")throw new Error(`TOOL_CALL_SAID of ${Ru} names a ${Mu.kind} row.`);const Du=Au.items.slice();return Du[Ou]=withInput(Mu,{...Mu.input??{},...Pu},$u.toolText),{...Au,items:Du}}case"TOOL_CALL_RESULT":{const Ru=toolResultOf(lo.content);return changed$1(Au,text$g(lo.toolCallId),Iu=>Iu.kind==="tool"?withResult(Iu,Ru,$u.toolText):Iu)??noted(Au,lo)}case"TOOL_CALL_DONE":{const Ru=required(lo,"toolCallId");if(typeof lo.success!="boolean")throw new Error(`TOOL_CALL_DONE of ${Ru} does not say whether it succeeded.`);if(lo.error!==void 0&&typeof lo.error!="string")throw new Error(`TOOL_CALL_DONE of ${Ru} says its error in no words.`);const Iu={result:lo.result,success:lo.success,...lo.error!==void 0?{error:lo.error}:{}};return changed$1(Au,Ru,Pu=>Pu.kind==="tool"?withResult(Pu,Iu,$u.toolText,lo.answered===!0):Pu)??noted(Au,lo)}case"STEP_STARTED":{const Ru=text$g(lo.stepName)||text$g(lo.name);return withItems(Au,[...Au.items,{kind:"step",id:rowId("step"),name:Ru,status:"running"}],1)}case"STEP_FINISHED":{const Ru=text$g(lo.stepName)||text$g(lo.name),Iu=Au.items.map((Ou,Mu)=>({item:Ou,index:Mu})).reverse().find(({item:Ou})=>Ou.kind==="step"&&Ou.name===Ru&&Ou.status==="running");if(!Iu)return noted(Au,lo);const Pu=Au.items.slice();return Pu[Iu.index]={...Iu.item,status:"complete"},{...Au,items:Pu}}case"MESSAGES_SNAPSHOT":{const Ru=[],Iu=rowsOfSnapshot(lo.messages,$u,Ru),Pu=withItems({...Au,dropped:0},Iu,1);return Ru.reduce((Ou,Mu)=>noted(Ou,{type:"TOOL_CALL_RESULT",name:`${Mu} (no call)`}),Pu)}case"CUSTOM":{if(lo.name===REACTOR_UI_NAME)return withError(Au,UI_ON_RUN);if(lo.name==="loop.session"&&isRecord$2(lo.value)){const Ru=lo.value;return{...Au,session:Ru,asking:questionOf$1(Ru.asking)??Au.asking}}return lo.name===HARNESS_TOOL_CALL?withRunningDisplay(Au,lo.value)??noted(Au,lo):noted(Au,lo)}case"ACTIVITY_SNAPSHOT":case"ACTIVITY_DELTA":return lo.activityType===REACTOR_UI_NAME?withError(Au,UI_ON_RUN):noted(Au,lo);case"RUN_FINISHED":{const Ru=isRecord$2(lo.result)?lo.result:{},Iu=questionOf$1(Ru.asking),Pu=Au.items.map(Mu=>Mu.kind==="message"&&Mu.streaming?{...Mu,streaming:!1}:Mu),Ou={...Au,items:Pu,running:!1,asking:Iu};return Iu||Au.turnRows>0?Ou:withItems(Ou,[...Pu,{kind:"end",id:rowId("end"),end:"answered",words:RUN_END_WORDS.answered}])}case"RUN_ERROR":return withError(Au,text$g(lo.message)||"Run failed");default:return noted(Au,lo)}}const emptyChatLayer=()=>({extras:new Map,displays:new Map,speakers:new Map,steps:[]}),toolCardId=Au=>`tool-${Au}`,rowIdOf=Au=>"toolCallId"in Au&&Au.id===toolCardId(Au.toolCallId)?Au.toolCallId:Au.id;function cardStatusOf(Au){return Au.status!=="running"?Au.status:Au.awaiting==="approval"?"inProgress":"executing"}function toolCallOf(Au){return{id:toolCardId(Au.id),type:"tool-call",toolCallId:Au.id,toolName:Au.name,args:Au.input??{},...Au.value!==void 0?{result:Au.value}:Au.result?{result:Au.result}:{},status:cardStatusOf(Au),...Au.error?{error:Au.error}:{},...Au.executionError?{executionError:Au.executionError}:{},...Au.codeError?{codeError:{name:Au.codeError.name,value:Au.codeError.value,...Au.codeError.traceback?{traceback:Au.codeError.traceback}:{}}}:{},...Au.exitCode!==null?{exitCode:Au.exitCode}:{}}}function withToolSummaries(Au,lo=[]){const $u=lo.filter(Pu=>Pu.summaryOf);if($u.length===0)return Au;let Ru=!1;const Iu=Au.map(Pu=>{if(!isToolCallMessage(Pu))return Pu;const Ou=Pu,Mu=$u.find(Lu=>Lu.name===Ou.toolName);if(!Mu?.summaryOf||Ou.result===void 0)return Pu;const Du=Mu.summaryOf(Ou.args,Ou.result)?.trim();return!Du||Du===Ou.summary?Pu:(Ru=!0,{...Ou,summary:Du})});return Ru?Iu:Au}function conversationDrawer(Au){const lo=new Map,$u=(Iu,Pu)=>{const Ou=Pu.extras.get(Iu.id),Mu=Pu.displays.get(Iu.id),Du=Pu.speakers.get(Iu.id),Lu=lo.get(Iu.id);if(Lu&&Lu.row===Iu&&Lu.extras===Ou&&Lu.displays===Mu&&Lu.speaker===Du)return Lu.item;const Bu={...Ou,createdAt:Ou?.createdAt??new Date,id:Iu.id,role:Iu.kind==="message"?Iu.role:"assistant",content:Iu.kind==="message"?Iu.text:Au(Iu.text),...Mu?{displays:Mu}:{},...Du?{speaker:Du}:{}};return lo.set(Iu.id,{row:Iu,extras:Ou,displays:Mu,speaker:Du,item:Bu}),Bu},Ru=Iu=>{const Pu=lo.get(Iu.id);if(Pu&&Pu.row===Iu)return Pu.item;const Ou=toolCallOf(Iu);return lo.set(Iu.id,{row:Iu,item:Ou}),Ou};return(Iu,Pu)=>{const Ou=[],Mu=new Map;for(const Lu of Pu.steps)Mu.set(Lu.after,[...Mu.get(Lu.after)??[],Lu.item]);Ou.push(...Mu.get(null)??[]);const Du=new Set;for(const Lu of Iu.items)Du.add(Lu.id),Lu.kind==="message"||Lu.kind==="error"?Ou.push($u(Lu,Pu)):Lu.kind==="tool"&&Ou.push(Ru(Lu)),Ou.push(...Mu.get(Lu.id)??[]);for(const[Lu,Bu]of Mu)Lu!==null&&!Du.has(Lu)&&Ou.push(...Bu);for(const Lu of lo.keys())Du.has(Lu)||lo.delete(Lu);return Ou}}function isSubagentRunOver(Au){return Au.some(lo=>lo.phase==="end"||lo.phase==="error")}function getMonitoringCacheKey(Au,lo){return`${Au||"__unknown_service__"}::${lo||"__unknown_agent__"}`}function getTransportEndpoint(Au,lo,$u){switch(lo){case"vercel-ai":return`${Au}/api/v1/vercel-ai/${$u}`;case"a2a":return`${Au}/api/v1/a2a/agents/${$u}/`;case"acp":return`${Au}/api/v1/acp/ws/${$u}`;default:return`${Au}/api/v1/ag-ui/${$u}/`}}function toAgentRuntimeBaseUrl(Au){const lo=Au.replace(/\/$/,"");return lo.includes("/api/agent-runtimes")?lo:lo.includes("/api/jupyter-server")?lo.replace("/api/jupyter-server","/api/agent-runtimes"):lo.includes("/jupyter/server/")?lo.replace("/jupyter/server/","/agent-runtimes/"):lo.includes("/jupyter-server/")?lo.replace("/jupyter-server/","/agent-runtimes/"):lo.replace("/jupyter/","/agent-runtimes/")}async function createAgentOnRuntime(Au,lo,$u={}){const{iamStore:Ru}=await __vitePreload(async()=>{const{iamStore:Lu}=await import("./chunks/index-J-pyZzZ8.js");return{iamStore:Lu}},[],import.meta.url),Iu=Ru.getState().token||"";if(!$u.protocol&&!$u.agentSpecId)throw new Error("Agent protocol is required. Provide config.protocol from the selected spec/config.");const Pu=$u.protocol||"vercel-ai";if(!$u.model&&!$u.agentSpecId)throw new Error("Agent model is required. Provide config.model from the selected spec/config.");const Ou={name:$u.name||lo,description:$u.description||"AI assistant",agent_library:$u.agentLibrary||"pydantic-ai",transport:Pu,model:$u.model,system_prompt:$u.systemPrompt||"You are a helpful AI assistant."};$u.agentSpecId&&(Ou.agent_spec_id=$u.agentSpecId),typeof $u.enableSkills=="boolean"&&(Ou.enable_skills=$u.enableSkills),Array.isArray($u.backendTools)&&(Ou.backend_tools=$u.backendTools),$u.inferenceProvider&&(Ou.inferenceProvider=$u.inferenceProvider),typeof $u.enableCodemode=="boolean"&&(Ou.enable_codemode=$u.enableCodemode),$u.sandboxVariant&&(Ou.sandbox_variant=$u.sandboxVariant),$u.jupyterSandbox&&(Ou.jupyter_sandbox=$u.jupyterSandbox),$u.createPayload&&typeof $u.createPayload=="object"&&Object.assign(Ou,$u.createPayload);const Mu=await fetch(`${Au}/api/v1/agents`,{method:"POST",headers:{"Content-Type":"application/json",...Iu?{Authorization:`Bearer ${Iu}`}:{}},body:JSON.stringify(Ou)});if(Mu.ok||Mu.status===400||Mu.status===409){const Lu=getTransportEndpoint(Au,Pu,lo);return{agentId:lo,endpoint:Lu,isReady:!0}}const Du=await Mu.json().catch(()=>({}));throw new Error(Du.detail||`Failed to create agent: ${Mu.status}`)}const initialRuntimeState={runtime:null,status:"idle",error:null,isLaunching:!1,historyVersion:0,toolDecisionRequest:null},initialWsState={wsState:"closed",approvals:[],pendingApprovalCount:0,subagentActivity:{},compaction:null,contextSnapshot:null,costUsage:null,mcpStatus:null,codemodeStatus:null,fullContext:null,monitoringCache:{},loadedSkillsByAgentId:{}},initialNotebookState={ephemeralNotebookModels:{},ephemeralDocumentModels:{},editorModeByRuntime:{}},countPendingApprovals=Au=>Au.filter(lo=>lo.status==="pending").length;let _ws=null;const _wsByAgentId=new Map;function _resolveWs(Au){const lo=_wsByAgentId.size>0;if(Au){const $u=_wsByAgentId.get(Au);if($u&&$u.readyState===WebSocket.OPEN)return $u;if(lo)return null}return lo?null:_ws&&_ws.readyState===WebSocket.OPEN?_ws:null}const agentRuntimeStore=createStore$1()(subscribeWithSelector(persist((Au,lo)=>({agents:[],upsertAgent:$u=>{Au(Ru=>{const Iu=Ru.agents.findIndex(Mu=>Mu.id===$u.id),Pu=Date.now();if(Iu>=0){const Mu=[...Ru.agents];return Mu[Iu]={...Mu[Iu],...$u,lastUpdated:Pu},{agents:Mu}}const Ou={name:$u.name||$u.id,description:$u.description||"",status:$u.status||"initializing",lastUpdated:Pu,...$u};return{agents:[...Ru.agents,Ou]}})},getAgentById:$u=>lo().agents.find(Ru=>Ru.id===$u),getAgentByUrl:($u,Ru)=>lo().agents.find(Iu=>Iu.baseUrl===$u&&Iu.protocol===Ru),updateAgentStatus:($u,Ru,Iu=null)=>{Au(Pu=>{const Ou=Pu.agents.findIndex(Mu=>Mu.id===$u);if(Ou>=0){const Mu=[...Pu.agents];return Mu[Ou]={...Mu[Ou],status:Ru,error:Iu,lastUpdated:Date.now()},{agents:Mu}}return{}})},toggleAgentStatus:$u=>{Au(Ru=>{const Iu=Ru.agents.findIndex(Pu=>Pu.id===$u);if(Iu>=0){const Pu=[...Ru.agents],Ou=Pu[Iu].status;return Pu[Iu]={...Pu[Iu],status:Ou==="running"?"paused":"running",lastUpdated:Date.now()},{agents:Pu}}return{}})},deleteAgent:$u=>{Au(Ru=>{const{[$u]:Iu,...Pu}=Ru.loadedSkillsByAgentId;return{agents:Ru.agents.filter(Ou=>Ou.id!==$u),loadedSkillsByAgentId:Pu}})},clearAgents:()=>{Au({agents:[]})},setLoadedSkillsForAgent:($u,Ru)=>{Au(Iu=>({loadedSkillsByAgentId:{...Iu.loadedSkillsByAgentId,[$u]:Ru}}))},getLoadedSkillsForAgent:$u=>lo().loadedSkillsByAgentId[$u]??[],clearLoadedSkillsForAgent:$u=>{Au(Ru=>{if(!($u in Ru.loadedSkillsByAgentId))return{};const{[$u]:Iu,...Pu}=Ru.loadedSkillsByAgentId;return{loadedSkillsByAgentId:Pu}})},setEphemeralNotebookModel:($u,Ru)=>{Au(Iu=>({ephemeralNotebookModels:{...Iu.ephemeralNotebookModels,[$u]:Ru}}))},getEphemeralNotebookModel:$u=>lo().ephemeralNotebookModels[$u]??null,clearEphemeralNotebookModel:$u=>{Au(Ru=>{if(!($u in Ru.ephemeralNotebookModels))return{};const{[$u]:Iu,...Pu}=Ru.ephemeralNotebookModels;return{ephemeralNotebookModels:Pu}})},setEphemeralDocumentModel:($u,Ru)=>{Au(Iu=>({ephemeralDocumentModels:{...Iu.ephemeralDocumentModels,[$u]:Ru}}))},getEphemeralDocumentModel:$u=>lo().ephemeralDocumentModels[$u]??null,clearEphemeralDocumentModel:$u=>{Au(Ru=>{if(!($u in Ru.ephemeralDocumentModels))return{};const{[$u]:Iu,...Pu}=Ru.ephemeralDocumentModels;return{ephemeralDocumentModels:Pu}})},setEditorMode:($u,Ru)=>{$u&&Au(Iu=>({editorModeByRuntime:{...Iu.editorModeByRuntime,[$u]:Ru}}))},getEditorMode:$u=>lo().editorModeByRuntime[$u]??null,...initialRuntimeState,connectAgent:$u=>{const Ru=$u.jupyterBaseUrl||$u.serviceManager?.serverSettings.baseUrl;if(!Ru)throw new Error("connectAgent requires either jupyterBaseUrl or serviceManager");const Iu=toAgentRuntimeBaseUrl(Ru);Au({runtime:{runtimeName:$u.runtimeName,environmentName:$u.environmentName,jupyterBaseUrl:Ru,agentBaseUrl:Iu,serviceManager:$u.serviceManager,status:"ready",kernelId:$u.kernelId},status:"ready",error:null})},launchAgent:async $u=>{Au({status:"launching",error:null,isLaunching:!0});try{const{createRuntime:Ru}=await __vitePreload(async()=>{const{createRuntime:ju}=await Promise.resolve().then(()=>actions);return{createRuntime:ju}},void 0,import.meta.url),{runtimesStore:Iu}=await __vitePreload(async()=>{const{runtimesStore:ju}=await import("./chunks/index-DghIPf1A.js");return{runtimesStore:ju}},[],import.meta.url);$u.runtimesUrl&&Iu.setState({runtimesUrl:$u.runtimesUrl});const{runtimesUrl:Pu,...Ou}=$u,Mu=await Ru({environmentName:Ou.environmentName,creditsLimit:Ou.creditsLimit,type:Ou.type||"notebook",givenName:Ou.givenName,capabilities:Ou.capabilities,snapshot:Ou.snapshot,appSpec:Ou.appSpec,appUid:Ou.appUid,deploymentUid:Ou.deploymentUid});Au({status:"connecting"});const Du=Mu.ingress,Lu=toAgentRuntimeBaseUrl(Du),Bu={runtimeName:Mu.runtime_name,environmentName:Mu.environment.name,jupyterBaseUrl:Du,agentBaseUrl:Lu,status:"ready"};return Au({runtime:Bu,status:"ready",isLaunching:!1}),Bu}catch(Ru){const Iu=Ru instanceof Error?Ru.message:"Failed to launch runtime";throw Au({status:"error",error:Iu,isLaunching:!1}),Ru}},createAgent:async($u={})=>{const{runtime:Ru}=lo();if(!Ru)throw new Error("No runtime connected. Launch or connect to a runtime first.");try{const Iu=$u.name||Ru.runtimeName,Pu=await createAgentOnRuntime(Ru.agentBaseUrl,Iu,$u);return Au({runtime:{...Ru,agentId:Pu.agentId,endpoint:Pu.endpoint,isReady:Pu.isReady}}),Pu}catch(Iu){const Pu=Iu instanceof Error?Iu.message:"Failed to create agent";throw Au({error:Pu}),Iu}},disconnect:()=>{Au({runtime:null,status:"disconnected",error:null})},clearError:()=>Au({error:null}),setError:$u=>Au({error:$u,status:"error"}),...initialWsState,...initialNotebookState,setWsState:$u=>Au({wsState:$u}),setWs:($u,Ru)=>{_ws=$u,Ru&&($u?_wsByAgentId.set(Ru,$u):_wsByAgentId.delete(Ru))},applySnapshot:$u=>Au(Ru=>({approvals:Ru.approvals,pendingApprovalCount:Ru.pendingApprovalCount,contextSnapshot:$u.contextSnapshot??null,costUsage:$u.costUsage??null,mcpStatus:$u.mcpStatus??null,codemodeStatus:$u.codemodeStatus??null,fullContext:$u.fullContext??null})),appendSubagentEvent:$u=>Au(Ru=>{const Iu=$u.toolCallId??$u.subagentName,Pu=Ru.subagentActivity[Iu]??[];return Pu.some(Ou=>Ou.phase==="error"&&Ou.error===SUBAGENT_STOPPED)?{}:{subagentActivity:{...Ru.subagentActivity,[Iu]:[...Pu,$u]}}}),clearSubagentActivity:()=>Au({subagentActivity:{}}),stopSubagentActivity:()=>Au($u=>{let Ru=!1;const Iu={};for(const[Pu,Ou]of Object.entries($u.subagentActivity)){if(Ou.length===0||isSubagentRunOver(Ou)){Iu[Pu]=Ou;continue}Ru=!0,Iu[Pu]=[...Ou,{subagentName:Ou[0].subagentName,toolCallId:Ou[0].toolCallId??Pu,phase:"error",error:SUBAGENT_STOPPED,transport:Ou[0].transport}]}return Ru?{subagentActivity:Iu}:{}}),requestHistoryReload:()=>Au($u=>({historyVersion:$u.historyVersion+1})),requestToolDecision:$u=>Au(Ru=>({toolDecisionRequest:{seq:(Ru.toolDecisionRequest?.seq??0)+1,...$u}})),setCompaction:$u=>Au({compaction:$u}),upsertApproval:$u=>Au(Ru=>{const Iu=Ru.approvals.filter(Ou=>Ou.id!==$u.id),Pu=[$u,...Iu];return{approvals:Pu,pendingApprovalCount:countPendingApprovals(Pu)}}),removeApproval:$u=>Au(Ru=>{const Iu=Ru.approvals.filter(Pu=>Pu.id!==$u);return{approvals:Iu,pendingApprovalCount:countPendingApprovals(Iu)}}),sendDecision:($u,Ru,Iu,Pu,Ou)=>{const Mu=_resolveWs(Ou);return Mu?(Mu.send(JSON.stringify({type:"tool_approval_decision",approvalId:$u,approved:Ru,...Iu?{note:Iu}:{},...Pu?{toolCallId:Pu}:{}})),!0):!1},requestRefresh:$u=>{const Ru=_resolveWs($u);return Ru?(Ru.send(JSON.stringify({type:"request_snapshot"})),Ru.send(JSON.stringify({type:"request_otel_flush"})),!0):!1},sendRawMessage:($u,Ru)=>{const Iu=_resolveWs(Ru);return Iu?(Iu.send(JSON.stringify($u)),!0):!1},appendLocalTokenTurn:({serviceName:$u,agentId:Ru,timestampMs:Iu,promptTokens:Pu,completionTokens:Ou,totalTokens:Mu})=>{Au(Du=>{const Lu=getMonitoringCacheKey($u,Ru),Bu=Du.monitoringCache[Lu]??{tokenTurns:[],costPoints:[]},ju=[...Bu.tokenTurns],Fu=ju[ju.length-1];if(Fu&&Fu.userMessageTokens===Pu&&Fu.aiMessageTokens===Ou&&Fu.systemPromptTokens===0&&Fu.toolsDescriptionTokens===0&&Fu.toolsUsageTokens===0&&Fu.totalTokens===Mu)return ju[ju.length-1]={...Fu,timestampMs:Math.max(Fu.timestampMs,Iu)},{monitoringCache:{...Du.monitoringCache,[Lu]:{...Bu,tokenTurns:ju}}};const zu=(Fu?.turnNumber??0)+1;return ju.push({turnNumber:zu,timestampMs:Iu,systemPromptTokens:0,toolsDescriptionTokens:0,userMessageTokens:Pu,aiMessageTokens:Ou,toolsUsageTokens:0,totalTokens:Mu}),{monitoringCache:{...Du.monitoringCache,[Lu]:{...Bu,tokenTurns:ju}}}})},mergeTokenTurns:({serviceName:$u,agentId:Ru,turns:Iu})=>{Iu.length!==0&&Au(Pu=>{const Ou=getMonitoringCacheKey($u,Ru),Mu=Pu.monitoringCache[Ou]??{tokenTurns:[],costPoints:[]},Du=new Map;for(const Bu of Mu.tokenTurns)Du.set(Bu.turnNumber,Bu);for(const Bu of Iu)Du.set(Bu.turnNumber,Bu);const Lu=Array.from(Du.values()).sort((Bu,ju)=>Bu.turnNumber-ju.turnNumber);return{monitoringCache:{...Pu.monitoringCache,[Ou]:{...Mu,tokenTurns:Lu}}}})},appendLocalTokenTurnFull:({serviceName:$u,agentId:Ru,timestampMs:Iu,systemPromptTokens:Pu,toolsDescriptionTokens:Ou,userMessageTokens:Mu,aiMessageTokens:Du,toolsUsageTokens:Lu,totalTokens:Bu})=>{Au(ju=>{const Fu=getMonitoringCacheKey($u,Ru),zu=ju.monitoringCache[Fu]??{tokenTurns:[],costPoints:[]},Uu=[...zu.tokenTurns],Hu=Uu[Uu.length-1];if(Hu&&Hu.systemPromptTokens===Pu&&Hu.toolsDescriptionTokens===Ou&&Hu.userMessageTokens===Mu&&Hu.aiMessageTokens===Du&&Hu.toolsUsageTokens===Lu&&Hu.totalTokens===Bu)return Uu[Uu.length-1]={...Hu,timestampMs:Math.max(Hu.timestampMs,Iu)},{monitoringCache:{...ju.monitoringCache,[Fu]:{...zu,tokenTurns:Uu}}};const Vu=(Hu?.turnNumber??0)+1;return Uu.push({turnNumber:Vu,timestampMs:Iu,systemPromptTokens:Pu,toolsDescriptionTokens:Ou,userMessageTokens:Mu,aiMessageTokens:Du,toolsUsageTokens:Lu,totalTokens:Bu}),{monitoringCache:{...ju.monitoringCache,[Fu]:{...zu,tokenTurns:Uu}}}})},upsertLocalCostPoint:({serviceName:$u,agentId:Ru,timestampMs:Iu,cumulativeUsd:Pu})=>{Au(Ou=>{const Mu=getMonitoringCacheKey($u,Ru),Du=Ou.monitoringCache[Mu]??{tokenTurns:[],costPoints:[]},Lu=[...Du.costPoints],Bu=Lu.findIndex(ju=>Math.abs(ju.timestampMs-Iu)<1);return Bu>=0?Lu[Bu]={...Lu[Bu],cumulativeUsd:Math.max(Lu[Bu].cumulativeUsd,Pu)}:Lu.push({timestampMs:Iu,cumulativeUsd:Pu}),Lu.sort((ju,Fu)=>ju.timestampMs-Fu.timestampMs),{monitoringCache:{...Ou.monitoringCache,[Mu]:{...Du,costPoints:Lu}}}})},mergeCostPoints:({serviceName:$u,agentId:Ru,points:Iu})=>{Iu.length!==0&&Au(Pu=>{const Ou=getMonitoringCacheKey($u,Ru),Mu=Pu.monitoringCache[Ou]??{tokenTurns:[],costPoints:[]},Du=new Map;for(const Bu of Mu.costPoints)Du.set(Bu.timestampMs,Bu);for(const Bu of Iu){const ju=Du.get(Bu.timestampMs);ju?Du.set(Bu.timestampMs,{timestampMs:Bu.timestampMs,cumulativeUsd:Math.max(ju.cumulativeUsd,Bu.cumulativeUsd)}):Du.set(Bu.timestampMs,Bu)}const Lu=Array.from(Du.values()).sort((Bu,ju)=>Bu.timestampMs-ju.timestampMs);return{monitoringCache:{...Pu.monitoringCache,[Ou]:{...Mu,costPoints:Lu}}}})},reset:()=>{if(_ws)try{_ws.close(1e3,"reset")}catch{}_ws=null,_wsByAgentId.clear(),Au($u=>({...initialRuntimeState,...initialWsState,ephemeralNotebookModels:$u.ephemeralNotebookModels,ephemeralDocumentModels:$u.ephemeralDocumentModels,editorModeByRuntime:$u.editorModeByRuntime}))},resetWs:()=>{if(_ws)try{_ws.close(1e3,"reset")}catch{}_ws=null,_wsByAgentId.clear(),Au($u=>({...initialWsState,ephemeralNotebookModels:$u.ephemeralNotebookModels,ephemeralDocumentModels:$u.ephemeralDocumentModels,editorModeByRuntime:$u.editorModeByRuntime,subagentActivity:$u.subagentActivity}))}}),{name:"agent-runtimes-storage",storage:createJSONStorage(()=>localStorage),partialize:Au=>({agents:Au.agents.map(lo=>({id:lo.id,name:lo.name,description:lo.description,baseUrl:lo.baseUrl,transport:lo.protocol,status:lo.status,lastUpdated:lo.lastUpdated,documentId:lo.documentId,runtimeId:lo.runtimeId})),monitoringCache:Au.monitoringCache,loadedSkillsByAgentId:Au.loadedSkillsByAgentId,ephemeralNotebookModels:Au.ephemeralNotebookModels,ephemeralDocumentModels:Au.ephemeralDocumentModels,editorModeByRuntime:Au.editorModeByRuntime})})));function useAgentRuntimeStore(Au){return useStore$1(agentRuntimeStore,Au||($u=>$u))}const useAgentRuntimeStoreWithStatics=useAgentRuntimeStore;useAgentRuntimeStoreWithStatics.getState=agentRuntimeStore.getState;useAgentRuntimeStoreWithStatics.subscribe=agentRuntimeStore.subscribe;const useAgentRuntimeConnection=()=>useAgentRuntimeStore(Au=>Au.runtime),useAgentRuntimeStatus=()=>useAgentRuntimeStore(Au=>Au.status),useAgentRuntimeError=()=>useAgentRuntimeStore(Au=>Au.error),useAgentRuntimeIsLaunching=()=>useAgentRuntimeStore(Au=>Au.isLaunching),useAgentRuntimeMcpStatus=()=>useAgentRuntimeStore(Au=>Au.mcpStatus),useAgentRuntimeFullContext=()=>useAgentRuntimeStore(Au=>Au.fullContext),useAgentRuntimeContextSnapshot=()=>useAgentRuntimeStore(Au=>Au.contextSnapshot),useAgentRuntimeCodemodeStatus=()=>useAgentRuntimeStore(Au=>Au.codemodeStatus),useAgentRuntimeWsState=()=>useAgentRuntimeStore(Au=>Au.wsState),EMPTY_SUBAGENT_EVENTS=[],useAgentRuntimeSubagentActivity=Au=>useAgentRuntimeStore(lo=>Au?lo.subagentActivity[Au]??EMPTY_SUBAGENT_EVENTS:EMPTY_SUBAGENT_EVENTS),useAgentRuntimeSubagentActivityByToolCall=(Au,lo)=>useAgentRuntimeStore($u=>{if(Au){const Ru=$u.subagentActivity[Au];if(Ru&&Ru.length>0)return Ru}if(lo){const Ru=$u.subagentActivity[lo];if(Ru&&Ru.length>0)return Ru;let Iu;for(const Pu of Object.values($u.subagentActivity))Pu.length>0&&Pu[0]?.subagentName===lo&&(Iu=Pu);if(Iu)return Iu}return EMPTY_SUBAGENT_EVENTS}),useAgentRuntimeActiveSubagentToolCallId=()=>useAgentRuntimeStore(Au=>{let lo=null;for(const[$u,Ru]of Object.entries(Au.subagentActivity))Ru.length!==0&&(isSubagentRunOver(Ru)||(lo=$u));return lo});agentRuntimeStore.subscribe;async function requestAPI(Au="",lo={}){const $u=libExports$3.ServerConnection.makeSettings(),Ru=libExports$5.URLExt.join($u.baseUrl,"agent_runtimes",Au);let Iu;try{Iu=await libExports$3.ServerConnection.makeRequest(Ru,lo,$u)}catch(Ou){throw new libExports$3.ServerConnection.NetworkError(Ou)}let Pu=await Iu.text();if(Pu.length>0)try{Pu=JSON.parse(Pu)}catch{}if(!Iu.ok)throw new libExports$3.ServerConnection.ResponseError(Iu,Pu.message||Pu);return Pu}function useConfig(Au,lo,$u,Ru){return reactExports.useContext(QueryClientContext)?useQuery({queryFn:async()=>{if(lo){const Pu={"Content-Type":"application/json"};$u&&(Pu.Authorization=`Bearer ${$u}`);let Ou=lo;if(Ru){const Du=new URL(lo,window.location.origin);Du.searchParams.set("agent_id",Ru),Ou=Du.toString()}const Mu=await fetch(Ou,{headers:Pu});if(!Mu.ok)throw new Error(`Config fetch failed: ${Mu.statusText}`);return Mu.json()}return requestAPI("configure")},queryKey:["models",lo||"jupyter-server",Ru||"global"],enabled:Au,retry:1}):{data:void 0,isLoading:!1,isError:!1,error:null,refetch:()=>Promise.resolve({data:void 0})}}function parseSkillStatus(Au){return Au==="available"||Au==="enabled"||Au==="loaded"?Au:"available"}function useSkills(Au,lo,$u){const Ru=useAgentRuntimeCodemodeStatus(),Iu=reactExports.useMemo(()=>{if(!Ru)return;const Pu=(Ru.skills??[]).map(Ou=>({id:Ou.id??Ou.name,name:Ou.name,description:Ou.description,tags:Ou.tags,has_scripts:Ou.has_scripts,has_resources:Ou.has_resources,status:parseSkillStatus(Ou.status),approved:Ou.approved!==!1,skill_definition:Ou.skill_definition??null,source_variant:Ou.source_variant,module:Ou.module,package:Ou.package,method:Ou.method,path:Ou.path}));return{skills:Pu,total:Pu.length}},[Ru]);return{data:Iu,isLoading:!1,isError:!1,error:null,refetch:()=>Promise.resolve({data:Iu})}}function useSkillActions(Au){const lo=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_enable",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_enable dropped: websocket not ready"),Ou},[Au]),$u=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_disable",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_disable dropped: websocket not ready"),Ou},[Au]),Ru=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_approve",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_approve dropped: websocket not ready"),Ou},[Au]),Iu=reactExports.useCallback(Pu=>{const Ou=agentRuntimeStore.getState().sendRawMessage({type:"skill_unapprove",skillId:Pu},Au);return Ou||console.warn("[useSkillActions] skill_unapprove dropped: websocket not ready"),Ou},[Au]);return{enableSkill:lo,disableSkill:$u,approveSkill:Ru,unapproveSkill:Iu}}function useContextSnapshot(Au,lo,$u,Ru){return{data:useAgentRuntimeContextSnapshot()??void 0,isLoading:!1,isError:!1,error:null}}const RECONNECT_BASE_MS$1=1e3,RECONNECT_MAX_MS$1=3e4;function isRetryableCloseCode(Au){return!new Set([1002,1003,1007,1008,4401,4403]).has(Au)}function useSandbox(Au,lo,$u,Ru){const[Iu,Pu]=reactExports.useState(void 0),Ou=reactExports.useRef(null);reactExports.useEffect(()=>{if(!Au||!lo){Pu(void 0);return}const Du=getApiBaseFromConfig(lo);if(!Du)return;const Lu=Du.replace(/^http/,"ws"),Bu=[];Ru&&Bu.push(`agent_id=${encodeURIComponent(Ru)}`),$u&&Bu.push(`token=${encodeURIComponent($u)}`);const ju=`${Lu}/configure/sandbox/ws${Bu.length?`?${Bu.join("&")}`:""}`;let Fu=!1,zu,Uu=0;const Hu=Gu=>{if(Fu||!isRetryableCloseCode(Gu))return;const Wu=Math.min(RECONNECT_BASE_MS$1*2**Uu,RECONNECT_MAX_MS$1);Uu+=1,zu=setTimeout(Vu,Wu)},Vu=()=>{if(Fu)return;const Gu=new WebSocket(ju);Ou.current=Gu,Gu.onopen=()=>{Uu=0},Gu.onmessage=Wu=>{try{const Zu=JSON.parse(Wu.data);if(Zu&&Zu.action==="interrupt")return;const Ju=typeof Zu?.variant=="string"?Zu.variant:"";Pu({available:Ju!=="unavailable"&&Ju!=="error",sandbox_running:!!Zu?.sandbox_running,is_executing:!!Zu?.is_executing,variant:Ju})}catch{}},Gu.onclose=Wu=>{Ou.current=null,Hu(Wu.code)},Gu.onerror=()=>{Gu.close()}};return Vu(),()=>{Fu=!0,zu&&clearTimeout(zu),Ou.current?.close(),Ou.current=null,Pu(void 0)}},[Au,lo,$u,Ru]);const Mu=reactExports.useCallback(()=>{const Du=Ou.current;Du&&Du.readyState===WebSocket.OPEN&&Du.send(JSON.stringify({action:"interrupt"}))},[]);return{data:Iu,interrupt:Mu}}function _typeof$8(Au){"@babel/helpers - typeof";return _typeof$8=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$8(Au)}function _createClass$8(Au,lo,$u){return Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _classCallCheck$8(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _callSuper$1(Au,lo,$u){return lo=_getPrototypeOf$1(lo),_possibleConstructorReturn$1(Au,_isNativeReflectConstruct$1()?Reflect.construct(lo,$u||[],_getPrototypeOf$1(Au).constructor):lo.apply(Au,$u))}function _possibleConstructorReturn$1(Au,lo){if(lo&&(_typeof$8(lo)==="object"||typeof lo=="function"))return lo;if(lo!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized$1(Au)}function _assertThisInitialized$1(Au){if(Au===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return Au}function _inherits$1(Au,lo){if(typeof lo!="function"&&lo!==null)throw new TypeError("Super expression must either be null or a function");Au.prototype=Object.create(lo&&lo.prototype,{constructor:{value:Au,writable:!0,configurable:!0}}),Object.defineProperty(Au,"prototype",{writable:!1}),lo&&_setPrototypeOf$1(Au,lo)}function _wrapNativeSuper(Au){var lo=typeof Map=="function"?new Map:void 0;return _wrapNativeSuper=function(Ru){if(Ru===null||!_isNativeFunction(Ru))return Ru;if(typeof Ru!="function")throw new TypeError("Super expression must either be null or a function");if(typeof lo<"u"){if(lo.has(Ru))return lo.get(Ru);lo.set(Ru,Iu)}function Iu(){return _construct(Ru,arguments,_getPrototypeOf$1(this).constructor)}return Iu.prototype=Object.create(Ru.prototype,{constructor:{value:Iu,enumerable:!1,writable:!0,configurable:!0}}),_setPrototypeOf$1(Iu,Ru)},_wrapNativeSuper(Au)}function _construct(Au,lo,$u){if(_isNativeReflectConstruct$1())return Reflect.construct.apply(null,arguments);var Ru=[null];Ru.push.apply(Ru,lo);var Iu=new(Au.bind.apply(Au,Ru));return $u&&_setPrototypeOf$1(Iu,$u.prototype),Iu}function _isNativeReflectConstruct$1(){try{var Au=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(_isNativeReflectConstruct$1=function(){return!!Au})()}function _isNativeFunction(Au){try{return Function.toString.call(Au).indexOf("[native code]")!==-1}catch{return typeof Au=="function"}}function _setPrototypeOf$1(Au,lo){return _setPrototypeOf$1=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(Ru,Iu){return Ru.__proto__=Iu,Ru},_setPrototypeOf$1(Au,lo)}function _getPrototypeOf$1(Au){return _getPrototypeOf$1=Object.setPrototypeOf?Object.getPrototypeOf.bind():function($u){return $u.__proto__||Object.getPrototypeOf($u)},_getPrototypeOf$1(Au)}var DetailedError=(function(Au){function lo($u){var Ru,Iu=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,Pu=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,Ou=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null;if(_classCallCheck$8(this,lo),Ru=_callSuper$1(this,lo,[$u]),Ru.originalRequest=Pu,Ru.originalResponse=Ou,Ru.causingError=Iu,Iu!=null&&($u+=", caused by ".concat(Iu.toString())),Pu!=null){var Mu=Pu.getHeader("X-Request-ID")||"n/a",Du=Pu.getMethod(),Lu=Pu.getURL(),Bu=Ou?Ou.getStatus():"n/a",ju=Ou?Ou.getBody()||"":"n/a";$u+=", originated from request (method: ".concat(Du,", url: ").concat(Lu,", response code: ").concat(Bu,", response text: ").concat(ju,", request id: ").concat(Mu,")")}return Ru.message=$u,Ru}return _inherits$1(lo,Au),_createClass$8(lo)})(_wrapNativeSuper(Error));function log(Au){}function _typeof$7(Au){"@babel/helpers - typeof";return _typeof$7=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$7(Au)}function _classCallCheck$7(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$7(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$7(Ru.key),Ru)}}function _createClass$7(Au,lo,$u){return lo&&_defineProperties$7(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$7(Au){var lo=_toPrimitive$7(Au,"string");return _typeof$7(lo)=="symbol"?lo:lo+""}function _toPrimitive$7(Au,lo){if(_typeof$7(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$7(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var NoopUrlStorage=(function(){function Au(){_classCallCheck$7(this,Au)}return _createClass$7(Au,[{key:"listAllUploads",value:function(){return Promise.resolve([])}},{key:"findUploadsByFingerprint",value:function($u){return Promise.resolve([])}},{key:"removeUpload",value:function($u){return Promise.resolve()}},{key:"addUpload",value:function($u,Ru){return Promise.resolve(null)}}])})();const version$1="3.9.5",VERSION=version$1,_TD=typeof TextDecoder=="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,_TE=typeof TextEncoder=="function"?new TextEncoder:void 0,b64ch="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",b64chs=Array.prototype.slice.call(b64ch),b64tab=(Au=>{let lo={};return Au.forEach(($u,Ru)=>lo[$u]=Ru),lo})(b64chs),b64re=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,_fromCC=String.fromCharCode.bind(String),_U8Afrom=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):Au=>new Uint8Array(Array.prototype.slice.call(Au,0)),_mkUriSafe=Au=>Au.replace(/=/g,"").replace(/[+\/]/g,lo=>lo=="+"?"-":"_"),_tidyB64=Au=>Au.replace(/[^A-Za-z0-9\+\/]/g,""),btoaPolyfill=Au=>{let lo,$u,Ru,Iu,Pu="";const Ou=Au.length%3;for(let Mu=0;Mu<Au.length;){if(($u=Au.charCodeAt(Mu++))>255||(Ru=Au.charCodeAt(Mu++))>255||(Iu=Au.charCodeAt(Mu++))>255)throw new TypeError("invalid character found");lo=$u<<16|Ru<<8|Iu,Pu+=b64chs[lo>>18&63]+b64chs[lo>>12&63]+b64chs[lo>>6&63]+b64chs[lo&63]}return Ou?Pu.slice(0,Ou-3)+"===".substring(Ou):Pu},_btoa=typeof btoa=="function"?Au=>btoa(Au):btoaPolyfill,_fromUint8Array=typeof Uint8Array.prototype.toBase64=="function"?Function.prototype.call.bind(Uint8Array.prototype.toBase64):Au=>{let $u=[];for(let Ru=0,Iu=Au.length;Ru<Iu;Ru+=4096)$u.push(_fromCC.apply(null,Au.subarray(Ru,Ru+4096)));return _btoa($u.join(""))},fromUint8Array=(Au,lo=!1)=>lo?_mkUriSafe(_fromUint8Array(Au)):_fromUint8Array(Au),cb_utob=Au=>{if(Au.length<2){var lo=Au.charCodeAt(0);return lo<128?Au:lo<2048?_fromCC(192|lo>>>6)+_fromCC(128|lo&63):_fromCC(224|lo>>>12&15)+_fromCC(128|lo>>>6&63)+_fromCC(128|lo&63)}else{var lo=65536+(Au.charCodeAt(0)-55296)*1024+(Au.charCodeAt(1)-56320);return _fromCC(240|lo>>>18&7)+_fromCC(128|lo>>>12&63)+_fromCC(128|lo>>>6&63)+_fromCC(128|lo&63)}},re_utob=/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\x00-\x7F]/g,utob=Au=>Au.replace(re_utob,cb_utob),_encode=_TE?Au=>_fromUint8Array(_TE.encode(Au)):Au=>_btoa(utob(Au)),encode$3=(Au,lo=!1)=>lo?_mkUriSafe(_encode(Au)):_encode(Au),encodeURI$1=Au=>encode$3(Au,!0),re_btou=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,cb_btou=Au=>{switch(Au.length){case 4:var lo=(7&Au.charCodeAt(0))<<18|(63&Au.charCodeAt(1))<<12|(63&Au.charCodeAt(2))<<6|63&Au.charCodeAt(3),$u=lo-65536;return _fromCC(($u>>>10)+55296)+_fromCC(($u&1023)+56320);case 3:return _fromCC((15&Au.charCodeAt(0))<<12|(63&Au.charCodeAt(1))<<6|63&Au.charCodeAt(2));default:return _fromCC((31&Au.charCodeAt(0))<<6|63&Au.charCodeAt(1))}},btou=Au=>Au.replace(re_btou,cb_btou),atobPolyfill=Au=>{if(Au=Au.replace(/\s+/g,""),!b64re.test(Au))throw new TypeError("malformed base64.");Au+="==".slice(2-(Au.length&3));let lo,$u,Ru,Iu=[];for(let Pu=0;Pu<Au.length;)lo=b64tab[Au.charAt(Pu++)]<<18|b64tab[Au.charAt(Pu++)]<<12|($u=b64tab[Au.charAt(Pu++)])<<6|(Ru=b64tab[Au.charAt(Pu++)]),$u===64?Iu.push(_fromCC(lo>>16&255)):Ru===64?Iu.push(_fromCC(lo>>16&255,lo>>8&255)):Iu.push(_fromCC(lo>>16&255,lo>>8&255,lo&255));return Iu.join("")},_atob=typeof atob=="function"?Au=>atob(_tidyB64(Au)):atobPolyfill,_toUint8Array=typeof Uint8Array.fromBase64=="function"?Au=>Uint8Array.fromBase64(Au):Au=>_U8Afrom(_atob(Au).split("").map(lo=>lo.charCodeAt(0))),toUint8Array=Au=>_toUint8Array(_unURI(Au)),_decode=_TD?Au=>_TD.decode(_toUint8Array(Au)):Au=>btou(_atob(Au)),_unURI=Au=>_tidyB64(Au.replace(/[-_]/g,lo=>lo=="-"?"+":"/")),decode$3=Au=>_decode(_unURI(Au)),isValid$1=Au=>{if(typeof Au!="string")return!1;const lo=Au.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(lo)||!/[^\s0-9a-zA-Z\-_]/.test(lo)},_noEnum=Au=>({value:Au,enumerable:!1,writable:!0,configurable:!0}),extendString=function(){const Au=(lo,$u)=>Object.defineProperty(String.prototype,lo,_noEnum($u));Au("fromBase64",function(){return decode$3(this)}),Au("toBase64",function(lo){return encode$3(this,lo)}),Au("toBase64URI",function(){return encode$3(this,!0)}),Au("toBase64URL",function(){return encode$3(this,!0)}),Au("toUint8Array",function(){return toUint8Array(this)})},extendUint8Array=function(){const Au=(lo,$u)=>Object.defineProperty(Uint8Array.prototype,lo,_noEnum($u));Au("toBase64",function(lo){return fromUint8Array(this,lo)}),Au("toBase64URI",function(){return fromUint8Array(this,!0)}),Au("toBase64URL",function(){return fromUint8Array(this,!0)})},extendBuiltins=()=>{extendString(),extendUint8Array()},gBase64={version:version$1,VERSION,atob:_atob,atobPolyfill,btoa:_btoa,btoaPolyfill,fromBase64:decode$3,toBase64:encode$3,encode:encode$3,encodeURI:encodeURI$1,encodeURL:encodeURI$1,utob,btou,decode:decode$3,isValid:isValid$1,fromUint8Array,toUint8Array,extendString,extendUint8Array,extendBuiltins};var urlParseExports=requireUrlParse();const URL$1=getDefaultExportFromCjs(urlParseExports);function uuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(Au){var lo=Math.random()*16|0,$u=Au==="x"?lo:lo&3|8;return $u.toString(16)})}function _regeneratorRuntime$1(){_regeneratorRuntime$1=function(){return lo};var Au,lo={},$u=Object.prototype,Ru=$u.hasOwnProperty,Iu=Object.defineProperty||function(_d,bd,wd){_d[bd]=wd.value},Pu=typeof Symbol=="function"?Symbol:{},Ou=Pu.iterator||"@@iterator",Mu=Pu.asyncIterator||"@@asyncIterator",Du=Pu.toStringTag||"@@toStringTag";function Lu(_d,bd,wd){return Object.defineProperty(_d,bd,{value:wd,enumerable:!0,configurable:!0,writable:!0}),_d[bd]}try{Lu({},"")}catch{Lu=function(wd,Ad,gd){return wd[Ad]=gd}}function Bu(_d,bd,wd,Ad){var gd=bd&&bd.prototype instanceof Gu?bd:Gu,dd=Object.create(gd.prototype),yd=new vd(Ad||[]);return Iu(dd,"_invoke",{value:od(_d,wd,yd)}),dd}function ju(_d,bd,wd){try{return{type:"normal",arg:_d.call(bd,wd)}}catch(Ad){return{type:"throw",arg:Ad}}}lo.wrap=Bu;var Fu="suspendedStart",zu="suspendedYield",Uu="executing",Hu="completed",Vu={};function Gu(){}function Wu(){}function Zu(){}var Ju={};Lu(Ju,Ou,function(){return this});var Yu=Object.getPrototypeOf,Xu=Yu&&Yu(Yu(Sd([])));Xu&&Xu!==$u&&Ru.call(Xu,Ou)&&(Ju=Xu);var ed=Zu.prototype=Gu.prototype=Object.create(Ju);function td(_d){["next","throw","return"].forEach(function(bd){Lu(_d,bd,function(wd){return this._invoke(bd,wd)})})}function nd(_d,bd){function wd(gd,dd,yd,ld){var ud=ju(_d[gd],_d,dd);if(ud.type!=="throw"){var hd=ud.arg,md=hd.value;return md&&_typeof$6(md)=="object"&&Ru.call(md,"__await")?bd.resolve(md.__await).then(function(Ed){wd("next",Ed,yd,ld)},function(Ed){wd("throw",Ed,yd,ld)}):bd.resolve(md).then(function(Ed){hd.value=Ed,yd(hd)},function(Ed){return wd("throw",Ed,yd,ld)})}ld(ud.arg)}var Ad;Iu(this,"_invoke",{value:function(dd,yd){function ld(){return new bd(function(ud,hd){wd(dd,yd,ud,hd)})}return Ad=Ad?Ad.then(ld,ld):ld()}})}function od(_d,bd,wd){var Ad=Fu;return function(gd,dd){if(Ad===Uu)throw Error("Generator is already running");if(Ad===Hu){if(gd==="throw")throw dd;return{value:Au,done:!0}}for(wd.method=gd,wd.arg=dd;;){var yd=wd.delegate;if(yd){var ld=sd(yd,wd);if(ld){if(ld===Vu)continue;return ld}}if(wd.method==="next")wd.sent=wd._sent=wd.arg;else if(wd.method==="throw"){if(Ad===Fu)throw Ad=Hu,wd.arg;wd.dispatchException(wd.arg)}else wd.method==="return"&&wd.abrupt("return",wd.arg);Ad=Uu;var ud=ju(_d,bd,wd);if(ud.type==="normal"){if(Ad=wd.done?Hu:zu,ud.arg===Vu)continue;return{value:ud.arg,done:wd.done}}ud.type==="throw"&&(Ad=Hu,wd.method="throw",wd.arg=ud.arg)}}}function sd(_d,bd){var wd=bd.method,Ad=_d.iterator[wd];if(Ad===Au)return bd.delegate=null,wd==="throw"&&_d.iterator.return&&(bd.method="return",bd.arg=Au,sd(_d,bd),bd.method==="throw")||wd!=="return"&&(bd.method="throw",bd.arg=new TypeError("The iterator does not provide a '"+wd+"' method")),Vu;var gd=ju(Ad,_d.iterator,bd.arg);if(gd.type==="throw")return bd.method="throw",bd.arg=gd.arg,bd.delegate=null,Vu;var dd=gd.arg;return dd?dd.done?(bd[_d.resultName]=dd.value,bd.next=_d.nextLoc,bd.method!=="return"&&(bd.method="next",bd.arg=Au),bd.delegate=null,Vu):dd:(bd.method="throw",bd.arg=new TypeError("iterator result is not an object"),bd.delegate=null,Vu)}function ad(_d){var bd={tryLoc:_d[0]};1 in _d&&(bd.catchLoc=_d[1]),2 in _d&&(bd.finallyLoc=_d[2],bd.afterLoc=_d[3]),this.tryEntries.push(bd)}function pd(_d){var bd=_d.completion||{};bd.type="normal",delete bd.arg,_d.completion=bd}function vd(_d){this.tryEntries=[{tryLoc:"root"}],_d.forEach(ad,this),this.reset(!0)}function Sd(_d){if(_d||_d===""){var bd=_d[Ou];if(bd)return bd.call(_d);if(typeof _d.next=="function")return _d;if(!isNaN(_d.length)){var wd=-1,Ad=function gd(){for(;++wd<_d.length;)if(Ru.call(_d,wd))return gd.value=_d[wd],gd.done=!1,gd;return gd.value=Au,gd.done=!0,gd};return Ad.next=Ad}}throw new TypeError(_typeof$6(_d)+" is not iterable")}return Wu.prototype=Zu,Iu(ed,"constructor",{value:Zu,configurable:!0}),Iu(Zu,"constructor",{value:Wu,configurable:!0}),Wu.displayName=Lu(Zu,Du,"GeneratorFunction"),lo.isGeneratorFunction=function(_d){var bd=typeof _d=="function"&&_d.constructor;return!!bd&&(bd===Wu||(bd.displayName||bd.name)==="GeneratorFunction")},lo.mark=function(_d){return Object.setPrototypeOf?Object.setPrototypeOf(_d,Zu):(_d.__proto__=Zu,Lu(_d,Du,"GeneratorFunction")),_d.prototype=Object.create(ed),_d},lo.awrap=function(_d){return{__await:_d}},td(nd.prototype),Lu(nd.prototype,Mu,function(){return this}),lo.AsyncIterator=nd,lo.async=function(_d,bd,wd,Ad,gd){gd===void 0&&(gd=Promise);var dd=new nd(Bu(_d,bd,wd,Ad),gd);return lo.isGeneratorFunction(bd)?dd:dd.next().then(function(yd){return yd.done?yd.value:dd.next()})},td(ed),Lu(ed,Du,"Generator"),Lu(ed,Ou,function(){return this}),Lu(ed,"toString",function(){return"[object Generator]"}),lo.keys=function(_d){var bd=Object(_d),wd=[];for(var Ad in bd)wd.push(Ad);return wd.reverse(),function gd(){for(;wd.length;){var dd=wd.pop();if(dd in bd)return gd.value=dd,gd.done=!1,gd}return gd.done=!0,gd}},lo.values=Sd,vd.prototype={constructor:vd,reset:function(bd){if(this.prev=0,this.next=0,this.sent=this._sent=Au,this.done=!1,this.delegate=null,this.method="next",this.arg=Au,this.tryEntries.forEach(pd),!bd)for(var wd in this)wd.charAt(0)==="t"&&Ru.call(this,wd)&&!isNaN(+wd.slice(1))&&(this[wd]=Au)},stop:function(){this.done=!0;var bd=this.tryEntries[0].completion;if(bd.type==="throw")throw bd.arg;return this.rval},dispatchException:function(bd){if(this.done)throw bd;var wd=this;function Ad(hd,md){return yd.type="throw",yd.arg=bd,wd.next=hd,md&&(wd.method="next",wd.arg=Au),!!md}for(var gd=this.tryEntries.length-1;gd>=0;--gd){var dd=this.tryEntries[gd],yd=dd.completion;if(dd.tryLoc==="root")return Ad("end");if(dd.tryLoc<=this.prev){var ld=Ru.call(dd,"catchLoc"),ud=Ru.call(dd,"finallyLoc");if(ld&&ud){if(this.prev<dd.catchLoc)return Ad(dd.catchLoc,!0);if(this.prev<dd.finallyLoc)return Ad(dd.finallyLoc)}else if(ld){if(this.prev<dd.catchLoc)return Ad(dd.catchLoc,!0)}else{if(!ud)throw Error("try statement without catch or finally");if(this.prev<dd.finallyLoc)return Ad(dd.finallyLoc)}}}},abrupt:function(bd,wd){for(var Ad=this.tryEntries.length-1;Ad>=0;--Ad){var gd=this.tryEntries[Ad];if(gd.tryLoc<=this.prev&&Ru.call(gd,"finallyLoc")&&this.prev<gd.finallyLoc){var dd=gd;break}}dd&&(bd==="break"||bd==="continue")&&dd.tryLoc<=wd&&wd<=dd.finallyLoc&&(dd=null);var yd=dd?dd.completion:{};return yd.type=bd,yd.arg=wd,dd?(this.method="next",this.next=dd.finallyLoc,Vu):this.complete(yd)},complete:function(bd,wd){if(bd.type==="throw")throw bd.arg;return bd.type==="break"||bd.type==="continue"?this.next=bd.arg:bd.type==="return"?(this.rval=this.arg=bd.arg,this.method="return",this.next="end"):bd.type==="normal"&&wd&&(this.next=wd),Vu},finish:function(bd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ad=this.tryEntries[wd];if(Ad.finallyLoc===bd)return this.complete(Ad.completion,Ad.afterLoc),pd(Ad),Vu}},catch:function(bd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ad=this.tryEntries[wd];if(Ad.tryLoc===bd){var gd=Ad.completion;if(gd.type==="throw"){var dd=gd.arg;pd(Ad)}return dd}}throw Error("illegal catch attempt")},delegateYield:function(bd,wd,Ad){return this.delegate={iterator:Sd(bd),resultName:wd,nextLoc:Ad},this.method==="next"&&(this.arg=Au),Vu}},lo}function asyncGeneratorStep$1(Au,lo,$u,Ru,Iu,Pu,Ou){try{var Mu=Au[Pu](Ou),Du=Mu.value}catch(Lu){$u(Lu);return}Mu.done?lo(Du):Promise.resolve(Du).then(Ru,Iu)}function _asyncToGenerator$1(Au){return function(){var lo=this,$u=arguments;return new Promise(function(Ru,Iu){var Pu=Au.apply(lo,$u);function Ou(Du){asyncGeneratorStep$1(Pu,Ru,Iu,Ou,Mu,"next",Du)}function Mu(Du){asyncGeneratorStep$1(Pu,Ru,Iu,Ou,Mu,"throw",Du)}Ou(void 0)})}}function _slicedToArray$1(Au,lo){return _arrayWithHoles$1(Au)||_iterableToArrayLimit$1(Au,lo)||_unsupportedIterableToArray$1(Au,lo)||_nonIterableRest$1()}function _nonIterableRest$1(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
2421
2421
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _iterableToArrayLimit$1(Au,lo){var $u=Au==null?null:typeof Symbol<"u"&&Au[Symbol.iterator]||Au["@@iterator"];if($u!=null){var Ru,Iu,Pu,Ou,Mu=[],Du=!0,Lu=!1;try{if(Pu=($u=$u.call(Au)).next,lo!==0)for(;!(Du=(Ru=Pu.call($u)).done)&&(Mu.push(Ru.value),Mu.length!==lo);Du=!0);}catch(Bu){Lu=!0,Iu=Bu}finally{try{if(!Du&&$u.return!=null&&(Ou=$u.return(),Object(Ou)!==Ou))return}finally{if(Lu)throw Iu}}return Mu}}function _arrayWithHoles$1(Au){if(Array.isArray(Au))return Au}function _typeof$6(Au){"@babel/helpers - typeof";return _typeof$6=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$6(Au)}function _createForOfIteratorHelper(Au,lo){var $u=typeof Symbol<"u"&&Au[Symbol.iterator]||Au["@@iterator"];if(!$u){if(Array.isArray(Au)||($u=_unsupportedIterableToArray$1(Au))||lo){$u&&(Au=$u);var Ru=0,Iu=function(){};return{s:Iu,n:function(){return Ru>=Au.length?{done:!0}:{done:!1,value:Au[Ru++]}},e:function(Lu){throw Lu},f:Iu}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
2422
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var Pu=!0,Ou=!1,Mu;return{s:function(){$u=$u.call(Au)},n:function(){var Lu=$u.next();return Pu=Lu.done,Lu},e:function(Lu){Ou=!0,Mu=Lu},f:function(){try{!Pu&&$u.return!=null&&$u.return()}finally{if(Ou)throw Mu}}}}function _unsupportedIterableToArray$1(Au,lo){if(Au){if(typeof Au=="string")return _arrayLikeToArray$1(Au,lo);var $u=Object.prototype.toString.call(Au).slice(8,-1);if($u==="Object"&&Au.constructor&&($u=Au.constructor.name),$u==="Map"||$u==="Set")return Array.from(Au);if($u==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test($u))return _arrayLikeToArray$1(Au,lo)}}function _arrayLikeToArray$1(Au,lo){(lo==null||lo>Au.length)&&(lo=Au.length);for(var $u=0,Ru=new Array(lo);$u<lo;$u++)Ru[$u]=Au[$u];return Ru}function ownKeys$1(Au,lo){var $u=Object.keys(Au);if(Object.getOwnPropertySymbols){var Ru=Object.getOwnPropertySymbols(Au);lo&&(Ru=Ru.filter(function(Iu){return Object.getOwnPropertyDescriptor(Au,Iu).enumerable})),$u.push.apply($u,Ru)}return $u}function _objectSpread$1(Au){for(var lo=1;lo<arguments.length;lo++){var $u=arguments[lo]!=null?arguments[lo]:{};lo%2?ownKeys$1(Object($u),!0).forEach(function(Ru){_defineProperty$1(Au,Ru,$u[Ru])}):Object.getOwnPropertyDescriptors?Object.defineProperties(Au,Object.getOwnPropertyDescriptors($u)):ownKeys$1(Object($u)).forEach(function(Ru){Object.defineProperty(Au,Ru,Object.getOwnPropertyDescriptor($u,Ru))})}return Au}function _defineProperty$1(Au,lo,$u){return lo=_toPropertyKey$6(lo),lo in Au?Object.defineProperty(Au,lo,{value:$u,enumerable:!0,configurable:!0,writable:!0}):Au[lo]=$u,Au}function _classCallCheck$6(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$6(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$6(Ru.key),Ru)}}function _createClass$6(Au,lo,$u){return lo&&_defineProperties$6(Au.prototype,lo),$u&&_defineProperties$6(Au,$u),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$6(Au){var lo=_toPrimitive$6(Au,"string");return _typeof$6(lo)=="symbol"?lo:lo+""}function _toPrimitive$6(Au,lo){if(_typeof$6(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$6(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var PROTOCOL_TUS_V1="tus-v1",PROTOCOL_IETF_DRAFT_03="ietf-draft-03",PROTOCOL_IETF_DRAFT_05="ietf-draft-05",defaultOptions$2={endpoint:null,uploadUrl:null,metadata:{},metadataForPartialUploads:{},fingerprint:null,uploadSize:null,onProgress:null,onChunkComplete:null,onSuccess:null,onError:null,onUploadUrlAvailable:null,overridePatchMethod:!1,headers:{},addRequestId:!1,onBeforeRequest:null,onAfterResponse:null,onShouldRetry:defaultOnShouldRetry,chunkSize:Number.POSITIVE_INFINITY,retryDelays:[0,1e3,3e3,5e3],parallelUploads:1,parallelUploadBoundaries:null,storeFingerprintForResuming:!0,removeFingerprintOnSuccess:!1,uploadLengthDeferred:!1,uploadDataDuringCreation:!1,urlStorage:null,fileReader:null,httpStack:null,protocol:PROTOCOL_TUS_V1},BaseUpload=(function(){function Au(lo,$u){_classCallCheck$6(this,Au),"resume"in $u&&console.log("tus: The `resume` option has been removed in tus-js-client v2. Please use the URL storage API instead."),this.options=$u,this.options.chunkSize=Number(this.options.chunkSize),this._urlStorage=this.options.urlStorage,this.file=lo,this.url=null,this._req=null,this._fingerprint=null,this._urlStorageKey=null,this._offset=null,this._aborted=!1,this._size=null,this._source=null,this._retryAttempt=0,this._retryTimeout=null,this._offsetBeforeRetry=0,this._parallelUploads=null,this._parallelUploadUrls=null}return _createClass$6(Au,[{key:"findPreviousUploads",value:function(){var $u=this;return this.options.fingerprint(this.file,this.options).then(function(Ru){return $u._urlStorage.findUploadsByFingerprint(Ru)})}},{key:"resumeFromPreviousUpload",value:function($u){this.url=$u.uploadUrl||null,this._parallelUploadUrls=$u.parallelUploadUrls||null,this._urlStorageKey=$u.urlStorageKey}},{key:"start",value:function(){var $u=this,Ru=this.file;if(!Ru){this._emitError(new Error("tus: no file or stream to upload provided"));return}if(![PROTOCOL_TUS_V1,PROTOCOL_IETF_DRAFT_03,PROTOCOL_IETF_DRAFT_05].includes(this.options.protocol)){this._emitError(new Error("tus: unsupported protocol ".concat(this.options.protocol)));return}if(!this.options.endpoint&&!this.options.uploadUrl&&!this.url){this._emitError(new Error("tus: neither an endpoint or an upload URL is provided"));return}var Iu=this.options.retryDelays;if(Iu!=null&&Object.prototype.toString.call(Iu)!=="[object Array]"){this._emitError(new Error("tus: the `retryDelays` option must either be an array or null"));return}if(this.options.parallelUploads>1)for(var Pu=0,Ou=["uploadUrl","uploadSize","uploadLengthDeferred"];Pu<Ou.length;Pu++){var Mu=Ou[Pu];if(this.options[Mu]){this._emitError(new Error("tus: cannot use the ".concat(Mu," option when parallelUploads is enabled")));return}}if(this.options.parallelUploadBoundaries){if(this.options.parallelUploads<=1){this._emitError(new Error("tus: cannot use the `parallelUploadBoundaries` option when `parallelUploads` is disabled"));return}if(this.options.parallelUploads!==this.options.parallelUploadBoundaries.length){this._emitError(new Error("tus: the `parallelUploadBoundaries` must have the same length as the value of `parallelUploads`"));return}}this.options.fingerprint(Ru,this.options).then(function(Du){return $u._fingerprint=Du,$u._source?$u._source:$u.options.fileReader.openFile(Ru,$u.options.chunkSize)}).then(function(Du){if($u._source=Du,$u.options.uploadLengthDeferred)$u._size=null;else if($u.options.uploadSize!=null){if($u._size=Number($u.options.uploadSize),Number.isNaN($u._size)){$u._emitError(new Error("tus: cannot convert `uploadSize` option into a number"));return}}else if($u._size=$u._source.size,$u._size==null){$u._emitError(new Error("tus: cannot automatically derive upload's size from input. Specify it manually using the `uploadSize` option or use the `uploadLengthDeferred` option"));return}$u.options.parallelUploads>1||$u._parallelUploadUrls!=null?$u._startParallelUpload():$u._startSingleUpload()}).catch(function(Du){$u._emitError(Du)})}},{key:"_startParallelUpload",value:function(){var $u,Ru=this,Iu=this._size,Pu=0;this._parallelUploads=[];var Ou=this._parallelUploadUrls!=null?this._parallelUploadUrls.length:this.options.parallelUploads,Mu=($u=this.options.parallelUploadBoundaries)!==null&&$u!==void 0?$u:splitSizeIntoParts(this._source.size,Ou);this._parallelUploadUrls&&Mu.forEach(function(Bu,ju){Bu.uploadUrl=Ru._parallelUploadUrls[ju]||null}),this._parallelUploadUrls=new Array(Mu.length);var Du=Mu.map(function(Bu,ju){var Fu=0;return Ru._source.slice(Bu.start,Bu.end).then(function(zu){var Uu=zu.value;return new Promise(function(Hu,Vu){var Gu=_objectSpread$1(_objectSpread$1({},Ru.options),{},{uploadUrl:Bu.uploadUrl||null,storeFingerprintForResuming:!1,removeFingerprintOnSuccess:!1,parallelUploads:1,parallelUploadBoundaries:null,metadata:Ru.options.metadataForPartialUploads,headers:_objectSpread$1(_objectSpread$1({},Ru.options.headers),{},{"Upload-Concat":"partial"}),onSuccess:Hu,onError:Vu,onProgress:function(Ju){Pu=Pu-Fu+Ju,Fu=Ju,Ru._emitProgress(Pu,Iu)},onUploadUrlAvailable:function(){Ru._parallelUploadUrls[ju]=Wu.url,Ru._parallelUploadUrls.filter(function(Ju){return!!Ju}).length===Mu.length&&Ru._saveUploadInUrlStorage()}}),Wu=new Au(Uu,Gu);Wu.start(),Ru._parallelUploads.push(Wu)})})}),Lu;Promise.all(Du).then(function(){Lu=Ru._openRequest("POST",Ru.options.endpoint),Lu.setHeader("Upload-Concat","final;".concat(Ru._parallelUploadUrls.join(" ")));var Bu=encodeMetadata(Ru.options.metadata);return Bu!==""&&Lu.setHeader("Upload-Metadata",Bu),Ru._sendRequest(Lu,null)}).then(function(Bu){if(!inStatusCategory(Bu.getStatus(),200)){Ru._emitHttpError(Lu,Bu,"tus: unexpected response while creating upload");return}var ju=Bu.getHeader("Location");if(ju==null){Ru._emitHttpError(Lu,Bu,"tus: invalid or missing Location header");return}Ru.url=resolveUrl(Ru.options.endpoint,ju),"Created upload at ".concat(Ru.url),Ru._emitSuccess(Bu)}).catch(function(Bu){Ru._emitError(Bu)})}},{key:"_startSingleUpload",value:function(){if(this._aborted=!1,this.url!=null){"Resuming upload from previous URL: ".concat(this.url),this._resumeUpload();return}if(this.options.uploadUrl!=null){"Resuming upload from provided URL: ".concat(this.options.uploadUrl),this.url=this.options.uploadUrl,this._resumeUpload();return}this._createUpload()}},{key:"abort",value:function($u){var Ru=this;if(this._parallelUploads!=null){var Iu=_createForOfIteratorHelper(this._parallelUploads),Pu;try{for(Iu.s();!(Pu=Iu.n()).done;){var Ou=Pu.value;Ou.abort($u)}}catch(Mu){Iu.e(Mu)}finally{Iu.f()}}return this._req!==null&&this._req.abort(),this._aborted=!0,this._retryTimeout!=null&&(clearTimeout(this._retryTimeout),this._retryTimeout=null),!$u||this.url==null?Promise.resolve():Au.terminate(this.url,this.options).then(function(){return Ru._removeFromUrlStorage()})}},{key:"_emitHttpError",value:function($u,Ru,Iu,Pu){this._emitError(new DetailedError(Iu,Pu,$u,Ru))}},{key:"_emitError",value:function($u){var Ru=this;if(!this._aborted){if(this.options.retryDelays!=null){var Iu=this._offset!=null&&this._offset>this._offsetBeforeRetry;if(Iu&&(this._retryAttempt=0),shouldRetry($u,this._retryAttempt,this.options)){var Pu=this.options.retryDelays[this._retryAttempt++];this._offsetBeforeRetry=this._offset,this._retryTimeout=setTimeout(function(){Ru.start()},Pu);return}}if(typeof this.options.onError=="function")this.options.onError($u);else throw $u}}},{key:"_emitSuccess",value:function($u){this.options.removeFingerprintOnSuccess&&this._removeFromUrlStorage(),typeof this.options.onSuccess=="function"&&this.options.onSuccess({lastResponse:$u})}},{key:"_emitProgress",value:function($u,Ru){typeof this.options.onProgress=="function"&&this.options.onProgress($u,Ru)}},{key:"_emitChunkComplete",value:function($u,Ru,Iu){typeof this.options.onChunkComplete=="function"&&this.options.onChunkComplete($u,Ru,Iu)}},{key:"_createUpload",value:function(){var $u=this;if(!this.options.endpoint){this._emitError(new Error("tus: unable to create upload because no endpoint is provided"));return}var Ru=this._openRequest("POST",this.options.endpoint);this.options.uploadLengthDeferred?Ru.setHeader("Upload-Defer-Length","1"):Ru.setHeader("Upload-Length","".concat(this._size));var Iu=encodeMetadata(this.options.metadata);Iu!==""&&Ru.setHeader("Upload-Metadata",Iu);var Pu;this.options.uploadDataDuringCreation&&!this.options.uploadLengthDeferred?(this._offset=0,Pu=this._addChunkToRequest(Ru)):((this.options.protocol===PROTOCOL_IETF_DRAFT_03||this.options.protocol===PROTOCOL_IETF_DRAFT_05)&&Ru.setHeader("Upload-Complete","?0"),Pu=this._sendRequest(Ru,null)),Pu.then(function(Ou){if(!inStatusCategory(Ou.getStatus(),200)){$u._emitHttpError(Ru,Ou,"tus: unexpected response while creating upload");return}var Mu=Ou.getHeader("Location");if(Mu==null){$u._emitHttpError(Ru,Ou,"tus: invalid or missing Location header");return}if($u.url=resolveUrl($u.options.endpoint,Mu),"Created upload at ".concat($u.url),typeof $u.options.onUploadUrlAvailable=="function"&&$u.options.onUploadUrlAvailable(),$u._size===0){$u._emitSuccess(Ou),$u._source.close();return}$u._saveUploadInUrlStorage().then(function(){$u.options.uploadDataDuringCreation?$u._handleUploadResponse(Ru,Ou):($u._offset=0,$u._performUpload())})}).catch(function(Ou){$u._emitHttpError(Ru,null,"tus: failed to create upload",Ou)})}},{key:"_resumeUpload",value:function(){var $u=this,Ru=this._openRequest("HEAD",this.url),Iu=this._sendRequest(Ru,null);Iu.then(function(Pu){var Ou=Pu.getStatus();if(!inStatusCategory(Ou,200)){if(Ou===423){$u._emitHttpError(Ru,Pu,"tus: upload is currently locked; retry later");return}if(inStatusCategory(Ou,400)&&$u._removeFromUrlStorage(),!$u.options.endpoint){$u._emitHttpError(Ru,Pu,"tus: unable to resume upload (new upload cannot be created without an endpoint)");return}$u.url=null,$u._createUpload();return}var Mu=Number.parseInt(Pu.getHeader("Upload-Offset"),10);if(Number.isNaN(Mu)){$u._emitHttpError(Ru,Pu,"tus: invalid or missing offset value");return}var Du=Number.parseInt(Pu.getHeader("Upload-Length"),10);if(Number.isNaN(Du)&&!$u.options.uploadLengthDeferred&&$u.options.protocol===PROTOCOL_TUS_V1){$u._emitHttpError(Ru,Pu,"tus: invalid or missing length value");return}typeof $u.options.onUploadUrlAvailable=="function"&&$u.options.onUploadUrlAvailable(),$u._saveUploadInUrlStorage().then(function(){if(Mu===Du){$u._emitProgress(Du,Du),$u._emitSuccess(Pu);return}$u._offset=Mu,$u._performUpload()})}).catch(function(Pu){$u._emitHttpError(Ru,null,"tus: failed to resume upload",Pu)})}},{key:"_performUpload",value:function(){var $u=this;if(!this._aborted){var Ru;this.options.overridePatchMethod?(Ru=this._openRequest("POST",this.url),Ru.setHeader("X-HTTP-Method-Override","PATCH")):Ru=this._openRequest("PATCH",this.url),Ru.setHeader("Upload-Offset","".concat(this._offset));var Iu=this._addChunkToRequest(Ru);Iu.then(function(Pu){if(!inStatusCategory(Pu.getStatus(),200)){$u._emitHttpError(Ru,Pu,"tus: unexpected response while uploading chunk");return}$u._handleUploadResponse(Ru,Pu)}).catch(function(Pu){$u._aborted||$u._emitHttpError(Ru,null,"tus: failed to upload chunk at offset ".concat($u._offset),Pu)})}}},{key:"_addChunkToRequest",value:function($u){var Ru=this,Iu=this._offset,Pu=this._offset+this.options.chunkSize;return $u.setProgressHandler(function(Ou){Ru._emitProgress(Iu+Ou,Ru._size)}),this.options.protocol===PROTOCOL_TUS_V1?$u.setHeader("Content-Type","application/offset+octet-stream"):this.options.protocol===PROTOCOL_IETF_DRAFT_05&&$u.setHeader("Content-Type","application/partial-upload"),(Pu===Number.POSITIVE_INFINITY||Pu>this._size)&&!this.options.uploadLengthDeferred&&(Pu=this._size),this._source.slice(Iu,Pu).then(function(Ou){var Mu=Ou.value,Du=Ou.done,Lu=Mu!=null&&Mu.size?Mu.size:0;Ru.options.uploadLengthDeferred&&Du&&(Ru._size=Ru._offset+Lu,$u.setHeader("Upload-Length","".concat(Ru._size)));var Bu=Ru._offset+Lu;return!Ru.options.uploadLengthDeferred&&Du&&Bu!==Ru._size?Promise.reject(new Error("upload was configured with a size of ".concat(Ru._size," bytes, but the source is done after ").concat(Bu," bytes"))):Mu===null?Ru._sendRequest($u):((Ru.options.protocol===PROTOCOL_IETF_DRAFT_03||Ru.options.protocol===PROTOCOL_IETF_DRAFT_05)&&$u.setHeader("Upload-Complete",Du?"?1":"?0"),Ru._emitProgress(Ru._offset,Ru._size),Ru._sendRequest($u,Mu))})}},{key:"_handleUploadResponse",value:function($u,Ru){var Iu=Number.parseInt(Ru.getHeader("Upload-Offset"),10);if(Number.isNaN(Iu)){this._emitHttpError($u,Ru,"tus: invalid or missing offset value");return}if(this._emitProgress(Iu,this._size),this._emitChunkComplete(Iu-this._offset,Iu,this._size),this._offset=Iu,Iu===this._size){this._emitSuccess(Ru),this._source.close();return}this._performUpload()}},{key:"_openRequest",value:function($u,Ru){var Iu=openRequest($u,Ru,this.options);return this._req=Iu,Iu}},{key:"_removeFromUrlStorage",value:function(){var $u=this;this._urlStorageKey&&(this._urlStorage.removeUpload(this._urlStorageKey).catch(function(Ru){$u._emitError(Ru)}),this._urlStorageKey=null)}},{key:"_saveUploadInUrlStorage",value:function(){var $u=this;if(!this.options.storeFingerprintForResuming||!this._fingerprint||this._urlStorageKey!==null)return Promise.resolve();var Ru={size:this._size,metadata:this.options.metadata,creationTime:new Date().toString()};return this._parallelUploads?Ru.parallelUploadUrls=this._parallelUploadUrls:Ru.uploadUrl=this.url,this._urlStorage.addUpload(this._fingerprint,Ru).then(function(Iu){$u._urlStorageKey=Iu})}},{key:"_sendRequest",value:function($u){var Ru=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;return sendRequest($u,Ru,this.options)}}],[{key:"terminate",value:function($u){var Ru=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Iu=openRequest("DELETE",$u,Ru);return sendRequest(Iu,null,Ru).then(function(Pu){if(Pu.getStatus()!==204)throw new DetailedError("tus: unexpected response while terminating upload",null,Iu,Pu)}).catch(function(Pu){if(Pu instanceof DetailedError||(Pu=new DetailedError("tus: failed to terminate upload",Pu,Iu,null)),!shouldRetry(Pu,0,Ru))throw Pu;var Ou=Ru.retryDelays[0],Mu=Ru.retryDelays.slice(1),Du=_objectSpread$1(_objectSpread$1({},Ru),{},{retryDelays:Mu});return new Promise(function(Lu){return setTimeout(Lu,Ou)}).then(function(){return Au.terminate($u,Du)})})}}])})();function encodeMetadata(Au){return Object.entries(Au).map(function(lo){var $u=_slicedToArray$1(lo,2),Ru=$u[0],Iu=$u[1];return"".concat(Ru," ").concat(gBase64.encode(String(Iu)))}).join(",")}function inStatusCategory(Au,lo){return Au>=lo&&Au<lo+100}function openRequest(Au,lo,$u){var Ru=$u.httpStack.createRequest(Au,lo);$u.protocol===PROTOCOL_IETF_DRAFT_03?Ru.setHeader("Upload-Draft-Interop-Version","5"):$u.protocol===PROTOCOL_IETF_DRAFT_05?Ru.setHeader("Upload-Draft-Interop-Version","6"):Ru.setHeader("Tus-Resumable","1.0.0");for(var Iu=$u.headers||{},Pu=0,Ou=Object.entries(Iu);Pu<Ou.length;Pu++){var Mu=_slicedToArray$1(Ou[Pu],2),Du=Mu[0],Lu=Mu[1];Ru.setHeader(Du,Lu)}if($u.addRequestId){var Bu=uuid();Ru.setHeader("X-Request-ID",Bu)}return Ru}function sendRequest(Au,lo,$u){return _sendRequest2.apply(this,arguments)}function _sendRequest2(){return _sendRequest2=_asyncToGenerator$1(_regeneratorRuntime$1().mark(function Au(lo,$u,Ru){var Iu;return _regeneratorRuntime$1().wrap(function(Ou){for(;;)switch(Ou.prev=Ou.next){case 0:if(typeof Ru.onBeforeRequest!="function"){Ou.next=3;break}return Ou.next=3,Ru.onBeforeRequest(lo);case 3:return Ou.next=5,lo.send($u);case 5:if(Iu=Ou.sent,typeof Ru.onAfterResponse!="function"){Ou.next=9;break}return Ou.next=9,Ru.onAfterResponse(lo,Iu);case 9:return Ou.abrupt("return",Iu);case 10:case"end":return Ou.stop()}},Au)})),_sendRequest2.apply(this,arguments)}function isOnline(){var Au=!0;return typeof navigator<"u"&&navigator.onLine===!1&&(Au=!1),Au}function shouldRetry(Au,lo,$u){return $u.retryDelays==null||lo>=$u.retryDelays.length||Au.originalRequest==null?!1:$u&&typeof $u.onShouldRetry=="function"?$u.onShouldRetry(Au,lo,$u):defaultOnShouldRetry(Au)}function defaultOnShouldRetry(Au){var lo=Au.originalResponse?Au.originalResponse.getStatus():0;return(!inStatusCategory(lo,400)||lo===409||lo===423)&&isOnline()}function resolveUrl(Au,lo){return new URL$1(lo,Au).toString()}function splitSizeIntoParts(Au,lo){for(var $u=Math.floor(Au/lo),Ru=[],Iu=0;Iu<lo;Iu++)Ru.push({start:$u*Iu,end:$u*(Iu+1)});return Ru[lo-1].end=Au,Ru}BaseUpload.defaultOptions=defaultOptions$2;var isReactNative=function Au(){return typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative"};function uriToBlob(Au){return new Promise(function(lo,$u){var Ru=new XMLHttpRequest;Ru.responseType="blob",Ru.onload=function(){var Iu=Ru.response;lo(Iu)},Ru.onerror=function(Iu){$u(Iu)},Ru.open("GET",Au),Ru.send()})}var isCordova=function Au(){return typeof window<"u"&&(typeof window.PhoneGap<"u"||typeof window.Cordova<"u"||typeof window.cordova<"u")};function readAsByteArray(Au){return new Promise(function(lo,$u){var Ru=new FileReader;Ru.onload=function(){var Iu=new Uint8Array(Ru.result);lo({value:Iu})},Ru.onerror=function(Iu){$u(Iu)},Ru.readAsArrayBuffer(Au)})}function _typeof$5(Au){"@babel/helpers - typeof";return _typeof$5=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$5(Au)}function _classCallCheck$5(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$5(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$5(Ru.key),Ru)}}function _createClass$5(Au,lo,$u){return lo&&_defineProperties$5(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$5(Au){var lo=_toPrimitive$5(Au,"string");return _typeof$5(lo)=="symbol"?lo:lo+""}function _toPrimitive$5(Au,lo){if(_typeof$5(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$5(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var FileSource=(function(){function Au(lo){_classCallCheck$5(this,Au),this._file=lo,this.size=lo.size}return _createClass$5(Au,[{key:"slice",value:function($u,Ru){if(isCordova())return readAsByteArray(this._file.slice($u,Ru));var Iu=this._file.slice($u,Ru),Pu=Ru>=this.size;return Promise.resolve({value:Iu,done:Pu})}},{key:"close",value:function(){}}])})();function _typeof$4(Au){"@babel/helpers - typeof";return _typeof$4=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$4(Au)}function _classCallCheck$4(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$4(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$4(Ru.key),Ru)}}function _createClass$4(Au,lo,$u){return lo&&_defineProperties$4(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$4(Au){var lo=_toPrimitive$4(Au,"string");return _typeof$4(lo)=="symbol"?lo:lo+""}function _toPrimitive$4(Au,lo){if(_typeof$4(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$4(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}function len(Au){return Au===void 0?0:Au.size!==void 0?Au.size:Au.length}function concat(Au,lo){if(Au.concat)return Au.concat(lo);if(Au instanceof Blob)return new Blob([Au,lo],{type:Au.type});if(Au.set){var $u=new Au.constructor(Au.length+lo.length);return $u.set(Au),$u.set(lo,Au.length),$u}throw new Error("Unknown data type")}var StreamSource=(function(){function Au(lo){_classCallCheck$4(this,Au),this._buffer=void 0,this._bufferOffset=0,this._reader=lo,this._done=!1}return _createClass$4(Au,[{key:"slice",value:function($u,Ru){return $u<this._bufferOffset?Promise.reject(new Error("Requested data is before the reader's current offset")):this._readUntilEnoughDataOrDone($u,Ru)}},{key:"_readUntilEnoughDataOrDone",value:function($u,Ru){var Iu=this,Pu=Ru<=this._bufferOffset+len(this._buffer);if(this._done||Pu){var Ou=this._getDataFromBuffer($u,Ru),Mu=Ou==null?this._done:!1;return Promise.resolve({value:Ou,done:Mu})}return this._reader.read().then(function(Du){var Lu=Du.value,Bu=Du.done;return Bu?Iu._done=!0:Iu._buffer===void 0?Iu._buffer=Lu:Iu._buffer=concat(Iu._buffer,Lu),Iu._readUntilEnoughDataOrDone($u,Ru)})}},{key:"_getDataFromBuffer",value:function($u,Ru){$u>this._bufferOffset&&(this._buffer=this._buffer.slice($u-this._bufferOffset),this._bufferOffset=$u);var Iu=len(this._buffer)===0;return this._done&&Iu?null:this._buffer.slice(0,Ru-$u)}},{key:"close",value:function(){this._reader.cancel&&this._reader.cancel()}}])})();function _typeof$3(Au){"@babel/helpers - typeof";return _typeof$3=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$3(Au)}function _regeneratorRuntime(){_regeneratorRuntime=function(){return lo};var Au,lo={},$u=Object.prototype,Ru=$u.hasOwnProperty,Iu=Object.defineProperty||function(_d,bd,wd){_d[bd]=wd.value},Pu=typeof Symbol=="function"?Symbol:{},Ou=Pu.iterator||"@@iterator",Mu=Pu.asyncIterator||"@@asyncIterator",Du=Pu.toStringTag||"@@toStringTag";function Lu(_d,bd,wd){return Object.defineProperty(_d,bd,{value:wd,enumerable:!0,configurable:!0,writable:!0}),_d[bd]}try{Lu({},"")}catch{Lu=function(wd,Ad,gd){return wd[Ad]=gd}}function Bu(_d,bd,wd,Ad){var gd=bd&&bd.prototype instanceof Gu?bd:Gu,dd=Object.create(gd.prototype),yd=new vd(Ad||[]);return Iu(dd,"_invoke",{value:od(_d,wd,yd)}),dd}function ju(_d,bd,wd){try{return{type:"normal",arg:_d.call(bd,wd)}}catch(Ad){return{type:"throw",arg:Ad}}}lo.wrap=Bu;var Fu="suspendedStart",zu="suspendedYield",Uu="executing",Hu="completed",Vu={};function Gu(){}function Wu(){}function Zu(){}var Ju={};Lu(Ju,Ou,function(){return this});var Yu=Object.getPrototypeOf,Xu=Yu&&Yu(Yu(Sd([])));Xu&&Xu!==$u&&Ru.call(Xu,Ou)&&(Ju=Xu);var ed=Zu.prototype=Gu.prototype=Object.create(Ju);function td(_d){["next","throw","return"].forEach(function(bd){Lu(_d,bd,function(wd){return this._invoke(bd,wd)})})}function nd(_d,bd){function wd(gd,dd,yd,ld){var ud=ju(_d[gd],_d,dd);if(ud.type!=="throw"){var hd=ud.arg,md=hd.value;return md&&_typeof$3(md)=="object"&&Ru.call(md,"__await")?bd.resolve(md.__await).then(function(Ed){wd("next",Ed,yd,ld)},function(Ed){wd("throw",Ed,yd,ld)}):bd.resolve(md).then(function(Ed){hd.value=Ed,yd(hd)},function(Ed){return wd("throw",Ed,yd,ld)})}ld(ud.arg)}var Ad;Iu(this,"_invoke",{value:function(dd,yd){function ld(){return new bd(function(ud,hd){wd(dd,yd,ud,hd)})}return Ad=Ad?Ad.then(ld,ld):ld()}})}function od(_d,bd,wd){var Ad=Fu;return function(gd,dd){if(Ad===Uu)throw Error("Generator is already running");if(Ad===Hu){if(gd==="throw")throw dd;return{value:Au,done:!0}}for(wd.method=gd,wd.arg=dd;;){var yd=wd.delegate;if(yd){var ld=sd(yd,wd);if(ld){if(ld===Vu)continue;return ld}}if(wd.method==="next")wd.sent=wd._sent=wd.arg;else if(wd.method==="throw"){if(Ad===Fu)throw Ad=Hu,wd.arg;wd.dispatchException(wd.arg)}else wd.method==="return"&&wd.abrupt("return",wd.arg);Ad=Uu;var ud=ju(_d,bd,wd);if(ud.type==="normal"){if(Ad=wd.done?Hu:zu,ud.arg===Vu)continue;return{value:ud.arg,done:wd.done}}ud.type==="throw"&&(Ad=Hu,wd.method="throw",wd.arg=ud.arg)}}}function sd(_d,bd){var wd=bd.method,Ad=_d.iterator[wd];if(Ad===Au)return bd.delegate=null,wd==="throw"&&_d.iterator.return&&(bd.method="return",bd.arg=Au,sd(_d,bd),bd.method==="throw")||wd!=="return"&&(bd.method="throw",bd.arg=new TypeError("The iterator does not provide a '"+wd+"' method")),Vu;var gd=ju(Ad,_d.iterator,bd.arg);if(gd.type==="throw")return bd.method="throw",bd.arg=gd.arg,bd.delegate=null,Vu;var dd=gd.arg;return dd?dd.done?(bd[_d.resultName]=dd.value,bd.next=_d.nextLoc,bd.method!=="return"&&(bd.method="next",bd.arg=Au),bd.delegate=null,Vu):dd:(bd.method="throw",bd.arg=new TypeError("iterator result is not an object"),bd.delegate=null,Vu)}function ad(_d){var bd={tryLoc:_d[0]};1 in _d&&(bd.catchLoc=_d[1]),2 in _d&&(bd.finallyLoc=_d[2],bd.afterLoc=_d[3]),this.tryEntries.push(bd)}function pd(_d){var bd=_d.completion||{};bd.type="normal",delete bd.arg,_d.completion=bd}function vd(_d){this.tryEntries=[{tryLoc:"root"}],_d.forEach(ad,this),this.reset(!0)}function Sd(_d){if(_d||_d===""){var bd=_d[Ou];if(bd)return bd.call(_d);if(typeof _d.next=="function")return _d;if(!isNaN(_d.length)){var wd=-1,Ad=function gd(){for(;++wd<_d.length;)if(Ru.call(_d,wd))return gd.value=_d[wd],gd.done=!1,gd;return gd.value=Au,gd.done=!0,gd};return Ad.next=Ad}}throw new TypeError(_typeof$3(_d)+" is not iterable")}return Wu.prototype=Zu,Iu(ed,"constructor",{value:Zu,configurable:!0}),Iu(Zu,"constructor",{value:Wu,configurable:!0}),Wu.displayName=Lu(Zu,Du,"GeneratorFunction"),lo.isGeneratorFunction=function(_d){var bd=typeof _d=="function"&&_d.constructor;return!!bd&&(bd===Wu||(bd.displayName||bd.name)==="GeneratorFunction")},lo.mark=function(_d){return Object.setPrototypeOf?Object.setPrototypeOf(_d,Zu):(_d.__proto__=Zu,Lu(_d,Du,"GeneratorFunction")),_d.prototype=Object.create(ed),_d},lo.awrap=function(_d){return{__await:_d}},td(nd.prototype),Lu(nd.prototype,Mu,function(){return this}),lo.AsyncIterator=nd,lo.async=function(_d,bd,wd,Ad,gd){gd===void 0&&(gd=Promise);var dd=new nd(Bu(_d,bd,wd,Ad),gd);return lo.isGeneratorFunction(bd)?dd:dd.next().then(function(yd){return yd.done?yd.value:dd.next()})},td(ed),Lu(ed,Du,"Generator"),Lu(ed,Ou,function(){return this}),Lu(ed,"toString",function(){return"[object Generator]"}),lo.keys=function(_d){var bd=Object(_d),wd=[];for(var Ad in bd)wd.push(Ad);return wd.reverse(),function gd(){for(;wd.length;){var dd=wd.pop();if(dd in bd)return gd.value=dd,gd.done=!1,gd}return gd.done=!0,gd}},lo.values=Sd,vd.prototype={constructor:vd,reset:function(bd){if(this.prev=0,this.next=0,this.sent=this._sent=Au,this.done=!1,this.delegate=null,this.method="next",this.arg=Au,this.tryEntries.forEach(pd),!bd)for(var wd in this)wd.charAt(0)==="t"&&Ru.call(this,wd)&&!isNaN(+wd.slice(1))&&(this[wd]=Au)},stop:function(){this.done=!0;var bd=this.tryEntries[0].completion;if(bd.type==="throw")throw bd.arg;return this.rval},dispatchException:function(bd){if(this.done)throw bd;var wd=this;function Ad(hd,md){return yd.type="throw",yd.arg=bd,wd.next=hd,md&&(wd.method="next",wd.arg=Au),!!md}for(var gd=this.tryEntries.length-1;gd>=0;--gd){var dd=this.tryEntries[gd],yd=dd.completion;if(dd.tryLoc==="root")return Ad("end");if(dd.tryLoc<=this.prev){var ld=Ru.call(dd,"catchLoc"),ud=Ru.call(dd,"finallyLoc");if(ld&&ud){if(this.prev<dd.catchLoc)return Ad(dd.catchLoc,!0);if(this.prev<dd.finallyLoc)return Ad(dd.finallyLoc)}else if(ld){if(this.prev<dd.catchLoc)return Ad(dd.catchLoc,!0)}else{if(!ud)throw Error("try statement without catch or finally");if(this.prev<dd.finallyLoc)return Ad(dd.finallyLoc)}}}},abrupt:function(bd,wd){for(var Ad=this.tryEntries.length-1;Ad>=0;--Ad){var gd=this.tryEntries[Ad];if(gd.tryLoc<=this.prev&&Ru.call(gd,"finallyLoc")&&this.prev<gd.finallyLoc){var dd=gd;break}}dd&&(bd==="break"||bd==="continue")&&dd.tryLoc<=wd&&wd<=dd.finallyLoc&&(dd=null);var yd=dd?dd.completion:{};return yd.type=bd,yd.arg=wd,dd?(this.method="next",this.next=dd.finallyLoc,Vu):this.complete(yd)},complete:function(bd,wd){if(bd.type==="throw")throw bd.arg;return bd.type==="break"||bd.type==="continue"?this.next=bd.arg:bd.type==="return"?(this.rval=this.arg=bd.arg,this.method="return",this.next="end"):bd.type==="normal"&&wd&&(this.next=wd),Vu},finish:function(bd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ad=this.tryEntries[wd];if(Ad.finallyLoc===bd)return this.complete(Ad.completion,Ad.afterLoc),pd(Ad),Vu}},catch:function(bd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ad=this.tryEntries[wd];if(Ad.tryLoc===bd){var gd=Ad.completion;if(gd.type==="throw"){var dd=gd.arg;pd(Ad)}return dd}}throw Error("illegal catch attempt")},delegateYield:function(bd,wd,Ad){return this.delegate={iterator:Sd(bd),resultName:wd,nextLoc:Ad},this.method==="next"&&(this.arg=Au),Vu}},lo}function asyncGeneratorStep(Au,lo,$u,Ru,Iu,Pu,Ou){try{var Mu=Au[Pu](Ou),Du=Mu.value}catch(Lu){$u(Lu);return}Mu.done?lo(Du):Promise.resolve(Du).then(Ru,Iu)}function _asyncToGenerator(Au){return function(){var lo=this,$u=arguments;return new Promise(function(Ru,Iu){var Pu=Au.apply(lo,$u);function Ou(Du){asyncGeneratorStep(Pu,Ru,Iu,Ou,Mu,"next",Du)}function Mu(Du){asyncGeneratorStep(Pu,Ru,Iu,Ou,Mu,"throw",Du)}Ou(void 0)})}}function _classCallCheck$3(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$3(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$3(Ru.key),Ru)}}function _createClass$3(Au,lo,$u){return lo&&_defineProperties$3(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$3(Au){var lo=_toPrimitive$3(Au,"string");return _typeof$3(lo)=="symbol"?lo:lo+""}function _toPrimitive$3(Au,lo){if(_typeof$3(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$3(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var FileReader$1=(function(){function Au(){_classCallCheck$3(this,Au)}return _createClass$3(Au,[{key:"openFile",value:(function(){var lo=_asyncToGenerator(_regeneratorRuntime().mark(function Ru(Iu,Pu){var Ou;return _regeneratorRuntime().wrap(function(Du){for(;;)switch(Du.prev=Du.next){case 0:if(!(isReactNative()&&Iu&&typeof Iu.uri<"u")){Du.next=11;break}return Du.prev=1,Du.next=4,uriToBlob(Iu.uri);case 4:return Ou=Du.sent,Du.abrupt("return",new FileSource(Ou));case 8:throw Du.prev=8,Du.t0=Du.catch(1),new Error("tus: cannot fetch `file.uri` as Blob, make sure the uri is correct and accessible. ".concat(Du.t0));case 11:if(!(typeof Iu.slice=="function"&&typeof Iu.size<"u")){Du.next=13;break}return Du.abrupt("return",Promise.resolve(new FileSource(Iu)));case 13:if(typeof Iu.read!="function"){Du.next=18;break}if(Pu=Number(Pu),Number.isFinite(Pu)){Du.next=17;break}return Du.abrupt("return",Promise.reject(new Error("cannot create source for stream without a finite value for the `chunkSize` option")));case 17:return Du.abrupt("return",Promise.resolve(new StreamSource(Iu,Pu)));case 18:return Du.abrupt("return",Promise.reject(new Error("source object may only be an instance of File, Blob, or Reader in this environment")));case 19:case"end":return Du.stop()}},Ru,null,[[1,8]])}));function $u(Ru,Iu){return lo.apply(this,arguments)}return $u})()}])})();function fingerprint(Au,lo){return isReactNative()?Promise.resolve(reactNativeFingerprint(Au,lo)):Promise.resolve(["tus-br",Au.name,Au.type,Au.size,Au.lastModified,lo.endpoint].join("-"))}function reactNativeFingerprint(Au,lo){var $u=Au.exif?hashCode(JSON.stringify(Au.exif)):"noexif";return["tus-rn",Au.name||"noname",Au.size||"nosize",$u,lo.endpoint].join("/")}function hashCode(Au){var lo=0;if(Au.length===0)return lo;for(var $u=0;$u<Au.length;$u++){var Ru=Au.charCodeAt($u);lo=(lo<<5)-lo+Ru,lo&=lo}return lo}function _typeof$2(Au){"@babel/helpers - typeof";return _typeof$2=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$2(Au)}function _classCallCheck$2(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$2(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$2(Ru.key),Ru)}}function _createClass$2(Au,lo,$u){return lo&&_defineProperties$2(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$2(Au){var lo=_toPrimitive$2(Au,"string");return _typeof$2(lo)=="symbol"?lo:lo+""}function _toPrimitive$2(Au,lo){if(_typeof$2(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$2(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var XHRHttpStack=(function(){function Au(){_classCallCheck$2(this,Au)}return _createClass$2(Au,[{key:"createRequest",value:function($u,Ru){return new Request$1($u,Ru)}},{key:"getName",value:function(){return"XHRHttpStack"}}])})(),Request$1=(function(){function Au(lo,$u){_classCallCheck$2(this,Au),this._xhr=new XMLHttpRequest,this._xhr.open(lo,$u,!0),this._method=lo,this._url=$u,this._headers={}}return _createClass$2(Au,[{key:"getMethod",value:function(){return this._method}},{key:"getURL",value:function(){return this._url}},{key:"setHeader",value:function($u,Ru){this._xhr.setRequestHeader($u,Ru),this._headers[$u]=Ru}},{key:"getHeader",value:function($u){return this._headers[$u]}},{key:"setProgressHandler",value:function($u){"upload"in this._xhr&&(this._xhr.upload.onprogress=function(Ru){Ru.lengthComputable&&$u(Ru.loaded)})}},{key:"send",value:function(){var $u=this,Ru=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null;return new Promise(function(Iu,Pu){$u._xhr.onload=function(){Iu(new Response$1($u._xhr))},$u._xhr.onerror=function(Ou){Pu(Ou)},$u._xhr.send(Ru)})}},{key:"abort",value:function(){return this._xhr.abort(),Promise.resolve()}},{key:"getUnderlyingObject",value:function(){return this._xhr}}])})(),Response$1=(function(){function Au(lo){_classCallCheck$2(this,Au),this._xhr=lo}return _createClass$2(Au,[{key:"getStatus",value:function(){return this._xhr.status}},{key:"getHeader",value:function($u){return this._xhr.getResponseHeader($u)}},{key:"getBody",value:function(){return this._xhr.responseText}},{key:"getUnderlyingObject",value:function(){return this._xhr}}])})();function _typeof$1(Au){"@babel/helpers - typeof";return _typeof$1=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$1(Au)}function _classCallCheck$1(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$1(Ru.key),Ru)}}function _createClass$1(Au,lo,$u){return lo&&_defineProperties$1(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$1(Au){var lo=_toPrimitive$1(Au,"string");return _typeof$1(lo)=="symbol"?lo:lo+""}function _toPrimitive$1(Au,lo){if(_typeof$1(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$1(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var hasStorage=!1;try{hasStorage="localStorage"in window;var key="tusSupport",originalValue=localStorage.getItem(key);localStorage.setItem(key,originalValue),originalValue===null&&localStorage.removeItem(key)}catch(Au){if(Au.code===Au.SECURITY_ERR||Au.code===Au.QUOTA_EXCEEDED_ERR)hasStorage=!1;else throw Au}var canStoreURLs=hasStorage,WebStorageUrlStorage=(function(){function Au(){_classCallCheck$1(this,Au)}return _createClass$1(Au,[{key:"findAllUploads",value:function(){var $u=this._findEntries("tus::");return Promise.resolve($u)}},{key:"findUploadsByFingerprint",value:function($u){var Ru=this._findEntries("tus::".concat($u,"::"));return Promise.resolve(Ru)}},{key:"removeUpload",value:function($u){return localStorage.removeItem($u),Promise.resolve()}},{key:"addUpload",value:function($u,Ru){var Iu=Math.round(Math.random()*1e12),Pu="tus::".concat($u,"::").concat(Iu);return localStorage.setItem(Pu,JSON.stringify(Ru)),Promise.resolve(Pu)}},{key:"_findEntries",value:function($u){for(var Ru=[],Iu=0;Iu<localStorage.length;Iu++){var Pu=localStorage.key(Iu);if(Pu.indexOf($u)===0)try{var Ou=JSON.parse(localStorage.getItem(Pu));Ou.urlStorageKey=Pu,Ru.push(Ou)}catch{}}return Ru}}])})();function _typeof(Au){"@babel/helpers - typeof";return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof(Au)}function _classCallCheck(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey(Ru.key),Ru)}}function _createClass(Au,lo,$u){return $u&&_defineProperties(Au,$u),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _callSuper(Au,lo,$u){return lo=_getPrototypeOf(lo),_possibleConstructorReturn(Au,_isNativeReflectConstruct()?Reflect.construct(lo,$u||[],_getPrototypeOf(Au).constructor):lo.apply(Au,$u))}function _possibleConstructorReturn(Au,lo){if(lo&&(_typeof(lo)==="object"||typeof lo=="function"))return lo;if(lo!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized(Au)}function _assertThisInitialized(Au){if(Au===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return Au}function _isNativeReflectConstruct(){try{var Au=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(_isNativeReflectConstruct=function(){return!!Au})()}function _getPrototypeOf(Au){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function($u){return $u.__proto__||Object.getPrototypeOf($u)},_getPrototypeOf(Au)}function _inherits(Au,lo){if(typeof lo!="function"&&lo!==null)throw new TypeError("Super expression must either be null or a function");Au.prototype=Object.create(lo&&lo.prototype,{constructor:{value:Au,writable:!0,configurable:!0}}),Object.defineProperty(Au,"prototype",{writable:!1}),lo&&_setPrototypeOf(Au,lo)}function _setPrototypeOf(Au,lo){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(Ru,Iu){return Ru.__proto__=Iu,Ru},_setPrototypeOf(Au,lo)}function ownKeys(Au,lo){var $u=Object.keys(Au);if(Object.getOwnPropertySymbols){var Ru=Object.getOwnPropertySymbols(Au);lo&&(Ru=Ru.filter(function(Iu){return Object.getOwnPropertyDescriptor(Au,Iu).enumerable})),$u.push.apply($u,Ru)}return $u}function _objectSpread(Au){for(var lo=1;lo<arguments.length;lo++){var $u=arguments[lo]!=null?arguments[lo]:{};lo%2?ownKeys(Object($u),!0).forEach(function(Ru){_defineProperty(Au,Ru,$u[Ru])}):Object.getOwnPropertyDescriptors?Object.defineProperties(Au,Object.getOwnPropertyDescriptors($u)):ownKeys(Object($u)).forEach(function(Ru){Object.defineProperty(Au,Ru,Object.getOwnPropertyDescriptor($u,Ru))})}return Au}function _defineProperty(Au,lo,$u){return lo=_toPropertyKey(lo),lo in Au?Object.defineProperty(Au,lo,{value:$u,enumerable:!0,configurable:!0,writable:!0}):Au[lo]=$u,Au}function _toPropertyKey(Au){var lo=_toPrimitive(Au,"string");return _typeof(lo)=="symbol"?lo:lo+""}function _toPrimitive(Au,lo){if(_typeof(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var defaultOptions$1=_objectSpread(_objectSpread({},BaseUpload.defaultOptions),{},{httpStack:new XHRHttpStack,fileReader:new FileReader$1,urlStorage:canStoreURLs?new WebStorageUrlStorage:new NoopUrlStorage,fingerprint}),Upload=(function(Au){function lo(){var $u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,Ru=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return _classCallCheck(this,lo),Ru=_objectSpread(_objectSpread({},defaultOptions$1),Ru),_callSuper(this,lo,[$u,Ru])}return _inherits(lo,Au),_createClass(lo,null,[{key:"terminate",value:function(Ru){var Iu=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return Iu=_objectSpread(_objectSpread({},defaultOptions$1),Iu),BaseUpload.terminate(Ru,Iu)}}])})(BaseUpload);const RUNTIMES_API_PREFIX="api/runtimes/v1";function join$1(Au,lo){return`${Au.replace(/\/+$/,"")}/${lo.replace(/^\/+/,"")}`}function runtimesUrl(Au){return join$1(Au,`${RUNTIMES_API_PREFIX}/runtimes`)}function runtimeUrl(Au,lo){return`${runtimesUrl(Au)}/${lo}`}function sandboxSnapshotsUrl(Au){return join$1(Au,`${RUNTIMES_API_PREFIX}/sandbox-snapshots`)}function sandboxSnapshotUrl(Au,lo){return`${sandboxSnapshotsUrl(Au)}/${lo}`}function asCodeSandboxSnapshot(Au){const{uid:lo,updated_at:$u,format_version:Ru,...Iu}=Au;return{...Iu,id:lo,updatedAt:new Date($u),formatVersion:Ru}}async function getEnvironments(){const Au=await requestDatalayerAPI({url:libExports$5.URLExt.join(runtimesStore.getState().runtimesUrl,"api/runtimes/v1/environments"),token:iamStore.getState().token});return Au.success?Au.environments??[]:(console.error("Failed to fetch available environments.",Au),[])}async function createRuntime(Au){const{externalToken:lo,token:$u}=iamStore.getState();if(typeof Au.creditsLimit!="number"||!Number.isFinite(Au.creditsLimit)||Au.creditsLimit<0)throw new Error(`Invalid runtime creditsLimit for environment ${Au.environmentName}. A number of zero or more is required.`);if(Au.deploymentUid&&!Au.appUid)throw new Error(`Deployment ${Au.deploymentUid} is named without its application: give appUid.`);if(Au.appUid&&!Au.appSpec)throw new Error(`Application ${Au.appUid} is launched without its Appspec: give appSpec, so its runtime is given the secrets its connections declare.`);const Ru={name:Au.environmentName};Au.environmentVersion!==void 0&&Au.environmentVersion!==""&&(Ru.version=Au.environmentVersion);const Iu={environment:Ru,type:Au.type??"notebook",given_name:Au.givenName,credits_limit:Au.creditsLimit};Au.capabilities&&(Iu.capabilities=Au.capabilities),Au.snapshot&&(Iu.from=Au.snapshot),Au.appUid&&(Iu.app_uid=Au.appUid),Au.deploymentUid&&(Iu.deployment_uid=Au.deploymentUid),Au.appSpec&&(Iu.app_spec=Au.appSpec);const Pu=await requestDatalayerAPI({url:runtimesUrl(runtimesStore.getState().runtimesUrl),method:"POST",body:Iu,token:$u,headers:lo?{"X-External-Token":lo}:void 0});if(!Pu.success||!Pu.runtime){const Ou=`Failed to create a kernel for the environment ${Au.environmentName}.`;throw console.error(Ou,Pu),new Error(Ou)}return Pu.runtime}async function getRuntimes(){const Au=await requestDatalayerAPI({url:runtimesUrl(runtimesStore.getState().runtimesUrl),token:iamStore.getState().token});if(!Au.success){const lo="Failed to list the running kernels.";throw console.error(lo,Au),new Error(lo)}return Au.runtimes??[]}async function getRuntimeRecord(Au){try{return(await requestDatalayerAPI({url:runtimeUrl(runtimesStore.getState().runtimesUrl,Au),token:iamStore.getState().token})).runtime??null}catch(lo){if(lo.response?.status===404)return null;throw lo}}async function deleteRuntime(Au){const lo=iamStore.getState().externalToken;await requestDatalayerAPI({url:runtimeUrl(runtimesStore.getState().runtimesUrl,Au.id)+libExports$5.URLExt.objectToQueryString(Au.reason?{reason:Au.reason}:{}),method:"DELETE",token:iamStore.getState().token,headers:lo?{"X-External-Token":lo}:void 0})}async function snapshotRuntime(Au){const lo=await requestDatalayerAPI({url:sandboxSnapshotsUrl(runtimesStore.getState().runtimesUrl),method:"POST",body:{runtime_name:Au.id,name:Au.name,description:Au.description,stop:Au.stop},token:iamStore.getState().token});if(!lo.success)throw new Error(`Failed to take the code sandbox snapshot ${Au.id} - ${lo}`);if(lo.snapshot)return asCodeSandboxSnapshot(lo.snapshot)}async function getSandboxSnapshots(){const Au=await requestDatalayerAPI({url:sandboxSnapshotsUrl(runtimesStore.getState().runtimesUrl),token:iamStore.getState().token});return Au.success?(Au.snapshots??[]).map(asCodeSandboxSnapshot):(console.error("Failed to fetch code sandbox snapshots.",Au),[])}async function loadSandboxSnapshot(Au){const lo=await requestDatalayerAPI({url:runtimeUrl(runtimesStore.getState().runtimesUrl,Au.id),method:"PUT",body:{from:Au.from},token:iamStore.getState().token});if(!lo.success)throw new Error(`Failed to load the code sandbox snapshot; ${lo.message}`)}function createSandboxSnapshotDownloadURL(Au){return sandboxSnapshotUrl(runtimesStore.getState().runtimesUrl,Au)+libExports$5.URLExt.objectToQueryString({download:"1",token:iamStore.getState().token??""})}function exportCodeSandboxSnapshot(Au){const lo=createSandboxSnapshotDownloadURL(Au),$u=document.createElement("a");$u.href=lo,$u.download="",document.body.appendChild($u),$u.click(),document.body.removeChild($u)}async function deleteCodeSandboxSnapshot(Au){await requestDatalayerAPI({url:sandboxSnapshotUrl(runtimesStore.getState().runtimesUrl,Au),method:"DELETE",token:iamStore.getState().token})}async function updateCodeSandboxSnapshot(Au,lo){(lo.name||lo.description)&&await requestDatalayerAPI({url:sandboxSnapshotUrl(runtimesStore.getState().runtimesUrl,Au),method:"PATCH",body:{...lo},token:iamStore.getState().token})}async function uploadCodeSandboxSnapshot(Au){if(Au.file.size===0)return Promise.reject("Empty Code Sandbox Snapshot.");const lo=new PromiseDelegate,$u=new Upload(Au.file,{endpoint:`${sandboxSnapshotsUrl(runtimesStore.getState().runtimesUrl)}/upload`,headers:{Authorization:`Bearer ${iamStore.getState().token}`},retryDelays:null,metadata:Au.metadata,onError:Iu=>{console.error(`Failed to upload ${Au.metadata.filename}.`,Iu),lo.reject(Iu)},onProgress:Au.onProgress,onSuccess:()=>{lo.resolve()}}),Ru=await $u.findPreviousUploads();return Ru.length&&$u.resumeFromPreviousUpload(Ru[0]),$u.start(),lo.promise}const actions=Object.freeze(Object.defineProperty({__proto__:null,createRuntime,createSandboxSnapshotDownloadURL,deleteCodeSandboxSnapshot,deleteRuntime,exportCodeSandboxSnapshot,getEnvironments,getRuntimeRecord,getRuntimes,getSandboxSnapshots,loadSandboxSnapshot,snapshotRuntime,updateCodeSandboxSnapshot,uploadCodeSandboxSnapshot},Symbol.toStringTag,{value:"Module"})),CLAUDE_CODE_HARNESS_0_0_1={id:"claude-code",version:"0.0.1",name:"Claude Code",description:"Anthropic's coding agent, driven over ACP through the Agent Client Protocol project's adapter on the Claude Agent SDK.",enabled:!0,unavailable_because:"",tags:["harness"],docs:"https://github.com/agentclientprotocol/claude-agent-acp",acp:{command:"npx",args:["-y","@agentclientprotocol/claude-agent-acp@0.91.0"],protocolVersion:1,loadSession:!0,mcp:"lend",modes:["default","plan","acceptEdits","bypassPermissions"],env:{},nativeSession:"none"},requires:{secrets:["ANTHROPIC_API_KEY"],binaries:["node","git"]},terms:{servedToThirdParties:"api_key_only",licence:"Apache-2.0 (adapter); Anthropic Commercial Terms of Service (the agent)"},skills:{format:"skill-md",dir:".claude/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"load",forkHistory:"replay",interrupt:!0,steering:!1,images:!0,compaction:"own",modes:["default","plan","acceptEdits","bypassPermissions"],autoRun:["^(cal|uptime|cat|head|tail|wc|stat|strings|hexdump|od|nl|id|uname|free|df|du|locale|groups|nproc|basename|dirname|realpath|cut|paste|tr|column|tac|rev|fold|expand|unexpand|fmt|comm|cmp|numfmt|readlink|diff|true|false|sleep|which|type|expr|seq|tsort|pr)(\\s|$)","^(pwd|whoami|alias|history|arch|ifconfig|ip addr)(\\s|$)","^(claude (-h|--help)|node (-v|--version)|python3? --version)$","^(echo|uniq|jq|cd|ls|find)(\\s|$)","^(xargs|file|sed|sort|man|help|netstat|ps|base64|grep|egrep|fgrep|rg|sha256sum|sha1sum|md5sum|tree|date|hostname|lsof|pgrep|tput|ss|fd|fdfind|test)(\\s|$)","^git (diff|log|show|shortlog|reflog|stash (list|show)|ls-remote|status|blame|ls-files|config --get|remote( show)?|merge-base|rev-parse|rev-list|describe|cat-file|for-each-ref|grep|worktree list|tag|branch)(\\s|$)","^gh (pr (view|list|diff|checks|status)|issue (view|list|status)|repo view|run (list|view)|auth status|release (list|view)|workflow (list|view)|label list|search (repos|issues|prs|commits|code))(\\s|$)","^docker (ps|images|logs|inspect)(\\s|$)"]},instructionsFile:"CLAUDE.md",registered:{adapter:"@agentclientprotocol/claude-agent-acp",version:"0.91.0",licenceSource:"https://www.npmjs.com/package/@agentclientprotocol/claude-agent-acp",termsSource:"https://code.claude.com/docs/en/legal-and-compliance",credential:"An Anthropic API key (ANTHROPIC_API_KEY), the person's own",binaries:"Node 22 (engines.node >=22 on npm), git",note:"Anthropic's legal page (read 2026-10-15): running Claude Code in hosted sandboxes or agent infrastructure requires the Commercial Terms; each end user authenticates with their own API key or subscription; developers may not route requests through Free, Pro or Max plan credentials on behalf of their users, nor collect or intermediate Claude.ai credentials. So only API keys are taken; a subscription login is refused. The npm package moved from @zed-industries (0.23.1, March 2026) to @agentclientprotocol."}},CODEX_HARNESS_0_0_1={id:"codex",version:"0.0.1",name:"Codex",description:"OpenAI's coding agent, driven over ACP through the Agent Client Protocol project's adapter, which ships the Codex binary it drives.",enabled:!0,unavailable_because:"",tags:["harness"],docs:"https://github.com/agentclientprotocol/codex-acp",acp:{command:"npx",args:["-y","@agentclientprotocol/codex-acp@2.2.2"],protocolVersion:1,loadSession:!0,mcp:"lend",modes:["read-only","workspace-write","agent","agent-full-access"],env:{NO_BROWSER:"1"},nativeSession:"none"},requires:{secrets:["OPENAI_API_KEY"],binaries:["node","git"]},terms:{servedToThirdParties:"api_key_only",licence:"Apache-2.0 (adapter); OpenAI Terms of Use (the agent)"},skills:{format:"skill-md",dir:".agents/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"load",forkHistory:"replay",interrupt:!0,steering:!1,images:!0,compaction:"own",modes:["read-only","workspace-write","agent","agent-full-access"],autoRun:[]},instructionsFile:"AGENTS.md",registered:{adapter:"@agentclientprotocol/codex-acp",version:"2.2.2",licenceSource:"https://www.npmjs.com/package/@agentclientprotocol/codex-acp",termsSource:"https://learn.chatgpt.com/docs/auth",credential:"An OpenAI API key (OPENAI_API_KEY or CODEX_API_KEY), the person's own",binaries:"Node 22 (as the Agent Client Protocol project's adapters; unstated on npm), git",note:"Codex's authentication page (read 2026-10-15) recommends API keys for automation and device-code login for headless machines; a ChatGPT login needs a browser and is hidden with NO_BROWSER=1 in the adapter. Only API keys are taken; a ChatGPT login is refused. The Zed-scoped package was archived on 22 July 2026 and names this one."}},CUSTOM_HARNESS_0_0_1={id:"custom",version:"0.0.1",name:"Custom harness",description:"An organization's own ACP agent, its command named by the organization's own harness spec and never typed into a form.",enabled:!1,unavailable_because:"",tags:["harness"],docs:"",requires:{secrets:[],binaries:[]},terms:{servedToThirdParties:"organizations_own",licence:"The organization's own"},skills:{format:"none",dir:""},honours:{model:!1,subagents:!1},capabilities:{resume:"none",forkHistory:"none",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:[],autoRun:[]},instructionsFile:"",registered:{adapter:"The organization's own",version:"0",licenceSource:"https://agentspecs.datalayer.tech/harnesses",termsSource:"https://agentspecs.datalayer.tech/harnesses",credential:"The organization's own",binaries:"",note:"Not launchable from the shared catalogue; an organization's own harness spec names the command and answers for its terms."}},FAST_AGENT_HARNESS_0_0_1={id:"fast-agent",version:"0.0.1",name:"fast-agent",description:"llmindset's agent framework served over ACP; each agent it defines is a session mode, with any model provider it is configured with.",enabled:!1,unavailable_because:"the catalogue offers four harnesses today — Claude Code, Codex, OpenCode and pi (28 October 2026); fast-agent is a framework served over ACP, not a coding agent, its adapter is a Python tool the runtime image does not carry, and it has not been drilled on Datalayer.",tags:["harness","framework"],docs:"https://github.com/evalstate/fast-agent/blob/main/docs/docs/acp/index.md",acp:{command:"uvx",args:["fast-agent-acp==0.10.45"],protocolVersion:1,loadSession:!0,mcp:"lend",modes:[],env:{},nativeSession:"none"},requires:{secrets:["ANTHROPIC_API_KEY"],binaries:["uvx"]},terms:{servedToThirdParties:"permitted",licence:"Apache-2.0"},skills:{format:"skill-md",dir:".agents/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"load",forkHistory:"replay",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:[],autoRun:[]},instructionsFile:"AGENTS.md",registered:{adapter:"fast-agent-acp",version:"0.10.45",licenceSource:"https://pypi.org/project/fast-agent-acp/",termsSource:"https://github.com/evalstate/fast-agent/blob/main/LICENSE",credential:"The provider's key fast-agent is given (ANTHROPIC_API_KEY, OPENAI_API_KEY or HF_TOKEN); ANTHROPIC_API_KEY declared",binaries:"uv (uvx), Python 3.12 to 3.15 (requires_python on PyPI)",note:"A framework, not a coding agent: each agent it defines is an ACP mode; the client's MCP servers are attached; sessions are listed. Launched with uvx fast-agent-acp (docs/docs/acp/index.md); reads skills from .fast-agent/skills, .agents/skills and .claude/skills; its default prompt reads AGENTS.md."}},GEMINI_CLI_HARNESS_0_0_1={id:"gemini-cli",version:"0.0.1",name:"Gemini CLI",description:"Google's coding agent, which speaks ACP itself when started with --experimental-acp.",enabled:!1,unavailable_because:"the catalogue offers four harnesses today — Claude Code, Codex, OpenCode and pi (28 October 2026); Gemini CLI's API host (generativelanguage.googleapis.com) is outside a Datalayer runtime's egress boundary and is not routed through ai-inference, so it stays unfunded and unoffered there (the user's decision, 28 October 2026).",tags:["harness"],docs:"https://github.com/google-gemini/gemini-cli/blob/main/docs/cli/cli-reference.md",acp:{command:"npx",args:["-y","@google/gemini-cli@0.64.0","--experimental-acp"],protocolVersion:1,loadSession:!1,mcp:"lend",modes:["default","auto_edit","yolo","plan"],env:{},nativeSession:"none"},requires:{secrets:["GEMINI_API_KEY"],binaries:["node","git"]},terms:{servedToThirdParties:"api_key_only",licence:"Apache-2.0 (the agent); Gemini API or Gemini Code Assist terms (the model)",tierRestrictions:"Gemini Code Assist Standard or Enterprise for a Google login (the individuals tier stopped being served on 18 June 2026); a Gemini API key otherwise"},skills:{format:"skill-md",dir:".gemini/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"none",forkHistory:"replay",interrupt:!0,steering:!1,images:!0,compaction:"own",modes:["default","auto_edit","yolo","plan"],autoRun:[]},instructionsFile:"GEMINI.md",registered:{adapter:"@google/gemini-cli",version:"0.64.0",licenceSource:"https://www.npmjs.com/package/@google/gemini-cli",termsSource:"https://developers.google.com/gemini-code-assist/resources/privacy-notice-gemini-code-assist-individuals",credential:"A Gemini API key (GEMINI_API_KEY), the person's own; or a Google login on a Code Assist Standard or Enterprise subscription",binaries:"Node 20 or later (engines.node >=20 on npm), git",note:`Google's notice (read 2026-10-15): "Starting June 18, 2026, Gemini Code Assist IDE extensions stopped serving requests for the Gemini Code Assist for individuals"; Standard and Enterprise follow a separate schedule. The ACP flag is --experimental-acp in the CLI reference (docs/cli/cli-reference.md).`}},GOOSE_HARNESS_0_0_1={id:"goose",version:"0.0.1",name:"goose",description:"Block's open agent (now the Agentic AI Foundation's), which speaks ACP itself with goose acp; any model provider it is configured with.",enabled:!1,unavailable_because:"the catalogue offers four harnesses today — Claude Code, Codex, OpenCode and pi (28 October 2026); goose is a binary of its own release, not an npm adapter, the runtime image does not carry it, and it has not been drilled on Datalayer.",tags:["harness"],docs:"https://block.github.io/goose/docs/gdk/acp/",acp:{command:"goose",args:["acp"],protocolVersion:1,loadSession:!1,mcp:"lend",modes:[],env:{GOOSE_PROVIDER:"anthropic"},nativeSession:"none"},requires:{secrets:["ANTHROPIC_API_KEY"],binaries:["goose@1.54.0","git"]},terms:{servedToThirdParties:"permitted",licence:"Apache-2.0"},skills:{format:"skill-md",dir:".agents/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"none",forkHistory:"replay",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:[],autoRun:[]},instructionsFile:".goosehints",registered:{adapter:"goose",version:"1.54.0",licenceSource:"https://github.com/aaif-goose/goose",termsSource:"https://github.com/aaif-goose/goose/blob/main/LICENSE",credential:"The provider's key goose is configured with (GOOSE_PROVIDER); ANTHROPIC_API_KEY declared",binaries:"The goose CLI (release v1.54.0 of 8 October 2026), git",note:"Open source under Apache-2.0, no vendor terms of its own; the model provider's terms apply to the key. Launched as goose acp (documentation/docs/gdk/acp/index.md)."}},OPENCODE_HARNESS_0_0_1={id:"opencode",version:"0.0.1",name:"OpenCode",description:"Anomaly's open coding agent, which speaks ACP itself with opencode acp; any model provider it is configured with.",enabled:!0,unavailable_because:"",tags:["harness"],docs:"https://opencode.ai/docs/acp/",acp:{command:"npx",args:["-y","opencode-ai@1.19.0","acp"],protocolVersion:1,loadSession:!1,mcp:"lend",modes:[],env:{},nativeSession:"none"},requires:{secrets:["ANTHROPIC_API_KEY"],binaries:["node","git"]},terms:{servedToThirdParties:"permitted",licence:"MIT"},skills:{format:"skill-md",dir:".opencode/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"none",forkHistory:"replay",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:[],autoRun:[]},instructionsFile:"AGENTS.md",registered:{adapter:"opencode-ai",version:"1.19.0",licenceSource:"https://www.npmjs.com/package/opencode-ai",termsSource:"https://github.com/anomalyco/opencode/blob/dev/LICENSE",credential:"The provider's key OpenCode is configured with; ANTHROPIC_API_KEY declared",binaries:"Node (the opencode-ai package), git",note:"Open source under MIT, no vendor terms of its own; the model provider's terms apply to the key. Launched as opencode acp (opencode.ai/docs/acp); reads skills from .opencode/skills, .claude/skills and .agents/skills."}},OPENHANDS_HARNESS_0_0_1={id:"openhands",version:"0.0.1",name:"OpenHands",description:"The OpenHands CLI, which speaks ACP itself with openhands acp; any model provider it is configured with.",enabled:!1,unavailable_because:"the catalogue offers four harnesses today — Claude Code, Codex, OpenCode and pi (28 October 2026); OpenHands' adapter is a Python tool the runtime image does not carry, and it has not been drilled on Datalayer.",tags:["harness"],docs:"https://docs.openhands.dev/openhands/usage/run-openhands/acp",acp:{command:"uvx",args:["--from","openhands==1.16.0","openhands","acp","--override-with-envs"],protocolVersion:1,loadSession:!0,mcp:"lend",modes:["always-ask","always-approve","llm-approve"],env:{},nativeSession:"none"},requires:{secrets:["LLM_API_KEY"],binaries:["uvx","git"]},terms:{servedToThirdParties:"permitted",licence:"MIT"},skills:{format:"skill-md",dir:".agents/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"load",forkHistory:"replay",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:["always-ask","always-approve","llm-approve"],autoRun:[]},instructionsFile:"AGENTS.md",registered:{adapter:"openhands",version:"1.16.0",licenceSource:"https://pypi.org/project/openhands/",termsSource:"https://github.com/OpenHands/OpenHands-CLI/blob/main/LICENSE",credential:"The provider's key OpenHands reads as LLM_API_KEY, with LLM_MODEL, under --override-with-envs",binaries:"uv (uvx), Python 3.12 or later, git",note:"Open source under MIT, no vendor terms of its own; the model provider's terms apply to the key. Launched as openhands acp (OpenHands-CLI README; docs.openhands.dev's ACP page); resumes with --resume; reads skills from .agents/skills (.openhands/skills is legacy)."}},PI_HARNESS_0_0_1={id:"pi",version:"0.0.1",name:"pi",description:"Earendil's pi coding agent, driven over ACP through the pi-acp adapter, which spawns the published pi executable; any model provider pi is configured with.",enabled:!0,unavailable_because:"",tags:["harness"],docs:"https://github.com/svkozak/pi-acp",acp:{command:"npx",args:["-y","pi-acp@0.0.34"],protocolVersion:1,loadSession:!0,mcp:"lend",modes:[],env:{},nativeSession:"none"},requires:{secrets:["ANTHROPIC_API_KEY"],binaries:["node","git"]},terms:{servedToThirdParties:"permitted",licence:"MIT (adapter); MIT (the agent, @earendil-works/pi-coding-agent 1.4.0)"},skills:{format:"skill-md",dir:".pi/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"load",forkHistory:"replay",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:[],autoRun:[]},instructionsFile:"AGENTS.md",registered:{adapter:"pi-acp",version:"0.0.34",licenceSource:"https://www.npmjs.com/package/pi-acp",termsSource:"https://github.com/earendil-works/pi/blob/main/LICENSE",credential:"The provider's key pi is configured with; ANTHROPIC_API_KEY declared, the person's own",binaries:"Node 22 (pi-coding-agent engines.node >=22.19.0; pi-acp >=20), the pi executable 1.4.0 on the PATH (@earendil-works/pi-coding-agent), git",note:"Read 2026-10-28. pi speaks no ACP itself; pi-acp 0.0.34 (MIT, an individual's, github.com/svkozak/pi-acp) speaks ACP JSON-RPC over stdio and spawns the published `pi` executable with `pi --mode rpc`, so pi 1.4.0 runs as published — chosen over @automatalabs/pi-acp 0.9.4 (Apache-2.0, in-process, which embeds pi 0.87.1 through its SDK on a fork's package). Open source under MIT on both sides, no vendor terms of their own; the model provider's terms apply to the key. Session persistence through pi's own session files (session/load)."}},HARNESS_CATALOGUE={"claude-code":CLAUDE_CODE_HARNESS_0_0_1,codex:CODEX_HARNESS_0_0_1,custom:CUSTOM_HARNESS_0_0_1,"fast-agent":FAST_AGENT_HARNESS_0_0_1,"gemini-cli":GEMINI_CLI_HARNESS_0_0_1,goose:GOOSE_HARNESS_0_0_1,opencode:OPENCODE_HARNESS_0_0_1,openhands:OPENHANDS_HARNESS_0_0_1,pi:PI_HARNESS_0_0_1};function listHarnesses(){return Object.values(HARNESS_CATALOGUE)}const AGENT_RUNTIME_VARIANTS=["browser-vercelai","local-pydanticai","cloud-pydanticai"],DEFAULT_AGENT_RUNTIME_VARIANT="cloud-pydanticai",VARIANT_BY_LEGACY_TARGET={"backend-services":"cloud-pydanticai","local-agent-runtimes":"local-pydanticai"};function isAgentRuntimeVariant(Au){return typeof Au=="string"&&AGENT_RUNTIME_VARIANTS.includes(Au)}function toAgentRuntimeVariant(Au,lo=DEFAULT_AGENT_RUNTIME_VARIANT){return Au?isAgentRuntimeVariant(Au)?Au:VARIANT_BY_LEGACY_TARGET[Au]??lo:lo}function locationOf(Au){return Au.slice(0,Au.indexOf("-"))}function runsInBrowser(Au){return locationOf(Au)==="browser"}function legacyTargetOf(Au){return locationOf(Au)==="cloud"?"backend-services":"local-agent-runtimes"}const runtimesStore=createStore$1((Au,lo)=>({configuration:{maxNotebookRuntimes:5,maxCellRuntimes:3},setConfiguration:$u=>{Au(Ru=>JSONExt.deepEqual(Ru.configuration,$u)?{}:{configuration:{...$u}})},runtimesUrl:coreStore.getState().configuration?.runtimesUrl,tab:0,getIntTab:()=>Math.floor(lo().tab),setTab:$u=>Au(Ru=>({tab:$u})),runtimes:[],refreshRuntimes:async()=>{const $u=await getRuntimes();JSONExt.deepEqual(lo().runtimes,$u)||Au({runtimes:[...$u]})},removeRuntime:$u=>{if(!$u)return;const Ru=lo().runtimes,Iu=Ru.filter(Pu=>Pu.runtime_name!==$u);Iu.length!==Ru.length&&Au({runtimes:Iu})},runtimeModels:[],addRuntimeModel:$u=>{const Ru=lo().runtimeModels;Ru.findIndex(Pu=>$u.id&&$u.id===Pu.id||!!$u.uid&&$u.uid===Pu.uid)<0&&Au({runtimeModels:[...Ru,$u]})},removeRuntimeModel:$u=>{const Ru=[...lo().runtimeModels],Iu=Ru?.findIndex(Pu=>!!Pu.id&&$u===Pu.id||$u===Pu.runtime_name)??-1;Iu>=0&&(Ru.splice(Iu,1),Au({runtimeModels:Ru}))},setRuntimeModels:$u=>{JSONExt.deepEqual(lo().runtimeModels,$u)||Au({runtimeModels:[...$u]})},multiServiceManager:void 0,setMultiServiceManager:$u=>{Au(Ru=>({multiServiceManager:$u}))},showDisclaimer:!1,setShowDisclaimer:$u=>{Au(Ru=>({showDisclaimer:$u}))},runtimeSnapshots:[],addSandboxSnapshot:$u=>{const Ru=lo().runtimeSnapshots,Iu=Ru.findIndex(Pu=>Pu.id===$u.id);if(Iu<0){const Pu=[...Ru,$u];Au({runtimeSnapshots:Pu})}else if(!JSONExt.deepEqual(Ru[Iu],$u)){const Pu=[...Ru];Pu.splice(Iu,1,$u),Au({runtimeSnapshots:Pu})}},removeSandboxSnapshot:$u=>{const Ru=lo().runtimeSnapshots,Iu=Ru.findIndex(Pu=>Pu.id===$u);if(Iu>=0){const Pu=[...Ru];Pu.splice(Iu,1),Au({runtimeSnapshots:Pu})}},setSandboxSnapshots:$u=>{JSONExt.deepEqual(lo().runtimeSnapshots,$u)||Au({runtimeSnapshots:[...$u]})},version:"",setVersion:$u=>{$u&&!lo().version&&Au(Ru=>({version:$u}))}})),kernelsPoll=new Poll({auto:!0,factory:()=>runtimesStore.getState().refreshRuntimes(),frequency:{interval:61*1e3,backoff:!0,max:300*1e3},name:"@datalayer/jupyter-kernels:KernelsManager#kernels",standby:()=>iamStore.getState().token||runtimesStore.getState().runtimesUrl?"when-hidden":!0});runtimesStore.subscribe((Au,lo)=>{if(!JSONExt.deepEqual(Au.runtimes,lo.runtimes)){const $u=Date.now(),Ru=Math.min(...Au.runtimes.map(Iu=>Iu.expired_at?parseFloat(Iu.expired_at):1/0))*1e3;$u+kernelsPoll.frequency.interval>Ru+2e3&&setTimeout(()=>{kernelsPoll.refresh()},Ru+2e3-$u)}});coreStore.subscribe((Au,lo)=>{if(Au.configuration.runtimesUrl&&Au.configuration.runtimesUrl!==lo.configuration.runtimesUrl){const $u=Au.configuration.runtimesUrl;console.log(`Updating runtimesUrl with new value ${$u}`),runtimesStore.setState({runtimesUrl:$u}),kernelsPoll.refresh().then(()=>kernelsPoll.tick).catch(Ru=>{console.error("Failed to refresh kernel servers list following service URL changed.",Ru)})}});function useRuntimesStore(Au){return useStore$1(runtimesStore,Au)}const DEFAULT_AGENT_CONFIG={name:"ai-agent",description:"AI Assistant",model:"",systemPrompt:"You are a helpful AI assistant.",agentLibrary:"pydantic-ai",protocol:"vercel-ai"};requireManager();const sandboxManagersByRuntime=new Map;function registerSandboxServiceManager(Au,lo){const $u=String(Au||"").trim();if(!$u||!lo)return()=>{};let Ru=sandboxManagersByRuntime.get($u);return Ru||(Ru=new Set,sandboxManagersByRuntime.set($u,Ru)),Ru.add(lo),()=>{const Iu=sandboxManagersByRuntime.get($u);Iu&&(Iu.delete(lo),Iu.size===0&&sandboxManagersByRuntime.delete($u))}}function disposeSandboxServiceManagers(Au){const lo=String(Au||"").trim();if(!lo)return;const $u=sandboxManagersByRuntime.get(lo);$u&&(sandboxManagersByRuntime.delete(lo),$u.forEach(Ru=>{try{disposeServiceManager(Ru)}catch(Iu){console.warn(`[sandboxServiceManagers] Failed disposing service manager for pod ${lo}`,Iu)}}))}function launchesOwnRoutesOnly(Au){return!!Au?.deploymentUid}const base$2=Au=>Au.trim().replace(/\/$/,"");function agentDeletionUrl(Au,lo,$u){if(!$u)return`${base$2(Au)}/api/v1/agents/${encodeURIComponent(lo)}`}function runtimeModelsUrl(Au,lo,$u){if(!$u)return`${base$2(Au)}/api/v1/configure/models?agent_id=${encodeURIComponent(lo)}`}const EMPTY_RUNTIMES=[],BROWSER_AGENT_CONNECTION=Object.freeze({runtimeName:"",environmentName:"",jupyterBaseUrl:"",agentBaseUrl:"",status:"ready",isReady:!0}),AGENT_QUERY_OPTIONS={staleTime:300*1e3,gcTime:600*1e3},agentQueryKeys={agentRuntimes:{all:()=>["agentRuntimes"],lists:()=>[...agentQueryKeys.agentRuntimes.all(),"list"],details:()=>[...agentQueryKeys.agentRuntimes.all(),"detail"],detail:Au=>[...agentQueryKeys.agentRuntimes.details(),Au]},checkpoints:{all:()=>["checkpoints"],lists:()=>[...agentQueryKeys.checkpoints.all(),"list"]}},DELETED_POD_TOMBSTONE_TTL_MS=300*1e3,deletedRuntimeTombstones=new Map;function markRuntimeDeleted(Au){const lo=String(Au||"").trim();lo&&(deletedRuntimeTombstones.set(lo,Date.now()),disposeSandboxServiceManagers(lo))}function clearRuntimeDeleted(Au){deletedRuntimeTombstones.delete(String(Au||"").trim())}const LIVE_RUNTIME_STATUSES=new Set(["running","resumed","starting","resuming"]);function isStaleDeletedRuntime(Au){const lo=String(Au?.runtime_name||"").trim(),$u=deletedRuntimeTombstones.get(lo);return $u===void 0?!1:Date.now()-$u>DELETED_POD_TOMBSTONE_TTL_MS?(deletedRuntimeTombstones.delete(lo),!1):LIVE_RUNTIME_STATUSES.has(Au.status)}const RUNTIME_STATUS_MAP={resume:"resumed",resumed:"resumed",resuming:"resuming",pausing:"pausing",paused:"paused",starting:"starting",pending:"starting",launching:"starting",terminated:"terminated",archived:"archived",running:"running"};function toAgentRuntimeData(Au){const lo=typeof Au.status=="string"?Au.status.toLowerCase():"",$u=RUNTIME_STATUS_MAP[lo]??"running",Ru=Au.environment;return{...Au,environment:{name:String(Ru?.name||"").trim(),title:String(Ru?.title||"").trim()||void 0,cpu:String(Ru?.cpu||"").trim()||void 0,memory:String(Ru?.memory||"").trim()||void 0,gpu:String(Ru?.gpu||"").trim()||void 0,resources:Ru?.resources},status:$u,name:Au.given_name||Au.runtime_name,id:Au.runtime_name,url:Au.ingress,messageCount:0,agent_spec_id:Au.agent_spec_id||void 0,content_attachments:Array.isArray(Au.content_attachments)?Au.content_attachments:[]}}function useAgentRuntimes(Au={}){const{agentSpecId:lo,agentConfig:$u,autoCreateAgent:Ru=!0,autoStart:Iu=!1,agentSpec:Pu,variant:Ou,runtimeCreationTarget:Mu,runtimeCreationBaseUrl:Du,runtimeConnection:Lu,appLaunch:Bu}=Au,ju=toAgentRuntimeVariant(Ou??Mu),Fu=launchesOwnRoutesOnly(Bu),{configuration:zu}=useCoreStore(),Uu=useAgentRuntimeConnection(),Hu=useAgentRuntimeStatus(),Vu=useAgentRuntimeError(),Gu=useAgentRuntimeIsLaunching(),Wu=useAgentRuntimeStore($d=>$d.launchAgent),Zu=useAgentRuntimeStore($d=>$d.connectAgent),Ju=useAgentRuntimeStore($d=>$d.createAgent),Yu=useAgentRuntimeStore($d=>$d.disconnect),[Xu,ed]=reactExports.useState("idle"),[td,nd]=reactExports.useState(null),[od,sd]=reactExports.useState(!1),ad=reactExports.useRef(!1),[pd,vd]=reactExports.useState(!1),Sd=reactExports.useRef(!1),_d=reactExports.useRef(null),bd=reactExports.useRef(!1),wd=reactExports.useRef($u);wd.current=$u;const Ad=!!lo&&locationOf(ju)==="cloud",gd=Lu?[Lu.runtimeName,Lu.environmentName,Lu.jupyterBaseUrl||Lu.serviceManager?.serverSettings.baseUrl||"",Lu.kernelId||""].join(":"):null,dd=reactExports.useMemo(()=>Du||(runsInBrowser(ju)?"":locationOf(ju)==="local"?"http://localhost:8765":zu?.runtimesUrl||void 0||"https://r1.datalayer.run"),[zu?.runtimesUrl,Du,ju]),yd=reactExports.useCallback(async()=>{try{const{iamStore:$d,coreStore:Id}=await __vitePreload(async()=>{const{iamStore:th,coreStore:Eh}=await import("./chunks/index-J-pyZzZ8.js");return{iamStore:th,coreStore:Eh}},[],import.meta.url),Vd=$d.getState().token||"",Wd=Id.getState().configuration?.aiAgentsUrl||"";return{token:Vd,aiAgentsUrl:Wd,runtimesUrl:dd}}catch{return{token:"",aiAgentsUrl:"",runtimesUrl:""}}},[dd]);reactExports.useEffect(()=>{!Lu||!gd||(Uu?[Uu.runtimeName,Uu.environmentName,Uu.jupyterBaseUrl||"",Uu.kernelId||""].join(":"):null)===gd||(Sd.current=!1,Zu(Lu))},[Lu,gd,Uu,Zu]);const ld=reactExports.useCallback(async $d=>{if(runsInBrowser(ju))return BROWSER_AGENT_CONNECTION;if(Ad){ed("launching"),nd(null);try{const Vd=(typeof $u?.name=="string"&&$u.name||typeof Pu?.name=="string"&&Pu.name||`${lo}`).replace(/\//g,"-").replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,63),Md=await Wu($d?{...$d,...Bu,runtimesUrl:dd}:{environmentName:"ai-agents-env",creditsLimit:10,givenName:Vd,...Bu,runtimesUrl:dd});return ed("ready"),Md}catch(Id){const Vd=Id instanceof Error?Id.message:String(Id);throw nd(Vd),ed("error"),Id}}else{if(!$d)throw new Error("Runtime options are required in connect mode");return Wu({...$d,runtimesUrl:dd})}},[$u?.name,Pu?.name,lo,Bu,Ad,dd,Wu,ju]),ud=reactExports.useCallback(async $d=>{if(bd.current)throw new Error("Agent creation already in progress");bd.current=!0,sd(!0);try{const Id={};Pu&&(Pu.model&&(Id.model=Pu.model),Pu.protocol&&(Id.protocol=Pu.protocol),Pu.systemPrompt&&(Id.systemPrompt=Pu.systemPrompt),Pu.description&&(Id.description=Pu.description),Pu.name&&(Id.name=Pu.name));const Vd={...DEFAULT_AGENT_CONFIG,...Id,...$u,...$d,name:$d?.name||$u?.name||(Ad&&lo?lo:Uu?.runtimeName)};return await Ju(Vd)}catch(Id){const Vd=Id instanceof Error?Id.message:String(Id);throw Ad&&(nd(Vd),ed("error")),Id}finally{bd.current=!1,sd(!1)}},[lo,$u,Pu,Ad,Uu,Ju]),hd=reactExports.useCallback(async()=>{const $d=Uu?.agentId,Id=Uu?.agentBaseUrl,Vd=$d&&Id?agentDeletionUrl(Id,$d,Fu):void 0;if(Vd)try{const{token:Md}=await yd();await fetch(Vd,{method:"DELETE",headers:Md?{Authorization:`Bearer ${Md}`}:{}})}catch{}Sd.current=!1,ad.current=!1,ed("idle"),nd(null),agentRuntimeStore.getState().reset()},[Uu?.agentId,Uu?.agentBaseUrl,yd,Fu]);reactExports.useEffect(()=>{!Ad&&Ru&&Uu&&Hu==="ready"&&!Uu.isReady&&!Sd.current&&(Sd.current=!0,Ju(wd.current).catch($d=>{console.error("[useAgent] Failed to auto-create agent:",$d),Sd.current=!1}))},[Ad,Ru,Uu,Hu,Ju]),reactExports.useEffect(()=>{Ad&&Ru&&Uu&&(Xu==="ready"||Xu==="resumed")&&!Uu.isReady&&!Sd.current&&(Sd.current=!0,ud(wd.current).catch($d=>{console.error("[useAgents] Failed to auto-create agent:",$d);const Id=$d instanceof Error?$d.message:String($d);nd(Id),ed("error"),Sd.current=!1}))},[Ad,Ru,Uu,Xu,ud]),reactExports.useEffect(()=>{const $d=Uu?.runtimeName||null;if(!$d){_d.current=null;return}_d.current&&_d.current!==$d&&(Sd.current=!1),_d.current=$d},[Uu?.runtimeName]),reactExports.useEffect(()=>{if(!Ad||Uu||Xu!=="idle")return;if(Bu){vd(!0);return}let $d=!1;return(async()=>{try{const{token:Vd,runtimesUrl:Md}=await yd();if(!Vd)return;const{listRuntimes:Wd}=await __vitePreload(async()=>{const{listRuntimes:ih}=await import("./chunks/runtimes-D0qXa51n.js");return{listRuntimes:ih}},[],import.meta.url),ah=((await Wd(Vd,Md)).runtimes||[]).filter(ih=>ih.environment?.name!=="ai-agents-env"?!1:lo?ih.agent_spec_id===lo:!0).slice().sort((ih,Mh)=>{const qd=Number(ih.started_at||0);return Number(Mh.started_at||0)-qd})[0];if($d||!ah?.runtime_name||!ah?.ingress)return;Zu({runtimeName:ah.runtime_name,environmentName:ah.environment.name,jupyterBaseUrl:ah.ingress}),Sd.current=!1;const yh=ah,vh=typeof yh.status=="string"?yh.status.toLowerCase():"",Jd=RUNTIME_STATUS_MAP[vh]??"running",eh=Jd==="paused"?"paused":Jd==="resuming"||Jd==="resumed"?"resumed":"running";ed(eh==="paused"?"paused":eh==="resumed"?"resumed":"ready")}catch(Vd){console.warn("[useAgents] Failed to find existing runtime:",Vd)}finally{$d||vd(!0)}})(),()=>{$d=!0}},[Ad,Uu,Iu,Xu,yd,lo,Bu,Zu]),reactExports.useEffect(()=>{(Hu==="disconnected"||Hu==="idle")&&(Sd.current=!1)},[Hu]),reactExports.useEffect(()=>{Ad&&Iu&&pd&&!Uu&&!ad.current&&Xu==="idle"&&(ad.current=!0,ld())},[Ad,Iu,pd,Uu,Xu,ld]),reactExports.useEffect(()=>{Vu&&Ad&&Xu!=="error"&&(nd(Vu),ed("error"))},[Vu,Ad,Xu]);const md=runsInBrowser(ju),Ed=md?"ready":Ad?Xu:Hu,Td=md?null:Ad&&td||Vu,Rd=md?!0:Ad?(Xu==="ready"||Xu==="resumed")&&!!Uu?.isReady:Hu==="ready"&&!!Uu?.isReady,jd=Uu?.endpoint||null,Cd=Uu?.serviceManager||null;return{runtime:Uu,status:Ed,isLaunching:Gu,launchRuntime:ld,connectToRuntime:Zu,disconnect:Yu,endpoint:jd,serviceManager:Cd,createAgent:ud,teardown:hd,isCreating:od,isReady:Rd,error:Td,variant:ju,runtimeCreationTarget:legacyTargetOf(ju),runtimeCreationBaseUrl:dd}}function useAgentRuntimesQuery(Au,lo){const{configuration:$u}=useCoreStore(),{requestDatalayer:Ru}=useDatalayer({notifyOnError:!1}),{user:Iu}=useIAMStore(),Pu=useQueryClient();return useQuery({queryKey:[...agentQueryKeys.agentRuntimes.lists(),"","","",""],queryFn:async()=>{const Mu=new URLSearchParams().toString(),Du=await Ru({url:`${runtimesUrl($u.runtimesUrl)}${Mu?`?${Mu}`:""}`,method:"GET"});if(Du.success&&Du.runtimes){const Lu=Du.runtimes.filter(Bu=>Bu.environment?.name==="ai-agents-env").map(toAgentRuntimeData).filter(Bu=>!isStaleDeletedRuntime(Bu));return Lu.forEach(Bu=>{Pu.setQueryData(agentQueryKeys.agentRuntimes.detail(Bu.runtime_name),Bu)}),Lu}return[]},...AGENT_QUERY_OPTIONS,refetchInterval:lo?.refetchInterval??1e4,refetchOnMount:!0,refetchOnWindowFocus:!0,enabled:(lo?.enabled??!0)&&!!Iu})}function useCreateAgentRuntime(){const{configuration:Au}=useCoreStore(),{requestDatalayer:lo}=useDatalayer({notifyOnError:!1}),$u=useQueryClient();return useMutation({mutationFn:async Ru=>{const Iu=(Ru.contentAttachmentUids??[]).map(Pu=>String(Pu||"").trim()).filter(Boolean);return lo({url:runtimesUrl(Au.runtimesUrl),method:"POST",body:{environment:{name:Ru.environmentName||"ai-agents-env"},given_name:Ru.givenName||"Agent",credits_limit:Ru.creditsLimit||10,type:Ru.type||"notebook",editor_variant:Ru.editorVariant||"none",enable_codemode:Ru.enableCodemode??!1,agent_spec_id:Ru.agentSpecId||void 0,agent_spec:Ru.agentSpec||void 0,user_account_handle:Ru.userAccountHandle||void 0,billing_entity_uid:Ru.billingEntityUid||void 0,billing_entity_type:Ru.billingEntityType||void 0,billing_entity_handle:Ru.billingEntityHandle||void 0,billing_source_organization_uid:Ru.billingSourceOrganizationUid||void 0,billing_source_organization_handle:Ru.billingSourceOrganizationHandle||void 0,runtime_name:Ru.runtimeName||void 0,content_attachment_uids:Iu.length?Iu:void 0}})},onSuccess:Ru=>{if(Ru.success&&Ru.runtime){const Iu=toAgentRuntimeData(Ru.runtime);clearRuntimeDeleted(Iu.runtime_name),$u.setQueryData(agentQueryKeys.agentRuntimes.detail(Iu.runtime_name),Iu),$u.invalidateQueries({queryKey:agentQueryKeys.agentRuntimes.all()})}}})}function useDeleteAgentRuntime(){const{configuration:Au}=useCoreStore(),{requestDatalayer:lo}=useDatalayer({notifyOnError:!1}),$u=useQueryClient(),Ru=Pu=>{if(!Pu||typeof Pu!="object")return;const Ou=Pu.response;return typeof Ou?.status=="number"?Ou.status:void 0},Iu=Pu=>{if(!Pu||typeof Pu!="object")return"";const Ou=Pu.response?.data;return String(Ou?.detail||Ou?.message||Pu.message||"").toLowerCase()};return useMutation({mutationFn:async Pu=>{try{return await lo({url:runtimeUrl(Au.runtimesUrl,Pu),method:"DELETE"})}catch(Ou){const Mu=Ru(Ou),Du=Iu(Ou);if(!(Mu===404||Du.includes("no reservation")||Du.includes("unknown reservation")||Du.includes("not found")))throw Ou;try{throw await lo({url:runtimeUrl(Au.runtimesUrl,Pu),method:"GET"}),Ou}catch(Bu){if(Ru(Bu)===404)return{success:!0,recovered:!0};throw Ou}}},onSuccess:(Pu,Ou)=>{markRuntimeDeleted(Ou),runtimesStore.getState().removeRuntime(Ou),$u.setQueriesData({queryKey:agentQueryKeys.agentRuntimes.lists()},Mu=>Array.isArray(Mu)?Mu.filter(Du=>Du.runtime_name!==Ou):Mu),$u.cancelQueries({queryKey:agentQueryKeys.agentRuntimes.detail(Ou)}),$u.removeQueries({queryKey:agentQueryKeys.agentRuntimes.detail(Ou)}),$u.invalidateQueries({queryKey:agentQueryKeys.agentRuntimes.lists()}),$u.refetchQueries({queryKey:agentQueryKeys.agentRuntimes.lists(),type:"active"}),$u.invalidateQueries({queryKey:agentQueryKeys.checkpoints.all()})}})}function useRefreshAgentRuntimes(){const Au=useQueryClient();return reactExports.useCallback(()=>{Au.invalidateQueries({queryKey:agentQueryKeys.agentRuntimes.all()})},[Au])}const DEFAULT_LIFECYCLE_RECORD={resumePending:!1,pauseLockedForResumed:!1};create$f()(persist((Au,lo)=>({byRuntimeKey:{},markResumePending:$u=>{$u&&Au(Ru=>({byRuntimeKey:{...Ru.byRuntimeKey,[$u]:{...DEFAULT_LIFECYCLE_RECORD,...Ru.byRuntimeKey[$u]??{},resumePending:!0}}}))},markResumeFailed:$u=>{$u&&Au(Ru=>({byRuntimeKey:{...Ru.byRuntimeKey,[$u]:{...DEFAULT_LIFECYCLE_RECORD,...Ru.byRuntimeKey[$u]??{},resumePending:!1,pauseLockedForResumed:!1}}}))},markResumeSettled:$u=>{$u&&Au(Ru=>({byRuntimeKey:{...Ru.byRuntimeKey,[$u]:{...DEFAULT_LIFECYCLE_RECORD,...Ru.byRuntimeKey[$u]??{},resumePending:!1,pauseLockedForResumed:!0}}}))},clearRuntimeLifecycle:$u=>{if(!$u)return;const Ru={...lo().byRuntimeKey};delete Ru[$u],Au({byRuntimeKey:Ru})}}),{name:"datalayer-agent-lifecycle",storage:createJSONStorage(()=>localStorage),partialize:Au=>({byRuntimeKey:Au.byRuntimeKey})}));function useAgentsRuntimes(Au,lo){const $u=useAgentRuntimesQuery(Au,lo),Ru=useCreateAgentRuntime(),Iu=useDeleteAgentRuntime(),Pu=useRefreshAgentRuntimes(),Ou=reactExports.useCallback(async(Mu,Du)=>{const Lu=String(Mu||"").trim();if(Lu)return Du?.beforeStop&&await Du.beforeStop(),Iu.mutateAsync(Lu)},[Iu]);return reactExports.useMemo(()=>({runtimes:$u.data??EMPTY_RUNTIMES,isRuntimesLoading:$u.isLoading,isRuntimesError:$u.isError,runtimesError:$u.error,refetchRuntimes:()=>$u.refetch(),refreshRuntimes:Pu,stopRuntimeByName:Ou,createRuntime:async Mu=>Ru.mutateAsync(Mu)}),[$u.data,$u.isLoading,$u.isError,$u.error,$u.refetch,Pu,Ou,Ru,Iu])}const DEFAULT_WS_PATH="/api/v1/tool-approvals/ws",DEFAULT_RECONNECT_DELAY_MS=3e3;function useAgentRuntimeWebSocket(Au){const{enabled:lo=!0,baseUrl:$u,authToken:Ru,agentId:Iu,autoReconnect:Pu=!0,reconnectDelayMs:Ou=DEFAULT_RECONNECT_DELAY_MS,maxReconnectAttempts:Mu}=Au,Du=reactExports.useRef(Au.onMessage);Du.current=Au.onMessage,reactExports.useEffect(()=>{if(!lo||!$u){agentRuntimeStore.getState().setWsState("closed");return}let Lu=!1,Bu=0,ju=null;function Fu(){const Uu=`${$u}${DEFAULT_WS_PATH}`,Hu=new URL(Uu.replace(/^http/,"ws"));return Ru&&Hu.searchParams.set("token",Ru),Iu&&Hu.searchParams.set("agent_id",Iu),Hu.toString()}function zu(){if(Lu)return;const Uu=Fu();agentRuntimeStore.getState().setWsState("connecting");const Hu=new WebSocket(Uu);agentRuntimeStore.getState().setWs(Hu,Iu),Hu.onopen=()=>{Bu=0,agentRuntimeStore.getState().setWsState("connected")},Hu.onmessage=Vu=>{let Gu;try{Gu=JSON.parse(String(Vu.data))}catch{return}const Wu=parseAgentStreamMessage(Gu);if(Du.current?.({type:Wu?.type,payload:Wu?.payload,raw:Gu}),!Wu)return;const Zu=agentRuntimeStore.getState();if(Wu.type==="agent.snapshot"){Zu.applySnapshot(Wu.payload);return}if(Wu.type==="agent.subagent"){Zu.appendSubagentEvent(Wu.payload);return}if(Wu.type==="agent.compaction"){Zu.setCompaction(Wu.payload);return}},Hu.onclose=()=>{if(agentRuntimeStore.getState().setWs(null,Iu),agentRuntimeStore.getState().setWsState("closed"),Lu||!Pu||(Bu+=1,typeof Mu=="number"&&Bu>Mu))return;const Vu=typeof Ou=="function"?Ou(Bu):Ou;ju=setTimeout(zu,Math.max(0,Vu))},Hu.onerror=()=>{(Hu.readyState===WebSocket.CONNECTING||Hu.readyState===WebSocket.OPEN)&&Hu.close()}}return zu(),()=>{Lu=!0,ju&&clearTimeout(ju),agentRuntimeStore.getState().setWs(null,Iu),agentRuntimeStore.getState().resetWs()}},[lo,$u,Ru,Iu,Pu,Ou,Mu])}const ALPHAVANTAGE_MCP_SERVER_0_0_1={id:"alphavantage",version:"0.0.1",name:"Alpha Vantage",description:"Financial market data and stock information",icon:"@primer/octicons-react:graph",emoji:"💹",url:"",command:"uvx",args:["av-mcp==0.2.1","${ALPHAVANTAGE_API_KEY}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["ALPHAVANTAGE_API_KEY:0.0.1"]},CHART_MCP_SERVER_0_0_1={id:"chart",version:"0.0.1",name:"Chart Generator",description:"Generate charts and visualizations",icon:"@datalayer/icons-react:chart-bar",emoji:"📊",url:"",command:"npx",args:["-y","@antv/mcp-server-chart"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},DATALAYER_MCP_SERVER_0_0_1={id:"datalayer",version:"0.0.1",name:"Datalayer",description:"Read, edit and run Jupyter notebooks on Datalayer, with sandboxes and data",icon:"@datalayer/icons-react:datalayer",emoji:"🚀",url:"",command:"npx",args:["-y","mcp-remote","https://mcp.datalayer.run/mcp","--header","Authorization: Bearer ${DATALAYER_API_KEY}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["DATALAYER_API_KEY:0.0.1"]},EARTHDATA_MCP_SERVER_0_0_1={id:"earthdata",version:"0.0.1",name:"Earthdata MCP",description:"Access NASA Earthdata search and metadata capabilities",icon:"@datalayer/icons-react:globe-americas",emoji:"🌍",url:"",command:"npx",args:["-y","mcp-remote","https://mcp.datalayer.run/mcp?only=earthdata","--header","Authorization: Bearer ${DATALAYER_API_KEY}"],transport:"stdio",enabled:!0,isAvailable:!1,tools:[],requiredEnvVars:["DATALAYER_API_KEY:0.0.1"]},EURUS_MCP_SERVER_0_0_1={id:"eurus",version:"0.0.1",name:"Eurus Climate MCP",description:"Climate and reanalysis analysis tools for spatial workflows",icon:"@primer/octicons-react:cloud",emoji:"🌦️",url:"",command:"eurus-mcp",args:[],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},FILESYSTEM_MCP_SERVER_0_0_1={id:"filesystem",version:"0.0.1",name:"Filesystem",description:"Local filesystem read/write operations",icon:"@primer/octicons-react:file-directory",emoji:"📁",url:"",command:"npx",args:["-y","@modelcontextprotocol/server-filesystem","${TMPDIR}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},GITHUB_MCP_SERVER_0_0_1={id:"github",version:"0.0.1",name:"GitHub",description:"GitHub repository operations (issues, PRs, code search)",icon:"@datalayer/icons-react:github-mark",emoji:"🐙",url:"",command:"docker",args:["run","-i","--rm","-e","GITHUB_PERSONAL_ACCESS_TOKEN","ghcr.io/github/github-mcp-server"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["GITHUB_TOKEN:0.0.1"]},GOOGLE_WORKSPACE_MCP_SERVER_0_0_1={id:"google-workspace",version:"0.0.1",name:"Google Workspace",description:"Gmail of the person an application acts for, read or read and send, with a token Datalayer mints per call",icon:"@datalayer/icons-react:google",emoji:"📧",url:"http://127.0.0.1:9711/mcp",command:"uvx",args:["workspace-mcp","--transport","streamable-http","--permissions","gmail:send"],transport:"streamable-http",enabled:!0,isAvailable:!1,tools:[],requiredEnvVars:[]},HUGGINGFACE_MCP_SERVER_0_0_1={id:"huggingface",version:"0.0.1",name:"Hugging Face",description:"Hugging Face models, datasets, spaces, and papers access",icon:"@primer/octicons-react:hubot",emoji:"🤗",url:"",command:"npx",args:["-y","mcp-remote","https://huggingface.co/mcp","--header","Authorization: Bearer ${HF_TOKEN}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["HF_TOKEN:0.0.1"]},KAGGLE_MCP_SERVER_0_0_1={id:"kaggle",version:"0.0.1",name:"Kaggle",description:"Kaggle datasets, models, competitions, and notebooks access",icon:"@datalayer/icons-react:kaggle",emoji:"🏆",url:"",command:"npx",args:["-y","mcp-remote","https://www.kaggle.com/mcp","--header","Authorization: Bearer ${KAGGLE_API_TOKEN}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["KAGGLE_API_TOKEN:0.0.1"]},ODOO_ACCOUNTING_MCP_SERVER_0_0_1={id:"odoo-accounting",version:"0.0.1",name:"Odoo Accounting",description:"An accountant's day in Odoo — invoices, bills, journal entries, reconciliations, bank lines and tax returns — through the Datalayer MCP server",icon:"@datalayer/icons-react:odoo",emoji:"🧮",url:"",command:"npx",args:["-y","mcp-remote","https://mcp.datalayer.run/mcp?only=odoo-accounting","--header","Authorization: Bearer ${DATALAYER_API_KEY}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["DATALAYER_API_KEY:0.0.1"]},ODOO_MCP_SERVER_0_0_1={id:"odoo",version:"0.0.1",name:"Odoo",description:"Odoo ERP operations (search, invoices, journals, reconciliations)",icon:"@datalayer/icons-react:odoo",emoji:"🧾",url:"",command:"uvx",args:["mcp-server-odoo"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},SALESFORCE_MCP_SERVER_0_0_1={id:"salesforce",version:"0.0.1",name:"Salesforce",description:"Salesforce CRM operations (queries, reports, objects, SOQL)",icon:"@primer/octicons-react:briefcase",emoji:"☁️",url:"",command:"npx",args:["-y","@anthropic/salesforce-mcp-server"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["SALESFORCE_ACCESS_TOKEN:0.0.1","SALESFORCE_INSTANCE_URL:0.0.1"]},SLACK_MCP_SERVER_0_0_1={id:"slack",version:"0.0.1",name:"Slack",description:"Slack messaging and channel operations",icon:"@datalayer/icons-react:slack",emoji:"💬",url:"",command:"npx",args:["-y","@datalayer/slack-mcp-server"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["SLACK_BOT_TOKEN:0.0.1","SLACK_TEAM_ID:0.0.1","SLACK_CHANNEL_IDS:0.0.1"]},TAVILY_MCP_SERVER_0_0_1={id:"tavily",version:"0.0.1",name:"Tavily Search",description:"Web search and research capabilities via Tavily API",icon:"@primer/octicons-react:search",emoji:"🔍",url:"",command:"npx",args:["-y","tavily-mcp"],transport:"stdio",enabled:!0,isAvailable:!1,tools:[],requiredEnvVars:["TAVILY_API_KEY:0.0.1"]},MCP_SERVER_LIBRARY={alphavantage:ALPHAVANTAGE_MCP_SERVER_0_0_1,chart:CHART_MCP_SERVER_0_0_1,datalayer:DATALAYER_MCP_SERVER_0_0_1,earthdata:EARTHDATA_MCP_SERVER_0_0_1,eurus:EURUS_MCP_SERVER_0_0_1,filesystem:FILESYSTEM_MCP_SERVER_0_0_1,github:GITHUB_MCP_SERVER_0_0_1,"google-workspace":GOOGLE_WORKSPACE_MCP_SERVER_0_0_1,huggingface:HUGGINGFACE_MCP_SERVER_0_0_1,kaggle:KAGGLE_MCP_SERVER_0_0_1,"odoo-accounting":ODOO_ACCOUNTING_MCP_SERVER_0_0_1,odoo:ODOO_MCP_SERVER_0_0_1,salesforce:SALESFORCE_MCP_SERVER_0_0_1,slack:SLACK_MCP_SERVER_0_0_1,tavily:TAVILY_MCP_SERVER_0_0_1},ACCOUNTING_SKILL_SPEC_0_0_1={id:"accounting",version:"0.0.1",name:"Accounting Skill",description:"Accounting analysis workflows for reconciliation, close, variance, and audit-ready summaries",module:"agent_skills.skills.accounting",package:void 0,method:void 0,path:void 0,requiredEnvVars:[],optionalEnvVars:[],dependencies:["pandas>=2.0.0"],tags:["accounting","finance","reconciliation","close"],icon:"@primer/octicons-react:book",emoji:"🧮",enabled:!1},CRAWL_SKILL_SPEC_0_0_1={id:"crawl",version:"0.0.1",name:"Web Crawl Skill",description:"Web crawling and content extraction capabilities",module:"agent_skills.skills.crawl",package:void 0,method:void 0,path:void 0,requiredEnvVars:["TAVILY_API_KEY:0.0.1"],optionalEnvVars:[],dependencies:["requests>=2.31.0","beautifulsoup4>=4.12.0"],tags:["web","crawl","scraping"],icon:"@primer/octicons-react:globe",emoji:"🌐",enabled:!0},EVENTS_SKILL_SPEC_0_0_1={id:"events",version:"0.0.1",name:"Events Skill",description:"Event generation, enrichment, and lifecycle orchestration",module:"agent_skills.skills.events",package:void 0,method:void 0,path:void 0,requiredEnvVars:[],optionalEnvVars:[],dependencies:["httpx>=0.27.0"],tags:["events","orchestration","automation"],icon:"@primer/octicons-react:calendar",emoji:"📅",enabled:!1},GITHUB_SKILL_SPEC_0_0_1={id:"github",version:"0.0.1",name:"GitHub Skill",description:"GitHub repository management and code operations",module:"agent_skills.skills.github",package:void 0,method:void 0,path:void 0,requiredEnvVars:["GITHUB_TOKEN:0.0.1"],optionalEnvVars:[],dependencies:["PyGithub>=2.1.0"],tags:["github","git","code"],icon:"@datalayer/icons-react:github-mark",emoji:"🐙",enabled:!1},JOKES_SKILL_SPEC_0_0_1={id:"jokes",version:"0.0.1",name:"Jokes Skill",description:"Return random jokes from a local path-based skill.",module:void 0,package:void 0,method:void 0,path:"jokes",requiredEnvVars:[],optionalEnvVars:[],dependencies:[],tags:["fun","humor","demo"],icon:"@primer/octicons-react:smiley",emoji:"😄",enabled:!1},PDF_SKILL_SPEC_0_0_1={id:"pdf",version:"0.0.1",name:"PDF Processing Skill",description:"PDF document reading, parsing, and extraction",module:"agent_skills.skills.pdf",package:void 0,method:void 0,path:void 0,requiredEnvVars:[],optionalEnvVars:[],dependencies:["PyPDF2>=3.0.0","pdfplumber>=0.10.0"],tags:["pdf","documents","extraction"],icon:"@primer/octicons-react:file",emoji:"📄",enabled:!1},TEXT_SUMMARIZER_SKILL_SPEC_0_0_1={id:"text-summarizer",version:"0.0.1",name:"Text Summarizer Skill",description:"Summarize text content using extractive and abstractive techniques. Use when the user asks for summaries, key points, or condensed versions of documents.",module:void 0,package:"agent_skills.skills.text_summarizer",method:"summarize_text",path:void 0,requiredEnvVars:[],optionalEnvVars:[],dependencies:["agent-skills>=0.0.1"],tags:["nlp","summarization","text-processing"],icon:"@primer/octicons-react:note",emoji:"📝",enabled:!1},SKILLS_CATALOG={accounting:ACCOUNTING_SKILL_SPEC_0_0_1,crawl:CRAWL_SKILL_SPEC_0_0_1,events:EVENTS_SKILL_SPEC_0_0_1,github:GITHUB_SKILL_SPEC_0_0_1,jokes:JOKES_SKILL_SPEC_0_0_1,pdf:PDF_SKILL_SPEC_0_0_1,"text-summarizer":TEXT_SUMMARIZER_SKILL_SPEC_0_0_1},CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1={id:"create-plan",version:"0.0.1",name:"Create Plan",description:"Create a plan with multiple steps and emit an AG-UI state snapshot.",tags:["example","ag-ui","state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"create_plan"},icon:"@primer/octicons-react:list-unordered",emoji:"📋"},CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1={id:"current-time",version:"0.0.1",name:"Current Time",description:"Return the current time in ISO format for a given timezone.",tags:["example","ag-ui","time"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"current_time"},icon:"@primer/octicons-react:clock",emoji:"🕒"},DECIDE_BACKEND_TOOL_SPEC_0_0_1={id:"decide",version:"0.0.1",name:"Decide",description:"Ask Jev typed questions about a text — noul (does a statement hold, with its probability), choice (one of named options) or score (a step on a rubric) — and get the typed answers back, through datalayer-ai-inference.",tags:["runtime","decisions","jev"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.tools.decisions",method:"decide"},icon:"@primer/octicons-react:law",emoji:"⚖️"},DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1={id:"display-recipe",version:"0.0.1",name:"Display Recipe",description:"Update the shared recipe state and emit an AG-UI state snapshot.",tags:["example","ag-ui","shared-state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"display_recipe"},icon:"@primer/octicons-react:book",emoji:"🍳"},EXAMPLE_CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1={id:"example-create-plan",version:"0.0.1",name:"Create Plan",description:"Create a plan with multiple steps and emit an AG-UI state snapshot.",tags:["example","ag-ui","state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"create_plan"},icon:"@primer/octicons-react:list-unordered",emoji:"📋"},EXAMPLE_CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1={id:"example-current-time",version:"0.0.1",name:"Current Time",description:"Return the current time in ISO format for a given timezone.",tags:["example","ag-ui","time"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"current_time"},icon:"@primer/octicons-react:clock",emoji:"🕒"},EXAMPLE_DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1={id:"example-display-recipe",version:"0.0.1",name:"Display Recipe",description:"Update the shared recipe state and emit an AG-UI state snapshot.",tags:["example","ag-ui","shared-state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"display_recipe"},icon:"@primer/octicons-react:book",emoji:"🍳"},EXAMPLE_GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1={id:"example-generate-haiku",version:"0.0.1",name:"Generate Haiku",description:"Generate a haiku (Japanese + English + gradient) rendered as a card by the frontend.",tags:["example","ag-ui","generative-ui"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"generate_haiku"},icon:"@primer/octicons-react:pencil",emoji:"🖋️"},EXAMPLE_GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1={id:"example-generate-task-steps",version:"0.0.1",name:"Generate Task Steps",description:"Generate task steps for human review and emit an AG-UI state snapshot.",tags:["example","ag-ui","human-in-the-loop"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"generate_task_steps"},icon:"@primer/octicons-react:tasklist",emoji:"🙋"},EXAMPLE_GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1={id:"example-get-weather",version:"0.0.1",name:"Get Weather",description:"Fetch current weather for a location from the Open-Meteo API for frontend rendering.",tags:["example","ag-ui","weather"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"get_weather"},icon:"@primer/octicons-react:sun",emoji:"🌤️"},EXAMPLE_RENDER_A2UI_SURFACE_BACKEND_TOOL_SPEC_0_0_1={id:"example-render-a2ui-surface",version:"0.0.1",name:"Render A2UI Surface",description:"Turn a declarative field spec into a validated A2UI v0.9 surface rendered live by the frontend as an interactive form/card.",tags:["example","ag-ui","a2ui","generative-ui"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.a2ui",method:"render_a2ui_surface"},icon:"@primer/octicons-react:browser",emoji:"🎛️"},EXAMPLE_UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1={id:"example-update-plan-step",version:"0.0.1",name:"Update Plan Step",description:"Update a plan step and emit an AG-UI state delta (JSON Patch RFC 6902).",tags:["example","ag-ui","state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"update_plan_step"},icon:"@primer/octicons-react:checklist",emoji:"✅"},GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1={id:"generate-haiku",version:"0.0.1",name:"Generate Haiku",description:"Generate a haiku (Japanese + English + gradient) rendered as a card by the frontend.",tags:["example","ag-ui","generative-ui"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"generate_haiku"},icon:"@primer/octicons-react:pencil",emoji:"🖋️"},GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1={id:"generate-task-steps",version:"0.0.1",name:"Generate Task Steps",description:"Generate task steps for human review and emit an AG-UI state snapshot.",tags:["example","ag-ui","human-in-the-loop"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"generate_task_steps"},icon:"@primer/octicons-react:tasklist",emoji:"🙋"},GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1={id:"get-weather",version:"0.0.1",name:"Get Weather",description:"Fetch current weather for a location from the Open-Meteo API for frontend rendering.",tags:["example","ag-ui","weather"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"get_weather"},icon:"@primer/octicons-react:sun",emoji:"🌤️"},RUNTIME_ECHO_BACKEND_TOOL_SPEC_0_0_1={id:"runtime-echo",version:"0.0.1",name:"Runtime Echo",description:"Echo text back to the caller for quick runtime verification.",tags:["runtime","utility"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools",method:"runtime_echo"},icon:"@primer/octicons-react:comment",emoji:"💬"},RUNTIME_SEND_MAIL_BACKEND_TOOL_SPEC_0_0_1={id:"runtime-send-mail",version:"0.0.1",name:"Runtime Send Mail (Fake)",description:"Fake mail sender for tool approval demos; returns a simulated send receipt.",tags:["runtime","approval","mail"],enabled:!0,approval:"manual",timeout:void 0,requiresApproval:!0,runtime:{language:"python",package:"agent_runtimes.examples.tools",method:"runtime_send_mail"},icon:"@primer/octicons-react:mail",emoji:"📧"},RUNTIME_SENSITIVE_ECHO_BACKEND_TOOL_SPEC_0_0_1={id:"runtime-sensitive-echo",version:"0.0.1",name:"Runtime Sensitive Echo",description:"Echo text with a manual approval checkpoint before execution.",tags:["runtime","approval"],enabled:!0,approval:"manual",timeout:void 0,requiresApproval:!0,runtime:{language:"python",package:"agent_runtimes.examples.tools",method:"runtime_sensitive_echo"},icon:"@primer/octicons-react:shield",emoji:"🛡️"},UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1={id:"update-plan-step",version:"0.0.1",name:"Update Plan Step",description:"Update a plan step and emit an AG-UI state delta (JSON Patch RFC 6902).",tags:["example","ag-ui","state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"update_plan_step"},icon:"@primer/octicons-react:checklist",emoji:"✅"},BACKEND_TOOL_CATALOG={"create-plan":CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1,"current-time":CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1,decide:DECIDE_BACKEND_TOOL_SPEC_0_0_1,"display-recipe":DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1,"example-create-plan":EXAMPLE_CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1,"example-current-time":EXAMPLE_CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1,"example-display-recipe":EXAMPLE_DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1,"example-generate-haiku":EXAMPLE_GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1,"example-generate-task-steps":EXAMPLE_GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1,"example-get-weather":EXAMPLE_GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1,"example-render-a2ui-surface":EXAMPLE_RENDER_A2UI_SURFACE_BACKEND_TOOL_SPEC_0_0_1,"example-update-plan-step":EXAMPLE_UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1,"generate-haiku":GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1,"generate-task-steps":GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1,"get-weather":GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1,"runtime-echo":RUNTIME_ECHO_BACKEND_TOOL_SPEC_0_0_1,"runtime-send-mail":RUNTIME_SEND_MAIL_BACKEND_TOOL_SPEC_0_0_1,"runtime-sensitive-echo":RUNTIME_SENSITIVE_ECHO_BACKEND_TOOL_SPEC_0_0_1,"update-plan-step":UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1},DECKS_FRONTEND_TOOL_SPEC_0_0_1={id:"decks",version:"0.0.1",name:"Decks",description:"Read, write and drive presentations kept as data — a deck, its slides, and the one on screen.",tags:["frontend","decks","presentations"],enabled:!0,toolset:["decks_list_decks","decks_get_deck","decks_create_deck","decks_update_deck","decks_update_slide","decks_insert_slide","decks_delete_slide","decks_list_slides","decks_get_slide","decks_add_slide","decks_delete_deck","decks_list","decks_open","decks_go_to_slide","decks_next_slide","decks_previous_slide","decks_present","decks_print"],icon:"@primer/octicons-react:project",emoji:"🃏"},JUPYTER_NOTEBOOK_EDIT_FRONTEND_TOOL_SPEC_0_0_1={id:"jupyter-notebook-edit",version:"0.0.1",name:"Jupyter Notebook (edit)",description:"Read and edit a notebook, and run cells — but never delete from it.",tags:["frontend","notebook","edit"],enabled:!0,toolset:["readCell","readAllCells","insertCell","updateCell","runCell","executeCode"],icon:"@datalayer/icons-react:jupyter",emoji:"📓"},JUPYTER_NOTEBOOK_PROPOSE_FRONTEND_TOOL_SPEC_0_0_1={id:"jupyter-notebook-propose",version:"0.0.1",name:"Jupyter Notebook (propose)",description:"Read a notebook and propose changes for a person to accept, never applying them.",tags:["frontend","notebook","propose"],enabled:!0,toolset:["readCell","readAllCells","proposeCellUpdate","runCell"],icon:"@datalayer/icons-react:jupyter",emoji:"📓"},JUPYTER_NOTEBOOK_READ_FRONTEND_TOOL_SPEC_0_0_1={id:"jupyter-notebook-read",version:"0.0.1",name:"Jupyter Notebook (read only)",description:"Read a notebook without changing it — cells, outputs and errors.",tags:["frontend","notebook","read"],enabled:!0,toolset:["readCell","readAllCells"],icon:"@datalayer/icons-react:jupyter",emoji:"📓"},JUPYTER_NOTEBOOK_FRONTEND_TOOL_SPEC_0_0_1={id:"jupyter-notebook",version:"0.0.1",name:"Jupyter Notebook",description:"Frontend tools for interacting with Jupyter notebooks.",tags:["frontend","notebook","jupyter-server"],enabled:!0,toolset:"all",icon:"@datalayer/icons-react:jupyter",emoji:"📓"},LEXICAL_DOCUMENT_FRONTEND_TOOL_SPEC_0_0_1={id:"lexical-document",version:"0.0.1",name:"Lexical Document",description:"Frontend tools for interacting with Lexical documents: reading and writing blocks, running Jupyter cells in the page, and drawing diagrams into the document with Excalidraw.",tags:["frontend","document","lexical","drawing","diagram"],enabled:!0,toolset:"all",icon:"@primer/octicons-react:file",emoji:"📄"},FRONTEND_TOOL_CATALOG={decks:DECKS_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-edit":JUPYTER_NOTEBOOK_EDIT_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-propose":JUPYTER_NOTEBOOK_PROPOSE_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-read":JUPYTER_NOTEBOOK_READ_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook":JUPYTER_NOTEBOOK_FRONTEND_TOOL_SPEC_0_0_1,"lexical-document":LEXICAL_DOCUMENT_FRONTEND_TOOL_SPEC_0_0_1},MCP_SERVER_MAP$1={"alphavantage:0.0.1":ALPHAVANTAGE_MCP_SERVER_0_0_1,"chart:0.0.1":CHART_MCP_SERVER_0_0_1,"earthdata:0.0.1":EARTHDATA_MCP_SERVER_0_0_1,"eurus:0.0.1":EURUS_MCP_SERVER_0_0_1,"filesystem:0.0.1":FILESYSTEM_MCP_SERVER_0_0_1,"github:0.0.1":GITHUB_MCP_SERVER_0_0_1,"google-workspace:0.0.1":GOOGLE_WORKSPACE_MCP_SERVER_0_0_1,"huggingface:0.0.1":HUGGINGFACE_MCP_SERVER_0_0_1,"kaggle:0.0.1":KAGGLE_MCP_SERVER_0_0_1,"odoo:0.0.1":ODOO_MCP_SERVER_0_0_1,"salesforce:0.0.1":SALESFORCE_MCP_SERVER_0_0_1,"slack:0.0.1":SLACK_MCP_SERVER_0_0_1,"tavily:0.0.1":TAVILY_MCP_SERVER_0_0_1},SKILL_MAP$1={"accounting:0.0.1":ACCOUNTING_SKILL_SPEC_0_0_1,"crawl:0.0.1":CRAWL_SKILL_SPEC_0_0_1,"events:0.0.1":EVENTS_SKILL_SPEC_0_0_1,"github:0.0.1":GITHUB_SKILL_SPEC_0_0_1,"jokes:0.0.1":JOKES_SKILL_SPEC_0_0_1,"pdf:0.0.1":PDF_SKILL_SPEC_0_0_1,"text-summarizer:0.0.1":TEXT_SUMMARIZER_SKILL_SPEC_0_0_1};function toAgentSkillSpec$1(Au){return{id:Au.id,name:Au.name,description:Au.description,version:Au.version??"0.0.1",tags:Au.tags,enabled:Au.enabled,requiredEnvVars:Au.requiredEnvVars}}const TOOL_MAP$1={"decide:0.0.1":DECIDE_BACKEND_TOOL_SPEC_0_0_1,"example-create-plan:0.0.1":EXAMPLE_CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1,"example-current-time:0.0.1":EXAMPLE_CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1,"example-display-recipe:0.0.1":EXAMPLE_DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1,"example-generate-haiku:0.0.1":EXAMPLE_GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1,"example-generate-task-steps:0.0.1":EXAMPLE_GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1,"example-get-weather:0.0.1":EXAMPLE_GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1,"example-render-a2ui-surface:0.0.1":EXAMPLE_RENDER_A2UI_SURFACE_BACKEND_TOOL_SPEC_0_0_1,"example-update-plan-step:0.0.1":EXAMPLE_UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1,"runtime-echo:0.0.1":RUNTIME_ECHO_BACKEND_TOOL_SPEC_0_0_1,"runtime-send-mail:0.0.1":RUNTIME_SEND_MAIL_BACKEND_TOOL_SPEC_0_0_1,"runtime-sensitive-echo:0.0.1":RUNTIME_SENSITIVE_ECHO_BACKEND_TOOL_SPEC_0_0_1},FRONTEND_TOOL_MAP$1={"decks:0.0.1":DECKS_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-edit:0.0.1":JUPYTER_NOTEBOOK_EDIT_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-propose:0.0.1":JUPYTER_NOTEBOOK_PROPOSE_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-read:0.0.1":JUPYTER_NOTEBOOK_READ_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook:0.0.1":JUPYTER_NOTEBOOK_FRONTEND_TOOL_SPEC_0_0_1,"lexical-document:0.0.1":LEXICAL_DOCUMENT_FRONTEND_TOOL_SPEC_0_0_1},EXAMPLE_A2A_RESEARCHER_AGENTSPEC_0_0_1={id:"example-a2a-researcher",version:"0.0.1",name:"Example A2A Researcher",description:"A research specialist served over the A2A protocol. Given a topic, gathers the key facts and returns concise, source-aware notes.",tags:["research","a2a"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],frontendTools:[],environmentName:"ai-agents-env",icon:"search",emoji:"🔎",color:"#0EA5E9",suggestions:[{text:"Gather the key facts on a topic, with sources",summary:"Key facts with sources"}],welcomeMessage:"A2A researcher ready.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:void 0,harness:"pydantic-ai",systemPrompt:"You are a meticulous research specialist, reached by other agents over the A2A protocol. Given a topic, gather the key facts and return concise, source-aware notes. Prefer verifiable claims and flag anything uncertain. Answer with the notes themselves: no preamble, no questions back. You have no tools and no web access: work from what you know, and say when something should be checked.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"a2a",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_A2A_WRITER_AGENTSPEC_0_0_1={id:"example-a2a-writer",version:"0.0.1",name:"Example A2A Writer",description:"A writing specialist served over the A2A protocol. Given notes or instructions, produces clear, well-structured prose.",tags:["writing","a2a"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],frontendTools:[],environmentName:"ai-agents-env",icon:"pencil",emoji:"✍️",color:"#F59E0B",suggestions:[{text:"Turn a set of notes into a short, structured write-up",summary:"Notes into a write-up"}],welcomeMessage:"A2A writer ready.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:void 0,harness:"pydantic-ai",systemPrompt:"You are a concise writing specialist, reached by other agents over the A2A protocol. Given notes or findings, produce clear, well-structured prose. Keep it focused and free of filler. Answer with the text itself: no preamble, no questions back. You have no tools: work from the notes and instructions you are given.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"a2a",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_A2A_AGENTSPEC_0_0_1={id:"example-a2a",version:"0.0.1",name:"Example A2A Agent",description:"Demonstrates delegation to separate agents over the A2A protocol. The orchestrator hands research and writing to a researcher and a writer that run as agents of their own — launched beside it on the local server, or on Datalayer runtimes when it runs in the cloud — and talks to them over A2A.",tags:["research","workflow","a2a"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],frontendTools:[],environmentName:"ai-agents-env",icon:"broadcast",emoji:"📡",color:"#7C3AED",suggestions:[{text:"Research three key facts about the A2A protocol through the researcher, then have the writer turn them into one short paragraph.",summary:"Research then write over A2A"},{text:"Have the researcher gather five source-backed notes on Jupyter kernels and report them to me as they are.",summary:"Research via the A2A researcher"},{text:"Have the writer draft a short guide to naming variables from these points: be specific, prefer words to abbreviations, keep units in the name.",summary:"Draft via the A2A writer"}],welcomeMessage:"A2A example agent ready. Ask me to delegate research and writing to the agents I reach over A2A.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:'You are the A2A Orchestrator. You do not research or write yourself: you split a request into specialist tasks and hand each to a separate agent reached over the A2A protocol, then synthesize their answers into one coherent reply.\nYour agents are `researcher` — facts, background, source-backed notes — and `writer` — clear, structured prose from notes or instructions. Reach them with `delegate_task`, naming the agent; a request to "research and write" is two delegations, the researcher\'s notes handed to the writer. Give each a task it can carry out without the rest of this conversation. The first delegation to an agent may take a moment while it is launched.\nAnswer in the conversation, and only with the tools you actually have; never call a tool you were not given.',systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:{includeGeneralPurpose:!1,subagents:[{name:"researcher",description:"A separate research agent, reached over A2A. Gathers facts and source-backed notes on a topic; use for research, fact-finding and background gathering.",ref:"example-a2a-researcher:0.0.1",a2a:{launch:"auto"}},{name:"writer",description:"A separate writing agent, reached over A2A. Turns notes into clear, well-structured prose; use for summaries, drafts and final write-ups.",ref:"example-a2a-writer:0.0.1",a2a:{launch:"auto"}}]}},EXAMPLE_A2UI_AGENT_SPEC_0_0_1={id:"example-a2ui-agent",version:"0.0.1",name:"A2UI Agent",description:"An AG-UI agent that generates interactive A2UI surfaces on demand. Describe a form, intake, configurator, survey or booking flow and the agent renders a validated, themeable A2UI surface you can fill in.",tags:["workflow","automation","analysis"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[TOOL_MAP$1["example-render-a2ui-surface:0.0.1"]],frontendTools:[],frontendRenderTools:[{tool:"render_a2ui_surface",renderer:"a2ui-surface"}],environmentName:"ai-agents-env",icon:"browser",emoji:"🎛️",color:"#6366F1",suggestions:[{text:"Build a support ticket intake form with category, priority and a description.",summary:"Support ticket form"},{text:"Create a trip booking form with destination, dates, travelers and budget.",summary:"Trip booking form"},{text:"Generate a customer feedback survey with a rating slider and comments.",summary:"Feedback survey"},{text:"Make a product configurator for a laptop with CPU, RAM and add-ons.",summary:"Laptop configurator"}],welcomeMessage:`Hi! I turn requests into interactive A2UI surfaces. Ask me to build a form, survey, configurator or booking flow and I'll render it live for you.
2422
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var Pu=!0,Ou=!1,Mu;return{s:function(){$u=$u.call(Au)},n:function(){var Lu=$u.next();return Pu=Lu.done,Lu},e:function(Lu){Ou=!0,Mu=Lu},f:function(){try{!Pu&&$u.return!=null&&$u.return()}finally{if(Ou)throw Mu}}}}function _unsupportedIterableToArray$1(Au,lo){if(Au){if(typeof Au=="string")return _arrayLikeToArray$1(Au,lo);var $u=Object.prototype.toString.call(Au).slice(8,-1);if($u==="Object"&&Au.constructor&&($u=Au.constructor.name),$u==="Map"||$u==="Set")return Array.from(Au);if($u==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test($u))return _arrayLikeToArray$1(Au,lo)}}function _arrayLikeToArray$1(Au,lo){(lo==null||lo>Au.length)&&(lo=Au.length);for(var $u=0,Ru=new Array(lo);$u<lo;$u++)Ru[$u]=Au[$u];return Ru}function ownKeys$1(Au,lo){var $u=Object.keys(Au);if(Object.getOwnPropertySymbols){var Ru=Object.getOwnPropertySymbols(Au);lo&&(Ru=Ru.filter(function(Iu){return Object.getOwnPropertyDescriptor(Au,Iu).enumerable})),$u.push.apply($u,Ru)}return $u}function _objectSpread$1(Au){for(var lo=1;lo<arguments.length;lo++){var $u=arguments[lo]!=null?arguments[lo]:{};lo%2?ownKeys$1(Object($u),!0).forEach(function(Ru){_defineProperty$1(Au,Ru,$u[Ru])}):Object.getOwnPropertyDescriptors?Object.defineProperties(Au,Object.getOwnPropertyDescriptors($u)):ownKeys$1(Object($u)).forEach(function(Ru){Object.defineProperty(Au,Ru,Object.getOwnPropertyDescriptor($u,Ru))})}return Au}function _defineProperty$1(Au,lo,$u){return lo=_toPropertyKey$6(lo),lo in Au?Object.defineProperty(Au,lo,{value:$u,enumerable:!0,configurable:!0,writable:!0}):Au[lo]=$u,Au}function _classCallCheck$6(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$6(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$6(Ru.key),Ru)}}function _createClass$6(Au,lo,$u){return lo&&_defineProperties$6(Au.prototype,lo),$u&&_defineProperties$6(Au,$u),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$6(Au){var lo=_toPrimitive$6(Au,"string");return _typeof$6(lo)=="symbol"?lo:lo+""}function _toPrimitive$6(Au,lo){if(_typeof$6(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$6(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var PROTOCOL_TUS_V1="tus-v1",PROTOCOL_IETF_DRAFT_03="ietf-draft-03",PROTOCOL_IETF_DRAFT_05="ietf-draft-05",defaultOptions$2={endpoint:null,uploadUrl:null,metadata:{},metadataForPartialUploads:{},fingerprint:null,uploadSize:null,onProgress:null,onChunkComplete:null,onSuccess:null,onError:null,onUploadUrlAvailable:null,overridePatchMethod:!1,headers:{},addRequestId:!1,onBeforeRequest:null,onAfterResponse:null,onShouldRetry:defaultOnShouldRetry,chunkSize:Number.POSITIVE_INFINITY,retryDelays:[0,1e3,3e3,5e3],parallelUploads:1,parallelUploadBoundaries:null,storeFingerprintForResuming:!0,removeFingerprintOnSuccess:!1,uploadLengthDeferred:!1,uploadDataDuringCreation:!1,urlStorage:null,fileReader:null,httpStack:null,protocol:PROTOCOL_TUS_V1},BaseUpload=(function(){function Au(lo,$u){_classCallCheck$6(this,Au),"resume"in $u&&console.log("tus: The `resume` option has been removed in tus-js-client v2. Please use the URL storage API instead."),this.options=$u,this.options.chunkSize=Number(this.options.chunkSize),this._urlStorage=this.options.urlStorage,this.file=lo,this.url=null,this._req=null,this._fingerprint=null,this._urlStorageKey=null,this._offset=null,this._aborted=!1,this._size=null,this._source=null,this._retryAttempt=0,this._retryTimeout=null,this._offsetBeforeRetry=0,this._parallelUploads=null,this._parallelUploadUrls=null}return _createClass$6(Au,[{key:"findPreviousUploads",value:function(){var $u=this;return this.options.fingerprint(this.file,this.options).then(function(Ru){return $u._urlStorage.findUploadsByFingerprint(Ru)})}},{key:"resumeFromPreviousUpload",value:function($u){this.url=$u.uploadUrl||null,this._parallelUploadUrls=$u.parallelUploadUrls||null,this._urlStorageKey=$u.urlStorageKey}},{key:"start",value:function(){var $u=this,Ru=this.file;if(!Ru){this._emitError(new Error("tus: no file or stream to upload provided"));return}if(![PROTOCOL_TUS_V1,PROTOCOL_IETF_DRAFT_03,PROTOCOL_IETF_DRAFT_05].includes(this.options.protocol)){this._emitError(new Error("tus: unsupported protocol ".concat(this.options.protocol)));return}if(!this.options.endpoint&&!this.options.uploadUrl&&!this.url){this._emitError(new Error("tus: neither an endpoint or an upload URL is provided"));return}var Iu=this.options.retryDelays;if(Iu!=null&&Object.prototype.toString.call(Iu)!=="[object Array]"){this._emitError(new Error("tus: the `retryDelays` option must either be an array or null"));return}if(this.options.parallelUploads>1)for(var Pu=0,Ou=["uploadUrl","uploadSize","uploadLengthDeferred"];Pu<Ou.length;Pu++){var Mu=Ou[Pu];if(this.options[Mu]){this._emitError(new Error("tus: cannot use the ".concat(Mu," option when parallelUploads is enabled")));return}}if(this.options.parallelUploadBoundaries){if(this.options.parallelUploads<=1){this._emitError(new Error("tus: cannot use the `parallelUploadBoundaries` option when `parallelUploads` is disabled"));return}if(this.options.parallelUploads!==this.options.parallelUploadBoundaries.length){this._emitError(new Error("tus: the `parallelUploadBoundaries` must have the same length as the value of `parallelUploads`"));return}}this.options.fingerprint(Ru,this.options).then(function(Du){return $u._fingerprint=Du,$u._source?$u._source:$u.options.fileReader.openFile(Ru,$u.options.chunkSize)}).then(function(Du){if($u._source=Du,$u.options.uploadLengthDeferred)$u._size=null;else if($u.options.uploadSize!=null){if($u._size=Number($u.options.uploadSize),Number.isNaN($u._size)){$u._emitError(new Error("tus: cannot convert `uploadSize` option into a number"));return}}else if($u._size=$u._source.size,$u._size==null){$u._emitError(new Error("tus: cannot automatically derive upload's size from input. Specify it manually using the `uploadSize` option or use the `uploadLengthDeferred` option"));return}$u.options.parallelUploads>1||$u._parallelUploadUrls!=null?$u._startParallelUpload():$u._startSingleUpload()}).catch(function(Du){$u._emitError(Du)})}},{key:"_startParallelUpload",value:function(){var $u,Ru=this,Iu=this._size,Pu=0;this._parallelUploads=[];var Ou=this._parallelUploadUrls!=null?this._parallelUploadUrls.length:this.options.parallelUploads,Mu=($u=this.options.parallelUploadBoundaries)!==null&&$u!==void 0?$u:splitSizeIntoParts(this._source.size,Ou);this._parallelUploadUrls&&Mu.forEach(function(Bu,ju){Bu.uploadUrl=Ru._parallelUploadUrls[ju]||null}),this._parallelUploadUrls=new Array(Mu.length);var Du=Mu.map(function(Bu,ju){var Fu=0;return Ru._source.slice(Bu.start,Bu.end).then(function(zu){var Uu=zu.value;return new Promise(function(Hu,Vu){var Gu=_objectSpread$1(_objectSpread$1({},Ru.options),{},{uploadUrl:Bu.uploadUrl||null,storeFingerprintForResuming:!1,removeFingerprintOnSuccess:!1,parallelUploads:1,parallelUploadBoundaries:null,metadata:Ru.options.metadataForPartialUploads,headers:_objectSpread$1(_objectSpread$1({},Ru.options.headers),{},{"Upload-Concat":"partial"}),onSuccess:Hu,onError:Vu,onProgress:function(Ju){Pu=Pu-Fu+Ju,Fu=Ju,Ru._emitProgress(Pu,Iu)},onUploadUrlAvailable:function(){Ru._parallelUploadUrls[ju]=Wu.url,Ru._parallelUploadUrls.filter(function(Ju){return!!Ju}).length===Mu.length&&Ru._saveUploadInUrlStorage()}}),Wu=new Au(Uu,Gu);Wu.start(),Ru._parallelUploads.push(Wu)})})}),Lu;Promise.all(Du).then(function(){Lu=Ru._openRequest("POST",Ru.options.endpoint),Lu.setHeader("Upload-Concat","final;".concat(Ru._parallelUploadUrls.join(" ")));var Bu=encodeMetadata(Ru.options.metadata);return Bu!==""&&Lu.setHeader("Upload-Metadata",Bu),Ru._sendRequest(Lu,null)}).then(function(Bu){if(!inStatusCategory(Bu.getStatus(),200)){Ru._emitHttpError(Lu,Bu,"tus: unexpected response while creating upload");return}var ju=Bu.getHeader("Location");if(ju==null){Ru._emitHttpError(Lu,Bu,"tus: invalid or missing Location header");return}Ru.url=resolveUrl(Ru.options.endpoint,ju),"Created upload at ".concat(Ru.url),Ru._emitSuccess(Bu)}).catch(function(Bu){Ru._emitError(Bu)})}},{key:"_startSingleUpload",value:function(){if(this._aborted=!1,this.url!=null){"Resuming upload from previous URL: ".concat(this.url),this._resumeUpload();return}if(this.options.uploadUrl!=null){"Resuming upload from provided URL: ".concat(this.options.uploadUrl),this.url=this.options.uploadUrl,this._resumeUpload();return}this._createUpload()}},{key:"abort",value:function($u){var Ru=this;if(this._parallelUploads!=null){var Iu=_createForOfIteratorHelper(this._parallelUploads),Pu;try{for(Iu.s();!(Pu=Iu.n()).done;){var Ou=Pu.value;Ou.abort($u)}}catch(Mu){Iu.e(Mu)}finally{Iu.f()}}return this._req!==null&&this._req.abort(),this._aborted=!0,this._retryTimeout!=null&&(clearTimeout(this._retryTimeout),this._retryTimeout=null),!$u||this.url==null?Promise.resolve():Au.terminate(this.url,this.options).then(function(){return Ru._removeFromUrlStorage()})}},{key:"_emitHttpError",value:function($u,Ru,Iu,Pu){this._emitError(new DetailedError(Iu,Pu,$u,Ru))}},{key:"_emitError",value:function($u){var Ru=this;if(!this._aborted){if(this.options.retryDelays!=null){var Iu=this._offset!=null&&this._offset>this._offsetBeforeRetry;if(Iu&&(this._retryAttempt=0),shouldRetry($u,this._retryAttempt,this.options)){var Pu=this.options.retryDelays[this._retryAttempt++];this._offsetBeforeRetry=this._offset,this._retryTimeout=setTimeout(function(){Ru.start()},Pu);return}}if(typeof this.options.onError=="function")this.options.onError($u);else throw $u}}},{key:"_emitSuccess",value:function($u){this.options.removeFingerprintOnSuccess&&this._removeFromUrlStorage(),typeof this.options.onSuccess=="function"&&this.options.onSuccess({lastResponse:$u})}},{key:"_emitProgress",value:function($u,Ru){typeof this.options.onProgress=="function"&&this.options.onProgress($u,Ru)}},{key:"_emitChunkComplete",value:function($u,Ru,Iu){typeof this.options.onChunkComplete=="function"&&this.options.onChunkComplete($u,Ru,Iu)}},{key:"_createUpload",value:function(){var $u=this;if(!this.options.endpoint){this._emitError(new Error("tus: unable to create upload because no endpoint is provided"));return}var Ru=this._openRequest("POST",this.options.endpoint);this.options.uploadLengthDeferred?Ru.setHeader("Upload-Defer-Length","1"):Ru.setHeader("Upload-Length","".concat(this._size));var Iu=encodeMetadata(this.options.metadata);Iu!==""&&Ru.setHeader("Upload-Metadata",Iu);var Pu;this.options.uploadDataDuringCreation&&!this.options.uploadLengthDeferred?(this._offset=0,Pu=this._addChunkToRequest(Ru)):((this.options.protocol===PROTOCOL_IETF_DRAFT_03||this.options.protocol===PROTOCOL_IETF_DRAFT_05)&&Ru.setHeader("Upload-Complete","?0"),Pu=this._sendRequest(Ru,null)),Pu.then(function(Ou){if(!inStatusCategory(Ou.getStatus(),200)){$u._emitHttpError(Ru,Ou,"tus: unexpected response while creating upload");return}var Mu=Ou.getHeader("Location");if(Mu==null){$u._emitHttpError(Ru,Ou,"tus: invalid or missing Location header");return}if($u.url=resolveUrl($u.options.endpoint,Mu),"Created upload at ".concat($u.url),typeof $u.options.onUploadUrlAvailable=="function"&&$u.options.onUploadUrlAvailable(),$u._size===0){$u._emitSuccess(Ou),$u._source.close();return}$u._saveUploadInUrlStorage().then(function(){$u.options.uploadDataDuringCreation?$u._handleUploadResponse(Ru,Ou):($u._offset=0,$u._performUpload())})}).catch(function(Ou){$u._emitHttpError(Ru,null,"tus: failed to create upload",Ou)})}},{key:"_resumeUpload",value:function(){var $u=this,Ru=this._openRequest("HEAD",this.url),Iu=this._sendRequest(Ru,null);Iu.then(function(Pu){var Ou=Pu.getStatus();if(!inStatusCategory(Ou,200)){if(Ou===423){$u._emitHttpError(Ru,Pu,"tus: upload is currently locked; retry later");return}if(inStatusCategory(Ou,400)&&$u._removeFromUrlStorage(),!$u.options.endpoint){$u._emitHttpError(Ru,Pu,"tus: unable to resume upload (new upload cannot be created without an endpoint)");return}$u.url=null,$u._createUpload();return}var Mu=Number.parseInt(Pu.getHeader("Upload-Offset"),10);if(Number.isNaN(Mu)){$u._emitHttpError(Ru,Pu,"tus: invalid or missing offset value");return}var Du=Number.parseInt(Pu.getHeader("Upload-Length"),10);if(Number.isNaN(Du)&&!$u.options.uploadLengthDeferred&&$u.options.protocol===PROTOCOL_TUS_V1){$u._emitHttpError(Ru,Pu,"tus: invalid or missing length value");return}typeof $u.options.onUploadUrlAvailable=="function"&&$u.options.onUploadUrlAvailable(),$u._saveUploadInUrlStorage().then(function(){if(Mu===Du){$u._emitProgress(Du,Du),$u._emitSuccess(Pu);return}$u._offset=Mu,$u._performUpload()})}).catch(function(Pu){$u._emitHttpError(Ru,null,"tus: failed to resume upload",Pu)})}},{key:"_performUpload",value:function(){var $u=this;if(!this._aborted){var Ru;this.options.overridePatchMethod?(Ru=this._openRequest("POST",this.url),Ru.setHeader("X-HTTP-Method-Override","PATCH")):Ru=this._openRequest("PATCH",this.url),Ru.setHeader("Upload-Offset","".concat(this._offset));var Iu=this._addChunkToRequest(Ru);Iu.then(function(Pu){if(!inStatusCategory(Pu.getStatus(),200)){$u._emitHttpError(Ru,Pu,"tus: unexpected response while uploading chunk");return}$u._handleUploadResponse(Ru,Pu)}).catch(function(Pu){$u._aborted||$u._emitHttpError(Ru,null,"tus: failed to upload chunk at offset ".concat($u._offset),Pu)})}}},{key:"_addChunkToRequest",value:function($u){var Ru=this,Iu=this._offset,Pu=this._offset+this.options.chunkSize;return $u.setProgressHandler(function(Ou){Ru._emitProgress(Iu+Ou,Ru._size)}),this.options.protocol===PROTOCOL_TUS_V1?$u.setHeader("Content-Type","application/offset+octet-stream"):this.options.protocol===PROTOCOL_IETF_DRAFT_05&&$u.setHeader("Content-Type","application/partial-upload"),(Pu===Number.POSITIVE_INFINITY||Pu>this._size)&&!this.options.uploadLengthDeferred&&(Pu=this._size),this._source.slice(Iu,Pu).then(function(Ou){var Mu=Ou.value,Du=Ou.done,Lu=Mu!=null&&Mu.size?Mu.size:0;Ru.options.uploadLengthDeferred&&Du&&(Ru._size=Ru._offset+Lu,$u.setHeader("Upload-Length","".concat(Ru._size)));var Bu=Ru._offset+Lu;return!Ru.options.uploadLengthDeferred&&Du&&Bu!==Ru._size?Promise.reject(new Error("upload was configured with a size of ".concat(Ru._size," bytes, but the source is done after ").concat(Bu," bytes"))):Mu===null?Ru._sendRequest($u):((Ru.options.protocol===PROTOCOL_IETF_DRAFT_03||Ru.options.protocol===PROTOCOL_IETF_DRAFT_05)&&$u.setHeader("Upload-Complete",Du?"?1":"?0"),Ru._emitProgress(Ru._offset,Ru._size),Ru._sendRequest($u,Mu))})}},{key:"_handleUploadResponse",value:function($u,Ru){var Iu=Number.parseInt(Ru.getHeader("Upload-Offset"),10);if(Number.isNaN(Iu)){this._emitHttpError($u,Ru,"tus: invalid or missing offset value");return}if(this._emitProgress(Iu,this._size),this._emitChunkComplete(Iu-this._offset,Iu,this._size),this._offset=Iu,Iu===this._size){this._emitSuccess(Ru),this._source.close();return}this._performUpload()}},{key:"_openRequest",value:function($u,Ru){var Iu=openRequest($u,Ru,this.options);return this._req=Iu,Iu}},{key:"_removeFromUrlStorage",value:function(){var $u=this;this._urlStorageKey&&(this._urlStorage.removeUpload(this._urlStorageKey).catch(function(Ru){$u._emitError(Ru)}),this._urlStorageKey=null)}},{key:"_saveUploadInUrlStorage",value:function(){var $u=this;if(!this.options.storeFingerprintForResuming||!this._fingerprint||this._urlStorageKey!==null)return Promise.resolve();var Ru={size:this._size,metadata:this.options.metadata,creationTime:new Date().toString()};return this._parallelUploads?Ru.parallelUploadUrls=this._parallelUploadUrls:Ru.uploadUrl=this.url,this._urlStorage.addUpload(this._fingerprint,Ru).then(function(Iu){$u._urlStorageKey=Iu})}},{key:"_sendRequest",value:function($u){var Ru=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;return sendRequest($u,Ru,this.options)}}],[{key:"terminate",value:function($u){var Ru=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Iu=openRequest("DELETE",$u,Ru);return sendRequest(Iu,null,Ru).then(function(Pu){if(Pu.getStatus()!==204)throw new DetailedError("tus: unexpected response while terminating upload",null,Iu,Pu)}).catch(function(Pu){if(Pu instanceof DetailedError||(Pu=new DetailedError("tus: failed to terminate upload",Pu,Iu,null)),!shouldRetry(Pu,0,Ru))throw Pu;var Ou=Ru.retryDelays[0],Mu=Ru.retryDelays.slice(1),Du=_objectSpread$1(_objectSpread$1({},Ru),{},{retryDelays:Mu});return new Promise(function(Lu){return setTimeout(Lu,Ou)}).then(function(){return Au.terminate($u,Du)})})}}])})();function encodeMetadata(Au){return Object.entries(Au).map(function(lo){var $u=_slicedToArray$1(lo,2),Ru=$u[0],Iu=$u[1];return"".concat(Ru," ").concat(gBase64.encode(String(Iu)))}).join(",")}function inStatusCategory(Au,lo){return Au>=lo&&Au<lo+100}function openRequest(Au,lo,$u){var Ru=$u.httpStack.createRequest(Au,lo);$u.protocol===PROTOCOL_IETF_DRAFT_03?Ru.setHeader("Upload-Draft-Interop-Version","5"):$u.protocol===PROTOCOL_IETF_DRAFT_05?Ru.setHeader("Upload-Draft-Interop-Version","6"):Ru.setHeader("Tus-Resumable","1.0.0");for(var Iu=$u.headers||{},Pu=0,Ou=Object.entries(Iu);Pu<Ou.length;Pu++){var Mu=_slicedToArray$1(Ou[Pu],2),Du=Mu[0],Lu=Mu[1];Ru.setHeader(Du,Lu)}if($u.addRequestId){var Bu=uuid();Ru.setHeader("X-Request-ID",Bu)}return Ru}function sendRequest(Au,lo,$u){return _sendRequest2.apply(this,arguments)}function _sendRequest2(){return _sendRequest2=_asyncToGenerator$1(_regeneratorRuntime$1().mark(function Au(lo,$u,Ru){var Iu;return _regeneratorRuntime$1().wrap(function(Ou){for(;;)switch(Ou.prev=Ou.next){case 0:if(typeof Ru.onBeforeRequest!="function"){Ou.next=3;break}return Ou.next=3,Ru.onBeforeRequest(lo);case 3:return Ou.next=5,lo.send($u);case 5:if(Iu=Ou.sent,typeof Ru.onAfterResponse!="function"){Ou.next=9;break}return Ou.next=9,Ru.onAfterResponse(lo,Iu);case 9:return Ou.abrupt("return",Iu);case 10:case"end":return Ou.stop()}},Au)})),_sendRequest2.apply(this,arguments)}function isOnline(){var Au=!0;return typeof navigator<"u"&&navigator.onLine===!1&&(Au=!1),Au}function shouldRetry(Au,lo,$u){return $u.retryDelays==null||lo>=$u.retryDelays.length||Au.originalRequest==null?!1:$u&&typeof $u.onShouldRetry=="function"?$u.onShouldRetry(Au,lo,$u):defaultOnShouldRetry(Au)}function defaultOnShouldRetry(Au){var lo=Au.originalResponse?Au.originalResponse.getStatus():0;return(!inStatusCategory(lo,400)||lo===409||lo===423)&&isOnline()}function resolveUrl(Au,lo){return new URL$1(lo,Au).toString()}function splitSizeIntoParts(Au,lo){for(var $u=Math.floor(Au/lo),Ru=[],Iu=0;Iu<lo;Iu++)Ru.push({start:$u*Iu,end:$u*(Iu+1)});return Ru[lo-1].end=Au,Ru}BaseUpload.defaultOptions=defaultOptions$2;var isReactNative=function Au(){return typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative"};function uriToBlob(Au){return new Promise(function(lo,$u){var Ru=new XMLHttpRequest;Ru.responseType="blob",Ru.onload=function(){var Iu=Ru.response;lo(Iu)},Ru.onerror=function(Iu){$u(Iu)},Ru.open("GET",Au),Ru.send()})}var isCordova=function Au(){return typeof window<"u"&&(typeof window.PhoneGap<"u"||typeof window.Cordova<"u"||typeof window.cordova<"u")};function readAsByteArray(Au){return new Promise(function(lo,$u){var Ru=new FileReader;Ru.onload=function(){var Iu=new Uint8Array(Ru.result);lo({value:Iu})},Ru.onerror=function(Iu){$u(Iu)},Ru.readAsArrayBuffer(Au)})}function _typeof$5(Au){"@babel/helpers - typeof";return _typeof$5=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$5(Au)}function _classCallCheck$5(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$5(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$5(Ru.key),Ru)}}function _createClass$5(Au,lo,$u){return lo&&_defineProperties$5(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$5(Au){var lo=_toPrimitive$5(Au,"string");return _typeof$5(lo)=="symbol"?lo:lo+""}function _toPrimitive$5(Au,lo){if(_typeof$5(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$5(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var FileSource=(function(){function Au(lo){_classCallCheck$5(this,Au),this._file=lo,this.size=lo.size}return _createClass$5(Au,[{key:"slice",value:function($u,Ru){if(isCordova())return readAsByteArray(this._file.slice($u,Ru));var Iu=this._file.slice($u,Ru),Pu=Ru>=this.size;return Promise.resolve({value:Iu,done:Pu})}},{key:"close",value:function(){}}])})();function _typeof$4(Au){"@babel/helpers - typeof";return _typeof$4=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$4(Au)}function _classCallCheck$4(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$4(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$4(Ru.key),Ru)}}function _createClass$4(Au,lo,$u){return lo&&_defineProperties$4(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$4(Au){var lo=_toPrimitive$4(Au,"string");return _typeof$4(lo)=="symbol"?lo:lo+""}function _toPrimitive$4(Au,lo){if(_typeof$4(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$4(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}function len(Au){return Au===void 0?0:Au.size!==void 0?Au.size:Au.length}function concat(Au,lo){if(Au.concat)return Au.concat(lo);if(Au instanceof Blob)return new Blob([Au,lo],{type:Au.type});if(Au.set){var $u=new Au.constructor(Au.length+lo.length);return $u.set(Au),$u.set(lo,Au.length),$u}throw new Error("Unknown data type")}var StreamSource=(function(){function Au(lo){_classCallCheck$4(this,Au),this._buffer=void 0,this._bufferOffset=0,this._reader=lo,this._done=!1}return _createClass$4(Au,[{key:"slice",value:function($u,Ru){return $u<this._bufferOffset?Promise.reject(new Error("Requested data is before the reader's current offset")):this._readUntilEnoughDataOrDone($u,Ru)}},{key:"_readUntilEnoughDataOrDone",value:function($u,Ru){var Iu=this,Pu=Ru<=this._bufferOffset+len(this._buffer);if(this._done||Pu){var Ou=this._getDataFromBuffer($u,Ru),Mu=Ou==null?this._done:!1;return Promise.resolve({value:Ou,done:Mu})}return this._reader.read().then(function(Du){var Lu=Du.value,Bu=Du.done;return Bu?Iu._done=!0:Iu._buffer===void 0?Iu._buffer=Lu:Iu._buffer=concat(Iu._buffer,Lu),Iu._readUntilEnoughDataOrDone($u,Ru)})}},{key:"_getDataFromBuffer",value:function($u,Ru){$u>this._bufferOffset&&(this._buffer=this._buffer.slice($u-this._bufferOffset),this._bufferOffset=$u);var Iu=len(this._buffer)===0;return this._done&&Iu?null:this._buffer.slice(0,Ru-$u)}},{key:"close",value:function(){this._reader.cancel&&this._reader.cancel()}}])})();function _typeof$3(Au){"@babel/helpers - typeof";return _typeof$3=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$3(Au)}function _regeneratorRuntime(){_regeneratorRuntime=function(){return lo};var Au,lo={},$u=Object.prototype,Ru=$u.hasOwnProperty,Iu=Object.defineProperty||function(_d,bd,wd){_d[bd]=wd.value},Pu=typeof Symbol=="function"?Symbol:{},Ou=Pu.iterator||"@@iterator",Mu=Pu.asyncIterator||"@@asyncIterator",Du=Pu.toStringTag||"@@toStringTag";function Lu(_d,bd,wd){return Object.defineProperty(_d,bd,{value:wd,enumerable:!0,configurable:!0,writable:!0}),_d[bd]}try{Lu({},"")}catch{Lu=function(wd,Ad,gd){return wd[Ad]=gd}}function Bu(_d,bd,wd,Ad){var gd=bd&&bd.prototype instanceof Gu?bd:Gu,dd=Object.create(gd.prototype),yd=new vd(Ad||[]);return Iu(dd,"_invoke",{value:od(_d,wd,yd)}),dd}function ju(_d,bd,wd){try{return{type:"normal",arg:_d.call(bd,wd)}}catch(Ad){return{type:"throw",arg:Ad}}}lo.wrap=Bu;var Fu="suspendedStart",zu="suspendedYield",Uu="executing",Hu="completed",Vu={};function Gu(){}function Wu(){}function Zu(){}var Ju={};Lu(Ju,Ou,function(){return this});var Yu=Object.getPrototypeOf,Xu=Yu&&Yu(Yu(Sd([])));Xu&&Xu!==$u&&Ru.call(Xu,Ou)&&(Ju=Xu);var ed=Zu.prototype=Gu.prototype=Object.create(Ju);function td(_d){["next","throw","return"].forEach(function(bd){Lu(_d,bd,function(wd){return this._invoke(bd,wd)})})}function nd(_d,bd){function wd(gd,dd,yd,ld){var ud=ju(_d[gd],_d,dd);if(ud.type!=="throw"){var hd=ud.arg,md=hd.value;return md&&_typeof$3(md)=="object"&&Ru.call(md,"__await")?bd.resolve(md.__await).then(function(Ed){wd("next",Ed,yd,ld)},function(Ed){wd("throw",Ed,yd,ld)}):bd.resolve(md).then(function(Ed){hd.value=Ed,yd(hd)},function(Ed){return wd("throw",Ed,yd,ld)})}ld(ud.arg)}var Ad;Iu(this,"_invoke",{value:function(dd,yd){function ld(){return new bd(function(ud,hd){wd(dd,yd,ud,hd)})}return Ad=Ad?Ad.then(ld,ld):ld()}})}function od(_d,bd,wd){var Ad=Fu;return function(gd,dd){if(Ad===Uu)throw Error("Generator is already running");if(Ad===Hu){if(gd==="throw")throw dd;return{value:Au,done:!0}}for(wd.method=gd,wd.arg=dd;;){var yd=wd.delegate;if(yd){var ld=sd(yd,wd);if(ld){if(ld===Vu)continue;return ld}}if(wd.method==="next")wd.sent=wd._sent=wd.arg;else if(wd.method==="throw"){if(Ad===Fu)throw Ad=Hu,wd.arg;wd.dispatchException(wd.arg)}else wd.method==="return"&&wd.abrupt("return",wd.arg);Ad=Uu;var ud=ju(_d,bd,wd);if(ud.type==="normal"){if(Ad=wd.done?Hu:zu,ud.arg===Vu)continue;return{value:ud.arg,done:wd.done}}ud.type==="throw"&&(Ad=Hu,wd.method="throw",wd.arg=ud.arg)}}}function sd(_d,bd){var wd=bd.method,Ad=_d.iterator[wd];if(Ad===Au)return bd.delegate=null,wd==="throw"&&_d.iterator.return&&(bd.method="return",bd.arg=Au,sd(_d,bd),bd.method==="throw")||wd!=="return"&&(bd.method="throw",bd.arg=new TypeError("The iterator does not provide a '"+wd+"' method")),Vu;var gd=ju(Ad,_d.iterator,bd.arg);if(gd.type==="throw")return bd.method="throw",bd.arg=gd.arg,bd.delegate=null,Vu;var dd=gd.arg;return dd?dd.done?(bd[_d.resultName]=dd.value,bd.next=_d.nextLoc,bd.method!=="return"&&(bd.method="next",bd.arg=Au),bd.delegate=null,Vu):dd:(bd.method="throw",bd.arg=new TypeError("iterator result is not an object"),bd.delegate=null,Vu)}function ad(_d){var bd={tryLoc:_d[0]};1 in _d&&(bd.catchLoc=_d[1]),2 in _d&&(bd.finallyLoc=_d[2],bd.afterLoc=_d[3]),this.tryEntries.push(bd)}function pd(_d){var bd=_d.completion||{};bd.type="normal",delete bd.arg,_d.completion=bd}function vd(_d){this.tryEntries=[{tryLoc:"root"}],_d.forEach(ad,this),this.reset(!0)}function Sd(_d){if(_d||_d===""){var bd=_d[Ou];if(bd)return bd.call(_d);if(typeof _d.next=="function")return _d;if(!isNaN(_d.length)){var wd=-1,Ad=function gd(){for(;++wd<_d.length;)if(Ru.call(_d,wd))return gd.value=_d[wd],gd.done=!1,gd;return gd.value=Au,gd.done=!0,gd};return Ad.next=Ad}}throw new TypeError(_typeof$3(_d)+" is not iterable")}return Wu.prototype=Zu,Iu(ed,"constructor",{value:Zu,configurable:!0}),Iu(Zu,"constructor",{value:Wu,configurable:!0}),Wu.displayName=Lu(Zu,Du,"GeneratorFunction"),lo.isGeneratorFunction=function(_d){var bd=typeof _d=="function"&&_d.constructor;return!!bd&&(bd===Wu||(bd.displayName||bd.name)==="GeneratorFunction")},lo.mark=function(_d){return Object.setPrototypeOf?Object.setPrototypeOf(_d,Zu):(_d.__proto__=Zu,Lu(_d,Du,"GeneratorFunction")),_d.prototype=Object.create(ed),_d},lo.awrap=function(_d){return{__await:_d}},td(nd.prototype),Lu(nd.prototype,Mu,function(){return this}),lo.AsyncIterator=nd,lo.async=function(_d,bd,wd,Ad,gd){gd===void 0&&(gd=Promise);var dd=new nd(Bu(_d,bd,wd,Ad),gd);return lo.isGeneratorFunction(bd)?dd:dd.next().then(function(yd){return yd.done?yd.value:dd.next()})},td(ed),Lu(ed,Du,"Generator"),Lu(ed,Ou,function(){return this}),Lu(ed,"toString",function(){return"[object Generator]"}),lo.keys=function(_d){var bd=Object(_d),wd=[];for(var Ad in bd)wd.push(Ad);return wd.reverse(),function gd(){for(;wd.length;){var dd=wd.pop();if(dd in bd)return gd.value=dd,gd.done=!1,gd}return gd.done=!0,gd}},lo.values=Sd,vd.prototype={constructor:vd,reset:function(bd){if(this.prev=0,this.next=0,this.sent=this._sent=Au,this.done=!1,this.delegate=null,this.method="next",this.arg=Au,this.tryEntries.forEach(pd),!bd)for(var wd in this)wd.charAt(0)==="t"&&Ru.call(this,wd)&&!isNaN(+wd.slice(1))&&(this[wd]=Au)},stop:function(){this.done=!0;var bd=this.tryEntries[0].completion;if(bd.type==="throw")throw bd.arg;return this.rval},dispatchException:function(bd){if(this.done)throw bd;var wd=this;function Ad(hd,md){return yd.type="throw",yd.arg=bd,wd.next=hd,md&&(wd.method="next",wd.arg=Au),!!md}for(var gd=this.tryEntries.length-1;gd>=0;--gd){var dd=this.tryEntries[gd],yd=dd.completion;if(dd.tryLoc==="root")return Ad("end");if(dd.tryLoc<=this.prev){var ld=Ru.call(dd,"catchLoc"),ud=Ru.call(dd,"finallyLoc");if(ld&&ud){if(this.prev<dd.catchLoc)return Ad(dd.catchLoc,!0);if(this.prev<dd.finallyLoc)return Ad(dd.finallyLoc)}else if(ld){if(this.prev<dd.catchLoc)return Ad(dd.catchLoc,!0)}else{if(!ud)throw Error("try statement without catch or finally");if(this.prev<dd.finallyLoc)return Ad(dd.finallyLoc)}}}},abrupt:function(bd,wd){for(var Ad=this.tryEntries.length-1;Ad>=0;--Ad){var gd=this.tryEntries[Ad];if(gd.tryLoc<=this.prev&&Ru.call(gd,"finallyLoc")&&this.prev<gd.finallyLoc){var dd=gd;break}}dd&&(bd==="break"||bd==="continue")&&dd.tryLoc<=wd&&wd<=dd.finallyLoc&&(dd=null);var yd=dd?dd.completion:{};return yd.type=bd,yd.arg=wd,dd?(this.method="next",this.next=dd.finallyLoc,Vu):this.complete(yd)},complete:function(bd,wd){if(bd.type==="throw")throw bd.arg;return bd.type==="break"||bd.type==="continue"?this.next=bd.arg:bd.type==="return"?(this.rval=this.arg=bd.arg,this.method="return",this.next="end"):bd.type==="normal"&&wd&&(this.next=wd),Vu},finish:function(bd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ad=this.tryEntries[wd];if(Ad.finallyLoc===bd)return this.complete(Ad.completion,Ad.afterLoc),pd(Ad),Vu}},catch:function(bd){for(var wd=this.tryEntries.length-1;wd>=0;--wd){var Ad=this.tryEntries[wd];if(Ad.tryLoc===bd){var gd=Ad.completion;if(gd.type==="throw"){var dd=gd.arg;pd(Ad)}return dd}}throw Error("illegal catch attempt")},delegateYield:function(bd,wd,Ad){return this.delegate={iterator:Sd(bd),resultName:wd,nextLoc:Ad},this.method==="next"&&(this.arg=Au),Vu}},lo}function asyncGeneratorStep(Au,lo,$u,Ru,Iu,Pu,Ou){try{var Mu=Au[Pu](Ou),Du=Mu.value}catch(Lu){$u(Lu);return}Mu.done?lo(Du):Promise.resolve(Du).then(Ru,Iu)}function _asyncToGenerator(Au){return function(){var lo=this,$u=arguments;return new Promise(function(Ru,Iu){var Pu=Au.apply(lo,$u);function Ou(Du){asyncGeneratorStep(Pu,Ru,Iu,Ou,Mu,"next",Du)}function Mu(Du){asyncGeneratorStep(Pu,Ru,Iu,Ou,Mu,"throw",Du)}Ou(void 0)})}}function _classCallCheck$3(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$3(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$3(Ru.key),Ru)}}function _createClass$3(Au,lo,$u){return lo&&_defineProperties$3(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$3(Au){var lo=_toPrimitive$3(Au,"string");return _typeof$3(lo)=="symbol"?lo:lo+""}function _toPrimitive$3(Au,lo){if(_typeof$3(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$3(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var FileReader$1=(function(){function Au(){_classCallCheck$3(this,Au)}return _createClass$3(Au,[{key:"openFile",value:(function(){var lo=_asyncToGenerator(_regeneratorRuntime().mark(function Ru(Iu,Pu){var Ou;return _regeneratorRuntime().wrap(function(Du){for(;;)switch(Du.prev=Du.next){case 0:if(!(isReactNative()&&Iu&&typeof Iu.uri<"u")){Du.next=11;break}return Du.prev=1,Du.next=4,uriToBlob(Iu.uri);case 4:return Ou=Du.sent,Du.abrupt("return",new FileSource(Ou));case 8:throw Du.prev=8,Du.t0=Du.catch(1),new Error("tus: cannot fetch `file.uri` as Blob, make sure the uri is correct and accessible. ".concat(Du.t0));case 11:if(!(typeof Iu.slice=="function"&&typeof Iu.size<"u")){Du.next=13;break}return Du.abrupt("return",Promise.resolve(new FileSource(Iu)));case 13:if(typeof Iu.read!="function"){Du.next=18;break}if(Pu=Number(Pu),Number.isFinite(Pu)){Du.next=17;break}return Du.abrupt("return",Promise.reject(new Error("cannot create source for stream without a finite value for the `chunkSize` option")));case 17:return Du.abrupt("return",Promise.resolve(new StreamSource(Iu,Pu)));case 18:return Du.abrupt("return",Promise.reject(new Error("source object may only be an instance of File, Blob, or Reader in this environment")));case 19:case"end":return Du.stop()}},Ru,null,[[1,8]])}));function $u(Ru,Iu){return lo.apply(this,arguments)}return $u})()}])})();function fingerprint(Au,lo){return isReactNative()?Promise.resolve(reactNativeFingerprint(Au,lo)):Promise.resolve(["tus-br",Au.name,Au.type,Au.size,Au.lastModified,lo.endpoint].join("-"))}function reactNativeFingerprint(Au,lo){var $u=Au.exif?hashCode(JSON.stringify(Au.exif)):"noexif";return["tus-rn",Au.name||"noname",Au.size||"nosize",$u,lo.endpoint].join("/")}function hashCode(Au){var lo=0;if(Au.length===0)return lo;for(var $u=0;$u<Au.length;$u++){var Ru=Au.charCodeAt($u);lo=(lo<<5)-lo+Ru,lo&=lo}return lo}function _typeof$2(Au){"@babel/helpers - typeof";return _typeof$2=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$2(Au)}function _classCallCheck$2(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$2(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$2(Ru.key),Ru)}}function _createClass$2(Au,lo,$u){return lo&&_defineProperties$2(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$2(Au){var lo=_toPrimitive$2(Au,"string");return _typeof$2(lo)=="symbol"?lo:lo+""}function _toPrimitive$2(Au,lo){if(_typeof$2(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$2(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var XHRHttpStack=(function(){function Au(){_classCallCheck$2(this,Au)}return _createClass$2(Au,[{key:"createRequest",value:function($u,Ru){return new Request$1($u,Ru)}},{key:"getName",value:function(){return"XHRHttpStack"}}])})(),Request$1=(function(){function Au(lo,$u){_classCallCheck$2(this,Au),this._xhr=new XMLHttpRequest,this._xhr.open(lo,$u,!0),this._method=lo,this._url=$u,this._headers={}}return _createClass$2(Au,[{key:"getMethod",value:function(){return this._method}},{key:"getURL",value:function(){return this._url}},{key:"setHeader",value:function($u,Ru){this._xhr.setRequestHeader($u,Ru),this._headers[$u]=Ru}},{key:"getHeader",value:function($u){return this._headers[$u]}},{key:"setProgressHandler",value:function($u){"upload"in this._xhr&&(this._xhr.upload.onprogress=function(Ru){Ru.lengthComputable&&$u(Ru.loaded)})}},{key:"send",value:function(){var $u=this,Ru=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null;return new Promise(function(Iu,Pu){$u._xhr.onload=function(){Iu(new Response$1($u._xhr))},$u._xhr.onerror=function(Ou){Pu(Ou)},$u._xhr.send(Ru)})}},{key:"abort",value:function(){return this._xhr.abort(),Promise.resolve()}},{key:"getUnderlyingObject",value:function(){return this._xhr}}])})(),Response$1=(function(){function Au(lo){_classCallCheck$2(this,Au),this._xhr=lo}return _createClass$2(Au,[{key:"getStatus",value:function(){return this._xhr.status}},{key:"getHeader",value:function($u){return this._xhr.getResponseHeader($u)}},{key:"getBody",value:function(){return this._xhr.responseText}},{key:"getUnderlyingObject",value:function(){return this._xhr}}])})();function _typeof$1(Au){"@babel/helpers - typeof";return _typeof$1=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof$1(Au)}function _classCallCheck$1(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey$1(Ru.key),Ru)}}function _createClass$1(Au,lo,$u){return lo&&_defineProperties$1(Au.prototype,lo),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _toPropertyKey$1(Au){var lo=_toPrimitive$1(Au,"string");return _typeof$1(lo)=="symbol"?lo:lo+""}function _toPrimitive$1(Au,lo){if(_typeof$1(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof$1(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var hasStorage=!1;try{hasStorage="localStorage"in window;var key="tusSupport",originalValue=localStorage.getItem(key);localStorage.setItem(key,originalValue),originalValue===null&&localStorage.removeItem(key)}catch(Au){if(Au.code===Au.SECURITY_ERR||Au.code===Au.QUOTA_EXCEEDED_ERR)hasStorage=!1;else throw Au}var canStoreURLs=hasStorage,WebStorageUrlStorage=(function(){function Au(){_classCallCheck$1(this,Au)}return _createClass$1(Au,[{key:"findAllUploads",value:function(){var $u=this._findEntries("tus::");return Promise.resolve($u)}},{key:"findUploadsByFingerprint",value:function($u){var Ru=this._findEntries("tus::".concat($u,"::"));return Promise.resolve(Ru)}},{key:"removeUpload",value:function($u){return localStorage.removeItem($u),Promise.resolve()}},{key:"addUpload",value:function($u,Ru){var Iu=Math.round(Math.random()*1e12),Pu="tus::".concat($u,"::").concat(Iu);return localStorage.setItem(Pu,JSON.stringify(Ru)),Promise.resolve(Pu)}},{key:"_findEntries",value:function($u){for(var Ru=[],Iu=0;Iu<localStorage.length;Iu++){var Pu=localStorage.key(Iu);if(Pu.indexOf($u)===0)try{var Ou=JSON.parse(localStorage.getItem(Pu));Ou.urlStorageKey=Pu,Ru.push(Ou)}catch{}}return Ru}}])})();function _typeof(Au){"@babel/helpers - typeof";return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(lo){return typeof lo}:function(lo){return lo&&typeof Symbol=="function"&&lo.constructor===Symbol&&lo!==Symbol.prototype?"symbol":typeof lo},_typeof(Au)}function _classCallCheck(Au,lo){if(!(Au instanceof lo))throw new TypeError("Cannot call a class as a function")}function _defineProperties(Au,lo){for(var $u=0;$u<lo.length;$u++){var Ru=lo[$u];Ru.enumerable=Ru.enumerable||!1,Ru.configurable=!0,"value"in Ru&&(Ru.writable=!0),Object.defineProperty(Au,_toPropertyKey(Ru.key),Ru)}}function _createClass(Au,lo,$u){return $u&&_defineProperties(Au,$u),Object.defineProperty(Au,"prototype",{writable:!1}),Au}function _callSuper(Au,lo,$u){return lo=_getPrototypeOf(lo),_possibleConstructorReturn(Au,_isNativeReflectConstruct()?Reflect.construct(lo,$u||[],_getPrototypeOf(Au).constructor):lo.apply(Au,$u))}function _possibleConstructorReturn(Au,lo){if(lo&&(_typeof(lo)==="object"||typeof lo=="function"))return lo;if(lo!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized(Au)}function _assertThisInitialized(Au){if(Au===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return Au}function _isNativeReflectConstruct(){try{var Au=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(_isNativeReflectConstruct=function(){return!!Au})()}function _getPrototypeOf(Au){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function($u){return $u.__proto__||Object.getPrototypeOf($u)},_getPrototypeOf(Au)}function _inherits(Au,lo){if(typeof lo!="function"&&lo!==null)throw new TypeError("Super expression must either be null or a function");Au.prototype=Object.create(lo&&lo.prototype,{constructor:{value:Au,writable:!0,configurable:!0}}),Object.defineProperty(Au,"prototype",{writable:!1}),lo&&_setPrototypeOf(Au,lo)}function _setPrototypeOf(Au,lo){return _setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(Ru,Iu){return Ru.__proto__=Iu,Ru},_setPrototypeOf(Au,lo)}function ownKeys(Au,lo){var $u=Object.keys(Au);if(Object.getOwnPropertySymbols){var Ru=Object.getOwnPropertySymbols(Au);lo&&(Ru=Ru.filter(function(Iu){return Object.getOwnPropertyDescriptor(Au,Iu).enumerable})),$u.push.apply($u,Ru)}return $u}function _objectSpread(Au){for(var lo=1;lo<arguments.length;lo++){var $u=arguments[lo]!=null?arguments[lo]:{};lo%2?ownKeys(Object($u),!0).forEach(function(Ru){_defineProperty(Au,Ru,$u[Ru])}):Object.getOwnPropertyDescriptors?Object.defineProperties(Au,Object.getOwnPropertyDescriptors($u)):ownKeys(Object($u)).forEach(function(Ru){Object.defineProperty(Au,Ru,Object.getOwnPropertyDescriptor($u,Ru))})}return Au}function _defineProperty(Au,lo,$u){return lo=_toPropertyKey(lo),lo in Au?Object.defineProperty(Au,lo,{value:$u,enumerable:!0,configurable:!0,writable:!0}):Au[lo]=$u,Au}function _toPropertyKey(Au){var lo=_toPrimitive(Au,"string");return _typeof(lo)=="symbol"?lo:lo+""}function _toPrimitive(Au,lo){if(_typeof(Au)!="object"||!Au)return Au;var $u=Au[Symbol.toPrimitive];if($u!==void 0){var Ru=$u.call(Au,lo);if(_typeof(Ru)!="object")return Ru;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(Au)}var defaultOptions$1=_objectSpread(_objectSpread({},BaseUpload.defaultOptions),{},{httpStack:new XHRHttpStack,fileReader:new FileReader$1,urlStorage:canStoreURLs?new WebStorageUrlStorage:new NoopUrlStorage,fingerprint}),Upload=(function(Au){function lo(){var $u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,Ru=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return _classCallCheck(this,lo),Ru=_objectSpread(_objectSpread({},defaultOptions$1),Ru),_callSuper(this,lo,[$u,Ru])}return _inherits(lo,Au),_createClass(lo,null,[{key:"terminate",value:function(Ru){var Iu=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return Iu=_objectSpread(_objectSpread({},defaultOptions$1),Iu),BaseUpload.terminate(Ru,Iu)}}])})(BaseUpload);const RUNTIMES_API_PREFIX="api/runtimes/v1";function join$1(Au,lo){return`${Au.replace(/\/+$/,"")}/${lo.replace(/^\/+/,"")}`}function runtimesUrl(Au){return join$1(Au,`${RUNTIMES_API_PREFIX}/runtimes`)}function runtimeUrl(Au,lo){return`${runtimesUrl(Au)}/${lo}`}function sandboxSnapshotsUrl(Au){return join$1(Au,`${RUNTIMES_API_PREFIX}/sandbox-snapshots`)}function sandboxSnapshotUrl(Au,lo){return`${sandboxSnapshotsUrl(Au)}/${lo}`}function asCodeSandboxSnapshot(Au){const{uid:lo,updated_at:$u,format_version:Ru,...Iu}=Au;return{...Iu,id:lo,updatedAt:new Date($u),formatVersion:Ru}}async function getEnvironments(){const Au=await requestDatalayerAPI({url:libExports$5.URLExt.join(runtimesStore.getState().runtimesUrl,"api/runtimes/v1/environments"),token:iamStore.getState().token});return Au.success?Au.environments??[]:(console.error("Failed to fetch available environments.",Au),[])}async function createRuntime(Au){const{externalToken:lo,token:$u}=iamStore.getState();if(typeof Au.creditsLimit!="number"||!Number.isFinite(Au.creditsLimit)||Au.creditsLimit<0)throw new Error(`Invalid runtime creditsLimit for environment ${Au.environmentName}. A number of zero or more is required.`);if(Au.deploymentUid&&!Au.appUid)throw new Error(`Deployment ${Au.deploymentUid} is named without its application: give appUid.`);if(Au.appUid&&!Au.appSpec)throw new Error(`Application ${Au.appUid} is launched without its Appspec: give appSpec, so its runtime is given the secrets its connections declare.`);const Ru={name:Au.environmentName};Au.environmentVersion!==void 0&&Au.environmentVersion!==""&&(Ru.version=Au.environmentVersion);const Iu={environment:Ru,type:Au.type??"notebook",given_name:Au.givenName,credits_limit:Au.creditsLimit};Au.capabilities&&(Iu.capabilities=Au.capabilities),Au.snapshot&&(Iu.from=Au.snapshot),Au.appUid&&(Iu.app_uid=Au.appUid),Au.deploymentUid&&(Iu.deployment_uid=Au.deploymentUid),Au.appSpec&&(Iu.app_spec=Au.appSpec);const Pu=await requestDatalayerAPI({url:runtimesUrl(runtimesStore.getState().runtimesUrl),method:"POST",body:Iu,token:$u,headers:lo?{"X-External-Token":lo}:void 0});if(!Pu.success||!Pu.runtime){const Ou=`Failed to create a kernel for the environment ${Au.environmentName}.`;throw console.error(Ou,Pu),new Error(Ou)}return Pu.runtime}async function getRuntimes(){const Au=await requestDatalayerAPI({url:runtimesUrl(runtimesStore.getState().runtimesUrl),token:iamStore.getState().token});if(!Au.success){const lo="Failed to list the running kernels.";throw console.error(lo,Au),new Error(lo)}return Au.runtimes??[]}async function getRuntimeRecord(Au){try{return(await requestDatalayerAPI({url:runtimeUrl(runtimesStore.getState().runtimesUrl,Au),token:iamStore.getState().token})).runtime??null}catch(lo){if(lo.response?.status===404)return null;throw lo}}async function deleteRuntime(Au){const lo=iamStore.getState().externalToken;await requestDatalayerAPI({url:runtimeUrl(runtimesStore.getState().runtimesUrl,Au.id)+libExports$5.URLExt.objectToQueryString(Au.reason?{reason:Au.reason}:{}),method:"DELETE",token:iamStore.getState().token,headers:lo?{"X-External-Token":lo}:void 0})}async function snapshotRuntime(Au){const lo=await requestDatalayerAPI({url:sandboxSnapshotsUrl(runtimesStore.getState().runtimesUrl),method:"POST",body:{runtime_name:Au.id,name:Au.name,description:Au.description,stop:Au.stop},token:iamStore.getState().token});if(!lo.success)throw new Error(`Failed to take the code sandbox snapshot ${Au.id} - ${lo}`);if(lo.snapshot)return asCodeSandboxSnapshot(lo.snapshot)}async function getSandboxSnapshots(){const Au=await requestDatalayerAPI({url:sandboxSnapshotsUrl(runtimesStore.getState().runtimesUrl),token:iamStore.getState().token});return Au.success?(Au.snapshots??[]).map(asCodeSandboxSnapshot):(console.error("Failed to fetch code sandbox snapshots.",Au),[])}async function loadSandboxSnapshot(Au){const lo=await requestDatalayerAPI({url:runtimeUrl(runtimesStore.getState().runtimesUrl,Au.id),method:"PUT",body:{from:Au.from},token:iamStore.getState().token});if(!lo.success)throw new Error(`Failed to load the code sandbox snapshot; ${lo.message}`)}function createSandboxSnapshotDownloadURL(Au){return sandboxSnapshotUrl(runtimesStore.getState().runtimesUrl,Au)+libExports$5.URLExt.objectToQueryString({download:"1",token:iamStore.getState().token??""})}function exportCodeSandboxSnapshot(Au){const lo=createSandboxSnapshotDownloadURL(Au),$u=document.createElement("a");$u.href=lo,$u.download="",document.body.appendChild($u),$u.click(),document.body.removeChild($u)}async function deleteCodeSandboxSnapshot(Au){await requestDatalayerAPI({url:sandboxSnapshotUrl(runtimesStore.getState().runtimesUrl,Au),method:"DELETE",token:iamStore.getState().token})}async function updateCodeSandboxSnapshot(Au,lo){(lo.name||lo.description)&&await requestDatalayerAPI({url:sandboxSnapshotUrl(runtimesStore.getState().runtimesUrl,Au),method:"PATCH",body:{...lo},token:iamStore.getState().token})}async function uploadCodeSandboxSnapshot(Au){if(Au.file.size===0)return Promise.reject("Empty Code Sandbox Snapshot.");const lo=new PromiseDelegate,$u=new Upload(Au.file,{endpoint:`${sandboxSnapshotsUrl(runtimesStore.getState().runtimesUrl)}/upload`,headers:{Authorization:`Bearer ${iamStore.getState().token}`},retryDelays:null,metadata:Au.metadata,onError:Iu=>{console.error(`Failed to upload ${Au.metadata.filename}.`,Iu),lo.reject(Iu)},onProgress:Au.onProgress,onSuccess:()=>{lo.resolve()}}),Ru=await $u.findPreviousUploads();return Ru.length&&$u.resumeFromPreviousUpload(Ru[0]),$u.start(),lo.promise}const actions=Object.freeze(Object.defineProperty({__proto__:null,createRuntime,createSandboxSnapshotDownloadURL,deleteCodeSandboxSnapshot,deleteRuntime,exportCodeSandboxSnapshot,getEnvironments,getRuntimeRecord,getRuntimes,getSandboxSnapshots,loadSandboxSnapshot,snapshotRuntime,updateCodeSandboxSnapshot,uploadCodeSandboxSnapshot},Symbol.toStringTag,{value:"Module"})),CLAUDE_CODE_HARNESS_0_0_1={id:"claude-code",version:"0.0.1",name:"Claude Code",description:"Anthropic's coding agent, driven over ACP through the Agent Client Protocol project's adapter on the Claude Agent SDK.",enabled:!0,unavailable_because:"",tags:["harness"],docs:"https://github.com/agentclientprotocol/claude-agent-acp",acp:{command:"npx",args:["-y","@agentclientprotocol/claude-agent-acp@0.91.0"],protocolVersion:1,loadSession:!0,mcp:"lend",modes:["default","plan","acceptEdits","bypassPermissions"],env:{},nativeSession:"none"},requires:{secrets:["ANTHROPIC_API_KEY"],binaries:["node","git"]},terms:{servedToThirdParties:"api_key_only",licence:"Apache-2.0 (adapter); Anthropic Commercial Terms of Service (the agent)"},skills:{format:"skill-md",dir:".claude/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"load",forkHistory:"replay",interrupt:!0,steering:!1,images:!0,compaction:"own",modes:["default","plan","acceptEdits","bypassPermissions"],autoRun:["^(cal|uptime|cat|head|tail|wc|stat|strings|hexdump|od|nl|id|uname|free|df|du|locale|groups|nproc|basename|dirname|realpath|cut|paste|tr|column|tac|rev|fold|expand|unexpand|fmt|comm|cmp|numfmt|readlink|diff|true|false|sleep|which|type|expr|seq|tsort|pr)(\\s|$)","^(pwd|whoami|alias|history|arch|ifconfig|ip addr)(\\s|$)","^(claude (-h|--help)|node (-v|--version)|python3? --version)$","^(echo|uniq|jq|cd|ls|find)(\\s|$)","^(xargs|file|sed|sort|man|help|netstat|ps|base64|grep|egrep|fgrep|rg|sha256sum|sha1sum|md5sum|tree|date|hostname|lsof|pgrep|tput|ss|fd|fdfind|test)(\\s|$)","^git (diff|log|show|shortlog|reflog|stash (list|show)|ls-remote|status|blame|ls-files|config --get|remote( show)?|merge-base|rev-parse|rev-list|describe|cat-file|for-each-ref|grep|worktree list|tag|branch)(\\s|$)","^gh (pr (view|list|diff|checks|status)|issue (view|list|status)|repo view|run (list|view)|auth status|release (list|view)|workflow (list|view)|label list|search (repos|issues|prs|commits|code))(\\s|$)","^docker (ps|images|logs|inspect)(\\s|$)"]},instructionsFile:"CLAUDE.md",registered:{adapter:"@agentclientprotocol/claude-agent-acp",version:"0.91.0",licenceSource:"https://www.npmjs.com/package/@agentclientprotocol/claude-agent-acp",termsSource:"https://code.claude.com/docs/en/legal-and-compliance",credential:"An Anthropic API key (ANTHROPIC_API_KEY), the person's own",binaries:"Node 22 (engines.node >=22 on npm), git",note:"Anthropic's legal page (read 2026-10-15): running Claude Code in hosted sandboxes or agent infrastructure requires the Commercial Terms; each end user authenticates with their own API key or subscription; developers may not route requests through Free, Pro or Max plan credentials on behalf of their users, nor collect or intermediate Claude.ai credentials. So only API keys are taken; a subscription login is refused. The npm package moved from @zed-industries (0.23.1, March 2026) to @agentclientprotocol."}},CODEX_HARNESS_0_0_1={id:"codex",version:"0.0.1",name:"Codex",description:"OpenAI's coding agent, driven over ACP through the Agent Client Protocol project's adapter, which ships the Codex binary it drives.",enabled:!0,unavailable_because:"",tags:["harness"],docs:"https://github.com/agentclientprotocol/codex-acp",acp:{command:"npx",args:["-y","@agentclientprotocol/codex-acp@2.2.2"],protocolVersion:1,loadSession:!0,mcp:"lend",modes:["read-only","workspace-write","agent","agent-full-access"],env:{NO_BROWSER:"1"},nativeSession:"none"},requires:{secrets:["OPENAI_API_KEY"],binaries:["node","git"]},terms:{servedToThirdParties:"api_key_only",licence:"Apache-2.0 (adapter); OpenAI Terms of Use (the agent)"},skills:{format:"skill-md",dir:".agents/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"load",forkHistory:"replay",interrupt:!0,steering:!1,images:!0,compaction:"own",modes:["read-only","workspace-write","agent","agent-full-access"],autoRun:[]},instructionsFile:"AGENTS.md",registered:{adapter:"@agentclientprotocol/codex-acp",version:"2.2.2",licenceSource:"https://www.npmjs.com/package/@agentclientprotocol/codex-acp",termsSource:"https://learn.chatgpt.com/docs/auth",credential:"An OpenAI API key (OPENAI_API_KEY or CODEX_API_KEY), the person's own",binaries:"Node 22 (as the Agent Client Protocol project's adapters; unstated on npm), git",note:"Codex's authentication page (read 2026-10-15) recommends API keys for automation and device-code login for headless machines; a ChatGPT login needs a browser and is hidden with NO_BROWSER=1 in the adapter. Only API keys are taken; a ChatGPT login is refused. The Zed-scoped package was archived on 22 July 2026 and names this one."}},CUSTOM_HARNESS_0_0_1={id:"custom",version:"0.0.1",name:"Custom harness",description:"An organization's own ACP agent, its command named by the organization's own harness spec and never typed into a form.",enabled:!1,unavailable_because:"",tags:["harness"],docs:"",requires:{secrets:[],binaries:[]},terms:{servedToThirdParties:"organizations_own",licence:"The organization's own"},skills:{format:"none",dir:""},honours:{model:!1,subagents:!1},capabilities:{resume:"none",forkHistory:"none",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:[],autoRun:[]},instructionsFile:"",registered:{adapter:"The organization's own",version:"0",licenceSource:"https://agentspecs.datalayer.tech/harnesses",termsSource:"https://agentspecs.datalayer.tech/harnesses",credential:"The organization's own",binaries:"",note:"Not launchable from the shared catalogue; an organization's own harness spec names the command and answers for its terms."}},FAST_AGENT_HARNESS_0_0_1={id:"fast-agent",version:"0.0.1",name:"fast-agent",description:"llmindset's agent framework served over ACP; each agent it defines is a session mode, with any model provider it is configured with.",enabled:!1,unavailable_because:"the catalogue offers four harnesses today — Claude Code, Codex, OpenCode and pi (28 October 2026); fast-agent is a framework served over ACP, not a coding agent, its adapter is a Python tool the runtime image does not carry, and it has not been drilled on Datalayer.",tags:["harness","framework"],docs:"https://github.com/evalstate/fast-agent/blob/main/docs/docs/acp/index.md",acp:{command:"uvx",args:["fast-agent-acp==0.10.45"],protocolVersion:1,loadSession:!0,mcp:"lend",modes:[],env:{},nativeSession:"none"},requires:{secrets:["ANTHROPIC_API_KEY"],binaries:["uvx"]},terms:{servedToThirdParties:"permitted",licence:"Apache-2.0"},skills:{format:"skill-md",dir:".agents/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"load",forkHistory:"replay",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:[],autoRun:[]},instructionsFile:"AGENTS.md",registered:{adapter:"fast-agent-acp",version:"0.10.45",licenceSource:"https://pypi.org/project/fast-agent-acp/",termsSource:"https://github.com/evalstate/fast-agent/blob/main/LICENSE",credential:"The provider's key fast-agent is given (ANTHROPIC_API_KEY, OPENAI_API_KEY or HF_TOKEN); ANTHROPIC_API_KEY declared",binaries:"uv (uvx), Python 3.12 to 3.15 (requires_python on PyPI)",note:"A framework, not a coding agent: each agent it defines is an ACP mode; the client's MCP servers are attached; sessions are listed. Launched with uvx fast-agent-acp (docs/docs/acp/index.md); reads skills from .fast-agent/skills, .agents/skills and .claude/skills; its default prompt reads AGENTS.md."}},GEMINI_CLI_HARNESS_0_0_1={id:"gemini-cli",version:"0.0.1",name:"Gemini CLI",description:"Google's coding agent, which speaks ACP itself when started with --experimental-acp.",enabled:!1,unavailable_because:"the catalogue offers four harnesses today — Claude Code, Codex, OpenCode and pi (28 October 2026); Gemini CLI's API host (generativelanguage.googleapis.com) is outside a Datalayer runtime's egress boundary and is not routed through ai-inference, so it stays unfunded and unoffered there (the user's decision, 28 October 2026).",tags:["harness"],docs:"https://github.com/google-gemini/gemini-cli/blob/main/docs/cli/cli-reference.md",acp:{command:"npx",args:["-y","@google/gemini-cli@0.64.0","--experimental-acp"],protocolVersion:1,loadSession:!1,mcp:"lend",modes:["default","auto_edit","yolo","plan"],env:{},nativeSession:"none"},requires:{secrets:["GEMINI_API_KEY"],binaries:["node","git"]},terms:{servedToThirdParties:"api_key_only",licence:"Apache-2.0 (the agent); Gemini API or Gemini Code Assist terms (the model)",tierRestrictions:"Gemini Code Assist Standard or Enterprise for a Google login (the individuals tier stopped being served on 18 June 2026); a Gemini API key otherwise"},skills:{format:"skill-md",dir:".gemini/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"none",forkHistory:"replay",interrupt:!0,steering:!1,images:!0,compaction:"own",modes:["default","auto_edit","yolo","plan"],autoRun:[]},instructionsFile:"GEMINI.md",registered:{adapter:"@google/gemini-cli",version:"0.64.0",licenceSource:"https://www.npmjs.com/package/@google/gemini-cli",termsSource:"https://developers.google.com/gemini-code-assist/resources/privacy-notice-gemini-code-assist-individuals",credential:"A Gemini API key (GEMINI_API_KEY), the person's own; or a Google login on a Code Assist Standard or Enterprise subscription",binaries:"Node 20 or later (engines.node >=20 on npm), git",note:`Google's notice (read 2026-10-15): "Starting June 18, 2026, Gemini Code Assist IDE extensions stopped serving requests for the Gemini Code Assist for individuals"; Standard and Enterprise follow a separate schedule. The ACP flag is --experimental-acp in the CLI reference (docs/cli/cli-reference.md).`}},GOOSE_HARNESS_0_0_1={id:"goose",version:"0.0.1",name:"goose",description:"Block's open agent (now the Agentic AI Foundation's), which speaks ACP itself with goose acp; any model provider it is configured with.",enabled:!1,unavailable_because:"the catalogue offers four harnesses today — Claude Code, Codex, OpenCode and pi (28 October 2026); goose is a binary of its own release, not an npm adapter, the runtime image does not carry it, and it has not been drilled on Datalayer.",tags:["harness"],docs:"https://block.github.io/goose/docs/gdk/acp/",acp:{command:"goose",args:["acp"],protocolVersion:1,loadSession:!1,mcp:"lend",modes:[],env:{GOOSE_PROVIDER:"anthropic"},nativeSession:"none"},requires:{secrets:["ANTHROPIC_API_KEY"],binaries:["goose@1.54.0","git"]},terms:{servedToThirdParties:"permitted",licence:"Apache-2.0"},skills:{format:"skill-md",dir:".agents/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"none",forkHistory:"replay",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:[],autoRun:[]},instructionsFile:".goosehints",registered:{adapter:"goose",version:"1.54.0",licenceSource:"https://github.com/aaif-goose/goose",termsSource:"https://github.com/aaif-goose/goose/blob/main/LICENSE",credential:"The provider's key goose is configured with (GOOSE_PROVIDER); ANTHROPIC_API_KEY declared",binaries:"The goose CLI (release v1.54.0 of 8 October 2026), git",note:"Open source under Apache-2.0, no vendor terms of its own; the model provider's terms apply to the key. Launched as goose acp (documentation/docs/gdk/acp/index.md)."}},OPENCODE_HARNESS_0_0_1={id:"opencode",version:"0.0.1",name:"OpenCode",description:"Anomaly's open coding agent, which speaks ACP itself with opencode acp; any model provider it is configured with.",enabled:!0,unavailable_because:"",tags:["harness"],docs:"https://opencode.ai/docs/acp/",acp:{command:"npx",args:["-y","opencode-ai@1.19.0","acp"],protocolVersion:1,loadSession:!1,mcp:"lend",modes:[],env:{},nativeSession:"none"},requires:{secrets:["ANTHROPIC_API_KEY"],binaries:["node","git"]},terms:{servedToThirdParties:"permitted",licence:"MIT"},skills:{format:"skill-md",dir:".opencode/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"none",forkHistory:"replay",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:[],autoRun:[]},instructionsFile:"AGENTS.md",registered:{adapter:"opencode-ai",version:"1.19.0",licenceSource:"https://www.npmjs.com/package/opencode-ai",termsSource:"https://github.com/anomalyco/opencode/blob/dev/LICENSE",credential:"The provider's key OpenCode is configured with; ANTHROPIC_API_KEY declared",binaries:"Node (the opencode-ai package), git",note:"Open source under MIT, no vendor terms of its own; the model provider's terms apply to the key. Launched as opencode acp (opencode.ai/docs/acp); reads skills from .opencode/skills, .claude/skills and .agents/skills."}},OPENHANDS_HARNESS_0_0_1={id:"openhands",version:"0.0.1",name:"OpenHands",description:"The OpenHands CLI, which speaks ACP itself with openhands acp; any model provider it is configured with.",enabled:!1,unavailable_because:"the catalogue offers four harnesses today — Claude Code, Codex, OpenCode and pi (28 October 2026); OpenHands' adapter is a Python tool the runtime image does not carry, and it has not been drilled on Datalayer.",tags:["harness"],docs:"https://docs.openhands.dev/openhands/usage/run-openhands/acp",acp:{command:"uvx",args:["--from","openhands==1.16.0","openhands","acp","--override-with-envs"],protocolVersion:1,loadSession:!0,mcp:"lend",modes:["always-ask","always-approve","llm-approve"],env:{},nativeSession:"none"},requires:{secrets:["LLM_API_KEY"],binaries:["uvx","git"]},terms:{servedToThirdParties:"permitted",licence:"MIT"},skills:{format:"skill-md",dir:".agents/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"load",forkHistory:"replay",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:["always-ask","always-approve","llm-approve"],autoRun:[]},instructionsFile:"AGENTS.md",registered:{adapter:"openhands",version:"1.16.0",licenceSource:"https://pypi.org/project/openhands/",termsSource:"https://github.com/OpenHands/OpenHands-CLI/blob/main/LICENSE",credential:"The provider's key OpenHands reads as LLM_API_KEY, with LLM_MODEL, under --override-with-envs",binaries:"uv (uvx), Python 3.12 or later, git",note:"Open source under MIT, no vendor terms of its own; the model provider's terms apply to the key. Launched as openhands acp (OpenHands-CLI README; docs.openhands.dev's ACP page); resumes with --resume; reads skills from .agents/skills (.openhands/skills is legacy)."}},PI_HARNESS_0_0_1={id:"pi",version:"0.0.1",name:"pi",description:"Earendil's pi coding agent, driven over ACP through the pi-acp adapter, which spawns the published pi executable; any model provider pi is configured with.",enabled:!0,unavailable_because:"",tags:["harness"],docs:"https://github.com/svkozak/pi-acp",acp:{command:"npx",args:["-y","pi-acp@0.0.34"],protocolVersion:1,loadSession:!0,mcp:"lend",modes:[],env:{},nativeSession:"none"},requires:{secrets:["ANTHROPIC_API_KEY"],binaries:["node","git"]},terms:{servedToThirdParties:"permitted",licence:"MIT (adapter); MIT (the agent, @earendil-works/pi-coding-agent 1.4.0)"},skills:{format:"skill-md",dir:".pi/skills"},honours:{model:!0,subagents:!1},capabilities:{resume:"load",forkHistory:"replay",interrupt:!0,steering:!1,images:!1,compaction:"own",modes:[],autoRun:[]},instructionsFile:"AGENTS.md",registered:{adapter:"pi-acp",version:"0.0.34",licenceSource:"https://www.npmjs.com/package/pi-acp",termsSource:"https://github.com/earendil-works/pi/blob/main/LICENSE",credential:"The provider's key pi is configured with; ANTHROPIC_API_KEY declared, the person's own",binaries:"Node 22 (pi-coding-agent engines.node >=22.19.0; pi-acp >=20), the pi executable 1.4.0 on the PATH (@earendil-works/pi-coding-agent), git",note:"Read 2026-10-28. pi speaks no ACP itself; pi-acp 0.0.34 (MIT, an individual's, github.com/svkozak/pi-acp) speaks ACP JSON-RPC over stdio and spawns the published `pi` executable with `pi --mode rpc`, so pi 1.4.0 runs as published — chosen over @automatalabs/pi-acp 0.9.4 (Apache-2.0, in-process, which embeds pi 0.87.1 through its SDK on a fork's package). Open source under MIT on both sides, no vendor terms of their own; the model provider's terms apply to the key. Session persistence through pi's own session files (session/load)."}},HARNESS_CATALOGUE={"claude-code":CLAUDE_CODE_HARNESS_0_0_1,codex:CODEX_HARNESS_0_0_1,custom:CUSTOM_HARNESS_0_0_1,"fast-agent":FAST_AGENT_HARNESS_0_0_1,"gemini-cli":GEMINI_CLI_HARNESS_0_0_1,goose:GOOSE_HARNESS_0_0_1,opencode:OPENCODE_HARNESS_0_0_1,openhands:OPENHANDS_HARNESS_0_0_1,pi:PI_HARNESS_0_0_1};function listHarnesses(){return Object.values(HARNESS_CATALOGUE)}const AGENT_RUNTIME_VARIANTS=["browser-vercelai","local-pydanticai","cloud-pydanticai"],DEFAULT_AGENT_RUNTIME_VARIANT="cloud-pydanticai",VARIANT_BY_LEGACY_TARGET={"backend-services":"cloud-pydanticai","local-agent-runtimes":"local-pydanticai"};function isAgentRuntimeVariant(Au){return typeof Au=="string"&&AGENT_RUNTIME_VARIANTS.includes(Au)}function toAgentRuntimeVariant(Au,lo=DEFAULT_AGENT_RUNTIME_VARIANT){return Au?isAgentRuntimeVariant(Au)?Au:VARIANT_BY_LEGACY_TARGET[Au]??lo:lo}function locationOf(Au){return Au.slice(0,Au.indexOf("-"))}function runsInBrowser(Au){return locationOf(Au)==="browser"}function legacyTargetOf(Au){return locationOf(Au)==="cloud"?"backend-services":"local-agent-runtimes"}const runtimesStore=createStore$1((Au,lo)=>({configuration:{maxNotebookRuntimes:5,maxCellRuntimes:3},setConfiguration:$u=>{Au(Ru=>JSONExt.deepEqual(Ru.configuration,$u)?{}:{configuration:{...$u}})},runtimesUrl:coreStore.getState().configuration?.runtimesUrl,tab:0,getIntTab:()=>Math.floor(lo().tab),setTab:$u=>Au(Ru=>({tab:$u})),runtimes:[],refreshRuntimes:async()=>{const $u=await getRuntimes();JSONExt.deepEqual(lo().runtimes,$u)||Au({runtimes:[...$u]})},removeRuntime:$u=>{if(!$u)return;const Ru=lo().runtimes,Iu=Ru.filter(Pu=>Pu.runtime_name!==$u);Iu.length!==Ru.length&&Au({runtimes:Iu})},runtimeModels:[],addRuntimeModel:$u=>{const Ru=lo().runtimeModels;Ru.findIndex(Pu=>$u.id&&$u.id===Pu.id||!!$u.uid&&$u.uid===Pu.uid)<0&&Au({runtimeModels:[...Ru,$u]})},removeRuntimeModel:$u=>{const Ru=[...lo().runtimeModels],Iu=Ru?.findIndex(Pu=>!!Pu.id&&$u===Pu.id||$u===Pu.runtime_name)??-1;Iu>=0&&(Ru.splice(Iu,1),Au({runtimeModels:Ru}))},setRuntimeModels:$u=>{JSONExt.deepEqual(lo().runtimeModels,$u)||Au({runtimeModels:[...$u]})},multiServiceManager:void 0,setMultiServiceManager:$u=>{Au(Ru=>({multiServiceManager:$u}))},showDisclaimer:!1,setShowDisclaimer:$u=>{Au(Ru=>({showDisclaimer:$u}))},runtimeSnapshots:[],addSandboxSnapshot:$u=>{const Ru=lo().runtimeSnapshots,Iu=Ru.findIndex(Pu=>Pu.id===$u.id);if(Iu<0){const Pu=[...Ru,$u];Au({runtimeSnapshots:Pu})}else if(!JSONExt.deepEqual(Ru[Iu],$u)){const Pu=[...Ru];Pu.splice(Iu,1,$u),Au({runtimeSnapshots:Pu})}},removeSandboxSnapshot:$u=>{const Ru=lo().runtimeSnapshots,Iu=Ru.findIndex(Pu=>Pu.id===$u);if(Iu>=0){const Pu=[...Ru];Pu.splice(Iu,1),Au({runtimeSnapshots:Pu})}},setSandboxSnapshots:$u=>{JSONExt.deepEqual(lo().runtimeSnapshots,$u)||Au({runtimeSnapshots:[...$u]})},version:"",setVersion:$u=>{$u&&!lo().version&&Au(Ru=>({version:$u}))}})),kernelsPoll=new Poll({auto:!0,factory:()=>runtimesStore.getState().refreshRuntimes(),frequency:{interval:61*1e3,backoff:!0,max:300*1e3},name:"@datalayer/jupyter-kernels:KernelsManager#kernels",standby:()=>iamStore.getState().token||runtimesStore.getState().runtimesUrl?"when-hidden":!0});runtimesStore.subscribe((Au,lo)=>{if(!JSONExt.deepEqual(Au.runtimes,lo.runtimes)){const $u=Date.now(),Ru=Math.min(...Au.runtimes.map(Iu=>Iu.expired_at?parseFloat(Iu.expired_at):1/0))*1e3;$u+kernelsPoll.frequency.interval>Ru+2e3&&setTimeout(()=>{kernelsPoll.refresh()},Ru+2e3-$u)}});coreStore.subscribe((Au,lo)=>{if(Au.configuration.runtimesUrl&&Au.configuration.runtimesUrl!==lo.configuration.runtimesUrl){const $u=Au.configuration.runtimesUrl;console.log(`Updating runtimesUrl with new value ${$u}`),runtimesStore.setState({runtimesUrl:$u}),kernelsPoll.refresh().then(()=>kernelsPoll.tick).catch(Ru=>{console.error("Failed to refresh kernel servers list following service URL changed.",Ru)})}});function useRuntimesStore(Au){return useStore$1(runtimesStore,Au)}const DEFAULT_AGENT_CONFIG={name:"ai-agent",description:"AI Assistant",model:"",systemPrompt:"You are a helpful AI assistant.",agentLibrary:"pydantic-ai",protocol:"vercel-ai"};requireManager();const sandboxManagersByRuntime=new Map;function registerSandboxServiceManager(Au,lo){const $u=String(Au||"").trim();if(!$u||!lo)return()=>{};let Ru=sandboxManagersByRuntime.get($u);return Ru||(Ru=new Set,sandboxManagersByRuntime.set($u,Ru)),Ru.add(lo),()=>{const Iu=sandboxManagersByRuntime.get($u);Iu&&(Iu.delete(lo),Iu.size===0&&sandboxManagersByRuntime.delete($u))}}function disposeSandboxServiceManagers(Au){const lo=String(Au||"").trim();if(!lo)return;const $u=sandboxManagersByRuntime.get(lo);$u&&(sandboxManagersByRuntime.delete(lo),$u.forEach(Ru=>{try{disposeServiceManager(Ru)}catch(Iu){console.warn(`[sandboxServiceManagers] Failed disposing service manager for pod ${lo}`,Iu)}}))}function launchesOwnRoutesOnly(Au){return!!Au?.deploymentUid}const base$2=Au=>Au.trim().replace(/\/$/,"");function agentDeletionUrl(Au,lo,$u){if(!$u)return`${base$2(Au)}/api/v1/agents/${encodeURIComponent(lo)}`}function runtimeModelsUrl(Au,lo,$u){if(!$u)return`${base$2(Au)}/api/v1/configure/models?agent_id=${encodeURIComponent(lo)}`}const EMPTY_RUNTIMES=[],BROWSER_AGENT_CONNECTION=Object.freeze({runtimeName:"",environmentName:"",jupyterBaseUrl:"",agentBaseUrl:"",status:"ready",isReady:!0}),AGENT_QUERY_OPTIONS={staleTime:300*1e3,gcTime:600*1e3},agentQueryKeys={agentRuntimes:{all:()=>["agentRuntimes"],lists:()=>[...agentQueryKeys.agentRuntimes.all(),"list"],details:()=>[...agentQueryKeys.agentRuntimes.all(),"detail"],detail:Au=>[...agentQueryKeys.agentRuntimes.details(),Au]},checkpoints:{all:()=>["checkpoints"],lists:()=>[...agentQueryKeys.checkpoints.all(),"list"]}},DELETED_POD_TOMBSTONE_TTL_MS=300*1e3,deletedRuntimeTombstones=new Map;function markRuntimeDeleted(Au){const lo=String(Au||"").trim();lo&&(deletedRuntimeTombstones.set(lo,Date.now()),disposeSandboxServiceManagers(lo))}function clearRuntimeDeleted(Au){deletedRuntimeTombstones.delete(String(Au||"").trim())}const LIVE_RUNTIME_STATUSES=new Set(["running","resumed","starting","resuming"]);function isStaleDeletedRuntime(Au){const lo=String(Au?.runtime_name||"").trim(),$u=deletedRuntimeTombstones.get(lo);return $u===void 0?!1:Date.now()-$u>DELETED_POD_TOMBSTONE_TTL_MS?(deletedRuntimeTombstones.delete(lo),!1):LIVE_RUNTIME_STATUSES.has(Au.status)}const RUNTIME_STATUS_MAP={resume:"resumed",resumed:"resumed",resuming:"resuming",pausing:"pausing",paused:"paused",starting:"starting",pending:"starting",launching:"starting",terminated:"terminated",archived:"archived",running:"running"};function toAgentRuntimeData(Au){const lo=typeof Au.status=="string"?Au.status.toLowerCase():"",$u=RUNTIME_STATUS_MAP[lo]??"running",Ru=Au.environment;return{...Au,environment:{name:String(Ru?.name||"").trim(),title:String(Ru?.title||"").trim()||void 0,cpu:String(Ru?.cpu||"").trim()||void 0,memory:String(Ru?.memory||"").trim()||void 0,gpu:String(Ru?.gpu||"").trim()||void 0,resources:Ru?.resources},status:$u,name:Au.given_name||Au.runtime_name,id:Au.runtime_name,url:Au.ingress,messageCount:0,agent_spec_id:Au.agent_spec_id||void 0,content_attachments:Array.isArray(Au.content_attachments)?Au.content_attachments:[]}}function useAgentRuntimes(Au={}){const{agentSpecId:lo,agentConfig:$u,autoCreateAgent:Ru=!0,autoStart:Iu=!1,agentSpec:Pu,variant:Ou,runtimeCreationTarget:Mu,runtimeCreationBaseUrl:Du,runtimeConnection:Lu,appLaunch:Bu}=Au,ju=toAgentRuntimeVariant(Ou??Mu),Fu=launchesOwnRoutesOnly(Bu),{configuration:zu}=useCoreStore(),Uu=useAgentRuntimeConnection(),Hu=useAgentRuntimeStatus(),Vu=useAgentRuntimeError(),Gu=useAgentRuntimeIsLaunching(),Wu=useAgentRuntimeStore($d=>$d.launchAgent),Zu=useAgentRuntimeStore($d=>$d.connectAgent),Ju=useAgentRuntimeStore($d=>$d.createAgent),Yu=useAgentRuntimeStore($d=>$d.disconnect),[Xu,ed]=reactExports.useState("idle"),[td,nd]=reactExports.useState(null),[od,sd]=reactExports.useState(!1),ad=reactExports.useRef(!1),[pd,vd]=reactExports.useState(!1),Sd=reactExports.useRef(!1),_d=reactExports.useRef(null),bd=reactExports.useRef(!1),wd=reactExports.useRef($u);wd.current=$u;const Ad=!!lo&&locationOf(ju)==="cloud",gd=Lu?[Lu.runtimeName,Lu.environmentName,Lu.jupyterBaseUrl||Lu.serviceManager?.serverSettings.baseUrl||"",Lu.kernelId||""].join(":"):null,dd=reactExports.useMemo(()=>Du||(runsInBrowser(ju)?"":locationOf(ju)==="local"?"http://localhost:8765":zu?.runtimesUrl||void 0||"https://r1.datalayer.run"),[zu?.runtimesUrl,Du,ju]),yd=reactExports.useCallback(async()=>{try{const{iamStore:$d,coreStore:Id}=await __vitePreload(async()=>{const{iamStore:th,coreStore:Eh}=await import("./chunks/index-J-pyZzZ8.js");return{iamStore:th,coreStore:Eh}},[],import.meta.url),Vd=$d.getState().token||"",Wd=Id.getState().configuration?.aiAgentsUrl||"";return{token:Vd,aiAgentsUrl:Wd,runtimesUrl:dd}}catch{return{token:"",aiAgentsUrl:"",runtimesUrl:""}}},[dd]);reactExports.useEffect(()=>{!Lu||!gd||(Uu?[Uu.runtimeName,Uu.environmentName,Uu.jupyterBaseUrl||"",Uu.kernelId||""].join(":"):null)===gd||(Sd.current=!1,Zu(Lu))},[Lu,gd,Uu,Zu]);const ld=reactExports.useCallback(async $d=>{if(runsInBrowser(ju))return BROWSER_AGENT_CONNECTION;if(Ad){ed("launching"),nd(null);try{const Vd=(typeof $u?.name=="string"&&$u.name||typeof Pu?.name=="string"&&Pu.name||`${lo}`).replace(/\//g,"-").replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,63),Md=await Wu($d?{...$d,...Bu,runtimesUrl:dd}:{environmentName:"ai-agents-env",creditsLimit:10,givenName:Vd,...Bu,runtimesUrl:dd});return ed("ready"),Md}catch(Id){const Vd=Id instanceof Error?Id.message:String(Id);throw nd(Vd),ed("error"),Id}}else{if(!$d)throw new Error("Runtime options are required in connect mode");return Wu({...$d,runtimesUrl:dd})}},[$u?.name,Pu?.name,lo,Bu,Ad,dd,Wu,ju]),ud=reactExports.useCallback(async $d=>{if(bd.current)throw new Error("Agent creation already in progress");bd.current=!0,sd(!0);try{const Id={};Pu&&(Pu.model&&(Id.model=Pu.model),Pu.protocol&&(Id.protocol=Pu.protocol),Pu.systemPrompt&&(Id.systemPrompt=Pu.systemPrompt),Pu.description&&(Id.description=Pu.description),Pu.name&&(Id.name=Pu.name));const Vd={...DEFAULT_AGENT_CONFIG,...Id,...$u,...$d,name:$d?.name||$u?.name||(Ad&&lo?lo:Uu?.runtimeName)};return await Ju(Vd)}catch(Id){const Vd=Id instanceof Error?Id.message:String(Id);throw Ad&&(nd(Vd),ed("error")),Id}finally{bd.current=!1,sd(!1)}},[lo,$u,Pu,Ad,Uu,Ju]),hd=reactExports.useCallback(async()=>{const $d=Uu?.agentId,Id=Uu?.agentBaseUrl,Vd=$d&&Id?agentDeletionUrl(Id,$d,Fu):void 0;if(Vd)try{const{token:Md}=await yd();await fetch(Vd,{method:"DELETE",headers:Md?{Authorization:`Bearer ${Md}`}:{}})}catch{}Sd.current=!1,ad.current=!1,ed("idle"),nd(null),agentRuntimeStore.getState().reset()},[Uu?.agentId,Uu?.agentBaseUrl,yd,Fu]);reactExports.useEffect(()=>{!Ad&&Ru&&Uu&&Hu==="ready"&&!Uu.isReady&&!Sd.current&&(Sd.current=!0,Ju(wd.current).catch($d=>{console.error("[useAgent] Failed to auto-create agent:",$d),Sd.current=!1}))},[Ad,Ru,Uu,Hu,Ju]),reactExports.useEffect(()=>{Ad&&Ru&&Uu&&(Xu==="ready"||Xu==="resumed")&&!Uu.isReady&&!Sd.current&&(Sd.current=!0,ud(wd.current).catch($d=>{console.error("[useAgents] Failed to auto-create agent:",$d);const Id=$d instanceof Error?$d.message:String($d);nd(Id),ed("error"),Sd.current=!1}))},[Ad,Ru,Uu,Xu,ud]),reactExports.useEffect(()=>{const $d=Uu?.runtimeName||null;if(!$d){_d.current=null;return}_d.current&&_d.current!==$d&&(Sd.current=!1),_d.current=$d},[Uu?.runtimeName]),reactExports.useEffect(()=>{if(!Ad||Uu||Xu!=="idle")return;if(Bu){vd(!0);return}let $d=!1;return(async()=>{try{const{token:Vd,runtimesUrl:Md}=await yd();if(!Vd)return;const{listRuntimes:Wd}=await __vitePreload(async()=>{const{listRuntimes:ih}=await import("./chunks/runtimes-D0qXa51n.js");return{listRuntimes:ih}},[],import.meta.url),ah=((await Wd(Vd,Md)).runtimes||[]).filter(ih=>ih.environment?.name!=="ai-agents-env"?!1:lo?ih.agent_spec_id===lo:!0).slice().sort((ih,Mh)=>{const qd=Number(ih.started_at||0);return Number(Mh.started_at||0)-qd})[0];if($d||!ah?.runtime_name||!ah?.ingress)return;Zu({runtimeName:ah.runtime_name,environmentName:ah.environment.name,jupyterBaseUrl:ah.ingress}),Sd.current=!1;const yh=ah,vh=typeof yh.status=="string"?yh.status.toLowerCase():"",Jd=RUNTIME_STATUS_MAP[vh]??"running",eh=Jd==="paused"?"paused":Jd==="resuming"||Jd==="resumed"?"resumed":"running";ed(eh==="paused"?"paused":eh==="resumed"?"resumed":"ready")}catch(Vd){console.warn("[useAgents] Failed to find existing runtime:",Vd)}finally{$d||vd(!0)}})(),()=>{$d=!0}},[Ad,Uu,Iu,Xu,yd,lo,Bu,Zu]),reactExports.useEffect(()=>{(Hu==="disconnected"||Hu==="idle")&&(Sd.current=!1)},[Hu]),reactExports.useEffect(()=>{Ad&&Iu&&pd&&!Uu&&!ad.current&&Xu==="idle"&&(ad.current=!0,ld())},[Ad,Iu,pd,Uu,Xu,ld]),reactExports.useEffect(()=>{Vu&&Ad&&Xu!=="error"&&(nd(Vu),ed("error"))},[Vu,Ad,Xu]);const md=runsInBrowser(ju),Ed=md?"ready":Ad?Xu:Hu,Td=md?null:Ad&&td||Vu,Rd=md?!0:Ad?(Xu==="ready"||Xu==="resumed")&&!!Uu?.isReady:Hu==="ready"&&!!Uu?.isReady,jd=Uu?.endpoint||null,Cd=Uu?.serviceManager||null;return{runtime:Uu,status:Ed,isLaunching:Gu,launchRuntime:ld,connectToRuntime:Zu,disconnect:Yu,endpoint:jd,serviceManager:Cd,createAgent:ud,teardown:hd,isCreating:od,isReady:Rd,error:Td,variant:ju,runtimeCreationTarget:legacyTargetOf(ju),runtimeCreationBaseUrl:dd}}function useAgentRuntimesQuery(Au,lo){const{configuration:$u}=useCoreStore(),{requestDatalayer:Ru}=useDatalayer({notifyOnError:!1}),{user:Iu}=useIAMStore(),Pu=useQueryClient();return useQuery({queryKey:[...agentQueryKeys.agentRuntimes.lists(),"","","",""],queryFn:async()=>{const Mu=new URLSearchParams().toString(),Du=await Ru({url:`${runtimesUrl($u.runtimesUrl)}${Mu?`?${Mu}`:""}`,method:"GET"});if(Du.success&&Du.runtimes){const Lu=Du.runtimes.filter(Bu=>Bu.environment?.name==="ai-agents-env").map(toAgentRuntimeData).filter(Bu=>!isStaleDeletedRuntime(Bu));return Lu.forEach(Bu=>{Pu.setQueryData(agentQueryKeys.agentRuntimes.detail(Bu.runtime_name),Bu)}),Lu}return[]},...AGENT_QUERY_OPTIONS,refetchInterval:lo?.refetchInterval??1e4,refetchOnMount:!0,refetchOnWindowFocus:!0,enabled:(lo?.enabled??!0)&&!!Iu})}function useCreateAgentRuntime(){const{configuration:Au}=useCoreStore(),{requestDatalayer:lo}=useDatalayer({notifyOnError:!1}),$u=useQueryClient();return useMutation({mutationFn:async Ru=>{const Iu=(Ru.contentAttachmentUids??[]).map(Pu=>String(Pu||"").trim()).filter(Boolean);return lo({url:runtimesUrl(Au.runtimesUrl),method:"POST",body:{environment:{name:Ru.environmentName||"ai-agents-env"},given_name:Ru.givenName||"Agent",credits_limit:Ru.creditsLimit||10,type:Ru.type||"notebook",editor_variant:Ru.editorVariant||"none",enable_codemode:Ru.enableCodemode??!1,agent_spec_id:Ru.agentSpecId||void 0,agent_spec:Ru.agentSpec||void 0,user_account_handle:Ru.userAccountHandle||void 0,billing_entity_uid:Ru.billingEntityUid||void 0,billing_entity_type:Ru.billingEntityType||void 0,billing_entity_handle:Ru.billingEntityHandle||void 0,billing_source_organization_uid:Ru.billingSourceOrganizationUid||void 0,billing_source_organization_handle:Ru.billingSourceOrganizationHandle||void 0,runtime_name:Ru.runtimeName||void 0,content_attachment_uids:Iu.length?Iu:void 0}})},onSuccess:Ru=>{if(Ru.success&&Ru.runtime){const Iu=toAgentRuntimeData(Ru.runtime);clearRuntimeDeleted(Iu.runtime_name),$u.setQueryData(agentQueryKeys.agentRuntimes.detail(Iu.runtime_name),Iu),$u.invalidateQueries({queryKey:agentQueryKeys.agentRuntimes.all()})}}})}function useDeleteAgentRuntime(){const{configuration:Au}=useCoreStore(),{requestDatalayer:lo}=useDatalayer({notifyOnError:!1}),$u=useQueryClient(),Ru=Pu=>{if(!Pu||typeof Pu!="object")return;const Ou=Pu.response;return typeof Ou?.status=="number"?Ou.status:void 0},Iu=Pu=>{if(!Pu||typeof Pu!="object")return"";const Ou=Pu.response?.data;return String(Ou?.detail||Ou?.message||Pu.message||"").toLowerCase()};return useMutation({mutationFn:async Pu=>{try{return await lo({url:runtimeUrl(Au.runtimesUrl,Pu),method:"DELETE"})}catch(Ou){const Mu=Ru(Ou),Du=Iu(Ou);if(!(Mu===404||Du.includes("no reservation")||Du.includes("unknown reservation")||Du.includes("not found")))throw Ou;try{throw await lo({url:runtimeUrl(Au.runtimesUrl,Pu),method:"GET"}),Ou}catch(Bu){if(Ru(Bu)===404)return{success:!0,recovered:!0};throw Ou}}},onSuccess:(Pu,Ou)=>{markRuntimeDeleted(Ou),runtimesStore.getState().removeRuntime(Ou),$u.setQueriesData({queryKey:agentQueryKeys.agentRuntimes.lists()},Mu=>Array.isArray(Mu)?Mu.filter(Du=>Du.runtime_name!==Ou):Mu),$u.cancelQueries({queryKey:agentQueryKeys.agentRuntimes.detail(Ou)}),$u.removeQueries({queryKey:agentQueryKeys.agentRuntimes.detail(Ou)}),$u.invalidateQueries({queryKey:agentQueryKeys.agentRuntimes.lists()}),$u.refetchQueries({queryKey:agentQueryKeys.agentRuntimes.lists(),type:"active"}),$u.invalidateQueries({queryKey:agentQueryKeys.checkpoints.all()})}})}function useRefreshAgentRuntimes(){const Au=useQueryClient();return reactExports.useCallback(()=>{Au.invalidateQueries({queryKey:agentQueryKeys.agentRuntimes.all()})},[Au])}const DEFAULT_LIFECYCLE_RECORD={resumePending:!1,pauseLockedForResumed:!1};create$f()(persist((Au,lo)=>({byRuntimeKey:{},markResumePending:$u=>{$u&&Au(Ru=>({byRuntimeKey:{...Ru.byRuntimeKey,[$u]:{...DEFAULT_LIFECYCLE_RECORD,...Ru.byRuntimeKey[$u]??{},resumePending:!0}}}))},markResumeFailed:$u=>{$u&&Au(Ru=>({byRuntimeKey:{...Ru.byRuntimeKey,[$u]:{...DEFAULT_LIFECYCLE_RECORD,...Ru.byRuntimeKey[$u]??{},resumePending:!1,pauseLockedForResumed:!1}}}))},markResumeSettled:$u=>{$u&&Au(Ru=>({byRuntimeKey:{...Ru.byRuntimeKey,[$u]:{...DEFAULT_LIFECYCLE_RECORD,...Ru.byRuntimeKey[$u]??{},resumePending:!1,pauseLockedForResumed:!0}}}))},clearRuntimeLifecycle:$u=>{if(!$u)return;const Ru={...lo().byRuntimeKey};delete Ru[$u],Au({byRuntimeKey:Ru})}}),{name:"datalayer-agent-lifecycle",storage:createJSONStorage(()=>localStorage),partialize:Au=>({byRuntimeKey:Au.byRuntimeKey})}));function useAgentsRuntimes(Au,lo){const $u=useAgentRuntimesQuery(Au,lo),Ru=useCreateAgentRuntime(),Iu=useDeleteAgentRuntime(),Pu=useRefreshAgentRuntimes(),Ou=reactExports.useCallback(async(Mu,Du)=>{const Lu=String(Mu||"").trim();if(Lu)return Du?.beforeStop&&await Du.beforeStop(),Iu.mutateAsync(Lu)},[Iu]);return reactExports.useMemo(()=>({runtimes:$u.data??EMPTY_RUNTIMES,isRuntimesLoading:$u.isLoading,isRuntimesError:$u.isError,runtimesError:$u.error,refetchRuntimes:()=>$u.refetch(),refreshRuntimes:Pu,stopRuntimeByName:Ou,createRuntime:async Mu=>Ru.mutateAsync(Mu)}),[$u.data,$u.isLoading,$u.isError,$u.error,$u.refetch,Pu,Ou,Ru,Iu])}const DEFAULT_WS_PATH="/api/v1/tool-approvals/ws",DEFAULT_RECONNECT_DELAY_MS=3e3;function useAgentRuntimeWebSocket(Au){const{enabled:lo=!0,baseUrl:$u,authToken:Ru,agentId:Iu,autoReconnect:Pu=!0,reconnectDelayMs:Ou=DEFAULT_RECONNECT_DELAY_MS,maxReconnectAttempts:Mu}=Au,Du=reactExports.useRef(Au.onMessage);Du.current=Au.onMessage,reactExports.useEffect(()=>{if(!lo||!$u){agentRuntimeStore.getState().setWsState("closed");return}let Lu=!1,Bu=0,ju=null;function Fu(){const Uu=`${$u}${DEFAULT_WS_PATH}`,Hu=new URL(Uu.replace(/^http/,"ws"));return Ru&&Hu.searchParams.set("token",Ru),Iu&&Hu.searchParams.set("agent_id",Iu),Hu.toString()}function zu(){if(Lu)return;const Uu=Fu();agentRuntimeStore.getState().setWsState("connecting");const Hu=new WebSocket(Uu);agentRuntimeStore.getState().setWs(Hu,Iu),Hu.onopen=()=>{Bu=0,agentRuntimeStore.getState().setWsState("connected")},Hu.onmessage=Vu=>{let Gu;try{Gu=JSON.parse(String(Vu.data))}catch{return}const Wu=parseAgentStreamMessage(Gu);if(Du.current?.({type:Wu?.type,payload:Wu?.payload,raw:Gu}),!Wu)return;const Zu=agentRuntimeStore.getState();if(Wu.type==="agent.snapshot"){Zu.applySnapshot(Wu.payload);return}if(Wu.type==="agent.subagent"){Zu.appendSubagentEvent(Wu.payload);return}if(Wu.type==="agent.compaction"){Zu.setCompaction(Wu.payload);return}},Hu.onclose=()=>{if(agentRuntimeStore.getState().setWs(null,Iu),agentRuntimeStore.getState().setWsState("closed"),Lu||!Pu||(Bu+=1,typeof Mu=="number"&&Bu>Mu))return;const Vu=typeof Ou=="function"?Ou(Bu):Ou;ju=setTimeout(zu,Math.max(0,Vu))},Hu.onerror=()=>{(Hu.readyState===WebSocket.CONNECTING||Hu.readyState===WebSocket.OPEN)&&Hu.close()}}return zu(),()=>{Lu=!0,ju&&clearTimeout(ju),agentRuntimeStore.getState().setWs(null,Iu),agentRuntimeStore.getState().resetWs()}},[lo,$u,Ru,Iu,Pu,Ou,Mu])}const ALPHAVANTAGE_MCP_SERVER_0_0_1={id:"alphavantage",version:"0.0.1",name:"Alpha Vantage",description:"Financial market data and stock information",icon:"@primer/octicons-react:graph",emoji:"💹",url:"",command:"uvx",args:["av-mcp==0.2.1","${ALPHAVANTAGE_API_KEY}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["ALPHAVANTAGE_API_KEY:0.0.1"]},CHART_MCP_SERVER_0_0_1={id:"chart",version:"0.0.1",name:"Chart Generator",description:"Generate charts and visualizations",icon:"@datalayer/icons-react:chart-bar",emoji:"📊",url:"",command:"npx",args:["-y","@antv/mcp-server-chart"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},DATALAYER_MCP_SERVER_0_0_1={id:"datalayer",version:"0.0.1",name:"Datalayer",description:"Read, edit and run Jupyter notebooks on Datalayer, with sandboxes and data",icon:"@datalayer/icons-react:datalayer",emoji:"🚀",url:"https://mcp.datalayer.run/mcp",args:[],headers:{Authorization:"Bearer ${DATALAYER_API_KEY}"},transport:"streamable-http",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["DATALAYER_API_KEY:0.0.1"]},EARTHDATA_MCP_SERVER_0_0_1={id:"earthdata",version:"0.0.1",name:"Earthdata MCP",description:"Access NASA Earthdata search and metadata capabilities",icon:"@datalayer/icons-react:globe-americas",emoji:"🌍",url:"https://mcp.datalayer.run/mcp?only=earthdata",args:[],headers:{Authorization:"Bearer ${DATALAYER_API_KEY}"},transport:"streamable-http",enabled:!0,isAvailable:!1,tools:[],requiredEnvVars:["DATALAYER_API_KEY:0.0.1"]},EURUS_MCP_SERVER_0_0_1={id:"eurus",version:"0.0.1",name:"Eurus Climate MCP",description:"Climate and reanalysis analysis tools for spatial workflows",icon:"@primer/octicons-react:cloud",emoji:"🌦️",url:"",command:"eurus-mcp",args:[],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},FILESYSTEM_MCP_SERVER_0_0_1={id:"filesystem",version:"0.0.1",name:"Filesystem",description:"Local filesystem read/write operations",icon:"@primer/octicons-react:file-directory",emoji:"📁",url:"",command:"npx",args:["-y","@modelcontextprotocol/server-filesystem","${TMPDIR}"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},GITHUB_MCP_SERVER_0_0_1={id:"github",version:"0.0.1",name:"GitHub",description:"GitHub repository operations (issues, PRs, code search)",icon:"@datalayer/icons-react:github-mark",emoji:"🐙",url:"",command:"docker",args:["run","-i","--rm","-e","GITHUB_PERSONAL_ACCESS_TOKEN","ghcr.io/github/github-mcp-server"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["GITHUB_TOKEN:0.0.1"]},GOOGLE_WORKSPACE_MCP_SERVER_0_0_1={id:"google-workspace",version:"0.0.1",name:"Google Workspace",description:"Gmail of the person an application acts for, read or read and send, with a token Datalayer mints per call",icon:"@datalayer/icons-react:google",emoji:"📧",url:"http://127.0.0.1:9711/mcp",command:"uvx",args:["workspace-mcp","--transport","streamable-http","--permissions","gmail:send"],transport:"streamable-http",enabled:!0,isAvailable:!1,tools:[],requiredEnvVars:[]},HUGGINGFACE_MCP_SERVER_0_0_1={id:"huggingface",version:"0.0.1",name:"Hugging Face",description:"Hugging Face models, datasets, spaces, and papers access",icon:"@primer/octicons-react:hubot",emoji:"🤗",url:"https://huggingface.co/mcp",args:[],headers:{Authorization:"Bearer ${HF_TOKEN}"},transport:"streamable-http",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["HF_TOKEN:0.0.1"]},KAGGLE_MCP_SERVER_0_0_1={id:"kaggle",version:"0.0.1",name:"Kaggle",description:"Kaggle datasets, models, competitions, and notebooks access",icon:"@datalayer/icons-react:kaggle",emoji:"🏆",url:"https://www.kaggle.com/mcp",args:[],headers:{Authorization:"Bearer ${KAGGLE_API_TOKEN}"},transport:"streamable-http",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["KAGGLE_API_TOKEN:0.0.1"]},ODOO_ACCOUNTING_MCP_SERVER_0_0_1={id:"odoo-accounting",version:"0.0.1",name:"Odoo Accounting",description:"An accountant's day in Odoo — invoices, bills, journal entries, reconciliations, bank lines and tax returns — through the Datalayer MCP server",icon:"@datalayer/icons-react:odoo",emoji:"🧮",url:"https://mcp.datalayer.run/mcp?only=odoo-accounting",args:[],headers:{Authorization:"Bearer ${DATALAYER_API_KEY}"},transport:"streamable-http",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["DATALAYER_API_KEY:0.0.1"]},ODOO_MCP_SERVER_0_0_1={id:"odoo",version:"0.0.1",name:"Odoo",description:"Odoo ERP operations (search, invoices, journals, reconciliations)",icon:"@datalayer/icons-react:odoo",emoji:"🧾",url:"",command:"uvx",args:["mcp-server-odoo"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:[]},SALESFORCE_MCP_SERVER_0_0_1={id:"salesforce",version:"0.0.1",name:"Salesforce",description:"Salesforce CRM operations (queries, reports, objects, SOQL)",icon:"@primer/octicons-react:briefcase",emoji:"☁️",url:"",command:"npx",args:["-y","@anthropic/salesforce-mcp-server"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["SALESFORCE_ACCESS_TOKEN:0.0.1","SALESFORCE_INSTANCE_URL:0.0.1"]},SLACK_MCP_SERVER_0_0_1={id:"slack",version:"0.0.1",name:"Slack",description:"Slack messaging and channel operations",icon:"@datalayer/icons-react:slack",emoji:"💬",url:"",command:"npx",args:["-y","@datalayer/slack-mcp-server"],transport:"stdio",enabled:!1,isAvailable:!1,tools:[],requiredEnvVars:["SLACK_BOT_TOKEN:0.0.1","SLACK_TEAM_ID:0.0.1","SLACK_CHANNEL_IDS:0.0.1"]},TAVILY_MCP_SERVER_0_0_1={id:"tavily",version:"0.0.1",name:"Tavily Search",description:"Web search and research capabilities via Tavily API",icon:"@primer/octicons-react:search",emoji:"🔍",url:"",command:"npx",args:["-y","tavily-mcp"],transport:"stdio",enabled:!0,isAvailable:!1,tools:[],requiredEnvVars:["TAVILY_API_KEY:0.0.1"]},MCP_SERVER_LIBRARY={alphavantage:ALPHAVANTAGE_MCP_SERVER_0_0_1,chart:CHART_MCP_SERVER_0_0_1,datalayer:DATALAYER_MCP_SERVER_0_0_1,earthdata:EARTHDATA_MCP_SERVER_0_0_1,eurus:EURUS_MCP_SERVER_0_0_1,filesystem:FILESYSTEM_MCP_SERVER_0_0_1,github:GITHUB_MCP_SERVER_0_0_1,"google-workspace":GOOGLE_WORKSPACE_MCP_SERVER_0_0_1,huggingface:HUGGINGFACE_MCP_SERVER_0_0_1,kaggle:KAGGLE_MCP_SERVER_0_0_1,"odoo-accounting":ODOO_ACCOUNTING_MCP_SERVER_0_0_1,odoo:ODOO_MCP_SERVER_0_0_1,salesforce:SALESFORCE_MCP_SERVER_0_0_1,slack:SLACK_MCP_SERVER_0_0_1,tavily:TAVILY_MCP_SERVER_0_0_1},ACCOUNTING_SKILL_SPEC_0_0_1={id:"accounting",version:"0.0.1",name:"Accounting Skill",description:"Accounting analysis workflows for reconciliation, close, variance, and audit-ready summaries",module:"agent_skills.skills.accounting",package:void 0,method:void 0,path:void 0,requiredEnvVars:[],optionalEnvVars:[],dependencies:["pandas>=2.0.0"],tags:["accounting","finance","reconciliation","close"],icon:"@primer/octicons-react:book",emoji:"🧮",enabled:!1},CRAWL_SKILL_SPEC_0_0_1={id:"crawl",version:"0.0.1",name:"Web Crawl Skill",description:"Web crawling and content extraction capabilities",module:"agent_skills.skills.crawl",package:void 0,method:void 0,path:void 0,requiredEnvVars:["TAVILY_API_KEY:0.0.1"],optionalEnvVars:[],dependencies:["requests>=2.31.0","beautifulsoup4>=4.12.0"],tags:["web","crawl","scraping"],icon:"@primer/octicons-react:globe",emoji:"🌐",enabled:!0},EVENTS_SKILL_SPEC_0_0_1={id:"events",version:"0.0.1",name:"Events Skill",description:"Event generation, enrichment, and lifecycle orchestration",module:"agent_skills.skills.events",package:void 0,method:void 0,path:void 0,requiredEnvVars:[],optionalEnvVars:[],dependencies:["httpx>=0.27.0"],tags:["events","orchestration","automation"],icon:"@primer/octicons-react:calendar",emoji:"📅",enabled:!1},GITHUB_SKILL_SPEC_0_0_1={id:"github",version:"0.0.1",name:"GitHub Skill",description:"GitHub repository management and code operations",module:"agent_skills.skills.github",package:void 0,method:void 0,path:void 0,requiredEnvVars:["GITHUB_TOKEN:0.0.1"],optionalEnvVars:[],dependencies:["PyGithub>=2.1.0"],tags:["github","git","code"],icon:"@datalayer/icons-react:github-mark",emoji:"🐙",enabled:!1},JOKES_SKILL_SPEC_0_0_1={id:"jokes",version:"0.0.1",name:"Jokes Skill",description:"Return random jokes from a local path-based skill.",module:void 0,package:void 0,method:void 0,path:"jokes",requiredEnvVars:[],optionalEnvVars:[],dependencies:[],tags:["fun","humor","demo"],icon:"@primer/octicons-react:smiley",emoji:"😄",enabled:!1},PDF_SKILL_SPEC_0_0_1={id:"pdf",version:"0.0.1",name:"PDF Processing Skill",description:"PDF document reading, parsing, and extraction",module:"agent_skills.skills.pdf",package:void 0,method:void 0,path:void 0,requiredEnvVars:[],optionalEnvVars:[],dependencies:["PyPDF2>=3.0.0","pdfplumber>=0.10.0"],tags:["pdf","documents","extraction"],icon:"@primer/octicons-react:file",emoji:"📄",enabled:!1},TEXT_SUMMARIZER_SKILL_SPEC_0_0_1={id:"text-summarizer",version:"0.0.1",name:"Text Summarizer Skill",description:"Summarize text content using extractive and abstractive techniques. Use when the user asks for summaries, key points, or condensed versions of documents.",module:void 0,package:"agent_skills.skills.text_summarizer",method:"summarize_text",path:void 0,requiredEnvVars:[],optionalEnvVars:[],dependencies:["agent-skills>=0.0.1"],tags:["nlp","summarization","text-processing"],icon:"@primer/octicons-react:note",emoji:"📝",enabled:!1},SKILLS_CATALOG={accounting:ACCOUNTING_SKILL_SPEC_0_0_1,crawl:CRAWL_SKILL_SPEC_0_0_1,events:EVENTS_SKILL_SPEC_0_0_1,github:GITHUB_SKILL_SPEC_0_0_1,jokes:JOKES_SKILL_SPEC_0_0_1,pdf:PDF_SKILL_SPEC_0_0_1,"text-summarizer":TEXT_SUMMARIZER_SKILL_SPEC_0_0_1},CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1={id:"create-plan",version:"0.0.1",name:"Create Plan",description:"Create a plan with multiple steps and emit an AG-UI state snapshot.",tags:["example","ag-ui","state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"create_plan"},icon:"@primer/octicons-react:list-unordered",emoji:"📋"},CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1={id:"current-time",version:"0.0.1",name:"Current Time",description:"Return the current time in ISO format for a given timezone.",tags:["example","ag-ui","time"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"current_time"},icon:"@primer/octicons-react:clock",emoji:"🕒"},DECIDE_BACKEND_TOOL_SPEC_0_0_1={id:"decide",version:"0.0.1",name:"Decide",description:"Ask Jev typed questions about a text — noul (does a statement hold, with its probability), choice (one of named options) or score (a step on a rubric) — and get the typed answers back, through datalayer-ai-inference.",tags:["runtime","decisions","jev"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.tools.decisions",method:"decide"},icon:"@primer/octicons-react:law",emoji:"⚖️"},DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1={id:"display-recipe",version:"0.0.1",name:"Display Recipe",description:"Update the shared recipe state and emit an AG-UI state snapshot.",tags:["example","ag-ui","shared-state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"display_recipe"},icon:"@primer/octicons-react:book",emoji:"🍳"},EXAMPLE_CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1={id:"example-create-plan",version:"0.0.1",name:"Create Plan",description:"Create a plan with multiple steps and emit an AG-UI state snapshot.",tags:["example","ag-ui","state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"create_plan"},icon:"@primer/octicons-react:list-unordered",emoji:"📋"},EXAMPLE_CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1={id:"example-current-time",version:"0.0.1",name:"Current Time",description:"Return the current time in ISO format for a given timezone.",tags:["example","ag-ui","time"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"current_time"},icon:"@primer/octicons-react:clock",emoji:"🕒"},EXAMPLE_DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1={id:"example-display-recipe",version:"0.0.1",name:"Display Recipe",description:"Update the shared recipe state and emit an AG-UI state snapshot.",tags:["example","ag-ui","shared-state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"display_recipe"},icon:"@primer/octicons-react:book",emoji:"🍳"},EXAMPLE_GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1={id:"example-generate-haiku",version:"0.0.1",name:"Generate Haiku",description:"Generate a haiku (Japanese + English + gradient) rendered as a card by the frontend.",tags:["example","ag-ui","generative-ui"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"generate_haiku"},icon:"@primer/octicons-react:pencil",emoji:"🖋️"},EXAMPLE_GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1={id:"example-generate-task-steps",version:"0.0.1",name:"Generate Task Steps",description:"Generate task steps for human review and emit an AG-UI state snapshot.",tags:["example","ag-ui","human-in-the-loop"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"generate_task_steps"},icon:"@primer/octicons-react:tasklist",emoji:"🙋"},EXAMPLE_GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1={id:"example-get-weather",version:"0.0.1",name:"Get Weather",description:"Fetch current weather for a location from the Open-Meteo API for frontend rendering.",tags:["example","ag-ui","weather"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"get_weather"},icon:"@primer/octicons-react:sun",emoji:"🌤️"},EXAMPLE_RENDER_A2UI_SURFACE_BACKEND_TOOL_SPEC_0_0_1={id:"example-render-a2ui-surface",version:"0.0.1",name:"Render A2UI Surface",description:"Turn a declarative field spec into a validated A2UI v0.9 surface rendered live by the frontend as an interactive form/card.",tags:["example","ag-ui","a2ui","generative-ui"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.a2ui",method:"render_a2ui_surface"},icon:"@primer/octicons-react:browser",emoji:"🎛️"},EXAMPLE_UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1={id:"example-update-plan-step",version:"0.0.1",name:"Update Plan Step",description:"Update a plan step and emit an AG-UI state delta (JSON Patch RFC 6902).",tags:["example","ag-ui","state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"update_plan_step"},icon:"@primer/octicons-react:checklist",emoji:"✅"},GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1={id:"generate-haiku",version:"0.0.1",name:"Generate Haiku",description:"Generate a haiku (Japanese + English + gradient) rendered as a card by the frontend.",tags:["example","ag-ui","generative-ui"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"generate_haiku"},icon:"@primer/octicons-react:pencil",emoji:"🖋️"},GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1={id:"generate-task-steps",version:"0.0.1",name:"Generate Task Steps",description:"Generate task steps for human review and emit an AG-UI state snapshot.",tags:["example","ag-ui","human-in-the-loop"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"generate_task_steps"},icon:"@primer/octicons-react:tasklist",emoji:"🙋"},GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1={id:"get-weather",version:"0.0.1",name:"Get Weather",description:"Fetch current weather for a location from the Open-Meteo API for frontend rendering.",tags:["example","ag-ui","weather"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"get_weather"},icon:"@primer/octicons-react:sun",emoji:"🌤️"},RUNTIME_ECHO_BACKEND_TOOL_SPEC_0_0_1={id:"runtime-echo",version:"0.0.1",name:"Runtime Echo",description:"Echo text back to the caller for quick runtime verification.",tags:["runtime","utility"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools",method:"runtime_echo"},icon:"@primer/octicons-react:comment",emoji:"💬"},RUNTIME_SEND_MAIL_BACKEND_TOOL_SPEC_0_0_1={id:"runtime-send-mail",version:"0.0.1",name:"Runtime Send Mail (Fake)",description:"Fake mail sender for tool approval demos; returns a simulated send receipt.",tags:["runtime","approval","mail"],enabled:!0,approval:"manual",timeout:void 0,requiresApproval:!0,runtime:{language:"python",package:"agent_runtimes.examples.tools",method:"runtime_send_mail"},icon:"@primer/octicons-react:mail",emoji:"📧"},RUNTIME_SENSITIVE_ECHO_BACKEND_TOOL_SPEC_0_0_1={id:"runtime-sensitive-echo",version:"0.0.1",name:"Runtime Sensitive Echo",description:"Echo text with a manual approval checkpoint before execution.",tags:["runtime","approval"],enabled:!0,approval:"manual",timeout:void 0,requiresApproval:!0,runtime:{language:"python",package:"agent_runtimes.examples.tools",method:"runtime_sensitive_echo"},icon:"@primer/octicons-react:shield",emoji:"🛡️"},UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1={id:"update-plan-step",version:"0.0.1",name:"Update Plan Step",description:"Update a plan step and emit an AG-UI state delta (JSON Patch RFC 6902).",tags:["example","ag-ui","state"],enabled:!0,approval:"auto",timeout:void 0,requiresApproval:!1,runtime:{language:"python",package:"agent_runtimes.examples.tools.ag_ui",method:"update_plan_step"},icon:"@primer/octicons-react:checklist",emoji:"✅"},BACKEND_TOOL_CATALOG={"create-plan":CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1,"current-time":CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1,decide:DECIDE_BACKEND_TOOL_SPEC_0_0_1,"display-recipe":DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1,"example-create-plan":EXAMPLE_CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1,"example-current-time":EXAMPLE_CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1,"example-display-recipe":EXAMPLE_DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1,"example-generate-haiku":EXAMPLE_GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1,"example-generate-task-steps":EXAMPLE_GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1,"example-get-weather":EXAMPLE_GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1,"example-render-a2ui-surface":EXAMPLE_RENDER_A2UI_SURFACE_BACKEND_TOOL_SPEC_0_0_1,"example-update-plan-step":EXAMPLE_UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1,"generate-haiku":GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1,"generate-task-steps":GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1,"get-weather":GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1,"runtime-echo":RUNTIME_ECHO_BACKEND_TOOL_SPEC_0_0_1,"runtime-send-mail":RUNTIME_SEND_MAIL_BACKEND_TOOL_SPEC_0_0_1,"runtime-sensitive-echo":RUNTIME_SENSITIVE_ECHO_BACKEND_TOOL_SPEC_0_0_1,"update-plan-step":UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1},CELLS_FRONTEND_TOOL_SPEC_0_0_1={id:"cells",version:"0.0.1",name:"Cells",description:"Read and write the spreadsheet on the person's screen, and chart it — the grid drawn by Datalayer Cells.",tags:["frontend","cells","spreadsheets"],enabled:!0,toolset:["cells_read_range","cells_write_range","cells_insert_chart","cells_list_charts","cells_select_range"],icon:"@primer/octicons-react:table",emoji:"🧮"},DECKS_FRONTEND_TOOL_SPEC_0_0_1={id:"decks",version:"0.0.1",name:"Decks",description:"Read, write and drive presentations kept as data — a deck, its slides, and the one on screen.",tags:["frontend","decks","presentations"],enabled:!0,toolset:["decks_list_decks","decks_get_deck","decks_create_deck","decks_update_deck","decks_update_slide","decks_insert_slide","decks_delete_slide","decks_list_slides","decks_get_slide","decks_add_slide","decks_delete_deck","decks_list","decks_open","decks_go_to_slide","decks_next_slide","decks_previous_slide","decks_present","decks_print"],icon:"@primer/octicons-react:project",emoji:"🃏"},JUPYTER_NOTEBOOK_EDIT_FRONTEND_TOOL_SPEC_0_0_1={id:"jupyter-notebook-edit",version:"0.0.1",name:"Jupyter Notebook (edit)",description:"Read and edit a notebook, and run cells — but never delete from it.",tags:["frontend","notebook","edit"],enabled:!0,toolset:["readCell","readAllCells","insertCell","updateCell","runCell","executeCode"],icon:"@datalayer/icons-react:jupyter",emoji:"📓"},JUPYTER_NOTEBOOK_PROPOSE_FRONTEND_TOOL_SPEC_0_0_1={id:"jupyter-notebook-propose",version:"0.0.1",name:"Jupyter Notebook (propose)",description:"Read a notebook and propose changes for a person to accept, never applying them.",tags:["frontend","notebook","propose"],enabled:!0,toolset:["readCell","readAllCells","proposeCellUpdate","runCell"],icon:"@datalayer/icons-react:jupyter",emoji:"📓"},JUPYTER_NOTEBOOK_READ_FRONTEND_TOOL_SPEC_0_0_1={id:"jupyter-notebook-read",version:"0.0.1",name:"Jupyter Notebook (read only)",description:"Read a notebook without changing it — cells, outputs and errors.",tags:["frontend","notebook","read"],enabled:!0,toolset:["readCell","readAllCells"],icon:"@datalayer/icons-react:jupyter",emoji:"📓"},JUPYTER_NOTEBOOK_FRONTEND_TOOL_SPEC_0_0_1={id:"jupyter-notebook",version:"0.0.1",name:"Jupyter Notebook",description:"Frontend tools for interacting with Jupyter notebooks.",tags:["frontend","notebook","jupyter-server"],enabled:!0,toolset:"all",icon:"@datalayer/icons-react:jupyter",emoji:"📓"},LEXICAL_DOCUMENT_FRONTEND_TOOL_SPEC_0_0_1={id:"lexical-document",version:"0.0.1",name:"Lexical Document",description:"Frontend tools for interacting with Lexical documents: reading and writing blocks, running Jupyter cells in the page, and drawing diagrams into the document with Excalidraw.",tags:["frontend","document","lexical","drawing","diagram"],enabled:!0,toolset:"all",icon:"@primer/octicons-react:file",emoji:"📄"},FRONTEND_TOOL_CATALOG={cells:CELLS_FRONTEND_TOOL_SPEC_0_0_1,decks:DECKS_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-edit":JUPYTER_NOTEBOOK_EDIT_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-propose":JUPYTER_NOTEBOOK_PROPOSE_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-read":JUPYTER_NOTEBOOK_READ_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook":JUPYTER_NOTEBOOK_FRONTEND_TOOL_SPEC_0_0_1,"lexical-document":LEXICAL_DOCUMENT_FRONTEND_TOOL_SPEC_0_0_1},MCP_SERVER_MAP$1={"alphavantage:0.0.1":ALPHAVANTAGE_MCP_SERVER_0_0_1,"chart:0.0.1":CHART_MCP_SERVER_0_0_1,"earthdata:0.0.1":EARTHDATA_MCP_SERVER_0_0_1,"eurus:0.0.1":EURUS_MCP_SERVER_0_0_1,"filesystem:0.0.1":FILESYSTEM_MCP_SERVER_0_0_1,"github:0.0.1":GITHUB_MCP_SERVER_0_0_1,"google-workspace:0.0.1":GOOGLE_WORKSPACE_MCP_SERVER_0_0_1,"huggingface:0.0.1":HUGGINGFACE_MCP_SERVER_0_0_1,"kaggle:0.0.1":KAGGLE_MCP_SERVER_0_0_1,"odoo:0.0.1":ODOO_MCP_SERVER_0_0_1,"salesforce:0.0.1":SALESFORCE_MCP_SERVER_0_0_1,"slack:0.0.1":SLACK_MCP_SERVER_0_0_1,"tavily:0.0.1":TAVILY_MCP_SERVER_0_0_1},SKILL_MAP$1={"accounting:0.0.1":ACCOUNTING_SKILL_SPEC_0_0_1,"crawl:0.0.1":CRAWL_SKILL_SPEC_0_0_1,"events:0.0.1":EVENTS_SKILL_SPEC_0_0_1,"github:0.0.1":GITHUB_SKILL_SPEC_0_0_1,"jokes:0.0.1":JOKES_SKILL_SPEC_0_0_1,"pdf:0.0.1":PDF_SKILL_SPEC_0_0_1,"text-summarizer:0.0.1":TEXT_SUMMARIZER_SKILL_SPEC_0_0_1};function toAgentSkillSpec$1(Au){return{id:Au.id,name:Au.name,description:Au.description,version:Au.version??"0.0.1",tags:Au.tags,enabled:Au.enabled,requiredEnvVars:Au.requiredEnvVars}}const TOOL_MAP$1={"decide:0.0.1":DECIDE_BACKEND_TOOL_SPEC_0_0_1,"example-create-plan:0.0.1":EXAMPLE_CREATE_PLAN_BACKEND_TOOL_SPEC_0_0_1,"example-current-time:0.0.1":EXAMPLE_CURRENT_TIME_BACKEND_TOOL_SPEC_0_0_1,"example-display-recipe:0.0.1":EXAMPLE_DISPLAY_RECIPE_BACKEND_TOOL_SPEC_0_0_1,"example-generate-haiku:0.0.1":EXAMPLE_GENERATE_HAIKU_BACKEND_TOOL_SPEC_0_0_1,"example-generate-task-steps:0.0.1":EXAMPLE_GENERATE_TASK_STEPS_BACKEND_TOOL_SPEC_0_0_1,"example-get-weather:0.0.1":EXAMPLE_GET_WEATHER_BACKEND_TOOL_SPEC_0_0_1,"example-render-a2ui-surface:0.0.1":EXAMPLE_RENDER_A2UI_SURFACE_BACKEND_TOOL_SPEC_0_0_1,"example-update-plan-step:0.0.1":EXAMPLE_UPDATE_PLAN_STEP_BACKEND_TOOL_SPEC_0_0_1,"runtime-echo:0.0.1":RUNTIME_ECHO_BACKEND_TOOL_SPEC_0_0_1,"runtime-send-mail:0.0.1":RUNTIME_SEND_MAIL_BACKEND_TOOL_SPEC_0_0_1,"runtime-sensitive-echo:0.0.1":RUNTIME_SENSITIVE_ECHO_BACKEND_TOOL_SPEC_0_0_1},FRONTEND_TOOL_MAP$1={"cells:0.0.1":CELLS_FRONTEND_TOOL_SPEC_0_0_1,"decks:0.0.1":DECKS_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-edit:0.0.1":JUPYTER_NOTEBOOK_EDIT_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-propose:0.0.1":JUPYTER_NOTEBOOK_PROPOSE_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook-read:0.0.1":JUPYTER_NOTEBOOK_READ_FRONTEND_TOOL_SPEC_0_0_1,"jupyter-notebook:0.0.1":JUPYTER_NOTEBOOK_FRONTEND_TOOL_SPEC_0_0_1,"lexical-document:0.0.1":LEXICAL_DOCUMENT_FRONTEND_TOOL_SPEC_0_0_1},EXAMPLE_A2A_RESEARCHER_AGENTSPEC_0_0_1={id:"example-a2a-researcher",version:"0.0.1",name:"Example A2A Researcher",description:"A research specialist served over the A2A protocol. Given a topic, gathers the key facts and returns concise, source-aware notes.",tags:["research","a2a"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],frontendTools:[],environmentName:"ai-agents-env",icon:"search",emoji:"🔎",color:"#0EA5E9",suggestions:[{text:"Gather the key facts on a topic, with sources",summary:"Key facts with sources"}],welcomeMessage:"A2A researcher ready.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:void 0,harness:"pydantic-ai",systemPrompt:"You are a meticulous research specialist, reached by other agents over the A2A protocol. Given a topic, gather the key facts and return concise, source-aware notes. Prefer verifiable claims and flag anything uncertain. Answer with the notes themselves: no preamble, no questions back. You have no tools and no web access: work from what you know, and say when something should be checked.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"a2a",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_A2A_WRITER_AGENTSPEC_0_0_1={id:"example-a2a-writer",version:"0.0.1",name:"Example A2A Writer",description:"A writing specialist served over the A2A protocol. Given notes or instructions, produces clear, well-structured prose.",tags:["writing","a2a"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],frontendTools:[],environmentName:"ai-agents-env",icon:"pencil",emoji:"✍️",color:"#F59E0B",suggestions:[{text:"Turn a set of notes into a short, structured write-up",summary:"Notes into a write-up"}],welcomeMessage:"A2A writer ready.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:void 0,harness:"pydantic-ai",systemPrompt:"You are a concise writing specialist, reached by other agents over the A2A protocol. Given notes or findings, produce clear, well-structured prose. Keep it focused and free of filler. Answer with the text itself: no preamble, no questions back. You have no tools: work from the notes and instructions you are given.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"a2a",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_A2A_AGENTSPEC_0_0_1={id:"example-a2a",version:"0.0.1",name:"Example A2A Agent",description:"Demonstrates delegation to separate agents over the A2A protocol. The orchestrator hands research and writing to a researcher and a writer that run as agents of their own — launched beside it on the local server, or on Datalayer runtimes when it runs in the cloud — and talks to them over A2A.",tags:["research","workflow","a2a"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],frontendTools:[],environmentName:"ai-agents-env",icon:"broadcast",emoji:"📡",color:"#7C3AED",suggestions:[{text:"Research three key facts about the A2A protocol through the researcher, then have the writer turn them into one short paragraph.",summary:"Research then write over A2A"},{text:"Have the researcher gather five source-backed notes on Jupyter kernels and report them to me as they are.",summary:"Research via the A2A researcher"},{text:"Have the writer draft a short guide to naming variables from these points: be specific, prefer words to abbreviations, keep units in the name.",summary:"Draft via the A2A writer"}],welcomeMessage:"A2A example agent ready. Ask me to delegate research and writing to the agents I reach over A2A.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:'You are the A2A Orchestrator. You do not research or write yourself: you split a request into specialist tasks and hand each to a separate agent reached over the A2A protocol, then synthesize their answers into one coherent reply.\nYour agents are `researcher` — facts, background, source-backed notes — and `writer` — clear, structured prose from notes or instructions. Reach them with `delegate_task`, naming the agent; a request to "research and write" is two delegations, the researcher\'s notes handed to the writer. Give each a task it can carry out without the rest of this conversation. The first delegation to an agent may take a moment while it is launched.\nAnswer in the conversation, and only with the tools you actually have; never call a tool you were not given.',systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:{includeGeneralPurpose:!1,subagents:[{name:"researcher",description:"A separate research agent, reached over A2A. Gathers facts and source-backed notes on a topic; use for research, fact-finding and background gathering.",ref:"example-a2a-researcher:0.0.1",a2a:{launch:"auto"}},{name:"writer",description:"A separate writing agent, reached over A2A. Turns notes into clear, well-structured prose; use for summaries, drafts and final write-ups.",ref:"example-a2a-writer:0.0.1",a2a:{launch:"auto"}}]}},EXAMPLE_A2UI_AGENT_SPEC_0_0_1={id:"example-a2ui-agent",version:"0.0.1",name:"A2UI Agent",description:"An AG-UI agent that generates interactive A2UI surfaces on demand. Describe a form, intake, configurator, survey or booking flow and the agent renders a validated, themeable A2UI surface you can fill in.",tags:["workflow","automation","analysis"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[TOOL_MAP$1["example-render-a2ui-surface:0.0.1"]],frontendTools:[],frontendRenderTools:[{tool:"render_a2ui_surface",renderer:"a2ui-surface"}],environmentName:"ai-agents-env",icon:"browser",emoji:"🎛️",color:"#6366F1",suggestions:[{text:"Build a support ticket intake form with category, priority and a description.",summary:"Support ticket form"},{text:"Create a trip booking form with destination, dates, travelers and budget.",summary:"Trip booking form"},{text:"Generate a customer feedback survey with a rating slider and comments.",summary:"Feedback survey"},{text:"Make a product configurator for a laptop with CPU, RAM and add-ons.",summary:"Laptop configurator"}],welcomeMessage:`Hi! I turn requests into interactive A2UI surfaces. Ask me to build a form, survey, configurator or booking flow and I'll render it live for you.
2423
2423
  `,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:void 0,harness:"pydantic-ai",systemPrompt:"You are an A2UI generative-UI agent. You render real, interactive user\ninterfaces (forms, intakes, configurators, surveys, bookings, checklists)\nfrom the user's request.\n\nHow to respond:\n1. ALWAYS call the `render_a2ui_surface` tool to produce the UI. Never\n describe the form in prose instead of rendering it.\n2. Choose a concise `title` and a one-sentence `intro`.\n3. Design a sensible ordered list of `fields`. Pick the best `type` for each:\n - `text` / `email` for short input, `longtext` for descriptions/notes\n - `choice` (single) or `multichoice` (many) with `options` for pick-lists\n - `checkbox` for yes/no, `slider` (with `min`/`max`) for ranges/ratings\n - `date` / `datetime` for scheduling\n4. When the request implies triage or categorization (e.g. support tickets),\n add `summary_items` such as detected Category or Priority.\n5. Keep forms focused: usually 4-8 fields.\n6. After the tool call, reply with ONE short sentence confirming what you\n built. Do NOT repeat every field in text — the surface is shown directly.\n",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"ag-ui",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_A2UI_JUPYTER_OUTPUT_AGENTSPEC_0_0_1={id:"example-a2ui-jupyter-output",version:"0.0.1",name:"A2UI Jupyter Output Agent",description:"Drives the A2UI Jupyter Output example by selecting a kernel-output demonstration and asking the frontend to execute it in the connected sandbox.",tags:["a2ui","jupyter","output"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],frontendTools:[],environmentName:"ai-agents-env",icon:"notebook",emoji:"📓",color:"#0969DA",suggestions:[{text:"Run something in the code sandbox that prints as it goes.",summary:"Streaming output",emoji:"📜"},{text:"Plot a chart in the code sandbox and show me the image.",summary:"Plot a chart",emoji:"📈"},{text:"Build a small DataFrame in the code sandbox and show it as a table.",summary:"DataFrame as a table",emoji:"🧮"},{text:"Run something in the code sandbox that fails, so I can see the traceback.",summary:"Show a traceback",emoji:"🐛"},{text:"Show me an interactive slider from the code sandbox.",summary:"Interactive slider",emoji:"🎛️"},{text:"Give me a surface with buttons I can press.",summary:"Buttons to press",emoji:"🖲️"}],welcomeMessage:"Choose a suggestion to execute a Jupyter output demonstration and compare the kernel output with its A2UI surface.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You operate the A2UI Jupyter Output example. It exists to show one code\nsandbox execution twice over: what the kernel itself returned, and the A2UI\nsurface the server converter made of the same outputs.\n\nShowing that comparison is done with one tool and nothing else:\n`run_jupyter_output_demo`, whose `kind` is one of `stream`, `figure`,\n`table`, `error`, `ipywidgets`, or `interactive`.\n\nSo: whenever somebody asks you to run something in the code sandbox, or to\nshow what some kind of output looks like, call `run_jupyter_output_demo`\nexactly once with the kind that matches what they asked for. They will ask\nin ordinary words rather than by naming the tool or the kind, and reading\nthe request is your job:\n\n- printing, stdout, output arriving as it goes, a returned value -> `stream`\n- a plot, a chart, a figure, an image -> `figure`\n- a DataFrame, a table, tabular data -> `table`\n- a failure, an exception, a traceback, something that breaks -> `error`\n- a slider, a widget, an interactive control -> `ipywidgets`\n- a surface with buttons, something to press or click -> `interactive`\n\nNever write or execute Python of your own instead. The six demonstrations\nare fixed on purpose: the two panels are only worth comparing when both are\nshowing the same execution, and substituted code breaks the comparison the\nexample exists to make.\n\nAfter the tool returns, say in a sentence what was run and that it is now\nvisible in both the A2UI Surface and the Jupyter Output panels, with a word\non what differs between them where it is interesting. An `error`\ndemonstration is deliberate and has succeeded when its traceback is on\nscreen — do not apologise for it or offer to fix the code.\n",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"vercel-ai",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_A2UI_VIEWER_AGENTSPEC_0_0_1={id:"example-a2ui-viewer",version:"0.0.1",name:"A2UI Viewer Agent",description:"Answers beside the A2UI Viewer, whose scenes — a recipe card, a booking form, a sales snapshot and a shipping status — it renders on request as live A2UI surfaces, and runs code in the sandbox to show its outputs.",tags:["a2ui","viewer","loop"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[TOOL_MAP$1["example-render-a2ui-surface:0.0.1"]],frontendTools:[],frontendRenderTools:[{tool:"render_a2ui_surface",renderer:"a2ui-surface"}],environmentName:"ai-agents-env",icon:"browser",emoji:"🔍",color:"#6366F1",suggestions:[{text:"Show a recipe card for a Mediterranean quinoa bowl, with a photo, its rating and review count, prep and cook time, and how many it serves.",summary:"Recipe Card",emoji:"🍲"},{text:"Build a table booking form with party size, date and time, dietary requirements and a Submit Reservation button.",summary:"Booking Form",emoji:"📅"},{text:"Show a Q2 sales snapshot by category — Apparel, Electronics, Home Goods and Health & Beauty — as KPI tiles under one headline.",summary:"Sales Snapshot",emoji:"📈"},{text:"Show a package status card with the tracking number, the steps from placed to shipped to out for delivery, and the ETA.",summary:"Shipping Status",emoji:"📦"},{text:"Plot a chart in the code sandbox and show me the image.",summary:"Plot a chart",emoji:"📈"},{text:"Build a small DataFrame in the code sandbox and show it as a table.",summary:"DataFrame as a table",emoji:"🧮"},{text:"Run something in the code sandbox that fails, so I can see the traceback.",summary:"Show a traceback",emoji:"🐛"},{text:"Show me an interactive slider from the code sandbox.",summary:"Interactive slider",emoji:"🎛️"}],welcomeMessage:"This is the A2UI Viewer. Pick a scene above to see a surface drawn from A2UI messages, ask me to render one of them here, or run something in the code sandbox and see its output.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"browser",harness:"vercel-ai",systemPrompt:"You answer beside the A2UI Viewer, an example that renders A2UI surfaces\nfrom pasted protocol messages: a recipe card, a table booking form, a sales\nsnapshot of KPI tiles, and a shipping status timeline.\n\nWhen asked for a surface — one of those, or anything like them:\n1. ALWAYS call the `render_a2ui_surface` tool to produce it. Never describe\n the surface in prose instead of rendering it.\n2. Choose a concise `title` and a one-sentence `intro`.\n3. Design a sensible ordered list of `fields`, picking the best `type` for\n each: `text` / `email` for short input, `longtext` for notes, `choice`\n or `multichoice` with `options` for pick-lists, `checkbox` for yes/no,\n `slider` with `min`/`max` for ranges and ratings, `date` / `datetime`\n for scheduling. A card that shows values rather than asking for them\n still renders as a surface: put each value in a field with its label.\n4. After the tool call, reply with ONE short sentence saying what you\n rendered. Do not repeat the fields in text — the surface is shown.\n\nWhen asked to run code, use `execute_code` in the sandbox and let the\noutputs speak: a figure, a table, a traceback, a widget. Do not look for\nhelpers or skills in the sandbox; write the Python yourself.\n",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"vercel-ai",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_AGENT_CRITIC_LOOP_FOR_ANALYSIS_AGENTSPEC_0_0_1={id:"example-agent-critic-loop-for-analysis",version:"0.0.1",name:"Agent Critic Loop for Analysis",description:"Use a planner, executor, and critic agent loop to iteratively improve analysis quality and reduce logical errors in outputs.",tags:["analysis","data-quality","analytics"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],frontendTools:[FRONTEND_TOOL_MAP$1["jupyter-notebook:0.0.1"],FRONTEND_TOOL_MAP$1["lexical-document:0.0.1"]],environmentName:"ai-agents-env",icon:"sync",emoji:"📊",color:"#1F883D",suggestions:[{text:"Use /home/datalayer/datasets/datalayer-nfs/finance/transactions_q1.csv and run a critic loop: first produce a reconciliation analysis, then critique it for gaps and publish a corrected final report.",summary:"Critic loop on transactions"}],welcomeMessage:"Hi! I can help with agent critic loop for analysis. Share data, files, or context and I will run the workflow end-to-end, explain what matters, and suggest practical next steps.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are a specialized assistant for this gallery workflow: Agent Critic Loop for Analysis. Objective: Use a planner, executor, and critic agent loop to iteratively improve analysis quality and reduce logical errors in outputs. Use the runtime tools and notebook execution environment when needed. Keep outputs concise, structured, and decision-oriented. Provide clear reasoning and recommended next actions.",systemPromptCodemodeAddons:"Compose focused execution steps, validate intermediate results, and summarize outcomes after each run. Prefer efficient, reproducible code paths.",goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:{enabled:!0,token_reduction:"~80%",speedup:"~1.5x"},output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_AGENTIC_CHAT_AGENTSPEC_0_0_1={id:"example-agentic-chat",version:"0.0.1",name:"Agentic Chat",description:"A basic conversational AG-UI agent that can chat and use a tool to get the current time in any timezone.",tags:["workflow","automation","analysis"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[TOOL_MAP$1["example-current-time:0.0.1"]],frontendTools:[],environmentName:"ai-agents-env",icon:"clock",emoji:"🕒",color:"#6366F1",suggestions:[{text:"What is the current time?",summary:"Current time"},{text:"What's the current date?",summary:"Current date"}],welcomeMessage:`Hi! Ask me for the current time in any timezone.
2424
2424
  `,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:void 0,harness:"pydantic-ai",systemPrompt:`You are a helpful assistant that can provide the current time in any timezone. Use the current_time tool when asked about the time. Keep your responses concise and helpful.
2425
2425
  `,systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"ag-ui",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_AGENTIC_GENERATIVE_UI_AGENTSPEC_0_0_1={id:"example-agentic-generative-ui",version:"0.0.1",name:"Agentic Generative UI",description:"An AG-UI agent that creates plans with steps and updates individual steps as progress is made using JSON Patch (RFC 6902) state deltas.",tags:["workflow","automation","analysis"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[TOOL_MAP$1["example-create-plan:0.0.1"],TOOL_MAP$1["example-update-plan-step:0.0.1"]],frontendTools:[],environmentName:"ai-agents-env",icon:"list-unordered",emoji:"📋",color:"#6366F1",suggestions:[{text:"Create a project plan for building a mobile app.",summary:"Mobile app plan"},{text:"Generate a marketing strategy for a new product launch.",summary:"Marketing strategy"}],welcomeMessage:`Hi! Give me a goal and I'll create a plan, then work through the steps.
@@ -2566,14 +2566,26 @@ IMPORTANT:
2566
2566
  - Keep your responses concise
2567
2567
  - Each step should be a brief imperative command (e.g., "Set up environment",
2568
2568
  "Install dependencies")
2569
- `,systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"ag-ui",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_INFERENCE_AGENTSPEC_0_0_1={id:"example-inference",version:"0.0.1",name:"Example Inference Provider Agent",description:"Demonstrates inference-provider switching (local vs datalayer) for a local agent runtime session.",tags:["workflow","automation","analysis"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",inferenceProvider:"local",mcpServers:[],skills:[SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],frontendTools:[],environmentName:"ai-agents-env",icon:"pulse",emoji:"🧠",color:"#2563EB",suggestions:[{text:"Compare local and datalayer inference providers for latency and routing.",summary:"Compare providers"},{text:"Explain where model responses are generated for this current provider.",summary:"Where responses come from"},{text:"Summarize the tradeoffs of switching providers for this agent.",summary:"Provider trade-offs"}],welcomeMessage:"Inference provider demo ready. Switch between local and datalayer providers, then ask me the same prompt to compare behavior.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are the inference provider demo agent. Be concise, technical, and explicit about provider-routing implications when asked.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_LONG_RUNNING_AGENT_OVERNIGHT_AGENTSPEC_0_0_1={id:"example-long-running-agent-overnight",version:"0.0.1",name:"Long-Running Agent Overnight",description:"Launch a data workflow that can continue running, recover from interruptions, and return results when the job is complete.",tags:["operations","workflow","automation"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],frontendTools:[FRONTEND_TOOL_MAP$1["jupyter-notebook:0.0.1"],FRONTEND_TOOL_MAP$1["lexical-document:0.0.1"]],environmentName:"ai-agents-env",icon:"play",emoji:"📊",color:"#1F883D",suggestions:[{text:"Use /home/datalayer/datasets/datalayer-nfs/etl/daily_events.csv to run an overnight-style batch analysis and provide a completion summary with checkpoints.",summary:"Overnight batch analysis"}],welcomeMessage:"Hi! I can help with long-running agent overnight. Share data, files, or context and I will run the workflow end-to-end, explain what matters, and suggest practical next steps.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are a specialized assistant for this gallery workflow: Long-Running Agent Overnight. Objective: Launch a data workflow that can continue running, recover from interruptions, and return results when the job is complete. Use the runtime tools and notebook execution environment when needed. Keep outputs concise, structured, and decision-oriented. Provide clear reasoning and recommended next actions.",systemPromptCodemodeAddons:"Compose focused execution steps, validate intermediate results, and summarize outcomes after each run. Prefer efficient, reproducible code paths.",goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:{enabled:!0,token_reduction:"~80%",speedup:"~1.5x"},output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_MCP_AGENTSPEC_0_0_1={id:"example-mcp",version:"0.0.1",name:"Example MCP Agent",description:"MCP-focused example agent for AgentMCPExample. It connects to the Tavily MCP server and demonstrates search/research style tool usage from the chat panel.",tags:["research","analysis","summarization"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[MCP_SERVER_MAP$1["tavily:0.0.1"]],skills:[SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0,SKILL_MAP$1["jokes:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["jokes:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],disableToolApprovals:!0,frontendTools:[],environmentName:"ai-agents-env",icon:"globe",emoji:"🌐",color:"#0EA5E9",suggestions:[{text:"Search the web for recent news about AI agents",summary:"AI agent news"},{text:"Find trending open-source Python projects on GitHub",summary:"Trending Python projects"},{text:"Research best practices for building RAG applications",summary:"RAG best practices"},{text:"Compare popular JavaScript frameworks in 2024",summary:"JavaScript frameworks 2024"}],welcomeMessage:"MCP example agent ready. Ask me to search, extract, crawl, and research via Tavily MCP tools.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are the Demo MCP Agent. Use Tavily MCP tools for web search and research requests, cite concise findings, and keep responses practical and clear.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_MEMORY_AGENTSPEC_0_0_1={id:"example-memory",version:"0.0.1",name:"Example Memory Agent",description:"Demonstrates durable conversational memory with the Mem0 backend. Persists user preferences and supports memory inspection/search.",tags:["customer-support","workflow","routing"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],frontendTools:[],environmentName:"ai-agents-env",icon:"database",emoji:"🧠",color:"#0D9488",suggestions:[{text:"Remember that I prefer dark mode, metric units and concise answers, then confirm what you stored.",summary:"Remember my preferences"},{text:"What do you remember about my preferences?",summary:"Recall my preferences"},{text:"Search your memory for anything about units or formatting.",summary:"Search memory"}],welcomeMessage:"Ready to demonstrate durable memory. I persist stable facts and preferences (name, preferences, constraints), and can recall them across turns/restarts. I do not persist every transient sentence.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are the Example Memory Agent. Capture durable user preferences and key facts, recall them accurately when asked, and summarize memory context clearly. Persist only durable, user-relevant information (identity, long-lived preferences, standing constraints, recurring goals). Do not persist one-off chatter, greetings, or ephemeral filler. When asked to remember something, confirm what was stored and suggest verifying it in the Memory Inspector.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"mem0",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_MONITORING_AGENTSPEC_0_0_1={id:"example-monitoring",version:"0.0.1",name:"Example Monitoring Agent",description:"Monitoring-focused example agent for AgentMonitoringExample. It is intentionally lightweight so it starts reliably in local example runs.",tags:["monitoring","operations","performance"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],frontendTools:[],environmentName:"ai-agents-env",icon:"pulse",emoji:"📊",color:"#0EA5E9",suggestions:[{text:"Show my current monitoring context summary",summary:"Monitoring summary"},{text:"Explain the last turn cost and total token usage",summary:"Last turn cost and tokens"},{text:"Summarize recent activity and potential anomalies",summary:"Recent activity and anomalies"}],welcomeMessage:"Monitoring example agent ready. Ask for runtime activity, cost trends, and token usage summaries.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are the Demo Monitoring Agent. Prioritize concise operational summaries, highlight anomalies, and provide clear next-step recommendations.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_MULTI_AGENT_DATA_CLEANING_AGENTSPEC_0_0_1={id:"example-multi-agent-data-cleaning",version:"0.0.1",name:"Multi-Agent Data Cleaning",description:"Split cleaning, validation, deduplication, normalization, and explanation into separate agents with a shared context.",tags:["data-acquisition","data-quality","etl"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],frontendTools:[FRONTEND_TOOL_MAP$1["jupyter-notebook:0.0.1"],FRONTEND_TOOL_MAP$1["lexical-document:0.0.1"]],environmentName:"ai-agents-env",icon:"tools",emoji:"📊",color:"#1F883D",suggestions:[{text:"Use /home/datalayer/datasets/datalayer-nfs/quality/dirty_customers.csv and coordinate multiple agents to deduplicate and clean the dataset.",summary:"Multi-agent data cleaning"}],welcomeMessage:"Hi! I can help with multi-agent data cleaning. Share data, files, or context and I will run the workflow end-to-end, explain what matters, and suggest practical next steps.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are a specialized assistant for this gallery workflow: Multi-Agent Data Cleaning. Objective: Split cleaning, validation, deduplication, normalization, and explanation into separate agents with a shared context. Use the runtime tools and notebook execution environment when needed. Keep outputs concise, structured, and decision-oriented. Provide clear reasoning and recommended next actions.",systemPromptCodemodeAddons:"Compose focused execution steps, validate intermediate results, and summarize outcomes after each run. Prefer efficient, reproducible code paths.",goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:{enabled:!0,token_reduction:"~80%",speedup:"~1.5x"},output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_MULTI_AGENT_ROOT_CAUSE_ANALYSIS_AGENTSPEC_0_0_1={id:"example-multi-agent-root-cause-analysis",version:"0.0.1",name:"Multi-Agent Root Cause Analysis",description:"Assign agents to anomaly detection, hypothesis generation, evidence review, and synthesis to produce root-cause findings.",tags:["analysis","analytics","reporting"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],frontendTools:[FRONTEND_TOOL_MAP$1["jupyter-notebook:0.0.1"],FRONTEND_TOOL_MAP$1["lexical-document:0.0.1"]],environmentName:"ai-agents-env",icon:"bug",emoji:"📊",color:"#1F883D",suggestions:[{text:"Use /home/datalayer/datasets/datalayer-nfs/ops/incidents.csv to run multi-agent root-cause analysis and produce a ranked remediation plan.",summary:"Multi-agent root cause"}],welcomeMessage:"Hi! I can help with multi-agent root cause analysis. Share data, files, or context and I will run the workflow end-to-end, explain what matters, and suggest practical next steps.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are a specialized assistant for this gallery workflow: Multi-Agent Root Cause Analysis. Objective: Assign agents to anomaly detection, hypothesis generation, evidence review, and synthesis to produce root-cause findings. Use the runtime tools and notebook execution environment when needed. Keep outputs concise, structured, and decision-oriented. Provide clear reasoning and recommended next actions.",systemPromptCodemodeAddons:"Compose focused execution steps, validate intermediate results, and summarize outcomes after each run. Prefer efficient, reproducible code paths.",goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:{enabled:!0,token_reduction:"~80%",speedup:"~1.5x"},output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_NO_CODEMODE_AGENTSPEC_0_0_1={id:"example-no-codemode",version:"0.0.1",name:"Example Tavily No Codemode Agent",description:"Tavily MCP demo agent without codemode conversion. MCP tools are used directly without codemode orchestration.",tags:["workflow","automation","analysis"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[MCP_SERVER_MAP$1["tavily:0.0.1"]],skills:[SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],disableToolApprovals:!0,frontendTools:[],environmentName:"ai-agents-env",icon:"globe",emoji:"🌐",color:"#0969DA",suggestions:[{text:"Run three web searches — Datalayer notebooks, Datalayer runtimes, Datalayer AI agents — extract the top result of each, and store the key points of all three in a variable named about_datalayer in the sandbox.",summary:"Three searches, tool by tool"},{text:"Search for the latest updates about Datalayer and summarize the top three results.",summary:"Latest Datalayer updates"},{text:"Extract the key points from https://datalayer.ai and list them.",summary:"Key points of one page"}],welcomeMessage:"Tavily MCP no-codemode agent ready. I use MCP tools directly.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are a Tavily MCP demo assistant without codemode. Use available MCP tools directly for search and research requests, and provide concise summaries.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:{enabled:!1},output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_NOTIFICATIONS_AGENTSPEC_0_0_1={id:"example-notifications",version:"0.0.1",name:"Example Notifications Agent",description:"Demonstrates multi-channel notifications including in-app, email, and Slack style destinations with preference management.",tags:["monitoring","email","operations"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],frontendTools:[],environmentName:"ai-agents-env",icon:"bell",emoji:"🔔",color:"#F59E0B",suggestions:[{text:'Send me an in-app notification titled "Hello from the example" saying the notifications channel works, then tell me which channels are enabled.',summary:"Send an in-app notification"},{text:"Send a warning-level notification through every enabled channel about disk space running low, and report how each channel took it.",summary:"Warn on every channel"},{text:"List the notifications sent so far and which are still unread.",summary:"Unread notifications"}],welcomeMessage:"Ready to demonstrate notifications. Configure your channels and send a test alert to validate delivery.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are the Example Notifications Agent. You notify the person through the channels configured for you — in-app, email, Slack — with `send_notification`, and you can see what was sent and how each channel took it with `list_notifications`. Channels are configured by the person in the panel beside the chat, not by you: when a channel is off or has no target, say so and point to the panel. Report deliveries honestly from the tool's answer — the local server records email rather than sending it. Answer in the conversation, and only with the tools you actually have; never call a tool you were not given.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:{"in-app":{enabled:!0},email:{enabled:!1},slack:{enabled:!1}},memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_ONE_TRIGGER_APPROVAL_AGENTSPEC_0_0_1={id:"example-one-trigger-approval",version:"0.0.1",name:"Example Once Trigger and Tool Approval Agent",description:'A demonstration agent for the "once" trigger type with manual tool approval. When launched, the agent executes its trigger prompt once and invokes the runtime-sensitive-echo tool, which requires manual approval before execution. After completion, the runtime is terminated automatically.',tags:["workflow","human-approval","automation"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-sensitive-echo:0.0.1"]],frontendTools:[FRONTEND_TOOL_MAP$1["jupyter-notebook:0.0.1"]],environmentName:"ai-agents-env",icon:"shield",emoji:"🛡️",color:"#ef4444",suggestions:[],welcomeMessage:void 0,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:void 0,systemPromptCodemodeAddons:void 0,goal:'Call runtime_sensitive_echo exactly once with message="Tool approval demo executed" and reason="audit". Do not call any other tool.',delegable:[],protocol:void 0,ui:[],protocols:[],trigger:{type:"once",description:"Run once with approval and terminate",prompt:"Call runtime_sensitive_echo exactly once with message='Tool approval demo executed' and reason='audit'. Do not call any other tool."},modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_ONE_TRIGGER_AGENTSPEC_0_0_1={id:"example-one-trigger",version:"0.0.1",name:"Example Once Trigger Agent",description:'A demonstration agent for the "once" trigger type. When launched, the agent executes its trigger prompt exactly once, emits AGENT_STARTED and AGENT_ENDED lifecycle events, and then terminates the runtime automatically.',tags:["workflow","automation","analysis"],domain:void 0,enabled:!0,model:"bedrock:us.anthropic.claude-sonnet-4-6",modelAdditionals:["alibaba:qwen-max"],mcpServers:[],skills:[SKILL_MAP$1["github:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["github:0.0.1"]):void 0,SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],disableToolApprovals:!0,frontendTools:[],environmentName:"ai-agents-env",icon:"zap",emoji:"⚡",color:"#f59e0b",suggestions:[{text:"Which trigger are you configured with, what prompt does it run, and what happens when it fires?",summary:"Your trigger"},{text:"Run your trigger prompt now, as if the trigger had just fired.",summary:"Run the trigger prompt"},{text:"How would a cron or a webhook trigger differ from your once trigger?",summary:"Cron and webhook versus once"}],welcomeMessage:void 0,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:void 0,systemPromptCodemodeAddons:void 0,goal:"Run a one-shot task: list the user's top 3 public and top 3 private GitHub repositories, ranked by recent activity, and provide a brief summary of each.",delegable:[],protocol:void 0,ui:[],protocols:[],trigger:{type:"once",description:"Run once and terminate",prompt:"List the user's top 3 public and top 3 private GitHub repositories, ranked by recent activity, and provide a brief summary of each."},modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_OTEL_AGENTSPEC_0_0_1={id:"example-otel",version:"0.0.1",name:"Example OTEL Agent",description:"OTEL observability example agent for AgentOtelExample. It assists the user in exploring traces, logs and metrics surfaced by the OTEL dashboard.",tags:["monitoring","visualization","operations"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],frontendTools:[],environmentName:"ai-agents-env",icon:"telescope",emoji:"🔭",color:"#7C3AED",suggestions:[{text:"What do the most recent traces show?",summary:"Recent traces"},{text:"Are there any errors or anomalies in the telemetry?",summary:"Errors and anomalies"},{text:"Give me a summary of the current metrics.",summary:"Metrics summary"},{text:"Help me find the root cause of slow requests.",summary:"Slow requests root cause"}],welcomeMessage:"OTEL example agent ready. Ask me about your traces, logs, and metrics — I can help summarize activity, spot anomalies, and investigate root causes.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are the Demo OTEL Agent. You observe OpenTelemetry telemetry data (traces, logs, metrics) and help the user reason about service behavior. Prioritize concise, evidence-grounded summaries, highlight anomalies, and recommend concrete next investigation steps.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_OUTPUT_AGENTSPEC_0_0_1={id:"example-output",version:"0.0.1",name:"Example Output Agent",description:"Demonstrates structured response rendering (table, json, chart, and file) for the AgentOutputsExample side panel, which detects the block in each answer and renders it.",tags:["workflow","visualization","automation"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],disableToolApprovals:!0,frontendTools:[],environmentName:"ai-agents-env",icon:"table",emoji:"📦",color:"#7C3AED",suggestions:[{text:"Return a Markdown table of the top 5 US cities by population, with the columns City, State and Population.",summary:"Population table"},{text:"Return a JSON object describing a product catalog with 3 items, each with an id, a name, a price and tags.",summary:"Catalog JSON"},{text:"Produce an ECharts bar chart of monthly sales from January to June, as a ```json fenced block whose first line is `// chart`.",summary:"Sales chart"},{text:"Create a CSV file named sales.csv with sample sales for the last 7 days, in a ```csv fenced block whose first line is `# filename: sales.csv`.",summary:"CSV file"}],welcomeMessage:"Example output agent ready. Ask for a TABLE, JSON, a CHART or a FILE and I will answer with exactly one structured output block.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:`You are the Example Output Agent.
2570
- The user may request one of exactly four output modes: TABLE, JSON, CHART, or FILE. For each response, emit exactly one mode and nothing else: no prose before or after the block. Answer from what you know: do not run code or call tools to produce the block.
2569
+ `,systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:"ag-ui",ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_INFERENCE_AGENTSPEC_0_0_1={id:"example-inference",version:"0.0.1",name:"Example Inference Provider Agent",description:"Demonstrates inference-provider switching (local vs datalayer) for a local agent runtime session.",tags:["workflow","automation","analysis"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",inferenceProvider:"local",mcpServers:[],skills:[SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],frontendTools:[],environmentName:"ai-agents-env",icon:"pulse",emoji:"🧠",color:"#2563EB",suggestions:[{text:"Compare local and datalayer inference providers for latency and routing.",summary:"Compare providers"},{text:"Explain where model responses are generated for this current provider.",summary:"Where responses come from"},{text:"Summarize the tradeoffs of switching providers for this agent.",summary:"Provider trade-offs"}],welcomeMessage:"Inference provider demo ready. Switch between local and datalayer providers, then ask me the same prompt to compare behavior.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are the inference provider demo agent. Be concise, technical, and explicit about provider-routing implications when asked.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_LONG_RUNNING_AGENT_OVERNIGHT_AGENTSPEC_0_0_1={id:"example-long-running-agent-overnight",version:"0.0.1",name:"Long-Running Agent Overnight",description:"Launch a data workflow that can continue running, recover from interruptions, and return results when the job is complete.",tags:["operations","workflow","automation"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],frontendTools:[FRONTEND_TOOL_MAP$1["jupyter-notebook:0.0.1"],FRONTEND_TOOL_MAP$1["lexical-document:0.0.1"]],environmentName:"ai-agents-env",icon:"play",emoji:"📊",color:"#1F883D",suggestions:[{text:"Use /home/datalayer/datasets/datalayer-nfs/etl/daily_events.csv to run an overnight-style batch analysis and provide a completion summary with checkpoints.",summary:"Overnight batch analysis"}],welcomeMessage:"Hi! I can help with long-running agent overnight. Share data, files, or context and I will run the workflow end-to-end, explain what matters, and suggest practical next steps.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are a specialized assistant for this gallery workflow: Long-Running Agent Overnight. Objective: Launch a data workflow that can continue running, recover from interruptions, and return results when the job is complete. Use the runtime tools and notebook execution environment when needed. Keep outputs concise, structured, and decision-oriented. Provide clear reasoning and recommended next actions.",systemPromptCodemodeAddons:"Compose focused execution steps, validate intermediate results, and summarize outcomes after each run. Prefer efficient, reproducible code paths.",goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:{enabled:!0,token_reduction:"~80%",speedup:"~1.5x"},output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_MCP_AGENTSPEC_0_0_1={id:"example-mcp",version:"0.0.1",name:"Example MCP Agent",description:"MCP-focused example agent for AgentMCPExample. It connects to the Tavily MCP server and demonstrates search/research style tool usage from the chat panel.",tags:["research","analysis","summarization"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[MCP_SERVER_MAP$1["tavily:0.0.1"]],skills:[SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0,SKILL_MAP$1["jokes:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["jokes:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],disableToolApprovals:!0,frontendTools:[],environmentName:"ai-agents-env",icon:"globe",emoji:"🌐",color:"#0EA5E9",suggestions:[{text:"Search the web for recent news about AI agents",summary:"AI agent news"},{text:"Find trending open-source Python projects on GitHub",summary:"Trending Python projects"},{text:"Research best practices for building RAG applications",summary:"RAG best practices"},{text:"Compare popular JavaScript frameworks in 2024",summary:"JavaScript frameworks 2024"}],welcomeMessage:"MCP example agent ready. Ask me to search, extract, crawl, and research via Tavily MCP tools.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are the Demo MCP Agent. Use Tavily MCP tools for web search and research requests, cite concise findings, and keep responses practical and clear.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_MEMORY_AGENTSPEC_0_0_1={id:"example-memory",version:"0.0.1",name:"Example Memory Agent",description:"Demonstrates durable conversational memory with the Mem0 backend. Persists user preferences and supports memory inspection/search.",tags:["customer-support","workflow","routing"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],frontendTools:[],environmentName:"ai-agents-env",icon:"database",emoji:"🧠",color:"#0D9488",suggestions:[{text:"Remember that I prefer dark mode, metric units and concise answers, then confirm what you stored.",summary:"Remember my preferences"},{text:"What do you remember about my preferences?",summary:"Recall my preferences"},{text:"Search your memory for anything about units or formatting.",summary:"Search memory"}],welcomeMessage:"Ready to demonstrate durable memory. I persist stable facts and preferences (name, preferences, constraints), and can recall them across turns/restarts. I do not persist every transient sentence.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are the Example Memory Agent. Capture durable user preferences and key facts, recall them accurately when asked, and summarize memory context clearly. Persist only durable, user-relevant information (identity, long-lived preferences, standing constraints, recurring goals). Do not persist one-off chatter, greetings, or ephemeral filler. When asked to remember something, confirm what was stored and suggest verifying it in the Memory Inspector.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"mem0",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_MONITORING_AGENTSPEC_0_0_1={id:"example-monitoring",version:"0.0.1",name:"Example Monitoring Agent",description:"Monitoring-focused example agent for AgentMonitoringExample. It is intentionally lightweight so it starts reliably in local example runs.",tags:["monitoring","operations","performance"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],frontendTools:[],environmentName:"ai-agents-env",icon:"pulse",emoji:"📊",color:"#0EA5E9",suggestions:[{text:"Show my current monitoring context summary",summary:"Monitoring summary"},{text:"Explain the last turn cost and total token usage",summary:"Last turn cost and tokens"},{text:"Summarize recent activity and potential anomalies",summary:"Recent activity and anomalies"}],welcomeMessage:"Monitoring example agent ready. Ask for runtime activity, cost trends, and token usage summaries.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are the Demo Monitoring Agent. Prioritize concise operational summaries, highlight anomalies, and provide clear next-step recommendations.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_MULTI_AGENT_DATA_CLEANING_AGENTSPEC_0_0_1={id:"example-multi-agent-data-cleaning",version:"0.0.1",name:"Multi-Agent Data Cleaning",description:"Split cleaning, validation, deduplication, normalization, and explanation into separate agents with a shared context.",tags:["data-acquisition","data-quality","etl"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],frontendTools:[FRONTEND_TOOL_MAP$1["jupyter-notebook:0.0.1"],FRONTEND_TOOL_MAP$1["lexical-document:0.0.1"]],environmentName:"ai-agents-env",icon:"tools",emoji:"📊",color:"#1F883D",suggestions:[{text:"Use /home/datalayer/datasets/datalayer-nfs/quality/dirty_customers.csv and coordinate multiple agents to deduplicate and clean the dataset.",summary:"Multi-agent data cleaning"}],welcomeMessage:"Hi! I can help with multi-agent data cleaning. Share data, files, or context and I will run the workflow end-to-end, explain what matters, and suggest practical next steps.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are a specialized assistant for this gallery workflow: Multi-Agent Data Cleaning. Objective: Split cleaning, validation, deduplication, normalization, and explanation into separate agents with a shared context. Use the runtime tools and notebook execution environment when needed. Keep outputs concise, structured, and decision-oriented. Provide clear reasoning and recommended next actions.",systemPromptCodemodeAddons:"Compose focused execution steps, validate intermediate results, and summarize outcomes after each run. Prefer efficient, reproducible code paths.",goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:{enabled:!0,token_reduction:"~80%",speedup:"~1.5x"},output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_MULTI_AGENT_ROOT_CAUSE_ANALYSIS_AGENTSPEC_0_0_1={id:"example-multi-agent-root-cause-analysis",version:"0.0.1",name:"Multi-Agent Root Cause Analysis",description:"Assign agents to anomaly detection, hypothesis generation, evidence review, and synthesis to produce root-cause findings.",tags:["analysis","analytics","reporting"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],frontendTools:[FRONTEND_TOOL_MAP$1["jupyter-notebook:0.0.1"],FRONTEND_TOOL_MAP$1["lexical-document:0.0.1"]],environmentName:"ai-agents-env",icon:"bug",emoji:"📊",color:"#1F883D",suggestions:[{text:"Use /home/datalayer/datasets/datalayer-nfs/ops/incidents.csv to run multi-agent root-cause analysis and produce a ranked remediation plan.",summary:"Multi-agent root cause"}],welcomeMessage:"Hi! I can help with multi-agent root cause analysis. Share data, files, or context and I will run the workflow end-to-end, explain what matters, and suggest practical next steps.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are a specialized assistant for this gallery workflow: Multi-Agent Root Cause Analysis. Objective: Assign agents to anomaly detection, hypothesis generation, evidence review, and synthesis to produce root-cause findings. Use the runtime tools and notebook execution environment when needed. Keep outputs concise, structured, and decision-oriented. Provide clear reasoning and recommended next actions.",systemPromptCodemodeAddons:"Compose focused execution steps, validate intermediate results, and summarize outcomes after each run. Prefer efficient, reproducible code paths.",goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:{enabled:!0,token_reduction:"~80%",speedup:"~1.5x"},output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_NO_CODEMODE_AGENTSPEC_0_0_1={id:"example-no-codemode",version:"0.0.1",name:"Example Tavily No Codemode Agent",description:"Tavily MCP demo agent without codemode conversion. MCP tools are used directly without codemode orchestration.",tags:["workflow","automation","analysis"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[MCP_SERVER_MAP$1["tavily:0.0.1"]],skills:[SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],disableToolApprovals:!0,frontendTools:[],environmentName:"ai-agents-env",icon:"globe",emoji:"🌐",color:"#0969DA",suggestions:[{text:"Run three web searches — Datalayer notebooks, Datalayer runtimes, Datalayer AI agents — extract the top result of each, and store the key points of all three in a variable named about_datalayer in the sandbox.",summary:"Three searches, tool by tool"},{text:"Search for the latest updates about Datalayer and summarize the top three results.",summary:"Latest Datalayer updates"},{text:"Extract the key points from https://datalayer.ai and list them.",summary:"Key points of one page"}],welcomeMessage:"Tavily MCP no-codemode agent ready. I use MCP tools directly.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are a Tavily MCP demo assistant without codemode. Use available MCP tools directly for search and research requests, and provide concise summaries.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:{enabled:!1},output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_NOTIFICATIONS_AGENTSPEC_0_0_1={id:"example-notifications",version:"0.0.1",name:"Example Notifications Agent",description:"Demonstrates multi-channel notifications including in-app, email, and Slack style destinations with preference management.",tags:["monitoring","email","operations"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],frontendTools:[],environmentName:"ai-agents-env",icon:"bell",emoji:"🔔",color:"#F59E0B",suggestions:[{text:'Send me an in-app notification titled "Hello from the example" saying the notifications channel works, then tell me which channels are enabled.',summary:"Send an in-app notification"},{text:"Send a warning-level notification through every enabled channel about disk space running low, and report how each channel took it.",summary:"Warn on every channel"},{text:"List the notifications sent so far and which are still unread.",summary:"Unread notifications"}],welcomeMessage:"Ready to demonstrate notifications. Configure your channels and send a test alert to validate delivery.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are the Example Notifications Agent. You notify the person through the channels configured for you — in-app, email, Slack — with `send_notification`, and you can see what was sent and how each channel took it with `list_notifications`. Channels are configured by the person in the panel beside the chat, not by you: when a channel is off or has no target, say so and point to the panel. Report deliveries honestly from the tool's answer — the local server records email rather than sending it. Answer in the conversation, and only with the tools you actually have; never call a tool you were not given.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:{"in-app":{enabled:!0},email:{enabled:!1},slack:{enabled:!1}},memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_ONE_TRIGGER_APPROVAL_AGENTSPEC_0_0_1={id:"example-one-trigger-approval",version:"0.0.1",name:"Example Once Trigger and Tool Approval Agent",description:'A demonstration agent for the "once" trigger type with manual tool approval. When launched, the agent executes its trigger prompt once and invokes the runtime-sensitive-echo tool, which requires manual approval before execution. After completion, the runtime is terminated automatically.',tags:["workflow","human-approval","automation"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-sensitive-echo:0.0.1"]],frontendTools:[FRONTEND_TOOL_MAP$1["jupyter-notebook:0.0.1"]],environmentName:"ai-agents-env",icon:"shield",emoji:"🛡️",color:"#ef4444",suggestions:[],welcomeMessage:void 0,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:void 0,systemPromptCodemodeAddons:void 0,goal:'Call runtime_sensitive_echo exactly once with message="Tool approval demo executed" and reason="audit". Do not call any other tool.',delegable:[],protocol:void 0,ui:[],protocols:[],trigger:{type:"once",description:"Run once with approval and terminate",prompt:"Call runtime_sensitive_echo exactly once with message='Tool approval demo executed' and reason='audit'. Do not call any other tool."},modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_ONE_TRIGGER_AGENTSPEC_0_0_1={id:"example-one-trigger",version:"0.0.1",name:"Example Once Trigger Agent",description:'A demonstration agent for the "once" trigger type. When launched, the agent executes its trigger prompt exactly once, emits AGENT_STARTED and AGENT_ENDED lifecycle events, and then terminates the runtime automatically.',tags:["workflow","automation","analysis"],domain:void 0,enabled:!0,model:"bedrock:us.anthropic.claude-sonnet-4-6",modelAdditionals:["alibaba:qwen-max"],mcpServers:[],skills:[SKILL_MAP$1["github:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["github:0.0.1"]):void 0,SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],disableToolApprovals:!0,frontendTools:[],environmentName:"ai-agents-env",icon:"zap",emoji:"⚡",color:"#f59e0b",suggestions:[{text:"Which trigger are you configured with, what prompt does it run, and what happens when it fires?",summary:"Your trigger"},{text:"Run your trigger prompt now, as if the trigger had just fired.",summary:"Run the trigger prompt"},{text:"How would a cron or a webhook trigger differ from your once trigger?",summary:"Cron and webhook versus once"}],welcomeMessage:void 0,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:void 0,systemPromptCodemodeAddons:void 0,goal:"Run a one-shot task: list the user's top 3 public and top 3 private GitHub repositories, ranked by recent activity, and provide a brief summary of each.",delegable:[],protocol:void 0,ui:[],protocols:[],trigger:{type:"once",description:"Run once and terminate",prompt:"List the user's top 3 public and top 3 private GitHub repositories, ranked by recent activity, and provide a brief summary of each."},modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_OTEL_AGENTSPEC_0_0_1={id:"example-otel",version:"0.0.1",name:"Example OTEL Agent",description:"OTEL observability example agent for AgentOtelExample. It assists the user in exploring traces, logs and metrics surfaced by the OTEL dashboard.",tags:["monitoring","visualization","operations"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[SKILL_MAP$1["events:0.0.1"]?toAgentSkillSpec$1(SKILL_MAP$1["events:0.0.1"]):void 0].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],frontendTools:[],environmentName:"ai-agents-env",icon:"telescope",emoji:"🔭",color:"#7C3AED",suggestions:[{text:"What do the most recent traces show?",summary:"Recent traces"},{text:"Are there any errors or anomalies in the telemetry?",summary:"Errors and anomalies"},{text:"Give me a summary of the current metrics.",summary:"Metrics summary"},{text:"Help me find the root cause of slow requests.",summary:"Slow requests root cause"}],welcomeMessage:"OTEL example agent ready. Ask me about your traces, logs, and metrics — I can help summarize activity, spot anomalies, and investigate root causes.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:"You are the Demo OTEL Agent. You observe OpenTelemetry telemetry data (traces, logs, metrics) and help the user reason about service behavior. Prioritize concise, evidence-grounded summaries, highlight anomalies, and recommend concrete next investigation steps.",systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_OUTPUT_AGENTSPEC_0_0_1={id:"example-output",version:"0.0.1",name:"Example Output Agent",description:"Demonstrates structured response rendering (table, json, chart, spreadsheet and file) for the AgentOutputsExample side panel, which detects the block in each answer and renders it; a spreadsheet is drawn with Datalayer Cells, in the chat and in the panel, and charted on the grid through the Cells frontend tools.",tags:["workflow","visualization","automation"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[],disableToolApprovals:!0,frontendTools:[FRONTEND_TOOL_MAP$1["cells:0.0.1"]],environmentName:"ai-agents-env",icon:"table",emoji:"📦",color:"#7C3AED",suggestions:[{text:"Return a Markdown table of the top 5 US cities by population, with the columns City, State and Population.",summary:"Population table"},{text:"Return a JSON object describing a product catalog with 3 items, each with an id, a name, a price and tags.",summary:"Catalog JSON"},{text:"Produce an ECharts bar chart of monthly sales from January to June, as a ```json fenced block whose first line is `// chart`.",summary:"Sales chart"},{text:"Give me a spreadsheet of twelve months of sales by region (North, South, Online), with a Month column, as one ```csv fenced block whose first line is `# filename: sales.csv`.",summary:"Sales spreadsheet"},{text:"Chart the sales spreadsheet: a column chart of the three regions by month, titled Sales by region, inserted on the grid below the data.",summary:"Chart the spreadsheet"},{text:"Create a YAML file named config.yaml for a small web service (name, port, log level and two routes), in a ```yaml fenced block whose first line is `# filename: config.yaml`.",summary:"YAML file"}],welcomeMessage:"Example output agent ready. Ask for a TABLE, JSON, a CHART, a SPREADSHEET or a FILE and I will answer with exactly one structured output block; once a spreadsheet is shown, ask me to chart it on its grid.",welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:`You are the Example Output Agent.
2570
+ The user may request one of exactly six output modes: TABLE, JSON, CHART, SPREADSHEET, FILE or SHEET CHART. For the first five, emit exactly one mode and nothing else: no prose before or after the block. Answer from what you know: do not run code or call tools to produce the block.
2571
2571
  Formatting rules: - TABLE: Return one GitHub-flavored markdown table, one row per line,
2572
2572
  never several rows joined on a single line.
2573
2573
  - JSON: Return exactly one fenced \`\`\`json code block. - CHART: Return exactly one fenced \`\`\`json code block whose first line is
2574
2574
  "// chart" and whose remaining body is valid ECharts option JSON.
2575
+ - SPREADSHEET: Return exactly one fenced \`\`\`csv code block whose first
2576
+ line is "# filename: <name>.csv", then a header row, then one row per
2577
+ line, comma-separated, numbers without thousands separators or units.
2575
2578
  - FILE: Return exactly one fenced code block whose info string is a file
2576
- extension, and whose first line is "# filename: <name.ext>".
2579
+ extension other than csv or tsv, and whose first line is
2580
+ "# filename: <name.ext>".
2581
+ - SHEET CHART: when asked to chart, plot or graph the spreadsheet already
2582
+ shown (the last SPREADSHEET answer), do not write a block: work on the
2583
+ grid with the Cells tools. Call cells_read_range with no range to find
2584
+ the data, then cells_insert_chart over that range (headers included) with
2585
+ the type and title asked for, at the first column two rows below the
2586
+ data (for data in A1:D13, at A15), unless told where. Answer in one short
2587
+ sentence naming the chart and its range. If the tools say no grid is
2588
+ shown, ask for the spreadsheet first.
2577
2589
 
2578
2590
  If mode is ambiguous, default to JSON.`,systemPromptCodemodeAddons:void 0,goal:void 0,delegable:[],protocol:void 0,ui:[],protocols:[],trigger:void 0,modelConfig:void 0,mcpServerTools:void 0,guardrails:void 0,evals:void 0,codemode:void 0,output:void 0,advanced:void 0,checkpoints:void 0,authorizationPolicy:void 0,notifications:void 0,memory:"ephemeral",preHooks:void 0,postHooks:void 0,toolHooks:void 0,parameters:void 0,subagents:void 0},EXAMPLE_PARAMETERS_AGENTSPEC_0_0_1={id:"example-parameters",version:"0.0.1",name:"Example Parameters Agent",description:"Demonstrates launch-time parameterization with JSON schema validation.",tags:["workflow","automation","analysis"],domain:void 0,enabled:!1,model:"bedrock:us.anthropic.claude-sonnet-4-6",mcpServers:[],skills:[].filter(Boolean),backendTools:[TOOL_MAP$1["runtime-echo:0.0.1"]],frontendTools:[],environmentName:"ai-agents-env",icon:"sliders",emoji:"🎛️",color:"#0F766E",suggestions:[{text:"Use execute_code to print(demo_params) from the sandbox, then explain the value.",summary:"Print and explain demo_params"},{text:"Use execute_code to print('demo_params =', demo_params).",summary:"Print demo_params"}],welcomeMessage:`This runtime was launched for project {{project}} and role {{role}}.
2579
2591
  `,welcomeNotebook:void 0,welcomeDocument:void 0,sandboxVariant:"jupyter-server",harness:"pydantic-ai",systemPrompt:`You are an assistant dedicated to {{project}}. Assume the user is a {{role}} and answer in a {{tone}} style. A sandbox pre-hook set a Python variable named demo_params with value {{demo_params}}.
@@ -3873,7 +3885,8 @@ ${expandCompactMarkdownTableBody(Iu.trim())}
3873
3885
  ${Pu.trim()}
3874
3886
 
3875
3887
  `:`\`\`\`${Ru}
3876
- ${Pu}\`\`\``}),lo}function ChatMarkdown({text:Au,density:lo="comfortable"}){return jsxRuntimeExports.jsx(Box,{"data-chat-markdown":"",sx:{...streamdownMarkdownStyles,...lo==="compact"?{lineHeight:1.4,"& p":{marginTop:0,marginBottom:"0.4em"},"& p:last-child":{marginBottom:0}}:{}},children:jsxRuntimeExports.jsx(_o$1,{rehypePlugins:REHYPE_PLUGINS_WITHOUT_HTML,children:normalizeAssistantMarkdown(Au)})})}const ICON_PACKAGES=["@datalayer/icons-react","@primer/octicons-react"],ICON_REF=/^(@datalayer\/icons-react|@primer\/octicons-react):([a-z0-9]+(?:-[a-z0-9]+)*)$/;function exportNameOf(Au){return Au.split("-").map(lo=>lo.charAt(0).toUpperCase()+lo.slice(1)).join("")+"Icon"}function parseIconRef(Au){const lo=ICON_REF.exec(Au);if(!lo)throw new Error(`The icon ${JSON.stringify(Au)} is not <package>:<name>, the package one of ${ICON_PACKAGES.join(", ")} and the name in kebab case`);const[,$u,Ru]=lo;return{pkg:$u,name:Ru,exportName:exportNameOf(Ru)}}const LOADERS={"@datalayer/icons-react":()=>__vitePreload(()=>import("./chunks/index.esm-086pkdGE.js"),[],import.meta.url),"@primer/octicons-react":()=>__vitePreload(()=>import("./chunks/index.esm-f0zNr1S2.js"),[],import.meta.url)},loaded=new Map,loading=new Map;function loadIconPackage(Au){const lo=loading.get(Au)??LOADERS[Au]().then($u=>(loaded.set(Au,$u),$u));return loading.set(Au,lo),lo}function iconOf(Au,lo){const $u=lo[Au.exportName];if(!$u)throw new Error(`${Au.pkg} has no icon ${Au.name} (${Au.exportName}): name one it has`);return $u}function useMarkIcon(Au){const lo=Au?parseIconRef(Au):void 0,$u=lo?.pkg,Ru=$u?loaded.get($u):void 0,[,Iu]=reactExports.useState(0),[Pu,Ou]=reactExports.useState(null);if(reactExports.useEffect(()=>{if(!$u||Ru)return;let Mu=!0;return loadIconPackage($u).then(()=>Mu&&Iu(Du=>Du+1),Du=>Mu&&Ou(Du)),()=>{Mu=!1}},[$u,Ru]),Pu)throw Pu;return lo&&Ru?iconOf(lo,Ru):void 0}function SpecMark({icon:Au,emoji:lo,size:$u=16}){const Ru=useMarkIcon(Au);return Au?Ru?jsxRuntimeExports.jsx("span",{"data-mark":Au,style:{display:"inline-flex",flexShrink:0,lineHeight:0},children:jsxRuntimeExports.jsx(Ru,{size:$u,"aria-hidden":"true",...Au.startsWith("@datalayer/icons-react:")?{colored:!0}:{}})}):jsxRuntimeExports.jsx("span",{"data-mark":Au,"aria-hidden":"true",style:{display:"inline-block",width:$u,height:$u}}):lo?jsxRuntimeExports.jsx("span",{"data-mark":"emoji","aria-hidden":"true",style:{display:"inline-flex",flexShrink:0,fontSize:Math.round($u*.9),lineHeight:1},children:lo}):null}function hasMark(Au){return!!(Au?.icon||Au?.emoji)}const SKILL_TOOLS=new Set(["run_skill_script","load_skill","read_skill_resource"]);function marksOf(Au){return{icon:Au?.icon,emoji:Au?.emoji}}function skillIdOfCall(Au,lo){if(!SKILL_TOOLS.has(Au))return null;const $u=lo?.skill_name??lo?.skill??lo?.name;return typeof $u!="string"||$u.length===0?null:$u.split(":",1)[0]||$u}let frontendIndex=null,runtimeIndex=null;function frontendTools(){if(!frontendIndex){frontendIndex=new Map;for(const Au of Object.values(FRONTEND_TOOL_CATALOG))for(const lo of Au.toolset??[])frontendIndex.has(lo)||frontendIndex.set(lo,{id:Au.id,...marksOf(Au)})}return frontendIndex}function runtimeTools(){if(!runtimeIndex){runtimeIndex=new Map;for(const Au of Object.values(BACKEND_TOOL_CATALOG)){const lo=Au.runtime?.method;lo&&!runtimeIndex.has(lo)&&runtimeIndex.set(lo,{id:Au.id,...marksOf(Au)})}}return runtimeIndex}function marksOfMcpServer(Au){return Au.icon||Au.emoji?marksOf(Au):marksOf(MCP_SERVER_LIBRARY[Au.id])}function marksOfSkill(Au){return marksOf(SKILLS_CATALOG[Au.split(":",1)[0]||Au])}function marksOfFrontendTool(Au){return marksOf(frontendTools().get(Au))}function marksOfRuntimeTool(Au){return marksOf(runtimeTools().get(Au))}function marksOfToolCall(Au,lo,$u=[]){const Ru=skillIdOfCall(Au,lo);if(Ru)return{kind:"skill",ownerId:Ru,...marksOfSkill(Ru)};const Iu=$u.find(Mu=>Mu.tools.some(Du=>Du.name===Au));if(Iu)return{kind:"mcp",ownerId:Iu.id,...marksOfMcpServer(Iu)};const Pu=frontendTools().get(Au);if(Pu)return{kind:"frontend",ownerId:Pu.id,...marksOf(Pu)};const Ou=runtimeTools().get(Au);return Ou?{kind:"runtime",ownerId:Ou.id,...marksOf(Ou)}:null}function getStatusDisplay(Au,lo,$u){switch(Au){case"inProgress":return{icon:jsxRuntimeExports.jsx(ClockIcon,{size:14}),color:"attention.fg",label:$u.toolPreparing,bgColor:"attention.subtle"};case"executing":return{icon:jsxRuntimeExports.jsx(ClockIcon,{size:14}),color:"attention.fg",label:$u.toolExecuting,bgColor:"attention.subtle"};case"complete":return{icon:jsxRuntimeExports.jsx(CheckCircleIcon,{size:14}),color:"success.fg",label:$u.toolComplete,bgColor:"success.subtle"};case"error":return lo==="execution"?{icon:jsxRuntimeExports.jsx(AlertIcon,{size:14}),color:"danger.fg",label:$u.toolExecutionFailed,bgColor:"danger.subtle"}:lo==="code"?{icon:jsxRuntimeExports.jsx(XCircleIcon,{size:14}),color:"severe.fg",label:$u.toolCodeError,bgColor:"severe.subtle"}:lo==="exit"?{icon:jsxRuntimeExports.jsx(AlertIcon,{size:14}),color:"attention.fg",label:$u.toolExited,bgColor:"attention.subtle"}:{icon:jsxRuntimeExports.jsx(XCircleIcon,{size:14}),color:"danger.fg",label:$u.toolFailed,bgColor:"danger.subtle"};default:return{icon:jsxRuntimeExports.jsx(ToolsIcon,{size:14}),color:"fg.muted",label:Au,bgColor:"neutral.subtle"}}}function formatToolName(Au){return Au.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(" ").map(lo=>lo.charAt(0).toUpperCase()+lo.slice(1).toLowerCase()).join(" ")}function getArgsSummary(Au,lo){const $u=Object.entries(Au);if($u.length===0)return lo.noParameters;const Ru=$u.slice(0,2).map(([Iu,Pu])=>{const Ou=typeof Pu=="string"?Pu.slice(0,30)+(Pu.length>30?"...":""):typeof Pu=="object"?JSON.stringify(Pu).slice(0,30)+"...":String(Pu);return`${Iu}: ${Ou}`}).join(", ");return $u.length>2?`${Ru} ${lo.moreArguments($u.length-2)}`:Ru}function ToolCallDisplay({toolCallId:Au,toolName:lo,args:$u,result:Ru,status:Iu,error:Pu,executionResult:Ou,codeError:Mu,exitCode:Du,executionError:Lu,approvalRequired:Bu=!1,approvalState:ju,approvalDecisionSource:Fu,onApprove:zu,onDeny:Uu,approvalLoading:Hu=!1,marks:Vu,summary:Gu,density:Wu="comfortable"}){const Zu=useChatWords(),Ju=Wu==="compact",[Yu,Xu]=reactExports.useState(!1),ed=Du??Ou?.exit_code,td=ed!=null&&ed!==0,nd=Iu==="error"?Lu||Ou?.execution_error?"execution":Mu||Ou?.code_error?"code":td?"exit":"unknown":void 0,od=getStatusDisplay(Iu,nd,Zu),sd=formatToolName(lo),ad=Gu||getArgsSummary($u,Zu),vd=ju==="pending"||Iu==="inProgress"&&(Ru&&typeof Ru=="object"?Ru:void 0)?.pending_approval===!0;reactExports.useEffect(()=>{vd&&Xu(!0)},[vd]);const Sd=Mu||Ou?.code_error||void 0,_d=Lu||Ou?.execution_error||void 0,bd=Pu||Ou?.error||_d||void 0,Ad=Ou?.output??(typeof Ru=="string"?Ru:Ru!=null&&typeof Ru=="object"?Ru.output??Ru.stdout??Ru.stderr??void 0:void 0);return jsxRuntimeExports.jsxs(Box,{"data-tool-call":lo,"data-tool-call-status":Iu,width:"100%",border:"1px solid",borderColor:"border.default",borderRadius:Ju?"8px":"12px",overflow:"hidden",backgroundColor:"canvas.default",children:[jsxRuntimeExports.jsxs(Box,{as:"button",onClick:()=>Xu(!Yu),width:"100%",display:"flex",alignItems:"center",gap:Ju?1:2,padding:Ju?1:2,backgroundColor:"canvas.subtle",border:"none",borderBottom:Yu?"1px solid":"none",borderColor:"border.default",cursor:"pointer",textAlign:"left",hover:{backgroundColor:"neutral.muted"},children:[jsxRuntimeExports.jsx(Box,{color:"fg.muted",flexShrink:0,children:Yu?jsxRuntimeExports.jsx(ChevronDownIcon,{size:16}):jsxRuntimeExports.jsx(ChevronRightIcon,{size:16})}),hasMark(Vu)&&jsxRuntimeExports.jsx(Box,{color:"fg.muted",flexShrink:0,display:"flex",children:jsxRuntimeExports.jsx(SpecMark,{icon:Vu?.icon,emoji:Vu?.emoji,size:16})}),jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold",fontSize:Ju?0:1,color:"fg.default",flexShrink:0},children:sd}),jsxRuntimeExports.jsxs(Box,{display:"inline-flex",alignItems:"center",gap:1,px:2,py:"2px",borderRadius:2,backgroundColor:od.bgColor,flexShrink:0,children:[jsxRuntimeExports.jsx(Box,{color:od.color,display:"flex",children:od.icon}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,fontWeight:"medium",color:od.color},children:vd?Zu.awaitingApproval:od.label})]}),!Yu&&jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:ad})]}),Yu&&jsxRuntimeExports.jsxs(Box,{p:3,children:[jsxRuntimeExports.jsxs(Box,{mb:Ru!==void 0||Pu?3:0,children:[jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"fg.muted",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:Zu.parameters}),jsxRuntimeExports.jsx(Box,{backgroundColor:"canvas.inset",borderRadius:2,border:"1px solid",borderColor:"border.default",overflow:"auto",maxHeight:"200px",children:jsxRuntimeExports.jsx("pre",{style:{margin:0,padding:"12px",fontSize:"12px",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:Object.keys($u).length>0?JSON.stringify($u,null,2):`(${Zu.noParameters})`})})]}),(Iu==="complete"||Iu==="executing")&&Ru!==void 0&&jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"success.fg",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:Zu.result}),jsxRuntimeExports.jsx(Box,{backgroundColor:"success.subtle",borderRadius:2,border:"1px solid",borderColor:"success.muted",overflow:"auto",maxHeight:"300px",children:jsxRuntimeExports.jsx("pre",{style:{margin:0,padding:"12px",fontSize:"12px",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:typeof Ru=="string"?Ru:JSON.stringify(Ru,null,2)})})]}),Bu&&jsxRuntimeExports.jsx(Box,{mt:Iu==="complete"&&Ru!==void 0?3:0,children:ju==="approved"?jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{color:"success.fg",fontSize:1,display:"block"},children:Zu.approvedRunning}),Fu==="external"&&jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0,display:"block"},children:Zu.approvedElsewhere})]}):ju==="denied"?jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{color:"danger.fg",fontSize:1,display:"block"},children:Zu.deniedWontRun}),Fu==="external"&&jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0,display:"block"},children:Zu.decidedElsewhere})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"fg.default"},children:Zu.approvalNeeded}),jsxRuntimeExports.jsxs(Box,{mt:2,display:"flex",gap:2,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",onClick:zu,disabled:Hu||!zu,children:Zu.approve}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"danger",onClick:Uu,disabled:Hu||!Uu,children:Zu.deny})]})]})}),Iu==="error"&&_d&&jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsxs(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"danger.fg",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:[jsxRuntimeExports.jsx(AlertIcon,{size:12})," ",Zu.executionError]}),jsxRuntimeExports.jsxs(Box,{backgroundColor:"danger.subtle",borderRadius:2,border:"1px solid",borderColor:"danger.muted",p:2,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"danger.fg"},children:_d}),jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,color:"fg.muted",mt:1},children:Zu.executionErrorWhy})]})]}),Iu==="error"&&Sd&&jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsxs(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"severe.fg",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:[Zu.toolCodeError,": ",Sd.name]}),jsxRuntimeExports.jsxs(Box,{backgroundColor:"severe.subtle",borderRadius:2,border:"1px solid",borderColor:"severe.muted",overflow:"hidden",children:[jsxRuntimeExports.jsx(Box,{p:2,children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"severe.fg"},children:Sd.value})}),Sd.traceback&&jsxRuntimeExports.jsx(Box,{borderTop:"1px solid",borderColor:"severe.muted",backgroundColor:"canvas.inset",children:jsxRuntimeExports.jsx("pre",{style:{margin:0,padding:"8px 12px",fontSize:"11px",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',lineHeight:1.4,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:"200px",overflow:"auto"},children:Sd.traceback})})]})]}),Iu==="error"&&bd&&!_d&&!Sd&&!td&&jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"danger.fg",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:Zu.errorHeading}),jsxRuntimeExports.jsx(Box,{backgroundColor:"danger.subtle",borderRadius:2,border:"1px solid",borderColor:"danger.muted",p:2,children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"danger.fg"},children:bd})})]}),td&&!_d&&!Sd&&jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsxs(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"attention.fg",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:[jsxRuntimeExports.jsx(AlertIcon,{size:12})," ",Zu.processExited]}),jsxRuntimeExports.jsxs(Box,{backgroundColor:"attention.subtle",borderRadius:2,border:"1px solid",borderColor:"attention.muted",p:2,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"attention.fg"},children:Zu.exitedWithCode(String(ed))}),jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,color:"fg.muted",mt:1},children:Zu.nonZeroExit})]}),Ad&&jsxRuntimeExports.jsx(Box,{mt:2,backgroundColor:"canvas.inset",borderRadius:2,border:"1px solid",borderColor:"attention.muted",overflow:"auto",children:jsxRuntimeExports.jsx("pre",{style:{margin:0,padding:"10px 12px",fontSize:"12px",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',lineHeight:1.4,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:"200px"},children:Ad})})]}),jsxRuntimeExports.jsx(Box,{mt:3,pt:2,borderTop:"1px solid",borderColor:"border.muted",children:jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.subtle",fontFamily:"monospace"},children:["ID: ",Au]})})]})]})}function TypingDots({size:Au=8}){return jsxRuntimeExports.jsx(Box,{"aria-hidden":"true","data-typing-dots":"",display:"inline-flex",alignItems:"center",gap:"4px",children:[0,.2,.4].map((lo,$u)=>jsxRuntimeExports.jsx(Box,{width:Au,height:Au,borderRadius:"50%",bg:"fg.muted",animation:"typingPulse 1.4s ease-in-out infinite",animationDelay:`${lo}s`,reducedMotion:{animation:"none",opacity:.7},sx:{"@keyframes typingPulse":{"0%, 60%, 100%":{transform:"scale(0.6)",opacity:.4},"30%":{transform:"scale(1)",opacity:1}}}},$u))})}function TurnFooter({usage:Au,live:lo,latest:$u,padding:Ru,onCopy:Iu,onRemove:Pu}){const Ou=useChatWords(),[Mu,Du]=reactExports.useState(!1),Lu=reactExports.useRef(null);reactExports.useEffect(()=>()=>{Lu.current!==null&&window.clearTimeout(Lu.current)},[]);const Bu=Au?{contextTokens:Au.totalTokens,contextWindow:Au.contextWindow,inputTokens:Au.turnUsage?.inputTokens??0,outputTokens:Au.turnUsage?.outputTokens??0}:null,ju=reactExports.useRef(null),[Fu,zu]=reactExports.useState(null);reactExports.useEffect(()=>{(lo||$u)&&Bu?ju.current=Bu:!lo&&!$u&&!Fu&&ju.current&&zu(ju.current)});const Uu=lo||$u?Bu:Fu;if(!Uu&&lo)return null;const Hu=async()=>{await Iu(),Du(!0),Lu.current!==null&&window.clearTimeout(Lu.current),Lu.current=window.setTimeout(()=>Du(!1),1500)};return jsxRuntimeExports.jsxs(Box,{"data-turn-footer":"",display:"flex",alignItems:"center",gap:1,px:Ru,mt:-1,pb:1,minHeight:24,sx:{opacity:.55,transition:"opacity 0.15s ease","&:hover, &:focus-within":{opacity:1},"& [data-turn-actions]":{opacity:0,transition:"opacity 0.15s ease"},"&:hover [data-turn-actions], &:focus-within [data-turn-actions]":{opacity:1}},children:[Uu&&jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted",flexShrink:0},children:[jsxRuntimeExports.jsx(Text$3,{as:"span",sx:{fontWeight:"semibold",color:"fg.default",fontSize:0},children:formatTokenCount(Uu.contextTokens)})," / ",formatTokenCount(Uu.contextWindow)," ctx · turn ",formatTokenCount(Uu.inputTokens),jsxRuntimeExports.jsx(Text$3,{as:"span",sx:{color:"success.fg",fontSize:0},children:"▲"})," ",formatTokenCount(Uu.outputTokens),jsxRuntimeExports.jsx(Text$3,{as:"span",sx:{color:"attention.fg",fontSize:0},children:"▼"})]}),!lo&&jsxRuntimeExports.jsxs(Box,{"data-turn-actions":"",display:"flex",alignItems:"center",children:[jsxRuntimeExports.jsx(IconButton,{"data-turn-copy":"",icon:Mu?CheckIcon:CopyIcon,"aria-label":Ou.copyTurn,size:"small",variant:"invisible",onClick:()=>{Hu()}}),jsxRuntimeExports.jsx(IconButton,{"data-turn-remove":"",icon:TrashIcon,"aria-label":Ou.removeTurn,size:"small",variant:"invisible",onClick:Pu})]})]})}const FORM_SUBMISSION_LANGUAGE="a2ui-submission",FENCE=new RegExp("```"+FORM_SUBMISSION_LANGUAGE+"\\s*\\n([\\s\\S]*?)\\n```");function encodeFormSubmission(Au){const lo=JSON.stringify(Au,null,2);return`I just submitted "${Au.title}".
3888
+ ${Pu}\`\`\``}),lo}const ChatCodeBlock=defineContributionPoint("chat.codeBlock"),LANGUAGE=/(?:^|\s)language-([^\s]+)/;function textOf(Au){return typeof Au=="string"||typeof Au=="number"?String(Au):Array.isArray(Au)?Au.map(textOf).join(""):reactExports.isValidElement(Au)?textOf(Au.props.children):""}function codeBlockOf(Au){const lo=Array.isArray(Au)?Au.filter(Iu=>Iu!==null&&Iu!==`
3889
+ `):[Au];if(lo.length!==1||!reactExports.isValidElement(lo[0]))return null;const $u=lo[0].props,Ru=LANGUAGE.exec($u.className??"")?.[1]?.toLowerCase();return Ru===void 0?null:{language:Ru,code:textOf($u.children)}}function codeBlockRenderer(Au,lo){return Au.map($u=>$u.value).find($u=>$u.languages.includes(lo.language)&&($u.match?$u.match(lo):!0))}const NO_SUBSCRIPTION$1=()=>()=>{};function ChatCodePre({children:Au}){const lo=useOptionalReactorPlatform();reactExports.useSyncExternalStore(lo?.subscribe??NO_SUBSCRIPTION$1,()=>lo?.getRevision()??0);const $u=lo?codeBlockOf(Au):null,Ru=$u?codeBlockRenderer(lo.getContributions(ChatCodeBlock),$u):void 0;if($u&&Ru){const{Component:Iu}=Ru;return jsxRuntimeExports.jsx("div",{"data-chat-code-block":Ru.id,children:jsxRuntimeExports.jsx(Iu,{language:$u.language,code:$u.code})})}return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Au})}const COMPONENTS={pre:ChatCodePre};function ChatMarkdown({text:Au,density:lo="comfortable"}){return jsxRuntimeExports.jsx(Box,{"data-chat-markdown":"",sx:{...streamdownMarkdownStyles,...lo==="compact"?{lineHeight:1.4,"& p":{marginTop:0,marginBottom:"0.4em"},"& p:last-child":{marginBottom:0}}:{}},children:jsxRuntimeExports.jsx(_o$1,{rehypePlugins:REHYPE_PLUGINS_WITHOUT_HTML,components:COMPONENTS,children:normalizeAssistantMarkdown(Au)})})}const ICON_PACKAGES=["@datalayer/icons-react","@primer/octicons-react"],ICON_REF=/^(@datalayer\/icons-react|@primer\/octicons-react):([a-z0-9]+(?:-[a-z0-9]+)*)$/;function exportNameOf(Au){return Au.split("-").map(lo=>lo.charAt(0).toUpperCase()+lo.slice(1)).join("")+"Icon"}function parseIconRef(Au){const lo=ICON_REF.exec(Au);if(!lo)throw new Error(`The icon ${JSON.stringify(Au)} is not <package>:<name>, the package one of ${ICON_PACKAGES.join(", ")} and the name in kebab case`);const[,$u,Ru]=lo;return{pkg:$u,name:Ru,exportName:exportNameOf(Ru)}}const LOADERS={"@datalayer/icons-react":()=>__vitePreload(()=>import("./chunks/index.esm-086pkdGE.js"),[],import.meta.url),"@primer/octicons-react":()=>__vitePreload(()=>import("./chunks/index.esm-f0zNr1S2.js"),[],import.meta.url)},loaded=new Map,loading=new Map;function loadIconPackage(Au){const lo=loading.get(Au)??LOADERS[Au]().then($u=>(loaded.set(Au,$u),$u));return loading.set(Au,lo),lo}function iconOf(Au,lo){const $u=lo[Au.exportName];if(!$u)throw new Error(`${Au.pkg} has no icon ${Au.name} (${Au.exportName}): name one it has`);return $u}function useMarkIcon(Au){const lo=Au?parseIconRef(Au):void 0,$u=lo?.pkg,Ru=$u?loaded.get($u):void 0,[,Iu]=reactExports.useState(0),[Pu,Ou]=reactExports.useState(null);if(reactExports.useEffect(()=>{if(!$u||Ru)return;let Mu=!0;return loadIconPackage($u).then(()=>Mu&&Iu(Du=>Du+1),Du=>Mu&&Ou(Du)),()=>{Mu=!1}},[$u,Ru]),Pu)throw Pu;return lo&&Ru?iconOf(lo,Ru):void 0}function SpecMark({icon:Au,emoji:lo,size:$u=16}){const Ru=useMarkIcon(Au);return Au?Ru?jsxRuntimeExports.jsx("span",{"data-mark":Au,style:{display:"inline-flex",flexShrink:0,lineHeight:0},children:jsxRuntimeExports.jsx(Ru,{size:$u,"aria-hidden":"true",...Au.startsWith("@datalayer/icons-react:")?{colored:!0}:{}})}):jsxRuntimeExports.jsx("span",{"data-mark":Au,"aria-hidden":"true",style:{display:"inline-block",width:$u,height:$u}}):lo?jsxRuntimeExports.jsx("span",{"data-mark":"emoji","aria-hidden":"true",style:{display:"inline-flex",flexShrink:0,fontSize:Math.round($u*.9),lineHeight:1},children:lo}):null}function hasMark(Au){return!!(Au?.icon||Au?.emoji)}const SKILL_TOOLS=new Set(["run_skill_script","load_skill","read_skill_resource"]);function marksOf(Au){return{icon:Au?.icon,emoji:Au?.emoji}}function skillIdOfCall(Au,lo){if(!SKILL_TOOLS.has(Au))return null;const $u=lo?.skill_name??lo?.skill??lo?.name;return typeof $u!="string"||$u.length===0?null:$u.split(":",1)[0]||$u}let frontendIndex=null,runtimeIndex=null;function frontendTools(){if(!frontendIndex){frontendIndex=new Map;for(const Au of Object.values(FRONTEND_TOOL_CATALOG))for(const lo of Au.toolset??[])frontendIndex.has(lo)||frontendIndex.set(lo,{id:Au.id,...marksOf(Au)})}return frontendIndex}function runtimeTools(){if(!runtimeIndex){runtimeIndex=new Map;for(const Au of Object.values(BACKEND_TOOL_CATALOG)){const lo=Au.runtime?.method;lo&&!runtimeIndex.has(lo)&&runtimeIndex.set(lo,{id:Au.id,...marksOf(Au)})}}return runtimeIndex}function marksOfMcpServer(Au){return Au.icon||Au.emoji?marksOf(Au):marksOf(MCP_SERVER_LIBRARY[Au.id])}function marksOfSkill(Au){return marksOf(SKILLS_CATALOG[Au.split(":",1)[0]||Au])}function marksOfFrontendTool(Au){return marksOf(frontendTools().get(Au))}function marksOfRuntimeTool(Au){return marksOf(runtimeTools().get(Au))}function marksOfToolCall(Au,lo,$u=[]){const Ru=skillIdOfCall(Au,lo);if(Ru)return{kind:"skill",ownerId:Ru,...marksOfSkill(Ru)};const Iu=$u.find(Mu=>Mu.tools.some(Du=>Du.name===Au));if(Iu)return{kind:"mcp",ownerId:Iu.id,...marksOfMcpServer(Iu)};const Pu=frontendTools().get(Au);if(Pu)return{kind:"frontend",ownerId:Pu.id,...marksOf(Pu)};const Ou=runtimeTools().get(Au);return Ou?{kind:"runtime",ownerId:Ou.id,...marksOf(Ou)}:null}function getStatusDisplay(Au,lo,$u){switch(Au){case"inProgress":return{icon:jsxRuntimeExports.jsx(ClockIcon,{size:14}),color:"attention.fg",label:$u.toolPreparing,bgColor:"attention.subtle"};case"executing":return{icon:jsxRuntimeExports.jsx(ClockIcon,{size:14}),color:"attention.fg",label:$u.toolExecuting,bgColor:"attention.subtle"};case"complete":return{icon:jsxRuntimeExports.jsx(CheckCircleIcon,{size:14}),color:"success.fg",label:$u.toolComplete,bgColor:"success.subtle"};case"error":return lo==="execution"?{icon:jsxRuntimeExports.jsx(AlertIcon,{size:14}),color:"danger.fg",label:$u.toolExecutionFailed,bgColor:"danger.subtle"}:lo==="code"?{icon:jsxRuntimeExports.jsx(XCircleIcon,{size:14}),color:"severe.fg",label:$u.toolCodeError,bgColor:"severe.subtle"}:lo==="exit"?{icon:jsxRuntimeExports.jsx(AlertIcon,{size:14}),color:"attention.fg",label:$u.toolExited,bgColor:"attention.subtle"}:{icon:jsxRuntimeExports.jsx(XCircleIcon,{size:14}),color:"danger.fg",label:$u.toolFailed,bgColor:"danger.subtle"};default:return{icon:jsxRuntimeExports.jsx(ToolsIcon,{size:14}),color:"fg.muted",label:Au,bgColor:"neutral.subtle"}}}function formatToolName(Au){return Au.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").split(" ").map(lo=>lo.charAt(0).toUpperCase()+lo.slice(1).toLowerCase()).join(" ")}function getArgsSummary(Au,lo){const $u=Object.entries(Au);if($u.length===0)return lo.noParameters;const Ru=$u.slice(0,2).map(([Iu,Pu])=>{const Ou=typeof Pu=="string"?Pu.slice(0,30)+(Pu.length>30?"...":""):typeof Pu=="object"?JSON.stringify(Pu).slice(0,30)+"...":String(Pu);return`${Iu}: ${Ou}`}).join(", ");return $u.length>2?`${Ru} ${lo.moreArguments($u.length-2)}`:Ru}function ToolCallDisplay({toolCallId:Au,toolName:lo,args:$u,result:Ru,status:Iu,error:Pu,executionResult:Ou,codeError:Mu,exitCode:Du,executionError:Lu,approvalRequired:Bu=!1,approvalState:ju,approvalDecisionSource:Fu,onApprove:zu,onDeny:Uu,approvalLoading:Hu=!1,marks:Vu,summary:Gu,density:Wu="comfortable"}){const Zu=useChatWords(),Ju=Wu==="compact",[Yu,Xu]=reactExports.useState(!1),ed=Du??Ou?.exit_code,td=ed!=null&&ed!==0,nd=Iu==="error"?Lu||Ou?.execution_error?"execution":Mu||Ou?.code_error?"code":td?"exit":"unknown":void 0,od=getStatusDisplay(Iu,nd,Zu),sd=formatToolName(lo),ad=Gu||getArgsSummary($u,Zu),vd=ju==="pending"||Iu==="inProgress"&&(Ru&&typeof Ru=="object"?Ru:void 0)?.pending_approval===!0;reactExports.useEffect(()=>{vd&&Xu(!0)},[vd]);const Sd=Mu||Ou?.code_error||void 0,_d=Lu||Ou?.execution_error||void 0,bd=Pu||Ou?.error||_d||void 0,Ad=Ou?.output??(typeof Ru=="string"?Ru:Ru!=null&&typeof Ru=="object"?Ru.output??Ru.stdout??Ru.stderr??void 0:void 0);return jsxRuntimeExports.jsxs(Box,{"data-tool-call":lo,"data-tool-call-status":Iu,width:"100%",border:"1px solid",borderColor:"border.default",borderRadius:Ju?"8px":"12px",overflow:"hidden",backgroundColor:"canvas.default",children:[jsxRuntimeExports.jsxs(Box,{as:"button",onClick:()=>Xu(!Yu),width:"100%",display:"flex",alignItems:"center",gap:Ju?1:2,padding:Ju?1:2,backgroundColor:"canvas.subtle",border:"none",borderBottom:Yu?"1px solid":"none",borderColor:"border.default",cursor:"pointer",textAlign:"left",hover:{backgroundColor:"neutral.muted"},children:[jsxRuntimeExports.jsx(Box,{color:"fg.muted",flexShrink:0,children:Yu?jsxRuntimeExports.jsx(ChevronDownIcon,{size:16}):jsxRuntimeExports.jsx(ChevronRightIcon,{size:16})}),hasMark(Vu)&&jsxRuntimeExports.jsx(Box,{color:"fg.muted",flexShrink:0,display:"flex",children:jsxRuntimeExports.jsx(SpecMark,{icon:Vu?.icon,emoji:Vu?.emoji,size:16})}),jsxRuntimeExports.jsx(Text$3,{sx:{fontWeight:"semibold",fontSize:Ju?0:1,color:"fg.default",flexShrink:0},children:sd}),jsxRuntimeExports.jsxs(Box,{display:"inline-flex",alignItems:"center",gap:1,px:2,py:"2px",borderRadius:2,backgroundColor:od.bgColor,flexShrink:0,children:[jsxRuntimeExports.jsx(Box,{color:od.color,display:"flex",children:od.icon}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,fontWeight:"medium",color:od.color},children:vd?Zu.awaitingApproval:od.label})]}),!Yu&&jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:ad})]}),Yu&&jsxRuntimeExports.jsxs(Box,{p:3,children:[jsxRuntimeExports.jsxs(Box,{mb:Ru!==void 0||Pu?3:0,children:[jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"fg.muted",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:Zu.parameters}),jsxRuntimeExports.jsx(Box,{backgroundColor:"canvas.inset",borderRadius:2,border:"1px solid",borderColor:"border.default",overflow:"auto",maxHeight:"200px",children:jsxRuntimeExports.jsx("pre",{style:{margin:0,padding:"12px",fontSize:"12px",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:Object.keys($u).length>0?JSON.stringify($u,null,2):`(${Zu.noParameters})`})})]}),(Iu==="complete"||Iu==="executing")&&Ru!==void 0&&jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"success.fg",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:Zu.result}),jsxRuntimeExports.jsx(Box,{backgroundColor:"success.subtle",borderRadius:2,border:"1px solid",borderColor:"success.muted",overflow:"auto",maxHeight:"300px",children:jsxRuntimeExports.jsx("pre",{style:{margin:0,padding:"12px",fontSize:"12px",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:typeof Ru=="string"?Ru:JSON.stringify(Ru,null,2)})})]}),Bu&&jsxRuntimeExports.jsx(Box,{mt:Iu==="complete"&&Ru!==void 0?3:0,children:ju==="approved"?jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{color:"success.fg",fontSize:1,display:"block"},children:Zu.approvedRunning}),Fu==="external"&&jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0,display:"block"},children:Zu.approvedElsewhere})]}):ju==="denied"?jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{color:"danger.fg",fontSize:1,display:"block"},children:Zu.deniedWontRun}),Fu==="external"&&jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0,display:"block"},children:Zu.decidedElsewhere})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"fg.default"},children:Zu.approvalNeeded}),jsxRuntimeExports.jsxs(Box,{mt:2,display:"flex",gap:2,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",onClick:zu,disabled:Hu||!zu,children:Zu.approve}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"danger",onClick:Uu,disabled:Hu||!Uu,children:Zu.deny})]})]})}),Iu==="error"&&_d&&jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsxs(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"danger.fg",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:[jsxRuntimeExports.jsx(AlertIcon,{size:12})," ",Zu.executionError]}),jsxRuntimeExports.jsxs(Box,{backgroundColor:"danger.subtle",borderRadius:2,border:"1px solid",borderColor:"danger.muted",p:2,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"danger.fg"},children:_d}),jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,color:"fg.muted",mt:1},children:Zu.executionErrorWhy})]})]}),Iu==="error"&&Sd&&jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsxs(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"severe.fg",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:[Zu.toolCodeError,": ",Sd.name]}),jsxRuntimeExports.jsxs(Box,{backgroundColor:"severe.subtle",borderRadius:2,border:"1px solid",borderColor:"severe.muted",overflow:"hidden",children:[jsxRuntimeExports.jsx(Box,{p:2,children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"severe.fg"},children:Sd.value})}),Sd.traceback&&jsxRuntimeExports.jsx(Box,{borderTop:"1px solid",borderColor:"severe.muted",backgroundColor:"canvas.inset",children:jsxRuntimeExports.jsx("pre",{style:{margin:0,padding:"8px 12px",fontSize:"11px",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',lineHeight:1.4,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:"200px",overflow:"auto"},children:Sd.traceback})})]})]}),Iu==="error"&&bd&&!_d&&!Sd&&!td&&jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"danger.fg",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:Zu.errorHeading}),jsxRuntimeExports.jsx(Box,{backgroundColor:"danger.subtle",borderRadius:2,border:"1px solid",borderColor:"danger.muted",p:2,children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"danger.fg"},children:bd})})]}),td&&!_d&&!Sd&&jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsxs(Text$3,{sx:{display:"block",fontSize:0,fontWeight:"semibold",color:"attention.fg",textTransform:"uppercase",letterSpacing:"0.05em",mb:2},children:[jsxRuntimeExports.jsx(AlertIcon,{size:12})," ",Zu.processExited]}),jsxRuntimeExports.jsxs(Box,{backgroundColor:"attention.subtle",borderRadius:2,border:"1px solid",borderColor:"attention.muted",p:2,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,color:"attention.fg"},children:Zu.exitedWithCode(String(ed))}),jsxRuntimeExports.jsx(Text$3,{sx:{display:"block",fontSize:0,color:"fg.muted",mt:1},children:Zu.nonZeroExit})]}),Ad&&jsxRuntimeExports.jsx(Box,{mt:2,backgroundColor:"canvas.inset",borderRadius:2,border:"1px solid",borderColor:"attention.muted",overflow:"auto",children:jsxRuntimeExports.jsx("pre",{style:{margin:0,padding:"10px 12px",fontSize:"12px",fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',lineHeight:1.4,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:"200px"},children:Ad})})]}),jsxRuntimeExports.jsx(Box,{mt:3,pt:2,borderTop:"1px solid",borderColor:"border.muted",children:jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.subtle",fontFamily:"monospace"},children:["ID: ",Au]})})]})]})}function TypingDots({size:Au=8}){return jsxRuntimeExports.jsx(Box,{"aria-hidden":"true","data-typing-dots":"",display:"inline-flex",alignItems:"center",gap:"4px",children:[0,.2,.4].map((lo,$u)=>jsxRuntimeExports.jsx(Box,{width:Au,height:Au,borderRadius:"50%",bg:"fg.muted",animation:"typingPulse 1.4s ease-in-out infinite",animationDelay:`${lo}s`,reducedMotion:{animation:"none",opacity:.7},sx:{"@keyframes typingPulse":{"0%, 60%, 100%":{transform:"scale(0.6)",opacity:.4},"30%":{transform:"scale(1)",opacity:1}}}},$u))})}function TurnFooter({usage:Au,live:lo,latest:$u,padding:Ru,onCopy:Iu,onRemove:Pu}){const Ou=useChatWords(),[Mu,Du]=reactExports.useState(!1),Lu=reactExports.useRef(null);reactExports.useEffect(()=>()=>{Lu.current!==null&&window.clearTimeout(Lu.current)},[]);const Bu=Au?{contextTokens:Au.totalTokens,contextWindow:Au.contextWindow,inputTokens:Au.turnUsage?.inputTokens??0,outputTokens:Au.turnUsage?.outputTokens??0}:null,ju=reactExports.useRef(null),[Fu,zu]=reactExports.useState(null);reactExports.useEffect(()=>{(lo||$u)&&Bu?ju.current=Bu:!lo&&!$u&&!Fu&&ju.current&&zu(ju.current)});const Uu=lo||$u?Bu:Fu;if(!Uu&&lo)return null;const Hu=async()=>{await Iu(),Du(!0),Lu.current!==null&&window.clearTimeout(Lu.current),Lu.current=window.setTimeout(()=>Du(!1),1500)};return jsxRuntimeExports.jsxs(Box,{"data-turn-footer":"",display:"flex",alignItems:"center",gap:1,px:Ru,mt:-1,pb:1,minHeight:24,sx:{opacity:.55,transition:"opacity 0.15s ease","&:hover, &:focus-within":{opacity:1},"& [data-turn-actions]":{opacity:0,transition:"opacity 0.15s ease"},"&:hover [data-turn-actions], &:focus-within [data-turn-actions]":{opacity:1}},children:[Uu&&jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted",flexShrink:0},children:[jsxRuntimeExports.jsx(Text$3,{as:"span",sx:{fontWeight:"semibold",color:"fg.default",fontSize:0},children:formatTokenCount(Uu.contextTokens)})," / ",formatTokenCount(Uu.contextWindow)," ctx · turn ",formatTokenCount(Uu.inputTokens),jsxRuntimeExports.jsx(Text$3,{as:"span",sx:{color:"success.fg",fontSize:0},children:"▲"})," ",formatTokenCount(Uu.outputTokens),jsxRuntimeExports.jsx(Text$3,{as:"span",sx:{color:"attention.fg",fontSize:0},children:"▼"})]}),!lo&&jsxRuntimeExports.jsxs(Box,{"data-turn-actions":"",display:"flex",alignItems:"center",children:[jsxRuntimeExports.jsx(IconButton,{"data-turn-copy":"",icon:Mu?CheckIcon:CopyIcon,"aria-label":Ou.copyTurn,size:"small",variant:"invisible",onClick:()=>{Hu()}}),jsxRuntimeExports.jsx(IconButton,{"data-turn-remove":"",icon:TrashIcon,"aria-label":Ou.removeTurn,size:"small",variant:"invisible",onClick:Pu})]})]})}const FORM_SUBMISSION_LANGUAGE="a2ui-submission",FENCE=new RegExp("```"+FORM_SUBMISSION_LANGUAGE+"\\s*\\n([\\s\\S]*?)\\n```");function encodeFormSubmission(Au){const lo=JSON.stringify(Au,null,2);return`I just submitted "${Au.title}".
3877
3890
 
3878
3891
  \`\`\``+FORM_SUBMISSION_LANGUAGE+`
3879
3892
  `+lo+"\n```\n\nPlease confirm you received it and briefly say what happens next."}function parseFormSubmission(Au){const lo=FENCE.exec(Au);if(!lo)return null;try{const $u=JSON.parse(lo[1]);return!$u||typeof $u!="object"||typeof $u.title!="string"||!$u.values||typeof $u.values!="object"?null:{title:$u.title,...$u.surfaceId?{surfaceId:String($u.surfaceId)}:{},values:$u.values}}catch{return null}}function labelOfFieldId(Au){const lo=Au.replace(/[-_]+/g," ").trim();return lo?lo[0].toUpperCase()+lo.slice(1):Au}function displayValue(Au){return Au==null?"—":typeof Au=="string"?Au.trim()===""?"—":Au:Array.isArray(Au)?Au.length===0?"—":Au.map(displayValue).join(", "):typeof Au=="boolean"?Au?"Yes":"No":typeof Au=="number"?String(Au):JSON.stringify(Au)}function FormSubmissionMessage({submission:Au}){const[lo,$u]=reactExports.useState(!0),Ru=Object.entries(Au.values),Iu=Ru.length;return jsxRuntimeExports.jsxs(Box,{width:"100%",minWidth:280,border:"1px solid",borderColor:"border.default",borderRadius:"12px",overflow:"hidden",backgroundColor:"canvas.default",color:"fg.default",children:[jsxRuntimeExports.jsxs(Box,{as:"button",type:"button","aria-expanded":lo,onClick:()=>$u(Pu=>!Pu),width:"100%",display:"flex",alignItems:"center",gap:2,padding:2,backgroundColor:"canvas.subtle",border:"none",borderBottom:lo?"1px solid":"none",borderColor:"border.default",cursor:"pointer",textAlign:"left",color:"fg.default",hover:{backgroundColor:"neutral.muted"},children:[jsxRuntimeExports.jsx(Box,{color:"fg.muted",flexShrink:0,children:lo?jsxRuntimeExports.jsx(ChevronDownIcon,{size:16}):jsxRuntimeExports.jsx(ChevronRightIcon,{size:16})}),jsxRuntimeExports.jsx(Box,{color:"fg.muted",flexShrink:0,children:jsxRuntimeExports.jsx(ChecklistIcon,{size:16})}),jsxRuntimeExports.jsxs(Text$3,{sx:{fontWeight:"semibold",fontSize:1},children:["Submitted ",Au.title]}),jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted",ml:"auto"},children:[Iu," field",Iu===1?"":"s"]})]}),lo?jsxRuntimeExports.jsx(Box,{as:"table",width:"100%",borderCollapse:"collapse",children:jsxRuntimeExports.jsx(Box,{as:"tbody",children:Ru.map(([Pu,Ou])=>jsxRuntimeExports.jsxs(Box,{as:"tr",sx:{"& + tr td":{borderTop:"1px solid",borderColor:"border.muted"}},children:[jsxRuntimeExports.jsx(Box,{as:"td",px:3,py:1,fontSize:0,color:"fg.muted",whiteSpace:"nowrap",verticalAlign:"top",width:"40%",children:labelOfFieldId(Pu)}),jsxRuntimeExports.jsx(Box,{as:"td",px:3,py:1,fontSize:1,wordBreak:"break-word",children:displayValue(Ou)})]},Pu))})}):null]})}function a2aAgentDetails(Au,lo){if(!Au.some(Ru=>Ru.transport==="a2a"))return null;const $u={name:Au[0]?.subagentName??lo??"agent"};for(const Ru of Au)Ru.url&&($u.url=Ru.url),Ru.launch&&Ru.launch!=="auto"&&($u.launch=Ru.launch),Ru.phase==="status"&&Ru.state&&($u.state=Ru.state),Ru.taskId&&($u.taskId=Ru.taskId),Ru.runtimeUid&&($u.runtimeUid=Ru.runtimeUid),Ru.agentCard&&($u.card=Ru.agentCard);return $u}function agentCardUrl(Au){return`${Au.replace(/\/+$/,"")}/.well-known/agent-card.json`}function useAgentCard(Au){const[lo,$u]=reactExports.useState({status:Au?"loading":"idle"});return reactExports.useEffect(()=>{if(!Au){$u({status:"idle"});return}const Ru=new AbortController;return $u({status:"loading"}),fetch(agentCardUrl(Au),{signal:Ru.signal,headers:{Accept:"application/json"}}).then(async Iu=>{if(!Iu.ok)throw new Error(`${Iu.status} ${Iu.statusText}`.trim());const Pu=await Iu.json();if(!Pu||typeof Pu!="object"||Array.isArray(Pu))throw new Error("The agent card is not a JSON object");$u({status:"loaded",card:Pu})}).catch(Iu=>{Ru.signal.aborted||$u({status:"error",error:Iu instanceof Error?Iu.message:String(Iu)})}),()=>Ru.abort()},[Au]),lo}const record=Au=>Au&&typeof Au=="object"&&!Array.isArray(Au)?Au:void 0,items=Au=>Array.isArray(Au)?Au.map(record).filter(lo=>!!lo):[],text$4=Au=>typeof Au=="string"&&Au?Au:void 0,strings=Au=>Array.isArray(Au)?Au.filter(lo=>typeof lo=="string"):[];function Section({title:Au,children:lo}){return jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",gap:2,children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:1,m:0},children:Au}),lo]})}function Row$1({label:Au,children:lo}){return jsxRuntimeExports.jsxs(Box,{display:"grid",gridTemplateColumns:"112px 1fr",gap:2,alignItems:"baseline",fontSize:0,children:[jsxRuntimeExports.jsx(Text$3,{sx:{color:"fg.muted",fontSize:0},children:Au}),jsxRuntimeExports.jsx(Box,{minWidth:0,wordBreak:"break-all",children:lo})]})}function External({href:Au,children:lo}){return jsxRuntimeExports.jsxs(Link$1,{href:Au,target:"_blank",rel:"noreferrer",sx:{fontSize:0,fontFamily:"mono",display:"inline-flex",alignItems:"center",gap:1},children:[lo??Au,jsxRuntimeExports.jsx(LinkExternalIcon,{size:12})]})}function Mono({children:Au}){return jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,fontFamily:"mono"},children:Au})}function humanize(Au){const lo=Au.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").toLowerCase();return lo.charAt(0).toUpperCase()+lo.slice(1)}const isUrl=Au=>/^https?:\/\//.test(Au),None=({word:Au="none"})=>jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:Au});function ValueView({value:Au,depth:lo=0}){if(Au==null)return jsxRuntimeExports.jsx(None,{word:"—"});if(typeof Au=="boolean")return jsxRuntimeExports.jsx(Label,{size:"small",variant:Au?"success":"secondary",children:Au?"yes":"no"});if(typeof Au=="number")return jsxRuntimeExports.jsx(Mono,{children:String(Au)});if(typeof Au=="string")return isUrl(Au)?jsxRuntimeExports.jsx(External,{href:Au}):jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:Au});if(lo>=3)return jsxRuntimeExports.jsx(Mono,{children:JSON.stringify(Au)});if(Array.isArray(Au))return Au.length===0?jsxRuntimeExports.jsx(None,{}):Au.every(Ru=>typeof Ru!="object"||Ru===null)?jsxRuntimeExports.jsx(Box,{display:"flex",gap:2,flexWrap:"wrap",children:Au.map((Ru,Iu)=>jsxRuntimeExports.jsx(ValueView,{value:Ru,depth:lo+1},Iu))}):jsxRuntimeExports.jsx(Box,{display:"flex",flexDirection:"column",gap:2,children:Au.map((Ru,Iu)=>jsxRuntimeExports.jsx(Box,{pl:2,borderLeft:"2px solid",borderColor:"border.muted",children:jsxRuntimeExports.jsx(ValueView,{value:Ru,depth:lo+1})},Iu))});const $u=Object.entries(Au);return $u.length===0?jsxRuntimeExports.jsx(None,{word:"empty"}):jsxRuntimeExports.jsx(Box,{display:"grid",gridTemplateColumns:"max-content 1fr",columnGap:2,rowGap:1,alignItems:"baseline",children:$u.map(([Ru,Iu])=>jsxRuntimeExports.jsxs(vM.Fragment,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:humanize(Ru)}),jsxRuntimeExports.jsx(Box,{minWidth:0,wordBreak:"break-all",children:jsxRuntimeExports.jsx(ValueView,{value:Iu,depth:lo+1})})]},Ru))})}const HANDLED_KEYS=new Set(["name","description","version","protocolVersion","url","documentationUrl","iconUrl","provider","supportedInterfaces","capabilities","skills","defaultInputModes","defaultOutputModes"]);function CardFields({card:Au}){const lo=record(Au.provider),$u=record(Au.capabilities),Ru=Object.entries($u??{}),Iu=items($u?.extensions),Pu=items(Au.supportedInterfaces),Ou=items(Au.skills),Mu=strings(Au.defaultInputModes),Du=strings(Au.defaultOutputModes),Lu=Object.entries(Au).filter(([Bu])=>!HANDLED_KEYS.has(Bu));return jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",gap:2,children:[jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:1,fontWeight:"bold"},children:text$4(Au.name)??"Unnamed agent"}),text$4(Au.version)?jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted",ml:2},children:["v",text$4(Au.version)]}):null,text$4(Au.protocolVersion)?jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted",ml:2},children:["A2A ",text$4(Au.protocolVersion)]}):null,text$4(Au.description)?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",mt:1,mb:0},children:text$4(Au.description)}):null]}),text$4(Au.url)?jsxRuntimeExports.jsx(Row$1,{label:"Endpoint",children:jsxRuntimeExports.jsx(External,{href:text$4(Au.url)})}):null,text$4(Au.documentationUrl)?jsxRuntimeExports.jsx(Row$1,{label:"Documentation",children:jsxRuntimeExports.jsx(External,{href:text$4(Au.documentationUrl)})}):null,text$4(Au.iconUrl)?jsxRuntimeExports.jsx(Row$1,{label:"Icon",children:jsxRuntimeExports.jsx(External,{href:text$4(Au.iconUrl)})}):null,lo?jsxRuntimeExports.jsx(Row$1,{label:"Provider",children:jsxRuntimeExports.jsx(ValueView,{value:lo,depth:1})}):null,Au.supportedInterfaces!==void 0?jsxRuntimeExports.jsx(Row$1,{label:"Interfaces",children:Pu.length===0?jsxRuntimeExports.jsx(None,{}):jsxRuntimeExports.jsx(Box,{display:"flex",flexDirection:"column",gap:1,children:Pu.map((Bu,ju)=>jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,alignItems:"center",flexWrap:"wrap",children:[jsxRuntimeExports.jsx(Label,{size:"small",children:text$4(Bu.protocolBinding)??"binding"}),text$4(Bu.url)?jsxRuntimeExports.jsx(Mono,{children:text$4(Bu.url)}):null,text$4(Bu.protocolVersion)?jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:["v",text$4(Bu.protocolVersion)]}):null]},ju))})}):null,$u!==void 0?jsxRuntimeExports.jsx(Row$1,{label:"Capabilities",children:Ru.length===0?jsxRuntimeExports.jsx(None,{}):jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",gap:1,children:[jsxRuntimeExports.jsx(Box,{display:"flex",gap:1,flexWrap:"wrap",children:Ru.filter(([,Bu])=>typeof Bu=="boolean").map(([Bu,ju])=>jsxRuntimeExports.jsxs(Label,{size:"small",variant:ju?"success":"secondary",children:[Bu,": ",ju?"yes":"no"]},Bu))}),Iu.map((Bu,ju)=>jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,alignItems:"baseline",flexWrap:"wrap",children:[jsxRuntimeExports.jsx(Mono,{children:text$4(Bu.uri)??"extension"}),Bu.required===!0?jsxRuntimeExports.jsx(Label,{size:"small",variant:"attention",children:"required"}):null,text$4(Bu.description)?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:text$4(Bu.description)}):null]},ju)),Ru.filter(([Bu,ju])=>typeof ju!="boolean"&&Bu!=="extensions").map(([Bu,ju])=>jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:humanize(Bu)}),jsxRuntimeExports.jsx(ValueView,{value:ju,depth:1})]},Bu))]})}):null,Au.skills!==void 0?jsxRuntimeExports.jsx(Row$1,{label:"Skills",children:Ou.length===0?jsxRuntimeExports.jsx(None,{}):jsxRuntimeExports.jsx(Box,{display:"flex",flexDirection:"column",gap:1,children:Ou.map((Bu,ju)=>jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,fontWeight:"bold"},children:text$4(Bu.name)??text$4(Bu.id)??"skill"}),text$4(Bu.description)?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted",ml:2},children:text$4(Bu.description)}):null,strings(Bu.tags).length>0?jsxRuntimeExports.jsx(Box,{display:"inline-flex",gap:1,ml:2,children:strings(Bu.tags).map(Fu=>jsxRuntimeExports.jsx(Label,{size:"small",children:Fu},Fu))}):null]},ju))})}):null,Au.defaultInputModes!==void 0?jsxRuntimeExports.jsx(Row$1,{label:"Input modes",children:Mu.length?jsxRuntimeExports.jsx(Mono,{children:Mu.join(", ")}):jsxRuntimeExports.jsx(None,{})}):null,Au.defaultOutputModes!==void 0?jsxRuntimeExports.jsx(Row$1,{label:"Output modes",children:Du.length?jsxRuntimeExports.jsx(Mono,{children:Du.join(", ")}):jsxRuntimeExports.jsx(None,{})}):null,Lu.map(([Bu,ju])=>jsxRuntimeExports.jsx(Row$1,{label:humanize(Bu),children:jsxRuntimeExports.jsx(ValueView,{value:ju})},Bu))]})}const LAUNCH_LABEL={local:"launched on the local agent-runtimes server",cloud:"launched on a Datalayer runtime",remote:"reached at a URL the spec named",auto:"launch not decided yet"};function A2AAgentDialog({details:Au,onClose:lo}){const $u=useAgentCard(Au.url),Ru=Au.url?agentCardUrl(Au.url):void 0,Iu=()=>{Ru&&window.open(Ru,"_blank","noopener,noreferrer")};return jsxRuntimeExports.jsx(Dialog$1,{onClose:lo,title:`A2A agent · ${Au.name}`,subtitle:"A separate agent, reached over the A2A protocol",width:"large",footerButtons:[...Ru?[{content:"Open agent card",onClick:Iu}]:[],{content:"Close",onClick:lo,buttonType:"primary"}],children:jsxRuntimeExports.jsxs(Box,{"data-a2a-agent-dialog":Au.name,"data-a2a-card-status":$u.status,display:"flex",flexDirection:"column",gap:3,children:[jsxRuntimeExports.jsxs(Section,{title:"This run",children:[Au.description?jsxRuntimeExports.jsx(Text$3,{as:"p",sx:{fontSize:0,color:"fg.muted",m:0},children:Au.description}):null,jsxRuntimeExports.jsx(Row$1,{label:"Launch",children:jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0},children:[Au.launch??"auto",jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:[" ","— ",LAUNCH_LABEL[Au.launch??"auto"]??""]})]})}),Au.ref?jsxRuntimeExports.jsx(Row$1,{label:"Agentspec",children:jsxRuntimeExports.jsx(Mono,{children:Au.ref})}):null,jsxRuntimeExports.jsx(Row$1,{label:"State",children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:Au.state??"unknown"})}),Au.taskId?jsxRuntimeExports.jsx(Row$1,{label:"Task",children:jsxRuntimeExports.jsx(Mono,{children:Au.taskId})}):null,Au.runtimeUid?jsxRuntimeExports.jsx(Row$1,{label:"Runtime",children:jsxRuntimeExports.jsx(Mono,{children:Au.runtimeUid})}):null,Au.url?jsxRuntimeExports.jsx(Row$1,{label:"Endpoint",children:jsxRuntimeExports.jsx(External,{href:Au.url})}):null,Ru?jsxRuntimeExports.jsx(Row$1,{label:"Agent card",children:jsxRuntimeExports.jsx(External,{href:Ru})}):null]}),jsxRuntimeExports.jsxs(Section,{title:"Agent card",children:[$u.status==="idle"?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:"No endpoint known yet: the card can be fetched once the agent is launched."}):null,$u.status==="loading"?jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,children:[jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}),jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"fg.muted"},children:["Fetching ",Ru,"…"]})]}):null,$u.status==="error"?jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0,color:"danger.fg"},children:["The card could not be fetched from here (",$u.error,"). It may still open in a tab through the link above."]}):null,$u.status==="loaded"?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(CardFields,{card:$u.card}),jsxRuntimeExports.jsxs(Box,{as:"details",fontSize:0,children:[jsxRuntimeExports.jsx(Box,{as:"summary",cursor:"pointer",color:"fg.muted",children:"Raw JSON"}),jsxRuntimeExports.jsx(Box,{as:"pre","data-a2a-card-json":!0,mt:2,p:2,bg:"canvas.subtle",border:"1px solid",borderColor:"border.default",borderRadius:2,overflow:"auto",maxHeight:280,fontSize:0,m:0,children:JSON.stringify($u.card,null,2)})]})]}):null]}),Au.card&&$u.status!=="loaded"?jsxRuntimeExports.jsxs(Section,{title:"Card, as the server saw it at launch",children:[jsxRuntimeExports.jsx(Row$1,{label:"Name",children:jsxRuntimeExports.jsxs(Text$3,{sx:{fontSize:0},children:[Au.card.name??"—",Au.card.version?` v${Au.card.version}`:""]})}),Au.card.description?jsxRuntimeExports.jsx(Row$1,{label:"Description",children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:Au.card.description})}):null,Au.card.skills&&Au.card.skills.length>0?jsxRuntimeExports.jsx(Row$1,{label:"Skills",children:jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:Au.card.skills.join(", ")})}):null]}):null]})})}const NO_SUBSCRIPTION=()=>()=>{},NotebookToolSurfaces=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/NotebookToolSurfaces-BmseoJs0.js"),[],import.meta.url));function normalizeName(Au){return Au.replace(/:[0-9]+\.[0-9]+\.[0-9]+.*$/,"").replace(/[-_]/g,"").toLowerCase()}function toneColorsOf(Au){return!Au||Au==="neutral"?{emphasis:"neutral.emphasis",subtle:"canvas.subtle",muted:"border.default",fg:"fg.default"}:{emphasis:`${Au}.emphasis`,subtle:`${Au}.subtle`,muted:`${Au}.muted`,fg:`${Au}.fg`}}const SUBAGENT_AVATAR_CONFIG={userAvatar:jsxRuntimeExports.jsx(PersonIcon,{size:14}),assistantAvatar:jsxRuntimeExports.jsx(DependabotIcon,{size:14}),showAvatars:!0,avatarSize:24,userAvatarBg:"neutral.muted",assistantAvatarBg:"accent.emphasis"};function buildSubagentDisplayItems(Au,lo){const $u=[],Ru=new Map;let Iu="",Pu=0;const Ou=()=>{Iu.trim()&&$u.push({id:`${lo}:msg:${Pu++}`,role:"assistant",content:Iu,createdAt:new Date(0)}),Iu=""};for(const Mu of Au)switch(Mu.phase){case"text":Iu+=Mu.text??"";break;case"tool_call":{Ou();const Du=`${lo}:tool:${Pu++}`,Lu={id:Du,type:"tool-call",toolCallId:Du,toolName:Mu.toolName??"tool",args:Mu.toolArgs??{},status:"inProgress"};$u.push(Lu),Mu.toolName&&Ru.set(Mu.toolName,Lu);break}case"tool_result":{Ou();const Du=Mu.toolName?Ru.get(Mu.toolName):void 0;if(Du)Du.result=Mu.result,Du.status="complete",Mu.toolName&&Ru.delete(Mu.toolName);else{const Lu=`${lo}:tool:${Pu++}`;$u.push({id:Lu,type:"tool-call",toolCallId:Lu,toolName:Mu.toolName??"tool",args:{},result:Mu.result,status:"complete"})}break}case"error":Ou(),$u.push({id:`${lo}:msg:${Pu++}`,role:"assistant",content:`**⚠️ ${Mu.error??"Subagent failed"}**`,createdAt:new Date(0)});break}return Ou(),$u}function SubagentChatPanel({toolCallId:Au,subagentName:lo,height:$u=280,avatarConfig:Ru=SUBAGENT_AVATAR_CONFIG}){const Iu=useAgentRuntimeSubagentActivityByToolCall(Au,lo),Pu=reactExports.useMemo(()=>buildSubagentDisplayItems(Iu,Au),[Iu,Au]),Ou=reactExports.useRef(null),Mu=reactExports.useMemo(()=>{for(const Wu of Iu)if(Wu.subagentName)return Wu.subagentName;return lo??"subagent"},[Iu,lo]),Du=reactExports.useMemo(()=>Iu.some(Wu=>Wu.phase==="end"||Wu.phase==="error"),[Iu]),Lu=reactExports.useMemo(()=>Iu.some(Wu=>Wu.phase==="error"),[Iu]),Bu=reactExports.useMemo(()=>Iu.some(Wu=>Wu.phase==="error"&&Wu.error===SUBAGENT_STOPPED),[Iu]),ju=reactExports.useMemo(()=>a2aAgentDetails(Iu,lo),[Iu,lo]),Fu=ju!==null,[zu,Uu]=reactExports.useState(!1),Hu=reactExports.useCallback(async(Wu,Zu)=>{if(Zu&&typeof Zu=="object"){const Ju=Zu;Ju.type==="tool-approval-decision"&&typeof Ju.approved=="boolean"&&typeof Ju.approvalId=="string"&&agentRuntimeStore.getState().sendDecision(Ju.approvalId,Ju.approved)}},[]);if(reactExports.useEffect(()=>{Ou.current?.scrollIntoView?.({block:"end"})},[Pu]),Iu.length===0)return null;const Vu=Lu?Bu?"attention":"danger":Du?"success":"accent",Gu=Lu?Bu?"stopped":"failed":Du?"done":Fu&&ju?.state==="launching"?"launching…":"working…";return jsxRuntimeExports.jsxs(Box,{"data-subagent-panel":Mu,"data-subagent-transport":Fu?"a2a":"in-process",mt:2,display:"flex",flexDirection:"column",height:$u,width:"100%",border:"1px solid",borderColor:`${Vu}.emphasis`,borderRadius:2,overflow:"hidden",bg:"canvas.default",children:[jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:1,px:2,py:1,borderBottom:"1px solid",borderColor:`${Vu}.muted`,bg:`${Vu}.subtle`,flexShrink:0,children:[jsxRuntimeExports.jsx(Box,{display:"flex",color:`${Vu}.fg`,children:Fu?jsxRuntimeExports.jsx(BroadcastIcon,{size:14}):jsxRuntimeExports.jsx(DependabotIcon,{size:14})}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:`${Vu}.fg`},children:Fu?"A2A agent":"Subagent"}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,fontWeight:"bold",color:`${Vu}.fg`},children:Mu}),ju?.launch?jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:`${Vu}.fg`,opacity:.8},children:ju.launch}):null,ju?jsxRuntimeExports.jsx(Link$1,{as:"button",type:"button","data-a2a-card-button":!0,onClick:()=>Uu(!0),sx:{fontSize:0,ml:1},children:"card"}):null,jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0,color:`${Vu}.fg`,ml:"auto"},children:Gu})]}),zu&&ju?jsxRuntimeExports.jsx(A2AAgentDialog,{details:ju,onClose:()=>Uu(!1)}):null,jsxRuntimeExports.jsx(Box,{flex:1,minHeight:0,overflowY:"auto",children:jsxRuntimeExports.jsx(ChatMessageList,{displayItems:Pu,isLoading:!Du,isStreaming:!Du,showLoadingIndicator:!Du,hideMessagesAfterToolUI:!1,avatarConfig:Ru,padding:2,onRespond:Hu,messagesEndRef:Ou,emptyContent:jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:1,color:"fg.muted",p:2,children:[jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}),jsxRuntimeExports.jsx(Text$3,{sx:{fontSize:0},children:"Starting…"})]})})})]})}function DefaultToolCallRenderer({item:Au,onRespond:lo,mcpServers:$u,density:Ru}){const Iu=Au.result&&typeof Au.result=="object"?Au.result:void 0,Pu=Au.status==="inProgress"&&Iu?.pending_approval===!0,Ou=typeof Iu?.approval_id=="string"?Iu.approval_id:void 0,Mu=Au.status==="executing",[Du,Lu]=reactExports.useState(),Bu=reactExports.useMemo(()=>normalizeName(Au.toolName),[Au.toolName]),ju=reactExports.useMemo(()=>{const sd=skillIdOfCall(Au.toolName,Au.args);return sd?`skill:${sd}`.toLowerCase():null},[Au.toolName,Au.args]),Fu=reactExports.useMemo(()=>marksOfToolCall(Au.toolName,Au.args,$u),[Au.toolName,Au.args,$u]),zu=useAgentRuntimeStore(sd=>sd.approvals),Uu=reactExports.useMemo(()=>Ou?zu.find(sd=>sd.id===Ou)??null:null,[zu,Ou]),Hu=reactExports.useMemo(()=>ju?zu.find(sd=>sd.tool_name?.toLowerCase()===ju)??null:null,[zu,ju]),Vu=reactExports.useMemo(()=>!Pu&&!Mu?null:zu.find(sd=>normalizeName(sd.tool_name)===Bu)??null,[zu,Bu,Pu,Mu]),Gu=Uu??Hu??Vu,Wu=Gu?.id??Ou??null,Zu=Gu?.status==="approved"?"approved":Gu?.status==="rejected"?"denied":void 0,Ju=reactExports.useCallback(sd=>{if(!Wu)return;const ad=sd==="approve";Lu(ad?"approved":"denied"),lo({type:"tool-approval-decision",approved:ad,approvalId:Wu,toolName:Au.toolName})},[Wu,lo,Au.toolName]),Yu=Pu||!!Wu||!!Zu,Xu=Du||Zu||(Yu?"pending":void 0),ed=Du?"inline":Zu?"external":void 0,td=useAgentRuntimeSubagentActivity(Au.toolCallId),nd=Bu==="delegatetask"||td.length>0,od=typeof Au.args?.subagent_name=="string"?Au.args.subagent_name:typeof Au.args?.subagent=="string"?Au.args.subagent:Bu==="delegatetask"?void 0:Au.toolName;return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ToolCallDisplay,{toolCallId:Au.toolCallId,toolName:Au.toolName,args:Au.args,result:Au.result,status:Au.status,error:Au.error,executionError:Au.executionError,codeError:Au.codeError,exitCode:Au.exitCode,approvalRequired:Yu,approvalState:Xu,approvalDecisionSource:ed,onApprove:Wu&&!Du&&!Zu?()=>Ju("approve"):void 0,onDeny:Wu&&!Du&&!Zu?()=>Ju("reject"):void 0,approvalLoading:!1,marks:Fu,summary:Au.summary,density:Ru}),nd&&jsxRuntimeExports.jsx(SubagentChatPanel,{toolCallId:Au.toolCallId,subagentName:od})]})}function ChatMessageList({displayItems:Au,actOn:lo,upload:$u,isLoading:Ru,isStreaming:Iu,showLoadingIndicator:Pu,hideMessagesAfterToolUI:Ou,avatarConfig:Mu,padding:Du,notebookToolSurfacesId:Lu,emptyContent:Bu,messagesEndRef:ju,onRespond:Fu,approvalConfig:zu,showTurnFooters:Uu=!1,agentUsage:Hu,onRemoveItems:Vu,renderMessageFooter:Gu,saidMessageId:Wu,mcpServers:Zu,density:Ju="comfortable"}){const Yu=useOptionalReactorPlatform();reactExports.useSyncExternalStore(Yu?.subscribe??NO_SUBSCRIPTION,()=>Yu?.getRevision()??0);const Xu=Ju==="compact";if(Xu&&(Mu={...Mu,showAvatars:!1},Uu=!1),Au.length===0)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Bu});const ed=vd=>Sd=>{Fu(vd,Sd)},td=Au.some(isToolCallMessage),nd=new Map;if(Uu){let vd=-1;Au.forEach((Sd,_d)=>{!isToolCallMessage(Sd)&&Sd.role==="user"&&(vd>=0&&nd.set(_d-1,vd),vd=_d)}),vd>=0&&nd.set(Au.length-1,vd)}const od=(vd,Sd)=>{const _d=[];for(let bd=vd;bd<=Sd;bd+=1){const wd=Au[bd];if(isToolCallMessage(wd))_d.push(`[tool · ${wd.toolName}]`);else{const Ad=wd,gd=getMessageText(Ad);gd&&_d.push(Ad.role==="user"?`You: ${gd}`:gd)}}return navigator.clipboard?.writeText(_d.join(`