@datalayer/agent-runtimes 1.3.97 → 1.3.99

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.
@@ -239,7 +239,7 @@ ${$u.comment}`:$u.comment}this.doc.range[2]=$u.offset;break}default:this.errors.
239
239
  `,$u)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(lo){const $u=lo.items[lo.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,$u.value){const Ru="end"in $u.value?$u.value.end:void 0;(Array.isArray(Ru)?Ru[Ru.length-1]:void 0)?.type==="comment"?Ru?.push(this.sourceToken):lo.items.push({start:[this.sourceToken]})}else $u.sep?$u.sep.push(this.sourceToken):$u.start.push(this.sourceToken);return;case"space":case"comment":if($u.value)lo.items.push({start:[this.sourceToken]});else if($u.sep)$u.sep.push(this.sourceToken);else{if(this.atIndentedComment($u.start,lo.indent)){const Iu=lo.items[lo.items.length-2]?.value?.end;if(Array.isArray(Iu)){arrayPushArray(Iu,$u.start),Iu.push(this.sourceToken),lo.items.pop();return}}$u.start.push(this.sourceToken)}return}if(this.indent>=lo.indent){const Ru=!this.onKeyLine&&this.indent===lo.indent,Iu=Ru&&($u.sep||$u.explicitKey)&&this.type!=="seq-item-ind";let Ou=[];if(Iu&&$u.sep&&!$u.value){const Pu=[];for(let Du=0;Du<$u.sep.length;++Du){const Lu=$u.sep[Du];switch(Lu.type){case"newline":Pu.push(Du);break;case"space":break;case"comment":Lu.indent>lo.indent&&(Pu.length=0);break;default:Pu.length=0}}Pu.length>=2&&(Ou=$u.sep.splice(Pu[1]))}switch(this.type){case"anchor":case"tag":Iu||$u.value?(Ou.push(this.sourceToken),lo.items.push({start:Ou}),this.onKeyLine=!0):$u.sep?$u.sep.push(this.sourceToken):$u.start.push(this.sourceToken);return;case"explicit-key-ind":!$u.sep&&!$u.explicitKey?($u.start.push(this.sourceToken),$u.explicitKey=!0):Iu||$u.value?(Ou.push(this.sourceToken),lo.items.push({start:Ou,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if($u.explicitKey)if($u.sep)if($u.value)lo.items.push({start:[],key:null,sep:[this.sourceToken]});else if(includesToken($u.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Ou,key:null,sep:[this.sourceToken]}]});else if(isFlowToken($u.key)&&!includesToken($u.sep,"newline")){const Pu=getFirstKeyStartProps($u.start),Du=$u.key,Lu=$u.sep;Lu.push(this.sourceToken),delete $u.key,delete $u.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Pu,key:Du,sep:Lu}]})}else Ou.length>0?$u.sep=$u.sep.concat(Ou,this.sourceToken):$u.sep.push(this.sourceToken);else if(includesToken($u.start,"newline"))Object.assign($u,{key:null,sep:[this.sourceToken]});else{const Pu=getFirstKeyStartProps($u.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Pu,key:null,sep:[this.sourceToken]}]})}else $u.sep?$u.value||Iu?lo.items.push({start:Ou,key:null,sep:[this.sourceToken]}):includesToken($u.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):$u.sep.push(this.sourceToken):Object.assign($u,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const Pu=this.flowScalar(this.type);Iu||$u.value?(lo.items.push({start:Ou,key:Pu,sep:[]}),this.onKeyLine=!0):$u.sep?this.stack.push(Pu):(Object.assign($u,{key:Pu,sep:[]}),this.onKeyLine=!0);return}default:{const Pu=this.startBlockValue(lo);if(Pu){if(Pu.type==="block-seq"){if(!$u.explicitKey&&$u.sep&&!includesToken($u.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else Ru&&lo.items.push({start:Ou});this.stack.push(Pu);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(lo){const $u=lo.items[lo.items.length-1];switch(this.type){case"newline":if($u.value){const Ru="end"in $u.value?$u.value.end:void 0;(Array.isArray(Ru)?Ru[Ru.length-1]:void 0)?.type==="comment"?Ru?.push(this.sourceToken):lo.items.push({start:[this.sourceToken]})}else $u.start.push(this.sourceToken);return;case"space":case"comment":if($u.value)lo.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment($u.start,lo.indent)){const Iu=lo.items[lo.items.length-2]?.value?.end;if(Array.isArray(Iu)){arrayPushArray(Iu,$u.start),Iu.push(this.sourceToken),lo.items.pop();return}}$u.start.push(this.sourceToken)}return;case"anchor":case"tag":if($u.value||this.indent<=lo.indent)break;$u.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==lo.indent)break;$u.value||includesToken($u.start,"seq-item-ind")?lo.items.push({start:[this.sourceToken]}):$u.start.push(this.sourceToken);return}if(this.indent>lo.indent){const Ru=this.startBlockValue(lo);if(Ru){this.stack.push(Ru);return}}yield*this.pop(),yield*this.step()}*flowCollection(lo){const $u=lo.items[lo.items.length-1];if(this.type==="flow-error-end"){let Ru;do yield*this.pop(),Ru=this.peek(1);while(Ru?.type==="flow-collection")}else if(lo.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!$u||$u.sep?lo.items.push({start:[this.sourceToken]}):$u.start.push(this.sourceToken);return;case"map-value-ind":!$u||$u.value?lo.items.push({start:[],key:null,sep:[this.sourceToken]}):$u.sep?$u.sep.push(this.sourceToken):Object.assign($u,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!$u||$u.value?lo.items.push({start:[this.sourceToken]}):$u.sep?$u.sep.push(this.sourceToken):$u.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const Iu=this.flowScalar(this.type);!$u||$u.value?lo.items.push({start:[],key:Iu,sep:[]}):$u.sep?this.stack.push(Iu):Object.assign($u,{key:Iu,sep:[]});return}case"flow-map-end":case"flow-seq-end":lo.end.push(this.sourceToken);return}const Ru=this.startBlockValue(lo);Ru?this.stack.push(Ru):(yield*this.pop(),yield*this.step())}else{const Ru=this.peek(2);if(Ru.type==="block-map"&&(this.type==="map-value-ind"&&Ru.indent===lo.indent||this.type==="newline"&&!Ru.items[Ru.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&Ru.type!=="flow-collection"){const Iu=getPrevProps(Ru),Ou=getFirstKeyStartProps(Iu);fixFlowSeqItems(lo);const Pu=lo.end.splice(1,lo.end.length);Pu.push(this.sourceToken);const Du={type:"block-map",offset:lo.offset,indent:lo.indent,items:[{start:Ou,key:lo,sep:Pu}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=Du}else yield*this.lineEnd(lo)}}flowScalar(lo){if(this.onNewLine){let $u=this.source.indexOf(`
240
240
  `)+1;for(;$u!==0;)this.onNewLine(this.offset+$u),$u=this.source.indexOf(`
241
241
  `,$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$1(Au,lo={}){const{lineCounter:$u,prettyErrors:Ru}=parseOptions$1(lo),Iu=new Parser$6($u?.addNewLine),Ou=new Composer(lo);let Pu=null;for(const Du of Ou.compose(Iu.parse(Au),!0,Au.length))if(!Pu)Pu=Du;else if(Pu.options.logLevel!=="silent"){Pu.errors.push(new YAMLParseError(Du.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return Ru&&$u&&(Pu.errors.forEach(prettifyError(Au,$u)),Pu.warnings.forEach(prettifyError(Au,$u))),Pu}function readAppspecYaml(Au){const lo=parseDocument$1(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(`
242
- `)[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 Ou={plugin:lo,id:Iu.id??lo,order:Iu.order??0,value:Ru,seq:this.seq++},Pu=this.byPoint.get($u.id);Pu?Pu.push(Ou):this.byPoint.set($u.id,[Ou]);let Du=!1;const Lu=()=>{if(Du)return;Du=!0;const Bu=this.byPoint.get($u.id);if(Bu){const Fu=Bu.indexOf(Ou);Fu>=0&&Bu.splice(Fu,1),Bu.length===0&&this.byPoint.delete($u.id)}this.byPlugin.get(lo)?.delete(Lu)},ju=this.byPlugin.get(lo);return ju?ju.add(Lu):this.byPlugin.set(lo,new Set([Lu])),Lu}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:Ou,value:Pu})=>({plugin:Ru,id:Iu,order:Ou,value:Pu}))}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:Ou})=>({plugin:$u,id:Ru,order:Iu,value:Ou}))}))}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 Ou=!1;const Pu=()=>{Ou||(Ou=!0,this.byId.get($u.id)===Iu&&this.byId.delete($u.id),this.byPlugin.get(lo)?.delete(Pu),this.notify())},Du=this.byPlugin.get(lo);return Du?Du.add(Pu):this.byPlugin.set(lo,new Set([Pu])),this.notify(),Pu}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 Ou;try{Ou=Iu.value.check(lo)}catch(Pu){Ou=Pu instanceof Error?Pu.message:String(Pu)}isRefusal(Ou)&&$u.push({plugin:Iu.plugin,reason:Ou})}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,Ou=Au.map(Pu=>({ref:Pu}));for(;Ou.length>0;){const Pu=Ou.shift();if(!Pu?.ref)continue;const{ref:Du,from:Lu}=Pu;if(isExtension(Du)){Iu.set(Du.name,Du);for(const Fu of Du.plugins)Ou.push({ref:Fu,from:Du.name});continue}if(isLazyPluginRef(Du)){if(!lo.has(Du.name)){$u.set(Du.name,Du),lo.set(Du.name,placeholderFor(Du)),Lu&&Ru.set(Du.name,Lu);for(const Fu of Du.dependencies??[])Ou.push({ref:Fu})}continue}const Bu=asConfigured(Du).plugin;if(!lo.has(Bu.name)){lo.set(Bu.name,Bu),Lu&&Ru.set(Bu.name,Lu);for(const Fu of Bu.dependencies??[])Ou.push({ref:Fu})}}return{plugins:Array.from(lo.values()),lazyByName:$u,extensionOf:Ru,extensions:Iu}}function topoSort(Au){const lo=new Map(Au.map(Pu=>[Pu.name,Pu])),$u=new Set,Ru=new Set,Iu=[];function Ou(Pu){if(Ru.has(Pu))return;if($u.has(Pu))throw new Error(`Circular dependency detected at ${Pu}`);$u.add(Pu);const Du=lo.get(Pu);if(!Du)throw new Error(`Unknown plugin ${Pu}`);for(const Lu of Du.dependencies??[])Ou(asConfigured(Lu).plugin.name);$u.delete(Pu),Ru.add(Pu),Iu.push(Du)}for(const Pu of Au)Ou(Pu.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 Lu of Ru.dependencies??[])$u.push(Lu);continue}const Iu=asConfigured(Ru),Ou=Iu.plugin.name,Pu=lo.get(Ou)??{},Du=shallowMergeConfig(Pu,Iu.config);lo.set(Ou,Du);for(const Lu of Iu.plugin.dependencies??[])$u.push(Lu)}return lo}function buildReactorFromPlugins(Au,lo={}){const{plugins:$u,lazyByName:Ru,extensionOf:Iu,extensions:Ou}=normalizePlugins(Au),Pu=topoSort($u),Du=new Map(Pu.map(gd=>[gd.name,gd])),Lu=collectOverrides(Au),ju=new Map,Bu=new Set,Fu=new ContributionRegistry,zu=new CommandRegistry$1;let qu=0,Uu=0,Hu,Vu=!1;const Gu=new Map,Ku=new Set,Zu=new Set;let Qu=new Set;function Yu(){if(!(Uu>0)){qu+=1;for(const gd of Bu)gd()}}function ed(gd){Uu+=1;try{return gd()}finally{Uu-=1,Uu===0&&Yu()}}for(const gd of Pu){const Ed=mergeWithDefaults(gd,Lu.get(gd.name)??{});ju.set(gd.name,{plugin:gd,config:Ed,enabled:!0,activated:!1,extension:Iu.get(gd.name),lazy:Ru.get(gd.name),loaded:!Ru.has(gd.name)})}for(const gd of Pu){for(const Ed of gd.conflictsWith??[])if(Du.has(Ed))throw new Error(`Plugin ${gd.name} conflicts with ${Ed}`);for(const Ed of gd.peerDependencies??[])if(!Ed.optional&&!Du.has(Ed.name)&&lo.strictPeerDependencies)throw new Error(`Missing required peer dependency ${Ed.name} for ${gd.name}`)}function Xu(gd){const Ed=[];for(const xd of Pu){const Od=ju.get(xd.name);!Od||Od.activated||matchesActivation(Od.plugin.activationEvents,gd)&&Ed.push(xd.name)}return Ed}function rd(gd){if(!Ku.has(gd.id)){Ku.add(gd.id);const Ed=onContributionPoint(gd);Xu(Ed).length>0&&Promise.resolve().then(()=>wd(Ed))}return Fu.get(gd)}const nd={hasPlugin(gd){return ju.has(gd)},getOutput(gd){return ju.get(gd)?.outputValue},getRequiredBackendPlugins(gd){return ju.get(gd)?.plugin.requiredBackendPlugins??[]},getOptionalBackendPlugins(gd){return ju.get(gd)?.plugin.optionalBackendPlugins??[]},getManifest(gd){const Ed=ju.get(gd);if(!Ed)return;const{plugin:xd}=Ed;return{name:xd.name,version:xd.version,displayName:xd.displayName??xd.name,description:xd.description,octicon:xd.octicon,emoji:xd.emoji,extension:Ed.extension,requiredBackendPlugins:xd.requiredBackendPlugins??[],optionalBackendPlugins:xd.optionalBackendPlugins??[],loaded:Ed.loaded,lazy:!!Ed.lazy,activated:Ed.activated,disabledBy:Ed.enabled?void 0:Ed.disabledBy??"user",loadError:Ed.loadError?.message,activationEvents:xd.activationEvents??[ON_STARTUP],deactivationEvents:xd.deactivationEvents??[],contributionPoints:(xd.contributionPoints??[]).map(Od=>Od.id),contributesTo:[...new Set((xd.contributes??[]).map(Od=>Od.point.id))]}},isEnabled(gd){return ju.get(gd)?.enabled??!1},getContributions(gd){return rd(gd)},checkGate(gd,Ed){return resolveGate(rd(gd),Ed)}};function od(gd,Ed){return{plugin:Ed.plugin,config:Ed.config,state:{getConfig:()=>Ed.config,getInit:()=>Ed.initValue,getOutput:()=>Ed.outputValue},reactor:nd,contribute(xd,Od,Bd){const Gd=Fu.add(gd,xd,Od,Bd);Yu();let Ud=!1;return()=>{Ud||(Ud=!0,Gd(),Yu())}},registerCommand(xd){const Od=zu.add(gd,xd);Yu();let Bd=!1;return()=>{Bd||(Bd=!0,Od(),Yu())}}}}function ad(gd){const Ed=ju.get(gd);if(!Ed)throw new Error(`Unknown plugin ${gd}`);if(!Ed.loaded)return;const xd=od(gd,Ed);Ed.initValue=Ed.plugin.init?.(xd),Ed.outputValue=Ed.plugin.build?.(xd)}function ld(gd){const Ed=ju.get(gd);if(!Ed||!Ed.enabled||!Ed.loaded)return;const xd=od(gd,Ed);for(const Od of Ed.plugin.contributes??[])Fu.add(gd,Od.point,Od.value,Od.options);for(const Od of Ed.plugin.commands??[])zu.add(gd,Od);Yu(),Ed.registerDispose=Ed.plugin.register?.(xd)??void 0,Ed.afterDispose=Ed.plugin.afterRegistration?.(xd)??void 0}function fd(gd){const Ed=ju.get(gd);!Ed||Ed.activated||!Ed.loaded||(Ed.activated=!0,ed(()=>{Ed.enabled&&(Ed.plugin.preserveOutput&&Ed.outputValue!==void 0||ad(gd),ld(gd))}))}async function pd(gd){const Ed=ju.get(gd);if(!(!Ed?.lazy||Ed.loaded)){Ed.loading??=Promise.resolve().then(()=>Ed.lazy.load());try{const xd=await Ed.loading;if(Ed.loaded)return;const Od=xd.default??xd;if(!Od||typeof Od!="object"||!Od.name)throw new Error(`Lazy plugin ${gd} did not resolve to a plugin`);Ed.plugin=mergeLoaded(Ed.lazy,Od),Ed.config=mergeWithDefaults(Ed.plugin,Lu.get(gd)??{}),Ed.loaded=!0}catch(xd){Ed.loadError=xd instanceof Error?xd:new Error(String(xd)),Yu()}}}function Sd(gd){const Ed=ju.get(gd);if(!Ed||Ed.activated)return Promise.resolve();const xd=Gu.get(gd);if(xd)return xd;const Od=(async()=>{for(const Bd of Ed.plugin.dependencies??[])await Sd(asConfigured(Bd).plugin.name);Ed.lazy&&!Ed.loaded&&await pd(gd),fd(gd),Zu.delete(gd)})().finally(()=>{Gu.delete(gd)});return Gu.set(gd,Od),Od}async function wd(gd){const Ed=Xu(gd);if(Ed.length===0)return[];for(const xd of Ed){const Od=ju.get(xd);Od?.lazy&&!Od.loaded&&(Od.loading??=Promise.resolve().then(()=>Od.lazy.load()))}for(const xd of Ed)await Sd(xd);return Ed.filter(xd=>ju.get(xd)?.activated)}function bd(gd){const Ed=new Set([gd]);for(const xd of Pu)(xd.dependencies??[]).some(Bd=>Ed.has(asConfigured(Bd).plugin.name))&&Ed.add(xd.name);return Ed.delete(gd),Pu.map(xd=>xd.name).filter(xd=>Ed.has(xd)).reverse()}function Td(gd){return(ju.get(gd)?.plugin?.dependencies??[]).every(xd=>ju.get(asConfigured(xd).plugin.name)?.enabled??!0)}function Pd(gd){const Ed=ju.get(gd);if(!Ed||Ed.enabled||(Ed.enabled=!0,Ed.disabledBy=void 0,!Ed.loaded||!Ed.activated))return;Ed.plugin.preserveOutput&&Ed.outputValue!==void 0||ad(gd),ld(gd)}function ud(gd,Ed="other"){const xd=ju.get(gd);if(!xd)throw new Error(`Unknown plugin ${gd}`);if(Ed==="other"&&Zu.delete(gd),!xd.activated)return[];const Od=[];if(ed(()=>{for(const Bd of bd(gd)){const Gd=ju.get(Bd);Gd?.activated&&(hd(Bd),Gd.activated=!1,md(Bd),Od.push(Bd))}hd(gd),xd.activated=!1,md(gd),Od.push(gd)}),Ed==="other")for(const Bd of Od)Zu.delete(Bd);return Od}function md(gd){const Ed=ju.get(gd)?.plugin.activationEvents??[];for(const xd of Ed)xd.startsWith("onContributionPoint:")&&Ku.delete(xd.slice(20))}function _d(gd){const Ed=[];for(const xd of Pu){const Od=ju.get(xd.name);Od?.activated&&matchesDeactivation(Od.plugin.deactivationEvents,gd)&&Ed.push(...ud(xd.name))}return Ed}function hd(gd){const Ed=ju.get(gd);Ed&&(Ed.afterDispose?.(),Ed.afterDispose=void 0,Ed.registerDispose?.(),Ed.registerDispose=void 0,Fu.disposePlugin(gd),zu.disposePlugin(gd))}return{...nd,start(){Vu=!0,ed(()=>{const gd=Pu.filter(Ed=>{const xd=ju.get(Ed.name);return xd&&xd.loaded&&!xd.activated&&activatesAtStartup(xd.plugin.activationEvents)});for(const Ed of gd)ju.get(Ed.name).activated=!0,ad(Ed.name);for(const Ed of gd)ld(Ed.name)}),Hu=wd(ON_STARTUP).then(()=>{})},whenReady(){return Hu??Promise.resolve()},async fire(gd){const Ed=_d(gd),xd=await wd(gd);return{deactivated:Ed,activated:xd}},deactivate(gd){ud(gd)},async setBackendPlugins(gd){Qu=new Set(gd);const Ed=Bd=>(ju.get(Bd)?.plugin.requiredBackendPlugins??[]).every(Gd=>Qu.has(Gd)),xd=[];for(const Bd of Pu){if(!ju.get(Bd.name)?.activated||Ed(Bd.name))continue;const Ud=ud(Bd.name,"backend");for(const Md of Ud)Zu.add(Md);xd.push(...Ud)}const Od=[];for(const Bd of Pu){const Gd=Bd.name;!Zu.has(Gd)||!Ed(Gd)||!ju.get(Gd)?.enabled||(Zu.delete(Gd),await Sd(Gd),ju.get(Gd)?.activated&&Od.push(Gd))}return{deactivated:xd,activated:Od}},async install(gd){const Ed=normalizePlugins([gd]),xd=Ed.plugins.filter(Ud=>!ju.has(Ud.name));if(xd.length===0)return[];for(const Ud of xd)for(const Md of Ud.conflictsWith??[])if(Du.has(Md)||xd.some(zd=>zd.name===Md))throw new Error(`Plugin ${Ud.name} conflicts with ${Md}`);for(const[Ud,Md]of Ed.lazyByName)Ru.set(Ud,Md);for(const[Ud,Md]of Ed.extensionOf)Iu.set(Ud,Md);for(const[Ud,Md]of Ed.extensions)Ou.set(Ud,Md);const Od=collectOverrides([gd]);for(const Ud of xd)Du.set(Ud.name,Ud),ju.set(Ud.name,{plugin:Ud,config:mergeWithDefaults(Ud,Od.get(Ud.name)??{}),enabled:!0,activated:!1,extension:Iu.get(Ud.name),lazy:Ru.get(Ud.name),loaded:!Ru.has(Ud.name)});const Bd=topoSort([...Pu,...xd]);if(Pu.splice(0,Pu.length,...Bd),Yu(),!Vu)return xd.map(Ud=>Ud.name);const Gd=[];for(const Ud of Bd)xd.some(Md=>Md.name===Ud.name)&&(Gd.push(Ud.name),activatesAtStartup(Ud.activationEvents)&&await Sd(Ud.name));return Gd},stop(){Vu=!1,ed(()=>{for(const gd of[...Pu].reverse()){hd(gd.name);const Ed=ju.get(gd.name);Ed&&(Ed.activated=!1)}Ku.clear()})},enable(gd){const Ed=ju.get(gd);if(!Ed)throw new Error(`Unknown plugin ${gd}`);Ed.enabled||ed(()=>{Pd(gd);for(const xd of[...bd(gd)].reverse()){const Od=ju.get(xd);!Od||Od.enabled||Od.disabledBy==="dependency"&&Td(xd)&&Pd(xd)}})},disable(gd){const Ed=ju.get(gd);if(!Ed)throw new Error(`Unknown plugin ${gd}`);Ed.enabled&&ed(()=>{for(const xd of bd(gd)){const Od=ju.get(xd);Od?.enabled&&(Od.enabled=!1,Od.disabledBy="dependency",hd(xd))}Ed.enabled=!1,Ed.disabledBy="user",hd(gd)})},subscribe(gd){return Bu.add(gd),()=>{Bu.delete(gd)}},listPlugins(){return Pu.map(gd=>gd.name)},listExtensions(){return[...Ou.keys()]},getExtensionManifest(gd){const Ed=Ou.get(gd);if(Ed)return{name:Ed.name,version:Ed.version,displayName:Ed.displayName??Ed.name,description:Ed.description,octicon:Ed.octicon,emoji:Ed.emoji,plugins:Pu.filter(xd=>Iu.get(xd.name)===gd).map(xd=>xd.name)}},getConfig(gd){return ju.get(gd)?.config},describeContributions(){return Fu.describe()},listCommands(){return zu.list()},getCommand(gd){return zu.get(gd)},executeCommand(gd,Ed){return zu.execute(gd,Ed)},getDependencies(gd){return(ju.get(gd)?.plugin.dependencies??[]).map(Ed=>asConfigured(Ed).plugin.name)},getRevision(){return qu}}}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,Ou)=>Ru!==""||Iu===Ou.length-1);for(const[Ru,Iu]of $u.entries()){const Ou=Iu.toLowerCase(),Pu=MODIFIERS[Ou];if(Pu&&Ru<$u.length-1){lo[Pu]=!0;continue}const Du=Iu===""?"+":KEY_ALIASES[Ou]??Ou;lo.key=Du}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,Ou=lo.meta||lo.mod&&$u;return Au.ctrlKey===Iu&&Au.metaKey===Ou&&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,Ou=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:"",Ou].join(""):[Ru?OTHER_LABELS.ctrl:"",Iu&&!Ru?OTHER_LABELS.meta:"",$u.alt?OTHER_LABELS.alt:"",$u.shift?OTHER_LABELS.shift:"",Ou].filter(Boolean).join("+")}function titleCase(Au){return Au.charAt(0).toUpperCase()+Au.slice(1)}const AgentTools=defineContributionPoint("reactor.agentTools");var ArrayExt;(function(Au){function lo(Xu,rd,nd=0,od=-1){let ad=Xu.length;if(ad===0)return-1;nd<0?nd=Math.max(0,nd+ad):nd=Math.min(nd,ad-1),od<0?od=Math.max(0,od+ad):od=Math.min(od,ad-1);let ld;od<nd?ld=od+1+(ad-nd):ld=od-nd+1;for(let fd=0;fd<ld;++fd){let pd=(nd+fd)%ad;if(Xu[pd]===rd)return pd}return-1}Au.firstIndexOf=lo;function $u(Xu,rd,nd=-1,od=0){let ad=Xu.length;if(ad===0)return-1;nd<0?nd=Math.max(0,nd+ad):nd=Math.min(nd,ad-1),od<0?od=Math.max(0,od+ad):od=Math.min(od,ad-1);let ld;nd<od?ld=nd+1+(ad-od):ld=nd-od+1;for(let fd=0;fd<ld;++fd){let pd=(nd-fd+ad)%ad;if(Xu[pd]===rd)return pd}return-1}Au.lastIndexOf=$u;function Ru(Xu,rd,nd=0,od=-1){let ad=Xu.length;if(ad===0)return-1;nd<0?nd=Math.max(0,nd+ad):nd=Math.min(nd,ad-1),od<0?od=Math.max(0,od+ad):od=Math.min(od,ad-1);let ld;od<nd?ld=od+1+(ad-nd):ld=od-nd+1;for(let fd=0;fd<ld;++fd){let pd=(nd+fd)%ad;if(rd(Xu[pd],pd))return pd}return-1}Au.findFirstIndex=Ru;function Iu(Xu,rd,nd=-1,od=0){let ad=Xu.length;if(ad===0)return-1;nd<0?nd=Math.max(0,nd+ad):nd=Math.min(nd,ad-1),od<0?od=Math.max(0,od+ad):od=Math.min(od,ad-1);let ld;nd<od?ld=nd+1+(ad-od):ld=nd-od+1;for(let fd=0;fd<ld;++fd){let pd=(nd-fd+ad)%ad;if(rd(Xu[pd],pd))return pd}return-1}Au.findLastIndex=Iu;function Ou(Xu,rd,nd=0,od=-1){let ad=Ru(Xu,rd,nd,od);return ad!==-1?Xu[ad]:void 0}Au.findFirstValue=Ou;function Pu(Xu,rd,nd=-1,od=0){let ad=Iu(Xu,rd,nd,od);return ad!==-1?Xu[ad]:void 0}Au.findLastValue=Pu;function Du(Xu,rd,nd,od=0,ad=-1){let ld=Xu.length;if(ld===0)return 0;od<0?od=Math.max(0,od+ld):od=Math.min(od,ld-1),ad<0?ad=Math.max(0,ad+ld):ad=Math.min(ad,ld-1);let fd=od,pd=ad-od+1;for(;pd>0;){let Sd=pd>>1,wd=fd+Sd;nd(Xu[wd],rd)<0?(fd=wd+1,pd-=Sd+1):pd=Sd}return fd}Au.lowerBound=Du;function Lu(Xu,rd,nd,od=0,ad=-1){let ld=Xu.length;if(ld===0)return 0;od<0?od=Math.max(0,od+ld):od=Math.min(od,ld-1),ad<0?ad=Math.max(0,ad+ld):ad=Math.min(ad,ld-1);let fd=od,pd=ad-od+1;for(;pd>0;){let Sd=pd>>1,wd=fd+Sd;nd(Xu[wd],rd)>0?pd=Sd:(fd=wd+1,pd-=Sd+1)}return fd}Au.upperBound=Lu;function ju(Xu,rd,nd){if(Xu===rd)return!0;if(Xu.length!==rd.length)return!1;for(let od=0,ad=Xu.length;od<ad;++od)if(nd?!nd(Xu[od],rd[od]):Xu[od]!==rd[od])return!1;return!0}Au.shallowEqual=ju;function Bu(Xu,rd={}){let{start:nd,stop:od,step:ad}=rd;if(ad===void 0&&(ad=1),ad===0)throw new Error("Slice `step` cannot be zero.");let ld=Xu.length;nd===void 0?nd=ad<0?ld-1:0:nd<0?nd=Math.max(nd+ld,ad<0?-1:0):nd>=ld&&(nd=ad<0?ld-1:ld),od===void 0?od=ad<0?-1:ld:od<0?od=Math.max(od+ld,ad<0?-1:0):od>=ld&&(od=ad<0?ld-1:ld);let fd;ad<0&&od>=nd||ad>0&&nd>=od?fd=0:ad<0?fd=Math.floor((od-nd+1)/ad+1):fd=Math.floor((od-nd-1)/ad+1);let pd=[];for(let Sd=0;Sd<fd;++Sd)pd[Sd]=Xu[nd+Sd*ad];return pd}Au.slice=Bu;function Fu(Xu,rd,nd){let od=Xu.length;if(od<=1||(rd<0?rd=Math.max(0,rd+od):rd=Math.min(rd,od-1),nd<0?nd=Math.max(0,nd+od):nd=Math.min(nd,od-1),rd===nd))return;let ad=Xu[rd],ld=rd<nd?1:-1;for(let fd=rd;fd!==nd;fd+=ld)Xu[fd]=Xu[fd+ld];Xu[nd]=ad}Au.move=Fu;function zu(Xu,rd=0,nd=-1){let od=Xu.length;if(!(od<=1))for(rd<0?rd=Math.max(0,rd+od):rd=Math.min(rd,od-1),nd<0?nd=Math.max(0,nd+od):nd=Math.min(nd,od-1);rd<nd;){let ad=Xu[rd],ld=Xu[nd];Xu[rd++]=ld,Xu[nd--]=ad}}Au.reverse=zu;function qu(Xu,rd,nd=0,od=-1){let ad=Xu.length;if(ad<=1||(nd<0?nd=Math.max(0,nd+ad):nd=Math.min(nd,ad-1),od<0?od=Math.max(0,od+ad):od=Math.min(od,ad-1),nd>=od))return;let ld=od-nd+1;if(rd>0?rd=rd%ld:rd<0&&(rd=(rd%ld+ld)%ld),rd===0)return;let fd=nd+rd;zu(Xu,nd,fd-1),zu(Xu,fd,od),zu(Xu,nd,od)}Au.rotate=qu;function Uu(Xu,rd,nd=0,od=-1){let ad=Xu.length;if(ad===0)return;nd<0?nd=Math.max(0,nd+ad):nd=Math.min(nd,ad-1),od<0?od=Math.max(0,od+ad):od=Math.min(od,ad-1);let ld;od<nd?ld=od+1+(ad-nd):ld=od-nd+1;for(let fd=0;fd<ld;++fd)Xu[(nd+fd)%ad]=rd}Au.fill=Uu;function Hu(Xu,rd,nd){let od=Xu.length;rd<0?rd=Math.max(0,rd+od):rd=Math.min(rd,od);for(let ad=od;ad>rd;--ad)Xu[ad]=Xu[ad-1];Xu[rd]=nd}Au.insert=Hu;function Vu(Xu,rd){let nd=Xu.length;if(rd<0&&(rd+=nd),rd<0||rd>=nd)return;let od=Xu[rd];for(let ad=rd+1;ad<nd;++ad)Xu[ad-1]=Xu[ad];return Xu.length=nd-1,od}Au.removeAt=Vu;function Gu(Xu,rd,nd=0,od=-1){let ad=lo(Xu,rd,nd,od);return ad!==-1&&Vu(Xu,ad),ad}Au.removeFirstOf=Gu;function Ku(Xu,rd,nd=-1,od=0){let ad=$u(Xu,rd,nd,od);return ad!==-1&&Vu(Xu,ad),ad}Au.removeLastOf=Ku;function Zu(Xu,rd,nd=0,od=-1){let ad=Xu.length;if(ad===0)return 0;nd<0?nd=Math.max(0,nd+ad):nd=Math.min(nd,ad-1),od<0?od=Math.max(0,od+ad):od=Math.min(od,ad-1);let ld=0;for(let fd=0;fd<ad;++fd)nd<=od&&fd>=nd&&fd<=od&&Xu[fd]===rd||od<nd&&(fd<=od||fd>=nd)&&Xu[fd]===rd?ld++:ld>0&&(Xu[fd-ld]=Xu[fd]);return ld>0&&(Xu.length=ad-ld),ld}Au.removeAllOf=Zu;function Qu(Xu,rd,nd=0,od=-1){let ad,ld=Ru(Xu,rd,nd,od);return ld!==-1&&(ad=Vu(Xu,ld)),{index:ld,value:ad}}Au.removeFirstWhere=Qu;function Yu(Xu,rd,nd=-1,od=0){let ad,ld=Iu(Xu,rd,nd,od);return ld!==-1&&(ad=Vu(Xu,ld)),{index:ld,value:ad}}Au.removeLastWhere=Yu;function ed(Xu,rd,nd=0,od=-1){let ad=Xu.length;if(ad===0)return 0;nd<0?nd=Math.max(0,nd+ad):nd=Math.min(nd,ad-1),od<0?od=Math.max(0,od+ad):od=Math.min(od,ad-1);let ld=0;for(let fd=0;fd<ad;++fd)nd<=od&&fd>=nd&&fd<=od&&rd(Xu[fd],fd)||od<nd&&(fd<=od||fd>=nd)&&rd(Xu[fd],fd)?ld++:ld>0&&(Xu[fd-ld]=Xu[fd]);return ld>0&&(Xu.length=ad-ld),ld}Au.removeAllWhere=ed})(ArrayExt||(ArrayExt={}));function*chain$1(...Au){for(const lo of Au)yield*lo}function*empty$4(){}function*enumerate(Au,lo=0){for(const $u of Au)yield[lo++,$u]}function*filter$5(Au,lo){let $u=0;for(const Ru of Au)lo(Ru,$u++)&&(yield Ru)}function find$5(Au,lo){let $u=0;for(const Ru of Au)if(lo(Ru,$u++))return Ru}function findIndex$1(Au,lo){let $u=0;for(const Ru of Au)if(lo(Ru,$u++))return $u-1;return-1}function min$2(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$2(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 Ou of Au)$u?(Ru=Ou,Iu=Ou,$u=!1):lo(Ou,Ru)<0?Ru=Ou:lo(Ou,Iu)>0&&(Iu=Ou);return $u?void 0:[Ru,Iu]}function toArray$2(Au){return Array.from(Au)}function toObject(Au){const lo={};for(const[$u,Ru]of Au)lo[$u]=Ru;return lo}function each$1(Au,lo){let $u=0;for(const Ru of Au)if(lo(Ru,$u++)===!1)return}function every$3(Au,lo){let $u=0;for(const Ru of Au)if(lo(Ru,$u++)===!1)return!1;return!0}function some$2(Au,lo){let $u=0;for(const Ru of Au)if(lo(Ru,$u++))return!0;return!1}function*map$8(Au,lo){let $u=0;for(const Ru of Au)yield lo(Ru,$u++)}function*range$4(Au,lo,$u){lo===void 0?(lo=Au,Au=0,$u=1):$u===void 0&&($u=1);const Ru=Private$I.rangeLength(Au,lo,$u);for(let Iu=0;Iu<Ru;Iu++)yield Au+$u*Iu}var Private$I;(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$I||(Private$I={}));function reduce$1(Au,lo,$u){const Ru=Au[Symbol.iterator]();let Iu=0,Ou=Ru.next();if(Ou.done&&$u===void 0)throw new TypeError("Reduce of empty iterable with no initial value.");if(Ou.done)return $u;let Pu=Ru.next();if(Pu.done&&$u===void 0)return Ou.value;if(Pu.done)return lo($u,Ou.value,Iu++);let Du;$u===void 0?Du=lo(Ou.value,Pu.value,Iu++):Du=lo(lo($u,Ou.value,Iu++),Pu.value,Iu++);let Lu;for(;!(Lu=Ru.next()).done;)Du=lo(Du,Lu.value,Iu++);return Du}function*repeat$1(Au,lo){for(;0<lo--;)yield Au}function*once$1(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 Pu of Au)Iu(Pu);for(const[Pu]of Ru)Ou(Pu);return lo;function Iu(Pu){let[Du,Lu]=Pu,ju=Ru.get(Lu);ju?ju.push(Du):Ru.set(Lu,[Du])}function Ou(Pu){if($u.has(Pu))return;$u.add(Pu);let Du=Ru.get(Pu);if(Du)for(const Lu of Du)Ou(Lu);lo.push(Pu)}}function*stride(Au,lo){let $u=0;for(const Ru of Au)$u++%lo===0&&(yield Ru)}var StringExt;(function(Au){function lo(Pu,Du,Lu=0){let ju=new Array(Du.length);for(let Bu=0,Fu=Lu,zu=Du.length;Bu<zu;++Bu,++Fu){if(Fu=Pu.indexOf(Du[Bu],Fu),Fu===-1)return null;ju[Bu]=Fu}return ju}Au.findIndices=lo;function $u(Pu,Du,Lu=0){let ju=lo(Pu,Du,Lu);if(!ju)return null;let Bu=0;for(let Fu=0,zu=ju.length;Fu<zu;++Fu){let qu=ju[Fu]-Lu;Bu+=qu*qu}return{score:Bu,indices:ju}}Au.matchSumOfSquares=$u;function Ru(Pu,Du,Lu=0){let ju=lo(Pu,Du,Lu);if(!ju)return null;let Bu=0,Fu=Lu-1;for(let zu=0,qu=ju.length;zu<qu;++zu){let Uu=ju[zu];Bu+=Uu-Fu-1,Fu=Uu}return{score:Bu,indices:ju}}Au.matchSumOfDeltas=Ru;function Iu(Pu,Du,Lu){let ju=[],Bu=0,Fu=0,zu=Du.length;for(;Bu<zu;){let qu=Du[Bu],Uu=Du[Bu];for(;++Bu<zu&&Du[Bu]===Uu+1;)Uu++;Fu<qu&&ju.push(Pu.slice(Fu,qu)),qu<Uu+1&&ju.push(Lu(Pu.slice(qu,Uu+1))),Fu=Uu+1}return Fu<Pu.length&&ju.push(Pu.slice(Fu)),ju}Au.highlight=Iu;function Ou(Pu,Du){return Pu<Du?-1:Pu>Du?1:0}Au.cmp=Ou})(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$1(...Au){const lo=Au.map(Ru=>Ru[Symbol.iterator]());let $u=lo.map(Ru=>Ru.next());for(;every$3($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:chain$1,each:each$1,empty:empty$4,enumerate,every:every$3,filter:filter$5,find:find$5,findIndex:findIndex$1,map:map$8,max:max$2,min:min$2,minmax,once:once$1,range:range$4,reduce:reduce$1,repeat:repeat$1,retro,some:some$2,stride,take,toArray:toArray$2,toObject,topologicSort,zip:zip$1},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,Fu){if(Bu===Fu)return!0;if(lo(Bu)||lo(Fu))return!1;let zu=$u(Bu),qu=$u(Fu);return zu!==qu?!1:zu&&qu?Pu(Bu,Fu):Du(Bu,Fu)}Au.deepEqual=Iu;function Ou(Bu){return lo(Bu)?Bu:$u(Bu)?Lu(Bu):ju(Bu)}Au.deepCopy=Ou;function Pu(Bu,Fu){if(Bu===Fu)return!0;if(Bu.length!==Fu.length)return!1;for(let zu=0,qu=Bu.length;zu<qu;++zu)if(!Iu(Bu[zu],Fu[zu]))return!1;return!0}function Du(Bu,Fu){if(Bu===Fu)return!0;for(let zu in Bu)if(Bu[zu]!==void 0&&!(zu in Fu))return!1;for(let zu in Fu)if(Fu[zu]!==void 0&&!(zu in Bu))return!1;for(let zu in Bu){let qu=Bu[zu],Uu=Fu[zu];if(!(qu===void 0&&Uu===void 0)&&(qu===void 0||Uu===void 0||!Iu(qu,Uu)))return!1}return!0}function Lu(Bu){let Fu=new Array(Bu.length);for(let zu=0,qu=Bu.length;zu<qu;++zu)Fu[zu]=Ou(Bu[zu]);return Fu}function ju(Bu){let Fu={};for(let zu in Bu){let qu=Bu[zu];qu!==void 0&&(Fu[zu]=Ou(qu))}return Fu}})(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$H.createPluginData(lo);Private$H.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(Ou=>this.resolveRequiredService(Ou)),Iu=$u.optional.map(Ou=>this.resolveOptionalService(Ou));return $u.promise=Promise.all([...Ru,...Iu]).then(Ou=>$u.activate.apply(void 0,[this.application,...Ou])).then(Ou=>{$u.service=Ou,$u.activated=!0,$u.promise=null}).catch(Ou=>{throw $u.promise=null,Ou}),$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$H.collectStartupPlugins(this._plugins,$u).map(async Ou=>{try{return await this.activatePlugin(Ou)}catch(Pu){console.error(`Plugin '${Ou}' failed to activate.`,Pu)}});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$H.findDependents(lo,this._plugins,this._services),Iu=Ru.map(Ou=>this._plugins.get(Ou));for(const Ou of Iu)if(!Ou.deactivate)throw new TypeError(`Plugin ${Ou.id}#deactivate() method missing (depends on ${lo})`);for(const Ou of Iu){const Pu=[...Ou.requires,...Ou.optional].map(Du=>{const Lu=this._services.get(Du);return Lu?this._plugins.get(Lu).service:null});await Ou.deactivate(this.application,...Pu),Ou.service=null,Ou.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$H;(function(Au){class lo{constructor(Du){var Lu,ju,Bu,Fu;this._activated=!1,this._promise=null,this._service=null,this.id=Du.id,this.description=(Lu=Du.description)!==null&&Lu!==void 0?Lu:"",this.activate=Du.activate,this.deactivate=(ju=Du.deactivate)!==null&&ju!==void 0?ju:null,this.provides=(Bu=Du.provides)!==null&&Bu!==void 0?Bu:null,this.autoStart=(Fu=Du.autoStart)!==null&&Fu!==void 0?Fu:!1,this.requires=Du.requires?Du.requires.slice():[],this.optional=Du.optional?Du.optional.slice():[]}get activated(){return this._activated}set activated(Du){this._activated=Du}get service(){return this._service}set service(Du){this._service=Du}get promise(){return this._promise}set promise(Du){this._promise=Du}}function $u(Pu){return new lo(Pu)}Au.createPluginData=$u;function Ru(Pu,Du,Lu){const ju=[...Pu.requires,...Pu.optional],Bu=zu=>{if(zu===Pu.provides)return!0;const qu=Lu.get(zu);if(!qu)return!1;const Uu=Du.get(qu),Hu=[...Uu.requires,...Uu.optional];return Hu.length===0?!1:(Fu.push(qu),Hu.some(Bu)?!0:(Fu.pop(),!1))};if(!Pu.provides||ju.length===0)return;const Fu=[Pu.id];if(ju.some(Bu))throw new ReferenceError(`Cycle detected: ${Fu.join(" -> ")}.`)}Au.ensureNoCycle=Ru;function Iu(Pu,Du,Lu){const ju=new Array,Bu=Hu=>{const Vu=Du.get(Hu),Gu=[...Vu.requires,...Vu.optional];ju.push(...Gu.reduce((Ku,Zu)=>{const Qu=Lu.get(Zu);return Qu&&Ku.push([Hu,Qu]),Ku},[]))};for(const Hu of Du.keys())Bu(Hu);const Fu=ju.filter(Hu=>Hu[1]===Pu);let zu=0;for(;Fu.length>zu;){const Hu=Fu.length,Vu=new Set(Fu.map(Gu=>Gu[0]));for(const Gu of Vu)ju.filter(Ku=>Ku[1]===Gu).forEach(Ku=>{Fu.includes(Ku)||Fu.push(Ku)});zu=Hu}const qu=topologicSort(Fu),Uu=qu.findIndex(Hu=>Hu===Pu);return Uu===-1?[Pu]:qu.slice(0,Uu+1)}Au.findDependents=Iu;function Ou(Pu,Du){const Lu=new Set;for(const ju of Pu.keys())Pu.get(ju).autoStart===!0&&Lu.add(ju);if(Du.startPlugins)for(const ju of Du.startPlugins)Lu.add(ju);if(Du.ignorePlugins)for(const ju of Du.ignorePlugins)Lu.delete(ju);return Array.from(Lu)}Au.collectStartupPlugins=Ou})(Private$H||(Private$H={}));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$G.connect(this,lo,$u)}disconnect(lo,$u){return Private$G.disconnect(this,lo,$u)}emit(lo){Private$G.emit(this,lo)}}(function(Au){function lo(Lu,ju){Private$G.disconnectBetween(Lu,ju)}Au.disconnectBetween=lo;function $u(Lu){Private$G.disconnectSender(Lu)}Au.disconnectSender=$u;function Ru(Lu){Private$G.disconnectReceiver(Lu)}Au.disconnectReceiver=Ru;function Iu(Lu){Private$G.disconnectAll(Lu)}Au.disconnectAll=Iu;function Ou(Lu){Private$G.disconnectAll(Lu)}Au.clearData=Ou;function Pu(){return Private$G.exceptionHandler}Au.getExceptionHandler=Pu;function Du(Lu){let ju=Private$G.exceptionHandler;return Private$G.exceptionHandler=Lu,ju}Au.setExceptionHandler=Du})(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$G;(function(Au){Au.exceptionHandler=Ku=>{console.error(Ku)};function lo(Ku,Zu,Qu){Qu=Qu||void 0;let Yu=Lu.get(Ku.sender);if(Yu||(Yu=[],Lu.set(Ku.sender,Yu)),zu(Yu,Ku,Zu,Qu))return!1;let ed=Qu||Zu,Xu=ju.get(ed);Xu||(Xu=[],ju.set(ed,Xu));let rd={signal:Ku,slot:Zu,thisArg:Qu};return Yu.push(rd),Xu.push(rd),!0}Au.connect=lo;function $u(Ku,Zu,Qu){Qu=Qu||void 0;let Yu=Lu.get(Ku.sender);if(!Yu||Yu.length===0)return!1;let ed=zu(Yu,Ku,Zu,Qu);if(!ed)return!1;let Xu=Qu||Zu,rd=ju.get(Xu);return ed.signal=null,Uu(Yu),Uu(rd),!0}Au.disconnect=$u;function Ru(Ku,Zu){let Qu=Lu.get(Ku);if(!Qu||Qu.length===0)return;let Yu=ju.get(Zu);if(!(!Yu||Yu.length===0)){for(const ed of Yu)ed.signal&&ed.signal.sender===Ku&&(ed.signal=null);Uu(Qu),Uu(Yu)}}Au.disconnectBetween=Ru;function Iu(Ku){let Zu=Lu.get(Ku);if(!(!Zu||Zu.length===0)){for(const Qu of Zu){if(!Qu.signal)continue;let Yu=Qu.thisArg||Qu.slot;Qu.signal=null,Uu(ju.get(Yu))}Uu(Zu)}}Au.disconnectSender=Iu;function Ou(Ku){let Zu=ju.get(Ku);if(!(!Zu||Zu.length===0)){for(const Qu of Zu){if(!Qu.signal)continue;let Yu=Qu.signal.sender;Qu.signal=null,Uu(Lu.get(Yu))}Uu(Zu)}}Au.disconnectReceiver=Ou;function Pu(Ku){Iu(Ku),Ou(Ku)}Au.disconnectAll=Pu;function Du(Ku,Zu){let Qu=Lu.get(Ku.sender);if(!(!Qu||Qu.length===0))for(let Yu=0,ed=Qu.length;Yu<ed;++Yu){let Xu=Qu[Yu];Xu.signal===Ku&&qu(Xu,Zu)}}Au.emit=Du;const Lu=new WeakMap,ju=new WeakMap,Bu=new Set,Fu=typeof requestAnimationFrame=="function"?requestAnimationFrame:setImmediate;function zu(Ku,Zu,Qu,Yu){return find$5(Ku,ed=>ed.signal===Zu&&ed.slot===Qu&&ed.thisArg===Yu)}function qu(Ku,Zu){let{signal:Qu,slot:Yu,thisArg:ed}=Ku;try{Yu.call(ed,Qu.sender,Zu)}catch(Xu){Au.exceptionHandler(Xu)}}function Uu(Ku){Bu.size===0&&Fu(Hu),Bu.add(Ku)}function Hu(){Bu.forEach(Vu),Bu.clear()}function Vu(Ku){ArrayExt.removeAllWhere(Ku,Gu)}function Gu(Ku){return Ku.signal===null}})(Private$G||(Private$G={}));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$F.DEFAULT_LINGER,this._standby=lo.standby||Private$F.DEFAULT_STANDBY,this._state={...Private$F.DEFAULT_STATE,timestamp:new Date().getTime()};const Ru=lo.frequency||{},Iu=Math.max(Ru.interval||0,Ru.max||0,Private$F.DEFAULT_FREQUENCY.max);this.frequency={...Private$F.DEFAULT_FREQUENCY,...Ru,max:Iu},this.name=lo.name||Private$F.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$F.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 Ou=()=>{this.isDisposed||this.tick!==Ru.promise||this._execute()};this._timeout=setTimeout(Ou,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$F.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$F.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$F;(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:Ou,interval:Pu,max:Du}=Ru;if(Pu===Poll.NEVER)return Pu;const Lu=Ou===!0?Au.DEFAULT_BACKOFF:Ou===!1?1:Ou,ju=$u(Pu,Iu.interval*Lu);return Math.min(Du,ju)}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$F||(Private$F={}));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:Ou}=this;if(Iu.phase==="resolved"){this.payload=new PromiseDelegate,Ou.resolve(Iu.payload);return}if(Iu.phase==="rejected"||Iu.phase==="stopped"){this.payload=new PromiseDelegate,Ou.promise.catch(Pu=>{}),Ou.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$3(){}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:Ou,queryKey:Pu,stale:Du}=Au;if(Pu){if(Ru){if(lo.queryHash!==hashQueryKeyByOptions(Pu,lo.options))return!1}else if(!partialMatchKey(lo.queryKey,Pu))return!1}if($u!=="all"){const Lu=lo.isActive();if($u==="active"&&!Lu||$u==="inactive"&&Lu)return!1}return!(typeof Du=="boolean"&&lo.isStale()!==Du||Iu&&Iu!==lo.state.fetchStatus||Ou&&!Ou(lo))}function matchMutation(Au,lo){const{exact:$u,status:Ru,predicate:Iu,mutationKey:Ou}=Au;if(Ou){if(!lo.options.mutationKey)return!1;if($u){if(hashKey(lo.options.mutationKey)!==hashKey(Ou))return!1}else if(!partialMatchKey(lo.options.mutationKey,Ou))return!1}return!(Ru&&lo.state.status!==Ru||Iu&&!Iu(lo))}function hashQueryKeyByOptions(Au,lo){return(lo?.queryKeyHashFn||hashKey)(Au)}function hashKey(Au){return JSON.stringify(Au,(lo,$u)=>isPlainObject$8($u)?Object.keys($u).sort().reduce((Ru,Iu)=>(Ru[Iu]=$u[Iu],Ru),{}):$u)}function partialMatchKey(Au,lo){if(Au===lo)return!0;if(typeof Au!=typeof lo)return!1;if(Au&&lo&&typeof Au=="object"&&typeof lo=="object"){if(Array.isArray(Au)&&Array.isArray(lo)){if(lo.length>Au.length)return!1;for(let Ru=0;Ru<lo.length;Ru++)if(!partialMatchKey(Au[Ru],lo[Ru]))return!1;return!0}const $u=Object.keys(lo);for(const Ru of $u)if(!partialMatchKey(Au[Ru],lo[Ru]))return!1;return!0}return!1}const hasOwn=Object.prototype.hasOwnProperty;function replaceEqualDeep(Au,lo,$u=0){if(Au===lo)return Au;if($u>500)return lo;const Ru=isPlainArray(Au)&&isPlainArray(lo);if(!Ru&&!(isPlainObject$8(Au)&&isPlainObject$8(lo)))return lo;const Iu=(Ru?Au:Object.keys(Au)).length,Ou=Ru?lo:Object.keys(lo),Pu=Ou.length,Du=Ru?new Array(Pu):{};let Lu=0;for(let ju=0;ju<Pu;ju++){const Bu=Ru?ju:Ou[ju],Fu=Au[Bu],zu=lo[Bu];if(Fu===zu){Du[Bu]=Fu,(Ru?ju<Iu:hasOwn.call(Au,Bu))&&Lu++;continue}if(Fu===null||zu===null||typeof Fu!="object"||typeof zu!="object"){Du[Bu]=zu;continue}const qu=replaceEqualDeep(Fu,zu,$u+1);Du[Bu]=qu,qu===Fu&&Lu++}return Iu===Pu&&Lu===Iu?Au:Du}function shallowEqualObjects(Au,lo){if(!lo||Object.keys(Au).length!==Object.keys(lo).length)return!1;for(const $u in Au)if(Au[$u]!==lo[$u])return!1;return!0}function isPlainArray(Au){return Array.isArray(Au)&&Au.length===Object.keys(Au).length}function isPlainObject$8(Au){if(!hasObjectPrototype(Au))return!1;const lo=Object.getPrototypeOf(Au),$u=lo?.constructor;if($u===void 0)return!0;if(typeof $u!="function")return!1;const Ru=$u.prototype;return!(!hasObjectPrototype(Ru)||!Ru.hasOwnProperty("isPrototypeOf")||lo!==Object.prototype)}function hasObjectPrototype(Au){return Object.prototype.toString.call(Au)==="[object Object]"}function sleep$2(Au){return new Promise(lo=>{timeoutManager.setTimeout(lo,Au)})}function replaceData(Au,lo,$u){return typeof $u.structuralSharing=="function"?$u.structuralSharing(Au,lo):$u.structuralSharing!==!1?replaceEqualDeep(Au,lo):lo}function addToEnd(Au,lo,$u=0){const Ru=[...Au,lo];return $u&&Ru.length>$u?Ru.slice(1):Ru}function addToStart(Au,lo,$u=0){const Ru=[lo,...Au];return $u&&Ru.length>$u?Ru.slice(0,-1):Ru}const skipToken=Symbol();function ensureQueryFn(Au,lo){return!Au.queryFn&&lo?.initialPromise?()=>lo.initialPromise:!Au.queryFn||Au.queryFn===skipToken?()=>Promise.reject(new Error(`Missing queryFn: '${Au.queryHash}'`)):Au.queryFn}function shouldThrowError(Au,lo){return typeof Au=="function"?Au(...lo):!!Au}function addConsumeAwareSignal(Au,lo,$u){let Ru=!1,Iu;return Object.defineProperty(Au,"signal",{enumerable:!0,get:()=>(Iu??=lo(),Ru||(Ru=!0,Iu.aborted?$u():Iu.addEventListener("abort",$u,{once:!0})),Iu)}),Au}let isServerFn=()=>isServer$1;const isServer=()=>isServerFn();var Subscribable=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(Au){return this.listeners.add(Au),this.onSubscribe(),()=>{this.listeners.delete(Au),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},FocusManager=class extends Subscribable{#e;#t;#r;constructor(){super(),this.#r=Au=>{if(typeof window<"u"&&window.addEventListener){const lo=()=>Au();return window.addEventListener("visibilitychange",lo,!1),()=>{window.removeEventListener("visibilitychange",lo)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(Au){this.#r=Au,this.#t?.(),this.#t=Au(lo=>{typeof lo=="boolean"?this.setFocused(lo):this.onFocus()})}setFocused(Au){this.#e!==Au&&(this.#e=Au,this.onFocus())}onFocus(){const Au=this.isFocused();this.listeners.forEach(lo=>{lo(Au)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}};const focusManager=new FocusManager,defaultScheduler=systemSetTimeoutZero;function createNotifyManager(){let Au=[],lo=0,$u=Du=>{Du()},Ru=Du=>{Du()},Iu=defaultScheduler;const Ou=Du=>{lo?Au.push(Du):Iu(()=>{$u(Du)})},Pu=()=>{const Du=Au;Au=[],Du.length&&Iu(()=>{Ru(()=>{Du.forEach(Lu=>{$u(Lu)})})})};return{batch:Du=>{let Lu;lo++;try{Lu=Du()}finally{lo--,lo||Pu()}return Lu},batchCalls:Du=>(...Lu)=>{Ou(()=>{Du(...Lu)})},schedule:Ou,setNotifyFunction:Du=>{$u=Du},setBatchNotifyFunction:Du=>{Ru=Du},setScheduler:Du=>{Iu=Du}}}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",Ou,Pu;const Du=new Promise((Ku,Zu)=>{Ou=Ku,Pu=Zu});Du.catch(noop$3);const Lu=()=>Iu!=="pending",ju=Ku=>{if(!Lu()){const Zu=new CancelledError(Ku);Hu(Zu),Au.onCancel?.(Zu)}},Bu=()=>{lo=!0},Fu=()=>{lo=!1},zu=()=>focusManager.isFocused()&&(Au.networkMode==="always"||onlineManager.isOnline())&&Au.canRun(),qu=()=>canFetch(Au.networkMode)&&Au.canRun(),Uu=Ku=>{Lu()||(Ru?.(),Iu="resolved",Ou(Ku))},Hu=Ku=>{Lu()||(Ru?.(),Iu="rejected",Pu(Ku))},Vu=()=>new Promise(Ku=>{Ru=Zu=>{(Lu()||zu())&&Ku(Zu)},Au.onPause?.()}).then(()=>{Ru=void 0,Lu()||Au.onContinue?.()}),Gu=()=>{if(Lu())return;let Ku;const Zu=$u===0?Au.initialPromise:void 0;try{Ku=Zu??Au.fn()}catch(Qu){Ku=Promise.reject(Qu)}Promise.resolve(Ku).then(Uu).catch(Qu=>{if(Lu())return;const Yu=Au.retry??(isServer()?0:3),ed=Au.retryDelay??defaultRetryDelay,Xu=typeof ed=="function"?ed($u,Qu):ed,rd=Yu===!0||typeof Yu=="number"&&$u<Yu||typeof Yu=="function"&&Yu($u,Qu);if(lo||!rd){Hu(Qu);return}$u++,Au.onFail?.($u,Qu),sleep$2(Xu).then(()=>zu()?void 0:Vu()).then(()=>{lo?Hu(Qu):Gu()})})};return{promise:Du,status:()=>Iu,cancel:ju,continue:()=>(Ru?.(),Du),cancelRetry:Bu,continueRetry:Fu,canStart:qu,start:()=>(qu()?Gu():Vu().then(Gu),Du)}}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,Ou=lo.state.data?.pages||[],Pu=lo.state.data?.pageParams||[];let Du={pages:[],pageParams:[]},Lu=0;const ju=async()=>{let Bu=!1;const Fu=Uu=>{addConsumeAwareSignal(Uu,()=>lo.signal,()=>Bu=!0)},zu=ensureQueryFn(lo.options,lo.fetchOptions),qu=async(Uu,Hu,Vu)=>{if(Bu)return Promise.reject(lo.signal.reason);if(Hu==null&&Uu.pages.length)return Promise.resolve(Uu);const Ku=(()=>{const ed={client:lo.client,queryKey:lo.queryKey,pageParam:Hu,direction:Vu?"backward":"forward",meta:lo.options.meta};return Fu(ed),ed})(),Zu=await zu(Ku),{maxPages:Qu}=lo.options,Yu=Vu?addToStart:addToEnd;return{pages:Yu(Uu.pages,Zu,Qu),pageParams:Yu(Uu.pageParams,Hu,Qu)}};if(Iu&&Ou.length){const Uu=Iu==="backward",Hu=Uu?getPreviousPageParam:getNextPageParam,Vu={pages:Ou,pageParams:Pu};Du=await qu(Vu,Hu(Ru,Vu),Uu)}else{const Uu=Au??Ou.length;do{const Hu=Lu===0?Pu[0]??Ru.initialPageParam:getNextPageParam(Ru,Du);if(Lu>0&&Hu==null)break;Du=await qu(Du,Hu),Lu++}while(Lu<Uu)}return Du};lo.options.persister?lo.fetchFn=()=>lo.options.persister?.(ju,{client:lo.client,queryKey:lo.queryKey,meta:lo.options.meta,signal:lo.signal},$u):lo.fetchFn=ju}}}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$3).catch(noop$3):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 Lu=this.observers.find(ju=>ju.options.queryFn);Lu&&this.setOptions(Lu.options)}const $u=new AbortController,Ru=Lu=>{Object.defineProperty(Lu,"signal",{enumerable:!0,get:()=>(this.#l=!0,$u.signal)})},Iu=()=>{const Lu=ensureQueryFn(this.options,lo),Bu=(()=>{const Fu={client:this.#i,queryKey:this.queryKey,meta:this.meta};return Ru(Fu),Fu})();return this.#l=!1,this.options.persister?this.options.persister(Lu,Bu,this):Lu(Bu)},Pu=(()=>{const Lu={fetchOptions:lo,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:Iu};return Ru(Lu),Lu})();(this.#e==="infinite"?infiniteQueryBehavior(this.options.pages):this.options.behavior)?.onFetch(Pu,this),this.#r=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==Pu.fetchOptions?.meta)&&this.#a({type:"fetch",meta:Pu.fetchOptions?.meta});const Du=this.#o=createRetryer({initialPromise:lo?.initialPromise,fn:Pu.fetchFn,onCancel:Lu=>{Lu instanceof CancelledError&&Lu.revert&&this.setState({...this.#r,fetchStatus:"idle"}),$u.abort()},onFail:(Lu,ju)=>{this.#a({type:"failed",failureCount:Lu,error:ju})},onPause:()=>{this.#a({type:"pause"})},onContinue:()=>{this.#a({type:"continue"})},retry:Pu.options.retry,retryDelay:Pu.options.retryDelay,networkMode:Pu.options.networkMode,canRun:()=>!0});try{const Lu=await Du.start();if(Lu===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(Lu),this.#n.config.onSuccess?.(Lu,this),this.#n.config.onSettled?.(Lu,this.state.error,this),Lu}catch(Lu){if(Lu instanceof CancelledError){if(Lu.silent)return this.#o.promise;if(Lu.revert){if(this.state.data===void 0)throw Lu;return this.state.data}}throw this.#a({type:"error",error:Lu}),this.#n.config.onError?.(Lu,this),this.#n.config.onSettled?.(this.state.data,Lu,this),Lu}finally{this.#o===Du&&(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;#f;#u;#d;#c;#p=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.#p.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 Ou=new Promise(Pu=>{Iu=Pu,Ru=this.#e.getQueryCache().subscribe(Du=>{Du.type==="updated"&&Du.query.queryHash===$u.queryHash&&$u.state.data!==void 0&&(Ru(),Pu(this.createResult($u,lo)))})});return Promise.race([$u.fetch().then(()=>{const Pu=this.createResult($u,lo);return Iu?.(Pu),Pu}).finally(()=>{Ru()}),Ou])}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$3)),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,Ou=this.#i,Pu=this.#o,Du=Au!==$u?Au.state:this.#r,{state:Lu}=Au;let ju={...Lu},Bu=!1,Fu;if(lo._optimisticResults){const Yu=this.hasListeners(),ed=!Yu&&shouldFetchOnMount(Au,lo),Xu=Yu&&shouldFetchOptionally(Au,$u,lo,Ru);(ed||Xu)&&(ju={...ju,...fetchState(Lu.data,Au.options)}),lo._optimisticResults==="isRestoring"&&(ju.fetchStatus="idle")}let{error:zu,errorUpdatedAt:qu,status:Uu}=ju;Fu=ju.data;let Hu=!1;if(lo.placeholderData!==void 0&&Fu===void 0&&Uu==="pending"){let Yu;Iu?.isPlaceholderData&&lo.placeholderData===Pu?.placeholderData?(Yu=Iu.data,Hu=!0):Yu=typeof lo.placeholderData=="function"?lo.placeholderData(this.#f?.state.data,this.#f):lo.placeholderData,Yu!==void 0&&(Uu="success",Fu=replaceData(Iu?.data,Yu,lo),Bu=!0)}if(lo.select&&Fu!==void 0&&!Hu)if(Iu&&Fu===Ou?.data&&lo.select===this.#l)Fu=this.#a;else try{this.#l=lo.select,Fu=lo.select(Fu),Fu=replaceData(Iu?.data,Fu,lo),this.#a=Fu,this.#s=null}catch(Yu){this.#s=Yu}else Fu===void 0&&(this.#s=null);this.#s&&(zu=this.#s,Fu=this.#a,qu=Date.now(),Uu="error",Bu=!1);const Vu=ju.fetchStatus==="fetching",Gu=Uu==="pending",Ku=Uu==="error",Zu=Gu&&Vu,Qu=Fu!==void 0;return{status:Uu,fetchStatus:ju.fetchStatus,isPending:Gu,isSuccess:Uu==="success",isError:Ku,isInitialLoading:Zu,isLoading:Zu,data:Fu,dataUpdatedAt:ju.dataUpdatedAt,error:zu,errorUpdatedAt:qu,failureCount:ju.fetchFailureCount,failureReason:ju.fetchFailureReason,errorUpdateCount:ju.errorUpdateCount,isFetched:Au.isFetched(),isFetchedAfterMount:ju.dataUpdateCount>Du.dataUpdateCount||ju.errorUpdateCount>Du.errorUpdateCount,isFetching:Vu,isRefetching:Vu&&!Gu,isLoadingError:Ku&&!Qu,isPaused:ju.fetchStatus==="paused",isPlaceholderData:Bu,isRefetchError:Ku&&Qu,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.#f=this.#t),shallowEqualObjects(lo,Au))return;this.#n=lo;const Ru=(()=>{if(!Au)return!0;const{notifyOnChangeProps:Iu}=this.options,Ou=typeof Iu=="function"?Iu():Iu;if(Ou==="all"||!Ou&&!this.#p.size)return!0;const Pu=new Set(Ou??this.#p);return this.options.throwOnError&&Pu.add("error"),Object.keys(this.#n).some(Du=>{const Lu=Du;return this.#n[Lu]!==Au[Lu]&&Pu.has(Lu)})})();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:(Pu,Du)=>{this.#i({type:"failed",failureCount:Pu,error:Du})},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",Ou=!Ru.canStart();try{if(Iu)lo();else{this.#i({type:"pending",variables:Au,isPaused:Ou}),this.#r.config.onMutate&&await this.#r.config.onMutate(Au,this,$u);const Du=await this.options.onMutate?.(Au,$u);Du!==this.state.context&&this.#i({type:"pending",context:Du,variables:Au,isPaused:Ou})}const Pu=await Ru.start();return await this.#r.config.onSuccess?.(Pu,Au,this.state.context,this,$u),await this.options.onSuccess?.(Pu,Au,this.state.context,$u),await this.#r.config.onSettled?.(Pu,null,this.state.variables,this.state.context,this,$u),await this.options.onSettled?.(Pu,null,Au,this.state.context,$u),this.#i({type:"success",data:Pu}),Pu}catch(Pu){try{await this.#r.config.onError?.(Pu,Au,this.state.context,this,$u)}catch(Du){Promise.reject(Du)}try{await this.options.onError?.(Pu,Au,this.state.context,$u)}catch(Du){Promise.reject(Du)}try{await this.#r.config.onSettled?.(void 0,Pu,this.state.variables,this.state.context,this,$u)}catch(Du){Promise.reject(Du)}try{await this.options.onSettled?.(void 0,Pu,Au,this.state.context,$u)}catch(Du){Promise.reject(Du)}throw this.#i({type:"error",error:Pu}),Pu}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(()=>{this.#e.forEach(Au=>{this.notify({type:"removed",mutation:Au})}),this.#e.clear(),this.#t.clear()})}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$3))))}};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(()=>{if(this.#n&&this.hasListeners()){const $u=this.#t.variables,Ru=this.#t.context,Iu={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(lo?.type==="success"){try{this.#n.onSuccess?.(lo.data,$u,Ru,Iu)}catch(Ou){Promise.reject(Ou)}try{this.#n.onSettled?.(lo.data,null,$u,Ru,Iu)}catch(Ou){Promise.reject(Ou)}}else if(lo?.type==="error"){try{this.#n.onError?.(lo.error,$u,Ru,Iu)}catch(Ou){Promise.reject(Ou)}try{this.#n.onSettled?.(void 0,lo.error,$u,Ru,Iu)}catch(Ou){Promise.reject(Ou)}}}this.listeners.forEach($u=>{$u(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 Ou=this.get(Iu);return Ou||(Ou=new Query({client:Au,queryKey:Ru,queryHash:Iu,options:Au.defaultQueryOptions(lo),state:$u,defaultOptions:Au.getQueryDefaults(Ru)}),this.add(Ou)),Ou}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,Ou=functionalUpdate(lo,Iu);if(Ou!==void 0)return this.#e.build(this,Ru).setData(Ou,{...$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(Ou=>{Ou.reset()}),this.refetchQueries({type:"active",predicate:Ou=>Iu.has(Ou)},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$3).catch(noop$3)}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 Ou=Iu.fetch(void 0,$u);return $u.throwOnError||(Ou=Ou.catch(noop$3)),Iu.state.fetchStatus==="paused"?Promise.resolve():Ou}));return Promise.all(Ru).then(noop$3)}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$3).catch(noop$3)}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$3).catch(noop$3)}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.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(),Ou=useQueryClient(),Pu=Ou.defaultQueryOptions(Au),Du=Ou.getQueryCache().get(Pu.queryHash),Lu=Au.subscribed!==!1;Pu._optimisticResults=Ru?"isRestoring":Lu?"optimistic":void 0,ensureSuspenseTimers(Pu),ensurePreventErrorBoundaryRetry(Pu,Iu,Du),useClearResetErrorBoundary(Iu);const[ju]=reactExports.useState(()=>new lo(Ou,Pu)),Bu=ju.getOptimisticResult(Pu),Fu=!Ru&&Lu;if(reactExports.useSyncExternalStore(reactExports.useCallback(zu=>{const qu=Fu?ju.subscribe(notifyManager.batchCalls(zu)):noop$3;return ju.updateResult(),qu},[ju,Fu]),()=>ju.getCurrentResult(),()=>ju.getCurrentResult()),reactExports.useEffect(()=>{ju.setOptions(Pu)},[Pu,ju]),shouldSuspend(Pu,Bu))throw fetchOptimistic(Pu,ju,Iu);if(getHasError({result:Bu,errorResetBoundary:Iu,throwOnError:Pu.throwOnError,query:Du,suspense:Pu.suspense}))throw Bu.error;return Pu.notifyOnChangeProps?Bu:ju.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(Pu=>Ru.subscribe(notifyManager.batchCalls(Pu)),[Ru]),()=>Ru.getCurrentResult(),()=>Ru.getCurrentResult()),Ou=reactExports.useCallback((...Pu)=>{Ru.mutate(Pu[0],Pu[1]).catch(noop$3)},[Ru]);if(Iu.error&&shouldThrowError(Ru.options.throwOnError,[Iu.error]))throw Iu.error;return{...Iu,mutate:Ou,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 Ou=0;Ou<Iu.length;Ou++){let Pu=Iu[Ou];for(;Pu.charAt(0)===" ";)Pu=Pu.substring(1);if(Pu.indexOf($u)===0)return Pu.substring($u.length,Pu.length)}}function setCookie(Au,lo,$u="/"){const Ru=new Date,Ou=Ru.getTime()+1e3*36e3;Ru.setTime(Ou),document.cookie=`${Au}=${lo}; expires=${Ru.toUTCString()}; SameSite=Lax; path=${$u}`}function deleteCookie$1(Au){document.cookie=`${Au}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`}function createError(Au){const lo=new Error(Au);return lo.source="ulid",lo}const ENCODING="0123456789ABCDEFGHJKMNPQRSTVWXYZ",ENCODING_LEN=ENCODING.length,TIME_MAX=Math.pow(2,48)-1,TIME_LEN=10,RANDOM_LEN=16;function randomChar(Au){let lo=Math.floor(Au()*ENCODING_LEN);return lo===ENCODING_LEN&&(lo=ENCODING_LEN-1),ENCODING.charAt(lo)}function encodeTime(Au,lo){if(isNaN(Au))throw new Error(Au+" must be a number");if(Au>TIME_MAX)throw createError("cannot encode time greater than "+TIME_MAX);if(Au<0)throw createError("time must be positive");if(Number.isInteger(Number(Au))===!1)throw createError("time must be an integer");let $u,Ru="";for(;lo>0;lo--)$u=Au%ENCODING_LEN,Ru=ENCODING.charAt($u)+Ru,Au=(Au-$u)/ENCODING_LEN;return Ru}function encodeRandom(Au,lo){let $u="";for(;Au>0;Au--)$u=randomChar(lo)+$u;return $u}function detectPrng(Au=!1,lo){lo||(lo=typeof window<"u"?window:null);const $u=lo&&(lo.crypto||lo.msCrypto);if($u)return()=>{const Ru=new Uint8Array(1);return $u.getRandomValues(Ru),Ru[0]/255};try{const Ru=require("crypto");return()=>Ru.randomBytes(1).readUInt8()/255}catch{}if(Au){try{console.error("secure crypto unusable, falling back to insecure Math.random()!")}catch{}return()=>Math.random()}throw createError("secure crypto unusable, insecure Math.random not allowed")}function factory$1(Au){return Au||(Au=detectPrng()),function($u){return isNaN($u)&&($u=Date.now()),encodeTime($u,TIME_LEN)+encodeRandom(RANDOM_LEN,Au)}}const ulid$1=factory$1(),asDisplayName=(Au,lo)=>Au?lo?Au+" "+lo:Au:lo??"",namesAsInitials=(Au,lo)=>((Au||" ").charAt(0)+(lo||" ").charAt(0)).toLocaleUpperCase().trim(),toFriendlyName=(Au,lo)=>Au||lo||"";function parseJwtPayload(Au){try{const lo=Au.split(".");if(lo.length<2)return null;const $u=lo[1].replace(/-/g,"+").replace(/_/g,"/"),Ru=$u.padEnd($u.length+(4-$u.length%4)%4,"="),Iu=atob(Ru);return JSON.parse(Iu)}catch{return null}}function getJwtExpiryMs(Au){if(!Au)return null;const $u=parseJwtPayload(Au)?.exp;return typeof $u=="number"&&Number.isFinite($u)?$u*1e3:null}function isJwtExpired(Au,lo=0){const $u=getJwtExpiryMs(Au);return $u===null?!1:$u-lo*1e3<=Date.now()}var lib$e={},activitymonitor={};const require$$0$7=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$7;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(Du){this.startLine=Du,this.code="",this.endLine=-1}}lo.MarkdownCodeBlock=Ru;function Iu(Pu){return $u.indexOf(Pu)>-1}lo.isMarkdown=Iu;function Ou(Pu){if(!Pu||Pu==="")return[];const Du=Pu.split(`
242
+ `)[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 Ou={plugin:lo,id:Iu.id??lo,order:Iu.order??0,value:Ru,seq:this.seq++},Pu=this.byPoint.get($u.id);Pu?Pu.push(Ou):this.byPoint.set($u.id,[Ou]);let Du=!1;const Lu=()=>{if(Du)return;Du=!0;const Bu=this.byPoint.get($u.id);if(Bu){const Fu=Bu.indexOf(Ou);Fu>=0&&Bu.splice(Fu,1),Bu.length===0&&this.byPoint.delete($u.id)}this.byPlugin.get(lo)?.delete(Lu)},ju=this.byPlugin.get(lo);return ju?ju.add(Lu):this.byPlugin.set(lo,new Set([Lu])),Lu}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:Ou,value:Pu})=>({plugin:Ru,id:Iu,order:Ou,value:Pu}))}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:Ou})=>({plugin:$u,id:Ru,order:Iu,value:Ou}))}))}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 Ou=!1;const Pu=()=>{Ou||(Ou=!0,this.byId.get($u.id)===Iu&&this.byId.delete($u.id),this.byPlugin.get(lo)?.delete(Pu),this.notify())},Du=this.byPlugin.get(lo);return Du?Du.add(Pu):this.byPlugin.set(lo,new Set([Pu])),this.notify(),Pu}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 Ou;try{Ou=Iu.value.check(lo)}catch(Pu){Ou=Pu instanceof Error?Pu.message:String(Pu)}isRefusal(Ou)&&$u.push({plugin:Iu.plugin,reason:Ou})}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,Ou=Au.map(Pu=>({ref:Pu}));for(;Ou.length>0;){const Pu=Ou.shift();if(!Pu?.ref)continue;const{ref:Du,from:Lu}=Pu;if(isExtension(Du)){Iu.set(Du.name,Du);for(const Fu of Du.plugins)Ou.push({ref:Fu,from:Du.name});continue}if(isLazyPluginRef(Du)){if(!lo.has(Du.name)){$u.set(Du.name,Du),lo.set(Du.name,placeholderFor(Du)),Lu&&Ru.set(Du.name,Lu);for(const Fu of Du.dependencies??[])Ou.push({ref:Fu})}continue}const Bu=asConfigured(Du).plugin;if(!lo.has(Bu.name)){lo.set(Bu.name,Bu),Lu&&Ru.set(Bu.name,Lu);for(const Fu of Bu.dependencies??[])Ou.push({ref:Fu})}}return{plugins:Array.from(lo.values()),lazyByName:$u,extensionOf:Ru,extensions:Iu}}function topoSort(Au){const lo=new Map(Au.map(Pu=>[Pu.name,Pu])),$u=new Set,Ru=new Set,Iu=[];function Ou(Pu){if(Ru.has(Pu))return;if($u.has(Pu))throw new Error(`Circular dependency detected at ${Pu}`);$u.add(Pu);const Du=lo.get(Pu);if(!Du)throw new Error(`Unknown plugin ${Pu}`);for(const Lu of Du.dependencies??[])Ou(asConfigured(Lu).plugin.name);$u.delete(Pu),Ru.add(Pu),Iu.push(Du)}for(const Pu of Au)Ou(Pu.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 Lu of Ru.dependencies??[])$u.push(Lu);continue}const Iu=asConfigured(Ru),Ou=Iu.plugin.name,Pu=lo.get(Ou)??{},Du=shallowMergeConfig(Pu,Iu.config);lo.set(Ou,Du);for(const Lu of Iu.plugin.dependencies??[])$u.push(Lu)}return lo}function buildReactorFromPlugins(Au,lo={}){const{plugins:$u,lazyByName:Ru,extensionOf:Iu,extensions:Ou}=normalizePlugins(Au),Pu=topoSort($u),Du=new Map(Pu.map(gd=>[gd.name,gd])),Lu=collectOverrides(Au),ju=new Map,Bu=new Set,Fu=new ContributionRegistry,zu=new CommandRegistry$1;let qu=0,Uu=0,Hu,Vu=!1;const Gu=new Map,Ku=new Set,Zu=new Set;let Qu=new Set;function Yu(){if(!(Uu>0)){qu+=1;for(const gd of Bu)gd()}}function ed(gd){Uu+=1;try{return gd()}finally{Uu-=1,Uu===0&&Yu()}}for(const gd of Pu){const Ed=mergeWithDefaults(gd,Lu.get(gd.name)??{});ju.set(gd.name,{plugin:gd,config:Ed,enabled:!0,activated:!1,extension:Iu.get(gd.name),lazy:Ru.get(gd.name),loaded:!Ru.has(gd.name)})}for(const gd of Pu){for(const Ed of gd.conflictsWith??[])if(Du.has(Ed))throw new Error(`Plugin ${gd.name} conflicts with ${Ed}`);for(const Ed of gd.peerDependencies??[])if(!Ed.optional&&!Du.has(Ed.name)&&lo.strictPeerDependencies)throw new Error(`Missing required peer dependency ${Ed.name} for ${gd.name}`)}function Xu(gd){const Ed=[];for(const xd of Pu){const Od=ju.get(xd.name);!Od||Od.activated||matchesActivation(Od.plugin.activationEvents,gd)&&Ed.push(xd.name)}return Ed}function rd(gd){if(!Ku.has(gd.id)){Ku.add(gd.id);const Ed=onContributionPoint(gd);Xu(Ed).length>0&&Promise.resolve().then(()=>wd(Ed))}return Fu.get(gd)}const nd={hasPlugin(gd){return ju.has(gd)},getOutput(gd){return ju.get(gd)?.outputValue},getRequiredBackendPlugins(gd){return ju.get(gd)?.plugin.requiredBackendPlugins??[]},getOptionalBackendPlugins(gd){return ju.get(gd)?.plugin.optionalBackendPlugins??[]},getManifest(gd){const Ed=ju.get(gd);if(!Ed)return;const{plugin:xd}=Ed;return{name:xd.name,version:xd.version,displayName:xd.displayName??xd.name,description:xd.description,octicon:xd.octicon,emoji:xd.emoji,extension:Ed.extension,requiredBackendPlugins:xd.requiredBackendPlugins??[],optionalBackendPlugins:xd.optionalBackendPlugins??[],loaded:Ed.loaded,lazy:!!Ed.lazy,activated:Ed.activated,disabledBy:Ed.enabled?void 0:Ed.disabledBy??"user",loadError:Ed.loadError?.message,activationEvents:xd.activationEvents??[ON_STARTUP],deactivationEvents:xd.deactivationEvents??[],contributionPoints:(xd.contributionPoints??[]).map(Od=>Od.id),contributesTo:[...new Set((xd.contributes??[]).map(Od=>Od.point.id))]}},isEnabled(gd){return ju.get(gd)?.enabled??!1},getContributions(gd){return rd(gd)},checkGate(gd,Ed){return resolveGate(rd(gd),Ed)}};function od(gd,Ed){return{plugin:Ed.plugin,config:Ed.config,state:{getConfig:()=>Ed.config,getInit:()=>Ed.initValue,getOutput:()=>Ed.outputValue},reactor:nd,contribute(xd,Od,Bd){const Gd=Fu.add(gd,xd,Od,Bd);Yu();let Ud=!1;return()=>{Ud||(Ud=!0,Gd(),Yu())}},registerCommand(xd){const Od=zu.add(gd,xd);Yu();let Bd=!1;return()=>{Bd||(Bd=!0,Od(),Yu())}}}}function ad(gd){const Ed=ju.get(gd);if(!Ed)throw new Error(`Unknown plugin ${gd}`);if(!Ed.loaded)return;const xd=od(gd,Ed);Ed.initValue=Ed.plugin.init?.(xd),Ed.outputValue=Ed.plugin.build?.(xd)}function ld(gd){const Ed=ju.get(gd);if(!Ed||!Ed.enabled||!Ed.loaded)return;const xd=od(gd,Ed);for(const Od of Ed.plugin.contributes??[])Fu.add(gd,Od.point,Od.value,Od.options);for(const Od of Ed.plugin.commands??[])zu.add(gd,Od);Yu(),Ed.registerDispose=Ed.plugin.register?.(xd)??void 0,Ed.afterDispose=Ed.plugin.afterRegistration?.(xd)??void 0}function fd(gd){const Ed=ju.get(gd);!Ed||Ed.activated||!Ed.loaded||(Ed.activated=!0,ed(()=>{Ed.enabled&&(Ed.plugin.preserveOutput&&Ed.outputValue!==void 0||ad(gd),ld(gd))}))}async function pd(gd){const Ed=ju.get(gd);if(!(!Ed?.lazy||Ed.loaded)){Ed.loading??=Promise.resolve().then(()=>Ed.lazy.load());try{const xd=await Ed.loading;if(Ed.loaded)return;const Od=xd.default??xd;if(!Od||typeof Od!="object"||!Od.name)throw new Error(`Lazy plugin ${gd} did not resolve to a plugin`);Ed.plugin=mergeLoaded(Ed.lazy,Od),Ed.config=mergeWithDefaults(Ed.plugin,Lu.get(gd)??{}),Ed.loaded=!0}catch(xd){Ed.loadError=xd instanceof Error?xd:new Error(String(xd)),Yu()}}}function Sd(gd){const Ed=ju.get(gd);if(!Ed||Ed.activated)return Promise.resolve();const xd=Gu.get(gd);if(xd)return xd;const Od=(async()=>{for(const Bd of Ed.plugin.dependencies??[])await Sd(asConfigured(Bd).plugin.name);Ed.lazy&&!Ed.loaded&&await pd(gd),fd(gd),Zu.delete(gd)})().finally(()=>{Gu.delete(gd)});return Gu.set(gd,Od),Od}async function wd(gd){const Ed=Xu(gd);if(Ed.length===0)return[];for(const xd of Ed){const Od=ju.get(xd);Od?.lazy&&!Od.loaded&&(Od.loading??=Promise.resolve().then(()=>Od.lazy.load()))}for(const xd of Ed)await Sd(xd);return Ed.filter(xd=>ju.get(xd)?.activated)}function bd(gd){const Ed=new Set([gd]);for(const xd of Pu)(xd.dependencies??[]).some(Bd=>Ed.has(asConfigured(Bd).plugin.name))&&Ed.add(xd.name);return Ed.delete(gd),Pu.map(xd=>xd.name).filter(xd=>Ed.has(xd)).reverse()}function Td(gd){return(ju.get(gd)?.plugin?.dependencies??[]).every(xd=>ju.get(asConfigured(xd).plugin.name)?.enabled??!0)}function Pd(gd){const Ed=ju.get(gd);if(!Ed||Ed.enabled||(Ed.enabled=!0,Ed.disabledBy=void 0,!Ed.loaded||!Ed.activated))return;Ed.plugin.preserveOutput&&Ed.outputValue!==void 0||ad(gd),ld(gd)}function ud(gd,Ed="other"){const xd=ju.get(gd);if(!xd)throw new Error(`Unknown plugin ${gd}`);if(Ed==="other"&&Zu.delete(gd),!xd.activated)return[];const Od=[];if(ed(()=>{for(const Bd of bd(gd)){const Gd=ju.get(Bd);Gd?.activated&&(hd(Bd),Gd.activated=!1,md(Bd),Od.push(Bd))}hd(gd),xd.activated=!1,md(gd),Od.push(gd)}),Ed==="other")for(const Bd of Od)Zu.delete(Bd);return Od}function md(gd){const Ed=ju.get(gd)?.plugin.activationEvents??[];for(const xd of Ed)xd.startsWith("onContributionPoint:")&&Ku.delete(xd.slice(20))}function _d(gd){const Ed=[];for(const xd of Pu){const Od=ju.get(xd.name);Od?.activated&&matchesDeactivation(Od.plugin.deactivationEvents,gd)&&Ed.push(...ud(xd.name))}return Ed}function hd(gd){const Ed=ju.get(gd);Ed&&(Ed.afterDispose?.(),Ed.afterDispose=void 0,Ed.registerDispose?.(),Ed.registerDispose=void 0,Fu.disposePlugin(gd),zu.disposePlugin(gd))}return{...nd,start(){Vu=!0,ed(()=>{const gd=Pu.filter(Ed=>{const xd=ju.get(Ed.name);return xd&&xd.loaded&&!xd.activated&&activatesAtStartup(xd.plugin.activationEvents)});for(const Ed of gd)ju.get(Ed.name).activated=!0,ad(Ed.name);for(const Ed of gd)ld(Ed.name)}),Hu=wd(ON_STARTUP).then(()=>{})},whenReady(){return Hu??Promise.resolve()},async fire(gd){const Ed=_d(gd),xd=await wd(gd);return{deactivated:Ed,activated:xd}},deactivate(gd){ud(gd)},async setBackendPlugins(gd){Qu=new Set(gd);const Ed=Bd=>(ju.get(Bd)?.plugin.requiredBackendPlugins??[]).every(Gd=>Qu.has(Gd)),xd=[];for(const Bd of Pu){if(!ju.get(Bd.name)?.activated||Ed(Bd.name))continue;const Ud=ud(Bd.name,"backend");for(const Md of Ud)Zu.add(Md);xd.push(...Ud)}const Od=[];for(const Bd of Pu){const Gd=Bd.name;!Zu.has(Gd)||!Ed(Gd)||!ju.get(Gd)?.enabled||(Zu.delete(Gd),await Sd(Gd),ju.get(Gd)?.activated&&Od.push(Gd))}return{deactivated:xd,activated:Od}},async install(gd){const Ed=normalizePlugins([gd]),xd=Ed.plugins.filter(Ud=>!ju.has(Ud.name));if(xd.length===0)return[];for(const Ud of xd)for(const Md of Ud.conflictsWith??[])if(Du.has(Md)||xd.some(zd=>zd.name===Md))throw new Error(`Plugin ${Ud.name} conflicts with ${Md}`);for(const[Ud,Md]of Ed.lazyByName)Ru.set(Ud,Md);for(const[Ud,Md]of Ed.extensionOf)Iu.set(Ud,Md);for(const[Ud,Md]of Ed.extensions)Ou.set(Ud,Md);const Od=collectOverrides([gd]);for(const Ud of xd)Du.set(Ud.name,Ud),ju.set(Ud.name,{plugin:Ud,config:mergeWithDefaults(Ud,Od.get(Ud.name)??{}),enabled:!0,activated:!1,extension:Iu.get(Ud.name),lazy:Ru.get(Ud.name),loaded:!Ru.has(Ud.name)});const Bd=topoSort([...Pu,...xd]);if(Pu.splice(0,Pu.length,...Bd),Yu(),!Vu)return xd.map(Ud=>Ud.name);const Gd=[];for(const Ud of Bd)xd.some(Md=>Md.name===Ud.name)&&(Gd.push(Ud.name),activatesAtStartup(Ud.activationEvents)&&await Sd(Ud.name));return Gd},stop(){Vu=!1,ed(()=>{for(const gd of[...Pu].reverse()){hd(gd.name);const Ed=ju.get(gd.name);Ed&&(Ed.activated=!1)}Ku.clear()})},enable(gd){const Ed=ju.get(gd);if(!Ed)throw new Error(`Unknown plugin ${gd}`);Ed.enabled||ed(()=>{Pd(gd);for(const xd of[...bd(gd)].reverse()){const Od=ju.get(xd);!Od||Od.enabled||Od.disabledBy==="dependency"&&Td(xd)&&Pd(xd)}})},disable(gd){const Ed=ju.get(gd);if(!Ed)throw new Error(`Unknown plugin ${gd}`);Ed.enabled&&ed(()=>{for(const xd of bd(gd)){const Od=ju.get(xd);Od?.enabled&&(Od.enabled=!1,Od.disabledBy="dependency",hd(xd))}Ed.enabled=!1,Ed.disabledBy="user",hd(gd)})},subscribe(gd){return Bu.add(gd),()=>{Bu.delete(gd)}},listPlugins(){return Pu.map(gd=>gd.name)},listExtensions(){return[...Ou.keys()]},getExtensionManifest(gd){const Ed=Ou.get(gd);if(Ed)return{name:Ed.name,version:Ed.version,displayName:Ed.displayName??Ed.name,description:Ed.description,octicon:Ed.octicon,emoji:Ed.emoji,plugins:Pu.filter(xd=>Iu.get(xd.name)===gd).map(xd=>xd.name)}},getConfig(gd){return ju.get(gd)?.config},describeContributions(){return Fu.describe()},listCommands(){return zu.list()},getCommand(gd){return zu.get(gd)},executeCommand(gd,Ed){return zu.execute(gd,Ed)},getDependencies(gd){return(ju.get(gd)?.plugin.dependencies??[]).map(Ed=>asConfigured(Ed).plugin.name)},getRevision(){return qu}}}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,Ou)=>Ru!==""||Iu===Ou.length-1);for(const[Ru,Iu]of $u.entries()){const Ou=Iu.toLowerCase(),Pu=MODIFIERS[Ou];if(Pu&&Ru<$u.length-1){lo[Pu]=!0;continue}const Du=Iu===""?"+":KEY_ALIASES[Ou]??Ou;lo.key=Du}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,Ou=lo.meta||lo.mod&&$u;return Au.ctrlKey===Iu&&Au.metaKey===Ou&&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,Ou=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:"",Ou].join(""):[Ru?OTHER_LABELS.ctrl:"",Iu&&!Ru?OTHER_LABELS.meta:"",$u.alt?OTHER_LABELS.alt:"",$u.shift?OTHER_LABELS.shift:"",Ou].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,Ou]of Object.entries($u)){const{shareConfig:Pu,...Du}=lo[Iu]??{};Ru[Iu]={lib:()=>Ou,version:Au[Iu],...Du,shareConfig:{singleton:!0,requiredVersion:!1,...Pu}}}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(/^\.\//,"")}`,Ou=await Ru.loadRemote(Iu);if(!Ou)throw new Error(`${lo?.name??$u}: the container at ${Au} exposes no ${Iu}.`);return Ou}}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 Ou=missingSharedModules();Ou.length>0&&console.warn(`[reactor] loading ${Au.name} from ${Au.entry} with these modules unpublished: ${Ou.join(", ")}. If it reaches for one it will get its own copy — call setReactorSharedModules() from the host before loading remotes.`);const Pu=await $u(Au.entry,{name:Au.name,scope:Au.scope,module:Au.module,type:Au.type,allowedOrigins:Iu}),Du=Au.export?Pu[Au.export]:Pu.default??Pu;if(!Du)throw new Error(`${Au.name}: ${Au.entry} has no ${Au.export?`export "${Au.export}"`:"default export"}.`);return Du}})}async function bootstrapExtensions(Au,lo={}){const{fetchJson:$u,allowedOrigins:Ru,...Iu}=lo,Ou=Au.replace(/\/+$/,""),Pu=`${Ou}/plugins/frontend-extensions`,Du={...Iu,allowedOrigins:/^[a-z]+:\/\//i.test(Ou)?[...Ru??[],Ou]:Ru};let Lu;try{Lu=($u?await $u(Pu):await fetch(Pu).then(Bu=>{if(!Bu.ok)throw new Error(`HTTP ${Bu.status}`);return Bu.json()}))??[]}catch(ju){return console.warn(`[reactor] could not read ${Pu}:`,ju),[]}return Lu.map(ju=>{const Bu=/^[a-z]+:\/\//i.test(ju.entry)?ju.entry:`${Ou}${ju.entry}`,Fu=ju.kind==="federated",zu=(ju.plugins??[]).map(qu=>{const Uu=qu.scope??ju.remoteName,Hu=qu.module??ju.module,Vu={...qu,entry:Bu,apiVersion:ju.apiVersion,scope:Uu,module:Hu,type:qu.type||ju.remoteType||void 0};return(Fu||qu.scope)&&Uu?defineFederatedPlugin({...Vu,scope:Uu},Du):defineRemotePlugin(Vu,Du)});return defineExtension({name:ju.name,version:ju.version,displayName:ju.displayName,description:ju.description,octicon:ju.octicon,emoji:ju.emoji,plugins:zu})})}const AgentTools=defineContributionPoint("reactor.agentTools");var ArrayExt;(function(Au){function lo(Xu,rd,nd=0,od=-1){let ad=Xu.length;if(ad===0)return-1;nd<0?nd=Math.max(0,nd+ad):nd=Math.min(nd,ad-1),od<0?od=Math.max(0,od+ad):od=Math.min(od,ad-1);let ld;od<nd?ld=od+1+(ad-nd):ld=od-nd+1;for(let fd=0;fd<ld;++fd){let pd=(nd+fd)%ad;if(Xu[pd]===rd)return pd}return-1}Au.firstIndexOf=lo;function $u(Xu,rd,nd=-1,od=0){let ad=Xu.length;if(ad===0)return-1;nd<0?nd=Math.max(0,nd+ad):nd=Math.min(nd,ad-1),od<0?od=Math.max(0,od+ad):od=Math.min(od,ad-1);let ld;nd<od?ld=nd+1+(ad-od):ld=nd-od+1;for(let fd=0;fd<ld;++fd){let pd=(nd-fd+ad)%ad;if(Xu[pd]===rd)return pd}return-1}Au.lastIndexOf=$u;function Ru(Xu,rd,nd=0,od=-1){let ad=Xu.length;if(ad===0)return-1;nd<0?nd=Math.max(0,nd+ad):nd=Math.min(nd,ad-1),od<0?od=Math.max(0,od+ad):od=Math.min(od,ad-1);let ld;od<nd?ld=od+1+(ad-nd):ld=od-nd+1;for(let fd=0;fd<ld;++fd){let pd=(nd+fd)%ad;if(rd(Xu[pd],pd))return pd}return-1}Au.findFirstIndex=Ru;function Iu(Xu,rd,nd=-1,od=0){let ad=Xu.length;if(ad===0)return-1;nd<0?nd=Math.max(0,nd+ad):nd=Math.min(nd,ad-1),od<0?od=Math.max(0,od+ad):od=Math.min(od,ad-1);let ld;nd<od?ld=nd+1+(ad-od):ld=nd-od+1;for(let fd=0;fd<ld;++fd){let pd=(nd-fd+ad)%ad;if(rd(Xu[pd],pd))return pd}return-1}Au.findLastIndex=Iu;function Ou(Xu,rd,nd=0,od=-1){let ad=Ru(Xu,rd,nd,od);return ad!==-1?Xu[ad]:void 0}Au.findFirstValue=Ou;function Pu(Xu,rd,nd=-1,od=0){let ad=Iu(Xu,rd,nd,od);return ad!==-1?Xu[ad]:void 0}Au.findLastValue=Pu;function Du(Xu,rd,nd,od=0,ad=-1){let ld=Xu.length;if(ld===0)return 0;od<0?od=Math.max(0,od+ld):od=Math.min(od,ld-1),ad<0?ad=Math.max(0,ad+ld):ad=Math.min(ad,ld-1);let fd=od,pd=ad-od+1;for(;pd>0;){let Sd=pd>>1,wd=fd+Sd;nd(Xu[wd],rd)<0?(fd=wd+1,pd-=Sd+1):pd=Sd}return fd}Au.lowerBound=Du;function Lu(Xu,rd,nd,od=0,ad=-1){let ld=Xu.length;if(ld===0)return 0;od<0?od=Math.max(0,od+ld):od=Math.min(od,ld-1),ad<0?ad=Math.max(0,ad+ld):ad=Math.min(ad,ld-1);let fd=od,pd=ad-od+1;for(;pd>0;){let Sd=pd>>1,wd=fd+Sd;nd(Xu[wd],rd)>0?pd=Sd:(fd=wd+1,pd-=Sd+1)}return fd}Au.upperBound=Lu;function ju(Xu,rd,nd){if(Xu===rd)return!0;if(Xu.length!==rd.length)return!1;for(let od=0,ad=Xu.length;od<ad;++od)if(nd?!nd(Xu[od],rd[od]):Xu[od]!==rd[od])return!1;return!0}Au.shallowEqual=ju;function Bu(Xu,rd={}){let{start:nd,stop:od,step:ad}=rd;if(ad===void 0&&(ad=1),ad===0)throw new Error("Slice `step` cannot be zero.");let ld=Xu.length;nd===void 0?nd=ad<0?ld-1:0:nd<0?nd=Math.max(nd+ld,ad<0?-1:0):nd>=ld&&(nd=ad<0?ld-1:ld),od===void 0?od=ad<0?-1:ld:od<0?od=Math.max(od+ld,ad<0?-1:0):od>=ld&&(od=ad<0?ld-1:ld);let fd;ad<0&&od>=nd||ad>0&&nd>=od?fd=0:ad<0?fd=Math.floor((od-nd+1)/ad+1):fd=Math.floor((od-nd-1)/ad+1);let pd=[];for(let Sd=0;Sd<fd;++Sd)pd[Sd]=Xu[nd+Sd*ad];return pd}Au.slice=Bu;function Fu(Xu,rd,nd){let od=Xu.length;if(od<=1||(rd<0?rd=Math.max(0,rd+od):rd=Math.min(rd,od-1),nd<0?nd=Math.max(0,nd+od):nd=Math.min(nd,od-1),rd===nd))return;let ad=Xu[rd],ld=rd<nd?1:-1;for(let fd=rd;fd!==nd;fd+=ld)Xu[fd]=Xu[fd+ld];Xu[nd]=ad}Au.move=Fu;function zu(Xu,rd=0,nd=-1){let od=Xu.length;if(!(od<=1))for(rd<0?rd=Math.max(0,rd+od):rd=Math.min(rd,od-1),nd<0?nd=Math.max(0,nd+od):nd=Math.min(nd,od-1);rd<nd;){let ad=Xu[rd],ld=Xu[nd];Xu[rd++]=ld,Xu[nd--]=ad}}Au.reverse=zu;function qu(Xu,rd,nd=0,od=-1){let ad=Xu.length;if(ad<=1||(nd<0?nd=Math.max(0,nd+ad):nd=Math.min(nd,ad-1),od<0?od=Math.max(0,od+ad):od=Math.min(od,ad-1),nd>=od))return;let ld=od-nd+1;if(rd>0?rd=rd%ld:rd<0&&(rd=(rd%ld+ld)%ld),rd===0)return;let fd=nd+rd;zu(Xu,nd,fd-1),zu(Xu,fd,od),zu(Xu,nd,od)}Au.rotate=qu;function Uu(Xu,rd,nd=0,od=-1){let ad=Xu.length;if(ad===0)return;nd<0?nd=Math.max(0,nd+ad):nd=Math.min(nd,ad-1),od<0?od=Math.max(0,od+ad):od=Math.min(od,ad-1);let ld;od<nd?ld=od+1+(ad-nd):ld=od-nd+1;for(let fd=0;fd<ld;++fd)Xu[(nd+fd)%ad]=rd}Au.fill=Uu;function Hu(Xu,rd,nd){let od=Xu.length;rd<0?rd=Math.max(0,rd+od):rd=Math.min(rd,od);for(let ad=od;ad>rd;--ad)Xu[ad]=Xu[ad-1];Xu[rd]=nd}Au.insert=Hu;function Vu(Xu,rd){let nd=Xu.length;if(rd<0&&(rd+=nd),rd<0||rd>=nd)return;let od=Xu[rd];for(let ad=rd+1;ad<nd;++ad)Xu[ad-1]=Xu[ad];return Xu.length=nd-1,od}Au.removeAt=Vu;function Gu(Xu,rd,nd=0,od=-1){let ad=lo(Xu,rd,nd,od);return ad!==-1&&Vu(Xu,ad),ad}Au.removeFirstOf=Gu;function Ku(Xu,rd,nd=-1,od=0){let ad=$u(Xu,rd,nd,od);return ad!==-1&&Vu(Xu,ad),ad}Au.removeLastOf=Ku;function Zu(Xu,rd,nd=0,od=-1){let ad=Xu.length;if(ad===0)return 0;nd<0?nd=Math.max(0,nd+ad):nd=Math.min(nd,ad-1),od<0?od=Math.max(0,od+ad):od=Math.min(od,ad-1);let ld=0;for(let fd=0;fd<ad;++fd)nd<=od&&fd>=nd&&fd<=od&&Xu[fd]===rd||od<nd&&(fd<=od||fd>=nd)&&Xu[fd]===rd?ld++:ld>0&&(Xu[fd-ld]=Xu[fd]);return ld>0&&(Xu.length=ad-ld),ld}Au.removeAllOf=Zu;function Qu(Xu,rd,nd=0,od=-1){let ad,ld=Ru(Xu,rd,nd,od);return ld!==-1&&(ad=Vu(Xu,ld)),{index:ld,value:ad}}Au.removeFirstWhere=Qu;function Yu(Xu,rd,nd=-1,od=0){let ad,ld=Iu(Xu,rd,nd,od);return ld!==-1&&(ad=Vu(Xu,ld)),{index:ld,value:ad}}Au.removeLastWhere=Yu;function ed(Xu,rd,nd=0,od=-1){let ad=Xu.length;if(ad===0)return 0;nd<0?nd=Math.max(0,nd+ad):nd=Math.min(nd,ad-1),od<0?od=Math.max(0,od+ad):od=Math.min(od,ad-1);let ld=0;for(let fd=0;fd<ad;++fd)nd<=od&&fd>=nd&&fd<=od&&rd(Xu[fd],fd)||od<nd&&(fd<=od||fd>=nd)&&rd(Xu[fd],fd)?ld++:ld>0&&(Xu[fd-ld]=Xu[fd]);return ld>0&&(Xu.length=ad-ld),ld}Au.removeAllWhere=ed})(ArrayExt||(ArrayExt={}));function*chain$1(...Au){for(const lo of Au)yield*lo}function*empty$4(){}function*enumerate(Au,lo=0){for(const $u of Au)yield[lo++,$u]}function*filter$5(Au,lo){let $u=0;for(const Ru of Au)lo(Ru,$u++)&&(yield Ru)}function find$5(Au,lo){let $u=0;for(const Ru of Au)if(lo(Ru,$u++))return Ru}function findIndex$1(Au,lo){let $u=0;for(const Ru of Au)if(lo(Ru,$u++))return $u-1;return-1}function min$2(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$2(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 Ou of Au)$u?(Ru=Ou,Iu=Ou,$u=!1):lo(Ou,Ru)<0?Ru=Ou:lo(Ou,Iu)>0&&(Iu=Ou);return $u?void 0:[Ru,Iu]}function toArray$2(Au){return Array.from(Au)}function toObject(Au){const lo={};for(const[$u,Ru]of Au)lo[$u]=Ru;return lo}function each$1(Au,lo){let $u=0;for(const Ru of Au)if(lo(Ru,$u++)===!1)return}function every$3(Au,lo){let $u=0;for(const Ru of Au)if(lo(Ru,$u++)===!1)return!1;return!0}function some$2(Au,lo){let $u=0;for(const Ru of Au)if(lo(Ru,$u++))return!0;return!1}function*map$8(Au,lo){let $u=0;for(const Ru of Au)yield lo(Ru,$u++)}function*range$4(Au,lo,$u){lo===void 0?(lo=Au,Au=0,$u=1):$u===void 0&&($u=1);const Ru=Private$I.rangeLength(Au,lo,$u);for(let Iu=0;Iu<Ru;Iu++)yield Au+$u*Iu}var Private$I;(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$I||(Private$I={}));function reduce$1(Au,lo,$u){const Ru=Au[Symbol.iterator]();let Iu=0,Ou=Ru.next();if(Ou.done&&$u===void 0)throw new TypeError("Reduce of empty iterable with no initial value.");if(Ou.done)return $u;let Pu=Ru.next();if(Pu.done&&$u===void 0)return Ou.value;if(Pu.done)return lo($u,Ou.value,Iu++);let Du;$u===void 0?Du=lo(Ou.value,Pu.value,Iu++):Du=lo(lo($u,Ou.value,Iu++),Pu.value,Iu++);let Lu;for(;!(Lu=Ru.next()).done;)Du=lo(Du,Lu.value,Iu++);return Du}function*repeat$1(Au,lo){for(;0<lo--;)yield Au}function*once$1(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 Pu of Au)Iu(Pu);for(const[Pu]of Ru)Ou(Pu);return lo;function Iu(Pu){let[Du,Lu]=Pu,ju=Ru.get(Lu);ju?ju.push(Du):Ru.set(Lu,[Du])}function Ou(Pu){if($u.has(Pu))return;$u.add(Pu);let Du=Ru.get(Pu);if(Du)for(const Lu of Du)Ou(Lu);lo.push(Pu)}}function*stride(Au,lo){let $u=0;for(const Ru of Au)$u++%lo===0&&(yield Ru)}var StringExt;(function(Au){function lo(Pu,Du,Lu=0){let ju=new Array(Du.length);for(let Bu=0,Fu=Lu,zu=Du.length;Bu<zu;++Bu,++Fu){if(Fu=Pu.indexOf(Du[Bu],Fu),Fu===-1)return null;ju[Bu]=Fu}return ju}Au.findIndices=lo;function $u(Pu,Du,Lu=0){let ju=lo(Pu,Du,Lu);if(!ju)return null;let Bu=0;for(let Fu=0,zu=ju.length;Fu<zu;++Fu){let qu=ju[Fu]-Lu;Bu+=qu*qu}return{score:Bu,indices:ju}}Au.matchSumOfSquares=$u;function Ru(Pu,Du,Lu=0){let ju=lo(Pu,Du,Lu);if(!ju)return null;let Bu=0,Fu=Lu-1;for(let zu=0,qu=ju.length;zu<qu;++zu){let Uu=ju[zu];Bu+=Uu-Fu-1,Fu=Uu}return{score:Bu,indices:ju}}Au.matchSumOfDeltas=Ru;function Iu(Pu,Du,Lu){let ju=[],Bu=0,Fu=0,zu=Du.length;for(;Bu<zu;){let qu=Du[Bu],Uu=Du[Bu];for(;++Bu<zu&&Du[Bu]===Uu+1;)Uu++;Fu<qu&&ju.push(Pu.slice(Fu,qu)),qu<Uu+1&&ju.push(Lu(Pu.slice(qu,Uu+1))),Fu=Uu+1}return Fu<Pu.length&&ju.push(Pu.slice(Fu)),ju}Au.highlight=Iu;function Ou(Pu,Du){return Pu<Du?-1:Pu>Du?1:0}Au.cmp=Ou})(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$1(...Au){const lo=Au.map(Ru=>Ru[Symbol.iterator]());let $u=lo.map(Ru=>Ru.next());for(;every$3($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:chain$1,each:each$1,empty:empty$4,enumerate,every:every$3,filter:filter$5,find:find$5,findIndex:findIndex$1,map:map$8,max:max$2,min:min$2,minmax,once:once$1,range:range$4,reduce:reduce$1,repeat:repeat$1,retro,some:some$2,stride,take,toArray:toArray$2,toObject,topologicSort,zip:zip$1},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,Fu){if(Bu===Fu)return!0;if(lo(Bu)||lo(Fu))return!1;let zu=$u(Bu),qu=$u(Fu);return zu!==qu?!1:zu&&qu?Pu(Bu,Fu):Du(Bu,Fu)}Au.deepEqual=Iu;function Ou(Bu){return lo(Bu)?Bu:$u(Bu)?Lu(Bu):ju(Bu)}Au.deepCopy=Ou;function Pu(Bu,Fu){if(Bu===Fu)return!0;if(Bu.length!==Fu.length)return!1;for(let zu=0,qu=Bu.length;zu<qu;++zu)if(!Iu(Bu[zu],Fu[zu]))return!1;return!0}function Du(Bu,Fu){if(Bu===Fu)return!0;for(let zu in Bu)if(Bu[zu]!==void 0&&!(zu in Fu))return!1;for(let zu in Fu)if(Fu[zu]!==void 0&&!(zu in Bu))return!1;for(let zu in Bu){let qu=Bu[zu],Uu=Fu[zu];if(!(qu===void 0&&Uu===void 0)&&(qu===void 0||Uu===void 0||!Iu(qu,Uu)))return!1}return!0}function Lu(Bu){let Fu=new Array(Bu.length);for(let zu=0,qu=Bu.length;zu<qu;++zu)Fu[zu]=Ou(Bu[zu]);return Fu}function ju(Bu){let Fu={};for(let zu in Bu){let qu=Bu[zu];qu!==void 0&&(Fu[zu]=Ou(qu))}return Fu}})(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$H.createPluginData(lo);Private$H.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(Ou=>this.resolveRequiredService(Ou)),Iu=$u.optional.map(Ou=>this.resolveOptionalService(Ou));return $u.promise=Promise.all([...Ru,...Iu]).then(Ou=>$u.activate.apply(void 0,[this.application,...Ou])).then(Ou=>{$u.service=Ou,$u.activated=!0,$u.promise=null}).catch(Ou=>{throw $u.promise=null,Ou}),$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$H.collectStartupPlugins(this._plugins,$u).map(async Ou=>{try{return await this.activatePlugin(Ou)}catch(Pu){console.error(`Plugin '${Ou}' failed to activate.`,Pu)}});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$H.findDependents(lo,this._plugins,this._services),Iu=Ru.map(Ou=>this._plugins.get(Ou));for(const Ou of Iu)if(!Ou.deactivate)throw new TypeError(`Plugin ${Ou.id}#deactivate() method missing (depends on ${lo})`);for(const Ou of Iu){const Pu=[...Ou.requires,...Ou.optional].map(Du=>{const Lu=this._services.get(Du);return Lu?this._plugins.get(Lu).service:null});await Ou.deactivate(this.application,...Pu),Ou.service=null,Ou.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$H;(function(Au){class lo{constructor(Du){var Lu,ju,Bu,Fu;this._activated=!1,this._promise=null,this._service=null,this.id=Du.id,this.description=(Lu=Du.description)!==null&&Lu!==void 0?Lu:"",this.activate=Du.activate,this.deactivate=(ju=Du.deactivate)!==null&&ju!==void 0?ju:null,this.provides=(Bu=Du.provides)!==null&&Bu!==void 0?Bu:null,this.autoStart=(Fu=Du.autoStart)!==null&&Fu!==void 0?Fu:!1,this.requires=Du.requires?Du.requires.slice():[],this.optional=Du.optional?Du.optional.slice():[]}get activated(){return this._activated}set activated(Du){this._activated=Du}get service(){return this._service}set service(Du){this._service=Du}get promise(){return this._promise}set promise(Du){this._promise=Du}}function $u(Pu){return new lo(Pu)}Au.createPluginData=$u;function Ru(Pu,Du,Lu){const ju=[...Pu.requires,...Pu.optional],Bu=zu=>{if(zu===Pu.provides)return!0;const qu=Lu.get(zu);if(!qu)return!1;const Uu=Du.get(qu),Hu=[...Uu.requires,...Uu.optional];return Hu.length===0?!1:(Fu.push(qu),Hu.some(Bu)?!0:(Fu.pop(),!1))};if(!Pu.provides||ju.length===0)return;const Fu=[Pu.id];if(ju.some(Bu))throw new ReferenceError(`Cycle detected: ${Fu.join(" -> ")}.`)}Au.ensureNoCycle=Ru;function Iu(Pu,Du,Lu){const ju=new Array,Bu=Hu=>{const Vu=Du.get(Hu),Gu=[...Vu.requires,...Vu.optional];ju.push(...Gu.reduce((Ku,Zu)=>{const Qu=Lu.get(Zu);return Qu&&Ku.push([Hu,Qu]),Ku},[]))};for(const Hu of Du.keys())Bu(Hu);const Fu=ju.filter(Hu=>Hu[1]===Pu);let zu=0;for(;Fu.length>zu;){const Hu=Fu.length,Vu=new Set(Fu.map(Gu=>Gu[0]));for(const Gu of Vu)ju.filter(Ku=>Ku[1]===Gu).forEach(Ku=>{Fu.includes(Ku)||Fu.push(Ku)});zu=Hu}const qu=topologicSort(Fu),Uu=qu.findIndex(Hu=>Hu===Pu);return Uu===-1?[Pu]:qu.slice(0,Uu+1)}Au.findDependents=Iu;function Ou(Pu,Du){const Lu=new Set;for(const ju of Pu.keys())Pu.get(ju).autoStart===!0&&Lu.add(ju);if(Du.startPlugins)for(const ju of Du.startPlugins)Lu.add(ju);if(Du.ignorePlugins)for(const ju of Du.ignorePlugins)Lu.delete(ju);return Array.from(Lu)}Au.collectStartupPlugins=Ou})(Private$H||(Private$H={}));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$G.connect(this,lo,$u)}disconnect(lo,$u){return Private$G.disconnect(this,lo,$u)}emit(lo){Private$G.emit(this,lo)}}(function(Au){function lo(Lu,ju){Private$G.disconnectBetween(Lu,ju)}Au.disconnectBetween=lo;function $u(Lu){Private$G.disconnectSender(Lu)}Au.disconnectSender=$u;function Ru(Lu){Private$G.disconnectReceiver(Lu)}Au.disconnectReceiver=Ru;function Iu(Lu){Private$G.disconnectAll(Lu)}Au.disconnectAll=Iu;function Ou(Lu){Private$G.disconnectAll(Lu)}Au.clearData=Ou;function Pu(){return Private$G.exceptionHandler}Au.getExceptionHandler=Pu;function Du(Lu){let ju=Private$G.exceptionHandler;return Private$G.exceptionHandler=Lu,ju}Au.setExceptionHandler=Du})(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$G;(function(Au){Au.exceptionHandler=Ku=>{console.error(Ku)};function lo(Ku,Zu,Qu){Qu=Qu||void 0;let Yu=Lu.get(Ku.sender);if(Yu||(Yu=[],Lu.set(Ku.sender,Yu)),zu(Yu,Ku,Zu,Qu))return!1;let ed=Qu||Zu,Xu=ju.get(ed);Xu||(Xu=[],ju.set(ed,Xu));let rd={signal:Ku,slot:Zu,thisArg:Qu};return Yu.push(rd),Xu.push(rd),!0}Au.connect=lo;function $u(Ku,Zu,Qu){Qu=Qu||void 0;let Yu=Lu.get(Ku.sender);if(!Yu||Yu.length===0)return!1;let ed=zu(Yu,Ku,Zu,Qu);if(!ed)return!1;let Xu=Qu||Zu,rd=ju.get(Xu);return ed.signal=null,Uu(Yu),Uu(rd),!0}Au.disconnect=$u;function Ru(Ku,Zu){let Qu=Lu.get(Ku);if(!Qu||Qu.length===0)return;let Yu=ju.get(Zu);if(!(!Yu||Yu.length===0)){for(const ed of Yu)ed.signal&&ed.signal.sender===Ku&&(ed.signal=null);Uu(Qu),Uu(Yu)}}Au.disconnectBetween=Ru;function Iu(Ku){let Zu=Lu.get(Ku);if(!(!Zu||Zu.length===0)){for(const Qu of Zu){if(!Qu.signal)continue;let Yu=Qu.thisArg||Qu.slot;Qu.signal=null,Uu(ju.get(Yu))}Uu(Zu)}}Au.disconnectSender=Iu;function Ou(Ku){let Zu=ju.get(Ku);if(!(!Zu||Zu.length===0)){for(const Qu of Zu){if(!Qu.signal)continue;let Yu=Qu.signal.sender;Qu.signal=null,Uu(Lu.get(Yu))}Uu(Zu)}}Au.disconnectReceiver=Ou;function Pu(Ku){Iu(Ku),Ou(Ku)}Au.disconnectAll=Pu;function Du(Ku,Zu){let Qu=Lu.get(Ku.sender);if(!(!Qu||Qu.length===0))for(let Yu=0,ed=Qu.length;Yu<ed;++Yu){let Xu=Qu[Yu];Xu.signal===Ku&&qu(Xu,Zu)}}Au.emit=Du;const Lu=new WeakMap,ju=new WeakMap,Bu=new Set,Fu=typeof requestAnimationFrame=="function"?requestAnimationFrame:setImmediate;function zu(Ku,Zu,Qu,Yu){return find$5(Ku,ed=>ed.signal===Zu&&ed.slot===Qu&&ed.thisArg===Yu)}function qu(Ku,Zu){let{signal:Qu,slot:Yu,thisArg:ed}=Ku;try{Yu.call(ed,Qu.sender,Zu)}catch(Xu){Au.exceptionHandler(Xu)}}function Uu(Ku){Bu.size===0&&Fu(Hu),Bu.add(Ku)}function Hu(){Bu.forEach(Vu),Bu.clear()}function Vu(Ku){ArrayExt.removeAllWhere(Ku,Gu)}function Gu(Ku){return Ku.signal===null}})(Private$G||(Private$G={}));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$F.DEFAULT_LINGER,this._standby=lo.standby||Private$F.DEFAULT_STANDBY,this._state={...Private$F.DEFAULT_STATE,timestamp:new Date().getTime()};const Ru=lo.frequency||{},Iu=Math.max(Ru.interval||0,Ru.max||0,Private$F.DEFAULT_FREQUENCY.max);this.frequency={...Private$F.DEFAULT_FREQUENCY,...Ru,max:Iu},this.name=lo.name||Private$F.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$F.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 Ou=()=>{this.isDisposed||this.tick!==Ru.promise||this._execute()};this._timeout=setTimeout(Ou,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$F.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$F.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$F;(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:Ou,interval:Pu,max:Du}=Ru;if(Pu===Poll.NEVER)return Pu;const Lu=Ou===!0?Au.DEFAULT_BACKOFF:Ou===!1?1:Ou,ju=$u(Pu,Iu.interval*Lu);return Math.min(Du,ju)}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$F||(Private$F={}));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:Ou}=this;if(Iu.phase==="resolved"){this.payload=new PromiseDelegate,Ou.resolve(Iu.payload);return}if(Iu.phase==="rejected"||Iu.phase==="stopped"){this.payload=new PromiseDelegate,Ou.promise.catch(Pu=>{}),Ou.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$3(){}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:Ou,queryKey:Pu,stale:Du}=Au;if(Pu){if(Ru){if(lo.queryHash!==hashQueryKeyByOptions(Pu,lo.options))return!1}else if(!partialMatchKey(lo.queryKey,Pu))return!1}if($u!=="all"){const Lu=lo.isActive();if($u==="active"&&!Lu||$u==="inactive"&&Lu)return!1}return!(typeof Du=="boolean"&&lo.isStale()!==Du||Iu&&Iu!==lo.state.fetchStatus||Ou&&!Ou(lo))}function matchMutation(Au,lo){const{exact:$u,status:Ru,predicate:Iu,mutationKey:Ou}=Au;if(Ou){if(!lo.options.mutationKey)return!1;if($u){if(hashKey(lo.options.mutationKey)!==hashKey(Ou))return!1}else if(!partialMatchKey(lo.options.mutationKey,Ou))return!1}return!(Ru&&lo.state.status!==Ru||Iu&&!Iu(lo))}function hashQueryKeyByOptions(Au,lo){return(lo?.queryKeyHashFn||hashKey)(Au)}function hashKey(Au){return JSON.stringify(Au,(lo,$u)=>isPlainObject$8($u)?Object.keys($u).sort().reduce((Ru,Iu)=>(Ru[Iu]=$u[Iu],Ru),{}):$u)}function partialMatchKey(Au,lo){if(Au===lo)return!0;if(typeof Au!=typeof lo)return!1;if(Au&&lo&&typeof Au=="object"&&typeof lo=="object"){if(Array.isArray(Au)&&Array.isArray(lo)){if(lo.length>Au.length)return!1;for(let Ru=0;Ru<lo.length;Ru++)if(!partialMatchKey(Au[Ru],lo[Ru]))return!1;return!0}const $u=Object.keys(lo);for(const Ru of $u)if(!partialMatchKey(Au[Ru],lo[Ru]))return!1;return!0}return!1}const hasOwn=Object.prototype.hasOwnProperty;function replaceEqualDeep(Au,lo,$u=0){if(Au===lo)return Au;if($u>500)return lo;const Ru=isPlainArray(Au)&&isPlainArray(lo);if(!Ru&&!(isPlainObject$8(Au)&&isPlainObject$8(lo)))return lo;const Iu=(Ru?Au:Object.keys(Au)).length,Ou=Ru?lo:Object.keys(lo),Pu=Ou.length,Du=Ru?new Array(Pu):{};let Lu=0;for(let ju=0;ju<Pu;ju++){const Bu=Ru?ju:Ou[ju],Fu=Au[Bu],zu=lo[Bu];if(Fu===zu){Du[Bu]=Fu,(Ru?ju<Iu:hasOwn.call(Au,Bu))&&Lu++;continue}if(Fu===null||zu===null||typeof Fu!="object"||typeof zu!="object"){Du[Bu]=zu;continue}const qu=replaceEqualDeep(Fu,zu,$u+1);Du[Bu]=qu,qu===Fu&&Lu++}return Iu===Pu&&Lu===Iu?Au:Du}function shallowEqualObjects(Au,lo){if(!lo||Object.keys(Au).length!==Object.keys(lo).length)return!1;for(const $u in Au)if(Au[$u]!==lo[$u])return!1;return!0}function isPlainArray(Au){return Array.isArray(Au)&&Au.length===Object.keys(Au).length}function isPlainObject$8(Au){if(!hasObjectPrototype(Au))return!1;const lo=Object.getPrototypeOf(Au),$u=lo?.constructor;if($u===void 0)return!0;if(typeof $u!="function")return!1;const Ru=$u.prototype;return!(!hasObjectPrototype(Ru)||!Ru.hasOwnProperty("isPrototypeOf")||lo!==Object.prototype)}function hasObjectPrototype(Au){return Object.prototype.toString.call(Au)==="[object Object]"}function sleep$2(Au){return new Promise(lo=>{timeoutManager.setTimeout(lo,Au)})}function replaceData(Au,lo,$u){return typeof $u.structuralSharing=="function"?$u.structuralSharing(Au,lo):$u.structuralSharing!==!1?replaceEqualDeep(Au,lo):lo}function addToEnd(Au,lo,$u=0){const Ru=[...Au,lo];return $u&&Ru.length>$u?Ru.slice(1):Ru}function addToStart(Au,lo,$u=0){const Ru=[lo,...Au];return $u&&Ru.length>$u?Ru.slice(0,-1):Ru}const skipToken=Symbol();function ensureQueryFn(Au,lo){return!Au.queryFn&&lo?.initialPromise?()=>lo.initialPromise:!Au.queryFn||Au.queryFn===skipToken?()=>Promise.reject(new Error(`Missing queryFn: '${Au.queryHash}'`)):Au.queryFn}function shouldThrowError(Au,lo){return typeof Au=="function"?Au(...lo):!!Au}function addConsumeAwareSignal(Au,lo,$u){let Ru=!1,Iu;return Object.defineProperty(Au,"signal",{enumerable:!0,get:()=>(Iu??=lo(),Ru||(Ru=!0,Iu.aborted?$u():Iu.addEventListener("abort",$u,{once:!0})),Iu)}),Au}let isServerFn=()=>isServer$1;const isServer=()=>isServerFn();var Subscribable=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(Au){return this.listeners.add(Au),this.onSubscribe(),()=>{this.listeners.delete(Au),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},FocusManager=class extends Subscribable{#e;#t;#r;constructor(){super(),this.#r=Au=>{if(typeof window<"u"&&window.addEventListener){const lo=()=>Au();return window.addEventListener("visibilitychange",lo,!1),()=>{window.removeEventListener("visibilitychange",lo)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(Au){this.#r=Au,this.#t?.(),this.#t=Au(lo=>{typeof lo=="boolean"?this.setFocused(lo):this.onFocus()})}setFocused(Au){this.#e!==Au&&(this.#e=Au,this.onFocus())}onFocus(){const Au=this.isFocused();this.listeners.forEach(lo=>{lo(Au)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}};const focusManager=new FocusManager,defaultScheduler=systemSetTimeoutZero;function createNotifyManager(){let Au=[],lo=0,$u=Du=>{Du()},Ru=Du=>{Du()},Iu=defaultScheduler;const Ou=Du=>{lo?Au.push(Du):Iu(()=>{$u(Du)})},Pu=()=>{const Du=Au;Au=[],Du.length&&Iu(()=>{Ru(()=>{Du.forEach(Lu=>{$u(Lu)})})})};return{batch:Du=>{let Lu;lo++;try{Lu=Du()}finally{lo--,lo||Pu()}return Lu},batchCalls:Du=>(...Lu)=>{Ou(()=>{Du(...Lu)})},schedule:Ou,setNotifyFunction:Du=>{$u=Du},setBatchNotifyFunction:Du=>{Ru=Du},setScheduler:Du=>{Iu=Du}}}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",Ou,Pu;const Du=new Promise((Ku,Zu)=>{Ou=Ku,Pu=Zu});Du.catch(noop$3);const Lu=()=>Iu!=="pending",ju=Ku=>{if(!Lu()){const Zu=new CancelledError(Ku);Hu(Zu),Au.onCancel?.(Zu)}},Bu=()=>{lo=!0},Fu=()=>{lo=!1},zu=()=>focusManager.isFocused()&&(Au.networkMode==="always"||onlineManager.isOnline())&&Au.canRun(),qu=()=>canFetch(Au.networkMode)&&Au.canRun(),Uu=Ku=>{Lu()||(Ru?.(),Iu="resolved",Ou(Ku))},Hu=Ku=>{Lu()||(Ru?.(),Iu="rejected",Pu(Ku))},Vu=()=>new Promise(Ku=>{Ru=Zu=>{(Lu()||zu())&&Ku(Zu)},Au.onPause?.()}).then(()=>{Ru=void 0,Lu()||Au.onContinue?.()}),Gu=()=>{if(Lu())return;let Ku;const Zu=$u===0?Au.initialPromise:void 0;try{Ku=Zu??Au.fn()}catch(Qu){Ku=Promise.reject(Qu)}Promise.resolve(Ku).then(Uu).catch(Qu=>{if(Lu())return;const Yu=Au.retry??(isServer()?0:3),ed=Au.retryDelay??defaultRetryDelay,Xu=typeof ed=="function"?ed($u,Qu):ed,rd=Yu===!0||typeof Yu=="number"&&$u<Yu||typeof Yu=="function"&&Yu($u,Qu);if(lo||!rd){Hu(Qu);return}$u++,Au.onFail?.($u,Qu),sleep$2(Xu).then(()=>zu()?void 0:Vu()).then(()=>{lo?Hu(Qu):Gu()})})};return{promise:Du,status:()=>Iu,cancel:ju,continue:()=>(Ru?.(),Du),cancelRetry:Bu,continueRetry:Fu,canStart:qu,start:()=>(qu()?Gu():Vu().then(Gu),Du)}}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,Ou=lo.state.data?.pages||[],Pu=lo.state.data?.pageParams||[];let Du={pages:[],pageParams:[]},Lu=0;const ju=async()=>{let Bu=!1;const Fu=Uu=>{addConsumeAwareSignal(Uu,()=>lo.signal,()=>Bu=!0)},zu=ensureQueryFn(lo.options,lo.fetchOptions),qu=async(Uu,Hu,Vu)=>{if(Bu)return Promise.reject(lo.signal.reason);if(Hu==null&&Uu.pages.length)return Promise.resolve(Uu);const Ku=(()=>{const ed={client:lo.client,queryKey:lo.queryKey,pageParam:Hu,direction:Vu?"backward":"forward",meta:lo.options.meta};return Fu(ed),ed})(),Zu=await zu(Ku),{maxPages:Qu}=lo.options,Yu=Vu?addToStart:addToEnd;return{pages:Yu(Uu.pages,Zu,Qu),pageParams:Yu(Uu.pageParams,Hu,Qu)}};if(Iu&&Ou.length){const Uu=Iu==="backward",Hu=Uu?getPreviousPageParam:getNextPageParam,Vu={pages:Ou,pageParams:Pu};Du=await qu(Vu,Hu(Ru,Vu),Uu)}else{const Uu=Au??Ou.length;do{const Hu=Lu===0?Pu[0]??Ru.initialPageParam:getNextPageParam(Ru,Du);if(Lu>0&&Hu==null)break;Du=await qu(Du,Hu),Lu++}while(Lu<Uu)}return Du};lo.options.persister?lo.fetchFn=()=>lo.options.persister?.(ju,{client:lo.client,queryKey:lo.queryKey,meta:lo.options.meta,signal:lo.signal},$u):lo.fetchFn=ju}}}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$3).catch(noop$3):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 Lu=this.observers.find(ju=>ju.options.queryFn);Lu&&this.setOptions(Lu.options)}const $u=new AbortController,Ru=Lu=>{Object.defineProperty(Lu,"signal",{enumerable:!0,get:()=>(this.#l=!0,$u.signal)})},Iu=()=>{const Lu=ensureQueryFn(this.options,lo),Bu=(()=>{const Fu={client:this.#i,queryKey:this.queryKey,meta:this.meta};return Ru(Fu),Fu})();return this.#l=!1,this.options.persister?this.options.persister(Lu,Bu,this):Lu(Bu)},Pu=(()=>{const Lu={fetchOptions:lo,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:Iu};return Ru(Lu),Lu})();(this.#e==="infinite"?infiniteQueryBehavior(this.options.pages):this.options.behavior)?.onFetch(Pu,this),this.#r=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==Pu.fetchOptions?.meta)&&this.#a({type:"fetch",meta:Pu.fetchOptions?.meta});const Du=this.#o=createRetryer({initialPromise:lo?.initialPromise,fn:Pu.fetchFn,onCancel:Lu=>{Lu instanceof CancelledError&&Lu.revert&&this.setState({...this.#r,fetchStatus:"idle"}),$u.abort()},onFail:(Lu,ju)=>{this.#a({type:"failed",failureCount:Lu,error:ju})},onPause:()=>{this.#a({type:"pause"})},onContinue:()=>{this.#a({type:"continue"})},retry:Pu.options.retry,retryDelay:Pu.options.retryDelay,networkMode:Pu.options.networkMode,canRun:()=>!0});try{const Lu=await Du.start();if(Lu===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(Lu),this.#n.config.onSuccess?.(Lu,this),this.#n.config.onSettled?.(Lu,this.state.error,this),Lu}catch(Lu){if(Lu instanceof CancelledError){if(Lu.silent)return this.#o.promise;if(Lu.revert){if(this.state.data===void 0)throw Lu;return this.state.data}}throw this.#a({type:"error",error:Lu}),this.#n.config.onError?.(Lu,this),this.#n.config.onSettled?.(this.state.data,Lu,this),Lu}finally{this.#o===Du&&(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;#f;#u;#d;#c;#p=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.#p.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 Ou=new Promise(Pu=>{Iu=Pu,Ru=this.#e.getQueryCache().subscribe(Du=>{Du.type==="updated"&&Du.query.queryHash===$u.queryHash&&$u.state.data!==void 0&&(Ru(),Pu(this.createResult($u,lo)))})});return Promise.race([$u.fetch().then(()=>{const Pu=this.createResult($u,lo);return Iu?.(Pu),Pu}).finally(()=>{Ru()}),Ou])}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$3)),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,Ou=this.#i,Pu=this.#o,Du=Au!==$u?Au.state:this.#r,{state:Lu}=Au;let ju={...Lu},Bu=!1,Fu;if(lo._optimisticResults){const Yu=this.hasListeners(),ed=!Yu&&shouldFetchOnMount(Au,lo),Xu=Yu&&shouldFetchOptionally(Au,$u,lo,Ru);(ed||Xu)&&(ju={...ju,...fetchState(Lu.data,Au.options)}),lo._optimisticResults==="isRestoring"&&(ju.fetchStatus="idle")}let{error:zu,errorUpdatedAt:qu,status:Uu}=ju;Fu=ju.data;let Hu=!1;if(lo.placeholderData!==void 0&&Fu===void 0&&Uu==="pending"){let Yu;Iu?.isPlaceholderData&&lo.placeholderData===Pu?.placeholderData?(Yu=Iu.data,Hu=!0):Yu=typeof lo.placeholderData=="function"?lo.placeholderData(this.#f?.state.data,this.#f):lo.placeholderData,Yu!==void 0&&(Uu="success",Fu=replaceData(Iu?.data,Yu,lo),Bu=!0)}if(lo.select&&Fu!==void 0&&!Hu)if(Iu&&Fu===Ou?.data&&lo.select===this.#l)Fu=this.#a;else try{this.#l=lo.select,Fu=lo.select(Fu),Fu=replaceData(Iu?.data,Fu,lo),this.#a=Fu,this.#s=null}catch(Yu){this.#s=Yu}else Fu===void 0&&(this.#s=null);this.#s&&(zu=this.#s,Fu=this.#a,qu=Date.now(),Uu="error",Bu=!1);const Vu=ju.fetchStatus==="fetching",Gu=Uu==="pending",Ku=Uu==="error",Zu=Gu&&Vu,Qu=Fu!==void 0;return{status:Uu,fetchStatus:ju.fetchStatus,isPending:Gu,isSuccess:Uu==="success",isError:Ku,isInitialLoading:Zu,isLoading:Zu,data:Fu,dataUpdatedAt:ju.dataUpdatedAt,error:zu,errorUpdatedAt:qu,failureCount:ju.fetchFailureCount,failureReason:ju.fetchFailureReason,errorUpdateCount:ju.errorUpdateCount,isFetched:Au.isFetched(),isFetchedAfterMount:ju.dataUpdateCount>Du.dataUpdateCount||ju.errorUpdateCount>Du.errorUpdateCount,isFetching:Vu,isRefetching:Vu&&!Gu,isLoadingError:Ku&&!Qu,isPaused:ju.fetchStatus==="paused",isPlaceholderData:Bu,isRefetchError:Ku&&Qu,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.#f=this.#t),shallowEqualObjects(lo,Au))return;this.#n=lo;const Ru=(()=>{if(!Au)return!0;const{notifyOnChangeProps:Iu}=this.options,Ou=typeof Iu=="function"?Iu():Iu;if(Ou==="all"||!Ou&&!this.#p.size)return!0;const Pu=new Set(Ou??this.#p);return this.options.throwOnError&&Pu.add("error"),Object.keys(this.#n).some(Du=>{const Lu=Du;return this.#n[Lu]!==Au[Lu]&&Pu.has(Lu)})})();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:(Pu,Du)=>{this.#i({type:"failed",failureCount:Pu,error:Du})},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",Ou=!Ru.canStart();try{if(Iu)lo();else{this.#i({type:"pending",variables:Au,isPaused:Ou}),this.#r.config.onMutate&&await this.#r.config.onMutate(Au,this,$u);const Du=await this.options.onMutate?.(Au,$u);Du!==this.state.context&&this.#i({type:"pending",context:Du,variables:Au,isPaused:Ou})}const Pu=await Ru.start();return await this.#r.config.onSuccess?.(Pu,Au,this.state.context,this,$u),await this.options.onSuccess?.(Pu,Au,this.state.context,$u),await this.#r.config.onSettled?.(Pu,null,this.state.variables,this.state.context,this,$u),await this.options.onSettled?.(Pu,null,Au,this.state.context,$u),this.#i({type:"success",data:Pu}),Pu}catch(Pu){try{await this.#r.config.onError?.(Pu,Au,this.state.context,this,$u)}catch(Du){Promise.reject(Du)}try{await this.options.onError?.(Pu,Au,this.state.context,$u)}catch(Du){Promise.reject(Du)}try{await this.#r.config.onSettled?.(void 0,Pu,this.state.variables,this.state.context,this,$u)}catch(Du){Promise.reject(Du)}try{await this.options.onSettled?.(void 0,Pu,Au,this.state.context,$u)}catch(Du){Promise.reject(Du)}throw this.#i({type:"error",error:Pu}),Pu}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(()=>{this.#e.forEach(Au=>{this.notify({type:"removed",mutation:Au})}),this.#e.clear(),this.#t.clear()})}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$3))))}};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(()=>{if(this.#n&&this.hasListeners()){const $u=this.#t.variables,Ru=this.#t.context,Iu={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(lo?.type==="success"){try{this.#n.onSuccess?.(lo.data,$u,Ru,Iu)}catch(Ou){Promise.reject(Ou)}try{this.#n.onSettled?.(lo.data,null,$u,Ru,Iu)}catch(Ou){Promise.reject(Ou)}}else if(lo?.type==="error"){try{this.#n.onError?.(lo.error,$u,Ru,Iu)}catch(Ou){Promise.reject(Ou)}try{this.#n.onSettled?.(void 0,lo.error,$u,Ru,Iu)}catch(Ou){Promise.reject(Ou)}}}this.listeners.forEach($u=>{$u(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 Ou=this.get(Iu);return Ou||(Ou=new Query({client:Au,queryKey:Ru,queryHash:Iu,options:Au.defaultQueryOptions(lo),state:$u,defaultOptions:Au.getQueryDefaults(Ru)}),this.add(Ou)),Ou}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,Ou=functionalUpdate(lo,Iu);if(Ou!==void 0)return this.#e.build(this,Ru).setData(Ou,{...$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(Ou=>{Ou.reset()}),this.refetchQueries({type:"active",predicate:Ou=>Iu.has(Ou)},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$3).catch(noop$3)}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 Ou=Iu.fetch(void 0,$u);return $u.throwOnError||(Ou=Ou.catch(noop$3)),Iu.state.fetchStatus==="paused"?Promise.resolve():Ou}));return Promise.all(Ru).then(noop$3)}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$3).catch(noop$3)}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$3).catch(noop$3)}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.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(),Ou=useQueryClient(),Pu=Ou.defaultQueryOptions(Au),Du=Ou.getQueryCache().get(Pu.queryHash),Lu=Au.subscribed!==!1;Pu._optimisticResults=Ru?"isRestoring":Lu?"optimistic":void 0,ensureSuspenseTimers(Pu),ensurePreventErrorBoundaryRetry(Pu,Iu,Du),useClearResetErrorBoundary(Iu);const[ju]=reactExports.useState(()=>new lo(Ou,Pu)),Bu=ju.getOptimisticResult(Pu),Fu=!Ru&&Lu;if(reactExports.useSyncExternalStore(reactExports.useCallback(zu=>{const qu=Fu?ju.subscribe(notifyManager.batchCalls(zu)):noop$3;return ju.updateResult(),qu},[ju,Fu]),()=>ju.getCurrentResult(),()=>ju.getCurrentResult()),reactExports.useEffect(()=>{ju.setOptions(Pu)},[Pu,ju]),shouldSuspend(Pu,Bu))throw fetchOptimistic(Pu,ju,Iu);if(getHasError({result:Bu,errorResetBoundary:Iu,throwOnError:Pu.throwOnError,query:Du,suspense:Pu.suspense}))throw Bu.error;return Pu.notifyOnChangeProps?Bu:ju.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(Pu=>Ru.subscribe(notifyManager.batchCalls(Pu)),[Ru]),()=>Ru.getCurrentResult(),()=>Ru.getCurrentResult()),Ou=reactExports.useCallback((...Pu)=>{Ru.mutate(Pu[0],Pu[1]).catch(noop$3)},[Ru]);if(Iu.error&&shouldThrowError(Ru.options.throwOnError,[Iu.error]))throw Iu.error;return{...Iu,mutate:Ou,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 Ou=0;Ou<Iu.length;Ou++){let Pu=Iu[Ou];for(;Pu.charAt(0)===" ";)Pu=Pu.substring(1);if(Pu.indexOf($u)===0)return Pu.substring($u.length,Pu.length)}}function setCookie(Au,lo,$u="/"){const Ru=new Date,Ou=Ru.getTime()+1e3*36e3;Ru.setTime(Ou),document.cookie=`${Au}=${lo}; expires=${Ru.toUTCString()}; SameSite=Lax; path=${$u}`}function deleteCookie$1(Au){document.cookie=`${Au}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`}function createError(Au){const lo=new Error(Au);return lo.source="ulid",lo}const ENCODING="0123456789ABCDEFGHJKMNPQRSTVWXYZ",ENCODING_LEN=ENCODING.length,TIME_MAX=Math.pow(2,48)-1,TIME_LEN=10,RANDOM_LEN=16;function randomChar(Au){let lo=Math.floor(Au()*ENCODING_LEN);return lo===ENCODING_LEN&&(lo=ENCODING_LEN-1),ENCODING.charAt(lo)}function encodeTime(Au,lo){if(isNaN(Au))throw new Error(Au+" must be a number");if(Au>TIME_MAX)throw createError("cannot encode time greater than "+TIME_MAX);if(Au<0)throw createError("time must be positive");if(Number.isInteger(Number(Au))===!1)throw createError("time must be an integer");let $u,Ru="";for(;lo>0;lo--)$u=Au%ENCODING_LEN,Ru=ENCODING.charAt($u)+Ru,Au=(Au-$u)/ENCODING_LEN;return Ru}function encodeRandom(Au,lo){let $u="";for(;Au>0;Au--)$u=randomChar(lo)+$u;return $u}function detectPrng(Au=!1,lo){lo||(lo=typeof window<"u"?window:null);const $u=lo&&(lo.crypto||lo.msCrypto);if($u)return()=>{const Ru=new Uint8Array(1);return $u.getRandomValues(Ru),Ru[0]/255};try{const Ru=require("crypto");return()=>Ru.randomBytes(1).readUInt8()/255}catch{}if(Au){try{console.error("secure crypto unusable, falling back to insecure Math.random()!")}catch{}return()=>Math.random()}throw createError("secure crypto unusable, insecure Math.random not allowed")}function factory$1(Au){return Au||(Au=detectPrng()),function($u){return isNaN($u)&&($u=Date.now()),encodeTime($u,TIME_LEN)+encodeRandom(RANDOM_LEN,Au)}}const ulid$1=factory$1(),asDisplayName=(Au,lo)=>Au?lo?Au+" "+lo:Au:lo??"",namesAsInitials=(Au,lo)=>((Au||" ").charAt(0)+(lo||" ").charAt(0)).toLocaleUpperCase().trim(),toFriendlyName=(Au,lo)=>Au||lo||"";function parseJwtPayload(Au){try{const lo=Au.split(".");if(lo.length<2)return null;const $u=lo[1].replace(/-/g,"+").replace(/_/g,"/"),Ru=$u.padEnd($u.length+(4-$u.length%4)%4,"="),Iu=atob(Ru);return JSON.parse(Iu)}catch{return null}}function getJwtExpiryMs(Au){if(!Au)return null;const $u=parseJwtPayload(Au)?.exp;return typeof $u=="number"&&Number.isFinite($u)?$u*1e3:null}function isJwtExpired(Au,lo=0){const $u=getJwtExpiryMs(Au);return $u===null?!1:$u-lo*1e3<=Date.now()}var lib$e={},activitymonitor={};const require$$0$7=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$7;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(Du){this.startLine=Du,this.code="",this.endLine=-1}}lo.MarkdownCodeBlock=Ru;function Iu(Pu){return $u.indexOf(Pu)>-1}lo.isMarkdown=Iu;function Ou(Pu){if(!Pu||Pu==="")return[];const Du=Pu.split(`
243
243
  `),Lu=[];let ju=null;for(let Bu=0;Bu<Du.length;Bu++){const Fu=Du[Bu],zu=Fu.indexOf(lo.CODE_BLOCK_MARKER)===0,qu=ju!=null;if(!(!zu&&!qu))if(qu)ju&&(zu?(ju.endLine=Bu-1,Lu.push(ju),ju=null):ju.code+=Fu+`
244
244
  `);else{ju=new Ru(Bu);const Uu=Fu.indexOf(lo.CODE_BLOCK_MARKER),Hu=Fu.lastIndexOf(lo.CODE_BLOCK_MARKER);Uu!==Hu&&(ju.code=Fu.substring(Uu+lo.CODE_BLOCK_MARKER.length,Hu),ju.endLine=Bu,Lu.push(ju),ju=null)}}return Lu}lo.findMarkdownCodeBlocks=Ou})(Au||(markdowncodeblocks.MarkdownCodeBlocks=Au={})),markdowncodeblocks}var pageconfig={},dist$3={exports:{}};const require$$0$6=getAugmentedNamespace(index_es6$4);var dist$2=dist$3.exports,hasRequiredDist;function requireDist(){return hasRequiredDist||(hasRequiredDist=1,(function(Au,lo){(function($u,Ru){Ru(lo,require$$0$6)})(dist$2,(function($u,Ru){$u.JSONExt=void 0,(function(Fu){Fu.emptyObject=Object.freeze({}),Fu.emptyArray=Object.freeze([]);function zu(Yu){return Yu===null||typeof Yu=="boolean"||typeof Yu=="number"||typeof Yu=="string"}Fu.isPrimitive=zu;function qu(Yu){return Array.isArray(Yu)}Fu.isArray=qu;function Uu(Yu){return!zu(Yu)&&!qu(Yu)}Fu.isObject=Uu;function Hu(Yu,ed){if(Yu===ed)return!0;if(zu(Yu)||zu(ed))return!1;let Xu=qu(Yu),rd=qu(ed);return Xu!==rd?!1:Xu&&rd?Gu(Yu,ed):Ku(Yu,ed)}Fu.deepEqual=Hu;function Vu(Yu){return zu(Yu)?Yu:qu(Yu)?Zu(Yu):Qu(Yu)}Fu.deepCopy=Vu;function Gu(Yu,ed){if(Yu===ed)return!0;if(Yu.length!==ed.length)return!1;for(let Xu=0,rd=Yu.length;Xu<rd;++Xu)if(!Hu(Yu[Xu],ed[Xu]))return!1;return!0}function Ku(Yu,ed){if(Yu===ed)return!0;for(let Xu in Yu)if(Yu[Xu]!==void 0&&!(Xu in ed))return!1;for(let Xu in ed)if(ed[Xu]!==void 0&&!(Xu in Yu))return!1;for(let Xu in Yu){let rd=Yu[Xu],nd=ed[Xu];if(!(rd===void 0&&nd===void 0)&&(rd===void 0||nd===void 0||!Hu(rd,nd)))return!1}return!0}function Zu(Yu){let ed=new Array(Yu.length);for(let Xu=0,rd=Yu.length;Xu<rd;++Xu)ed[Xu]=Vu(Yu[Xu]);return ed}function Qu(Yu){let ed={};for(let Xu in Yu){let rd=Yu[Xu];rd!==void 0&&(ed[Xu]=Vu(rd))}return ed}})($u.JSONExt||($u.JSONExt={}));class Iu{constructor(){this._types=[],this._values=[]}types(){return this._types.slice()}hasData(zu){return this._types.indexOf(zu)!==-1}getData(zu){let qu=this._types.indexOf(zu);return qu!==-1?this._values[qu]:void 0}setData(zu,qu){this.clearData(zu),this._types.push(zu),this._values.push(qu)}clearData(zu){let qu=this._types.indexOf(zu);qu!==-1&&(this._types.splice(qu,1),this._values.splice(qu,1))}clear(){this._types.length=0,this._values.length=0}}class Ou{constructor(zu={}){this._application=null,this._validatePlugin=()=>!0,this._plugins=new Map,this._services=new Map,zu.validatePlugin&&(console.info("Plugins may be rejected by the custom validation plugin method."),this._validatePlugin=zu.validatePlugin)}get application(){return this._application}set application(zu){if(this._application!==null)throw Error("PluginRegistry.application is already set. It cannot be overridden.");this._application=zu}get deferredPlugins(){return Array.from(this._plugins).filter(([zu,qu])=>qu.autoStart==="defer").map(([zu,qu])=>zu)}getPluginDescription(zu){var qu,Uu;return(Uu=(qu=this._plugins.get(zu))===null||qu===void 0?void 0:qu.description)!==null&&Uu!==void 0?Uu:""}hasPlugin(zu){return this._plugins.has(zu)}isPluginActivated(zu){var qu,Uu;return(Uu=(qu=this._plugins.get(zu))===null||qu===void 0?void 0:qu.activated)!==null&&Uu!==void 0?Uu:!1}listPlugins(){return Array.from(this._plugins.keys())}registerPlugin(zu){if(this._plugins.has(zu.id))throw new TypeError(`Plugin '${zu.id}' is already registered.`);if(!this._validatePlugin(zu))throw new Error(`Plugin '${zu.id}' is not valid.`);const qu=Pu.createPluginData(zu);Pu.ensureNoCycle(qu,this._plugins,this._services),qu.provides&&this._services.set(qu.provides,qu.id),this._plugins.set(qu.id,qu)}registerPlugins(zu){for(const qu of zu)this.registerPlugin(qu)}deregisterPlugin(zu,qu){const Uu=this._plugins.get(zu);if(Uu){if(Uu.activated&&!qu)throw new Error(`Plugin '${zu}' is still active.`);this._plugins.delete(zu)}}async activatePlugin(zu){const qu=this._plugins.get(zu);if(!qu)throw new ReferenceError(`Plugin '${zu}' is not registered.`);if(qu.activated)return;if(qu.promise)return qu.promise;const Uu=qu.requires.map(Vu=>this.resolveRequiredService(Vu)),Hu=qu.optional.map(Vu=>this.resolveOptionalService(Vu));return qu.promise=Promise.all([...Uu,...Hu]).then(Vu=>qu.activate.apply(void 0,[this.application,...Vu])).then(Vu=>{qu.service=Vu,qu.activated=!0,qu.promise=null}).catch(Vu=>{throw qu.promise=null,Vu}),qu.promise}async activatePlugins(zu,qu={}){switch(zu){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=Pu.collectStartupPlugins(this._plugins,qu).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(zu){const qu=this._plugins.get(zu);if(!qu)throw new ReferenceError(`Plugin '${zu}' is not registered.`);if(!qu.activated)return[];if(!qu.deactivate)throw new TypeError(`Plugin '${zu}'#deactivate() method missing`);const Uu=Pu.findDependents(zu,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 ${zu})`);for(const Vu of Hu){const Gu=[...Vu.requires,...Vu.optional].map(Ku=>{const Zu=this._services.get(Ku);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(zu){const qu=this._services.get(zu);if(!qu)throw new TypeError(`No provider for: ${zu.name}.`);const Uu=this._plugins.get(qu);return Uu.activated||await this.activatePlugin(qu),Uu.service}async resolveOptionalService(zu){const qu=this._services.get(zu);if(!qu)return null;const Uu=this._plugins.get(qu);if(!Uu.activated)try{await this.activatePlugin(qu)}catch(Hu){return console.error(Hu),null}return Uu.service}}var Pu;(function(Fu){class zu{constructor(Ku){var Zu,Qu,Yu,ed;this._activated=!1,this._promise=null,this._service=null,this.id=Ku.id,this.description=(Zu=Ku.description)!==null&&Zu!==void 0?Zu:"",this.activate=Ku.activate,this.deactivate=(Qu=Ku.deactivate)!==null&&Qu!==void 0?Qu:null,this.provides=(Yu=Ku.provides)!==null&&Yu!==void 0?Yu:null,this.autoStart=(ed=Ku.autoStart)!==null&&ed!==void 0?ed:!1,this.requires=Ku.requires?Ku.requires.slice():[],this.optional=Ku.optional?Ku.optional.slice():[]}get activated(){return this._activated}set activated(Ku){this._activated=Ku}get service(){return this._service}set service(Ku){this._service=Ku}get promise(){return this._promise}set promise(Ku){this._promise=Ku}}function qu(Gu){return new zu(Gu)}Fu.createPluginData=qu;function Uu(Gu,Ku,Zu){const Qu=[...Gu.requires,...Gu.optional],Yu=Xu=>{if(Xu===Gu.provides)return!0;const rd=Zu.get(Xu);if(!rd)return!1;const nd=Ku.get(rd),od=[...nd.requires,...nd.optional];return od.length===0?!1:(ed.push(rd),od.some(Yu)?!0:(ed.pop(),!1))};if(!Gu.provides||Qu.length===0)return;const ed=[Gu.id];if(Qu.some(Yu))throw new ReferenceError(`Cycle detected: ${ed.join(" -> ")}.`)}Fu.ensureNoCycle=Uu;function Hu(Gu,Ku,Zu){const Qu=new Array,Yu=od=>{const ad=Ku.get(od),ld=[...ad.requires,...ad.optional];Qu.push(...ld.reduce((fd,pd)=>{const Sd=Zu.get(pd);return Sd&&fd.push([od,Sd]),fd},[]))};for(const od of Ku.keys())Yu(od);const ed=Qu.filter(od=>od[1]===Gu);let Xu=0;for(;ed.length>Xu;){const od=ed.length,ad=new Set(ed.map(ld=>ld[0]));for(const ld of ad)Qu.filter(fd=>fd[1]===ld).forEach(fd=>{ed.includes(fd)||ed.push(fd)});Xu=od}const rd=Ru.topologicSort(ed),nd=rd.findIndex(od=>od===Gu);return nd===-1?[Gu]:rd.slice(0,nd+1)}Fu.findDependents=Hu;function Vu(Gu,Ku){const Zu=new Set;for(const Qu of Gu.keys())Gu.get(Qu).autoStart===!0&&Zu.add(Qu);if(Ku.startPlugins)for(const Qu of Ku.startPlugins)Zu.add(Qu);if(Ku.ignorePlugins)for(const Qu of Ku.ignorePlugins)Zu.delete(Qu);return Array.from(Zu)}Fu.collectStartupPlugins=Vu})(Pu||(Pu={}));class Du{constructor(){this.promise=new Promise((zu,qu)=>{this._resolve=zu,this._reject=qu})}resolve(zu){let qu=this._resolve;qu(zu)}reject(zu){let qu=this._reject;qu(zu)}}class Lu{constructor(zu,qu){this.name=zu,this.description=qu??"",this._tokenStructuralPropertyT=null}}function ju(Fu){let zu=0;for(let qu=0,Uu=Fu.length;qu<Uu;++qu)qu%4===0&&(zu=Math.random()*4294967295>>>0),Fu[qu]=zu&255,zu>>>=8}$u.Random=void 0,(function(Fu){Fu.getRandomValues=(()=>{const zu=typeof window<"u"&&(window.crypto||window.msCrypto)||null;return zu&&typeof zu.getRandomValues=="function"?function(Uu){return zu.getRandomValues(Uu)}:ju})()})($u.Random||($u.Random={}));function Bu(Fu){const zu=new Uint8Array(16),qu=new Array(256);for(let Uu=0;Uu<16;++Uu)qu[Uu]="0"+Uu.toString(16);for(let Uu=16;Uu<256;++Uu)qu[Uu]=Uu.toString(16);return function(){return Fu(zu),zu[6]=64|zu[6]&15,zu[8]=128|zu[8]&63,qu[zu[0]]+qu[zu[1]]+qu[zu[2]]+qu[zu[3]]+"-"+qu[zu[4]]+qu[zu[5]]+"-"+qu[zu[6]]+qu[zu[7]]+"-"+qu[zu[8]]+qu[zu[9]]+"-"+qu[zu[10]]+qu[zu[11]]+qu[zu[12]]+qu[zu[13]]+qu[zu[14]]+qu[zu[15]]}}$u.UUID=void 0,(function(Fu){Fu.uuid4=Bu($u.Random.getRandomValues)})($u.UUID||($u.UUID={})),$u.MimeData=Iu,$u.PluginRegistry=Ou,$u.PromiseDelegate=Du,$u.Token=Lu}))})(dist$3,dist$3.exports)),dist$3.exports}var minimist,hasRequiredMinimist;function requireMinimist(){if(hasRequiredMinimist)return minimist;hasRequiredMinimist=1;function Au(Ru,Iu){var Ou=Ru;Iu.slice(0,-1).forEach(function(Du){Ou=Ou[Du]||{}});var Pu=Iu[Iu.length-1];return Pu in Ou}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 Ou={bools:{},strings:{},unknownFn:null};typeof Iu.unknown=="function"&&(Ou.unknownFn=Iu.unknown),typeof Iu.boolean=="boolean"&&Iu.boolean?Ou.allBools=!0:[].concat(Iu.boolean).filter(Boolean).forEach(function(Xu){Ou.bools[Xu]=!0});var Pu={};function Du(Xu){return Pu[Xu].some(function(rd){return Ou.bools[rd]})}Object.keys(Iu.alias||{}).forEach(function(Xu){Pu[Xu]=[].concat(Iu.alias[Xu]),Pu[Xu].forEach(function(rd){Pu[rd]=[Xu].concat(Pu[Xu].filter(function(nd){return rd!==nd}))})}),[].concat(Iu.string).filter(Boolean).forEach(function(Xu){Ou.strings[Xu]=!0,Pu[Xu]&&[].concat(Pu[Xu]).forEach(function(rd){Ou.strings[rd]=!0})});var Lu=Iu.default||{},ju={_:[]};function Bu(Xu,rd){return Ou.allBools&&/^--[^=]+$/.test(rd)||Ou.strings[Xu]||Ou.bools[Xu]||Pu[Xu]}function Fu(Xu,rd,nd){for(var od=Xu,ad=0;ad<rd.length-1;ad++){var ld=rd[ad];if($u(od,ld))return;od[ld]===void 0&&(od[ld]={}),(od[ld]===Object.prototype||od[ld]===Number.prototype||od[ld]===String.prototype)&&(od[ld]={}),od[ld]===Array.prototype&&(od[ld]=[]),od=od[ld]}var fd=rd[rd.length-1];$u(od,fd)||((od===Object.prototype||od===Number.prototype||od===String.prototype)&&(od={}),od===Array.prototype&&(od=[]),od[fd]===void 0||Ou.bools[fd]||typeof od[fd]=="boolean"?od[fd]=nd:Array.isArray(od[fd])?od[fd].push(nd):od[fd]=[od[fd],nd])}function zu(Xu,rd,nd){if(!(nd&&Ou.unknownFn&&!Bu(Xu,nd)&&Ou.unknownFn(nd)===!1)){var od=!Ou.strings[Xu]&&lo(rd)?Number(rd):rd;Fu(ju,Xu.split("."),od),(Pu[Xu]||[]).forEach(function(ad){Fu(ju,ad.split("."),od)})}}Object.keys(Ou.bools).forEach(function(Xu){zu(Xu,Lu[Xu]===void 0?!1:Lu[Xu])});var qu=[];Ru.indexOf("--")!==-1&&(qu=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 Ku=Hu.match(/^--([^=]+)=([\s\S]*)$/);Vu=Ku[1];var Zu=Ku[2];Ou.bools[Vu]&&(Zu=Zu!=="false"),zu(Vu,Zu,Hu)}else if(/^--no-.+/.test(Hu))Vu=Hu.match(/^--no-(.+)/)[1],zu(Vu,!1,Hu);else if(/^--.+/.test(Hu))Vu=Hu.match(/^--(.+)/)[1],Gu=Ru[Uu+1],Gu!==void 0&&!/^(-|--)[^-]/.test(Gu)&&!Ou.bools[Vu]&&!Ou.allBools&&(!Pu[Vu]||!Du(Vu))?(zu(Vu,Gu,Hu),Uu+=1):/^(true|false)$/.test(Gu)?(zu(Vu,Gu==="true",Hu),Uu+=1):zu(Vu,Ou.strings[Vu]?"":!0,Hu);else if(/^-[^-]+/.test(Hu)){for(var Qu=Hu.slice(1,-1).split(""),Yu=!1,ed=0;ed<Qu.length;ed++){if(Gu=Hu.slice(ed+2),Gu==="-"){zu(Qu[ed],Gu,Hu);continue}if(/[A-Za-z]/.test(Qu[ed])&&Gu[0]==="="){zu(Qu[ed],Gu.slice(1),Hu),Yu=!0;break}if(/[A-Za-z]/.test(Qu[ed])&&/-?\d+(\.\d*)?(e-?\d+)?$/.test(Gu)){zu(Qu[ed],Gu,Hu),Yu=!0;break}if(Qu[ed+1]&&Qu[ed+1].match(/\W/)){zu(Qu[ed],Hu.slice(ed+2),Hu),Yu=!0;break}else zu(Qu[ed],Ou.strings[Qu[ed]]?"":!0,Hu)}Vu=Hu.slice(-1)[0],!Yu&&Vu!=="-"&&(Ru[Uu+1]&&!/^(-|--)[^-]/.test(Ru[Uu+1])&&!Ou.bools[Vu]&&(!Pu[Vu]||!Du(Vu))?(zu(Vu,Ru[Uu+1],Hu),Uu+=1):Ru[Uu+1]&&/^(true|false)$/.test(Ru[Uu+1])?(zu(Vu,Ru[Uu+1]==="true",Hu),Uu+=1):zu(Vu,Ou.strings[Vu]?"":!0,Hu))}else if((!Ou.unknownFn||Ou.unknownFn(Hu)!==!1)&&ju._.push(Ou.strings._||!lo(Hu)?Hu:Number(Hu)),Iu.stopEarly){ju._.push.apply(ju._,Ru.slice(Uu+1));break}}return Object.keys(Lu).forEach(function(Xu){Au(ju,Xu.split("."))||(Fu(ju,Xu.split("."),Lu[Xu]),(Pu[Xu]||[]).forEach(function(rd){Fu(ju,rd.split("."),Lu[Xu])}))}),Iu["--"]?ju["--"]=qu.slice():qu.forEach(function(Xu){ju._.push(Xu)}),ju},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,Ou){for(var Pu="",Du=0,Lu=-1,ju=0,Bu,Fu=0;Fu<=Iu.length;++Fu){if(Fu<Iu.length)Bu=Iu.charCodeAt(Fu);else{if(Bu===47)break;Bu=47}if(Bu===47){if(!(Lu===Fu-1||ju===1))if(Lu!==Fu-1&&ju===2){if(Pu.length<2||Du!==2||Pu.charCodeAt(Pu.length-1)!==46||Pu.charCodeAt(Pu.length-2)!==46){if(Pu.length>2){var zu=Pu.lastIndexOf("/");if(zu!==Pu.length-1){zu===-1?(Pu="",Du=0):(Pu=Pu.slice(0,zu),Du=Pu.length-1-Pu.lastIndexOf("/")),Lu=Fu,ju=0;continue}}else if(Pu.length===2||Pu.length===1){Pu="",Du=0,Lu=Fu,ju=0;continue}}Ou&&(Pu.length>0?Pu+="/..":Pu="..",Du=2)}else Pu.length>0?Pu+="/"+Iu.slice(Lu+1,Fu):Pu=Iu.slice(Lu+1,Fu),Du=Fu-Lu-1;Lu=Fu,ju=0}else Bu===46&&ju!==-1?++ju:ju=-1}return Pu}function $u(Iu,Ou){var Pu=Ou.dir||Ou.root,Du=Ou.base||(Ou.name||"")+(Ou.ext||"");return Pu?Pu===Ou.root?Pu+Du:Pu+Iu+Du:Du}var Ru={resolve:function(){for(var Ou="",Pu=!1,Du,Lu=arguments.length-1;Lu>=-1&&!Pu;Lu--){var ju;Lu>=0?ju=arguments[Lu]:(Du===void 0&&(Du=process.cwd()),ju=Du),Au(ju),ju.length!==0&&(Ou=ju+"/"+Ou,Pu=ju.charCodeAt(0)===47)}return Ou=lo(Ou,!Pu),Pu?Ou.length>0?"/"+Ou:"/":Ou.length>0?Ou:"."},normalize:function(Ou){if(Au(Ou),Ou.length===0)return".";var Pu=Ou.charCodeAt(0)===47,Du=Ou.charCodeAt(Ou.length-1)===47;return Ou=lo(Ou,!Pu),Ou.length===0&&!Pu&&(Ou="."),Ou.length>0&&Du&&(Ou+="/"),Pu?"/"+Ou:Ou},isAbsolute:function(Ou){return Au(Ou),Ou.length>0&&Ou.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var Ou,Pu=0;Pu<arguments.length;++Pu){var Du=arguments[Pu];Au(Du),Du.length>0&&(Ou===void 0?Ou=Du:Ou+="/"+Du)}return Ou===void 0?".":Ru.normalize(Ou)},relative:function(Ou,Pu){if(Au(Ou),Au(Pu),Ou===Pu||(Ou=Ru.resolve(Ou),Pu=Ru.resolve(Pu),Ou===Pu))return"";for(var Du=1;Du<Ou.length&&Ou.charCodeAt(Du)===47;++Du);for(var Lu=Ou.length,ju=Lu-Du,Bu=1;Bu<Pu.length&&Pu.charCodeAt(Bu)===47;++Bu);for(var Fu=Pu.length,zu=Fu-Bu,qu=ju<zu?ju:zu,Uu=-1,Hu=0;Hu<=qu;++Hu){if(Hu===qu){if(zu>qu){if(Pu.charCodeAt(Bu+Hu)===47)return Pu.slice(Bu+Hu+1);if(Hu===0)return Pu.slice(Bu+Hu)}else ju>qu&&(Ou.charCodeAt(Du+Hu)===47?Uu=Hu:Hu===0&&(Uu=0));break}var Vu=Ou.charCodeAt(Du+Hu),Gu=Pu.charCodeAt(Bu+Hu);if(Vu!==Gu)break;Vu===47&&(Uu=Hu)}var Ku="";for(Hu=Du+Uu+1;Hu<=Lu;++Hu)(Hu===Lu||Ou.charCodeAt(Hu)===47)&&(Ku.length===0?Ku+="..":Ku+="/..");return Ku.length>0?Ku+Pu.slice(Bu+Uu):(Bu+=Uu,Pu.charCodeAt(Bu)===47&&++Bu,Pu.slice(Bu))},_makeLong:function(Ou){return Ou},dirname:function(Ou){if(Au(Ou),Ou.length===0)return".";for(var Pu=Ou.charCodeAt(0),Du=Pu===47,Lu=-1,ju=!0,Bu=Ou.length-1;Bu>=1;--Bu)if(Pu=Ou.charCodeAt(Bu),Pu===47){if(!ju){Lu=Bu;break}}else ju=!1;return Lu===-1?Du?"/":".":Du&&Lu===1?"//":Ou.slice(0,Lu)},basename:function(Ou,Pu){if(Pu!==void 0&&typeof Pu!="string")throw new TypeError('"ext" argument must be a string');Au(Ou);var Du=0,Lu=-1,ju=!0,Bu;if(Pu!==void 0&&Pu.length>0&&Pu.length<=Ou.length){if(Pu.length===Ou.length&&Pu===Ou)return"";var Fu=Pu.length-1,zu=-1;for(Bu=Ou.length-1;Bu>=0;--Bu){var qu=Ou.charCodeAt(Bu);if(qu===47){if(!ju){Du=Bu+1;break}}else zu===-1&&(ju=!1,zu=Bu+1),Fu>=0&&(qu===Pu.charCodeAt(Fu)?--Fu===-1&&(Lu=Bu):(Fu=-1,Lu=zu))}return Du===Lu?Lu=zu:Lu===-1&&(Lu=Ou.length),Ou.slice(Du,Lu)}else{for(Bu=Ou.length-1;Bu>=0;--Bu)if(Ou.charCodeAt(Bu)===47){if(!ju){Du=Bu+1;break}}else Lu===-1&&(ju=!1,Lu=Bu+1);return Lu===-1?"":Ou.slice(Du,Lu)}},extname:function(Ou){Au(Ou);for(var Pu=-1,Du=0,Lu=-1,ju=!0,Bu=0,Fu=Ou.length-1;Fu>=0;--Fu){var zu=Ou.charCodeAt(Fu);if(zu===47){if(!ju){Du=Fu+1;break}continue}Lu===-1&&(ju=!1,Lu=Fu+1),zu===46?Pu===-1?Pu=Fu:Bu!==1&&(Bu=1):Pu!==-1&&(Bu=-1)}return Pu===-1||Lu===-1||Bu===0||Bu===1&&Pu===Lu-1&&Pu===Du+1?"":Ou.slice(Pu,Lu)},format:function(Ou){if(Ou===null||typeof Ou!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof Ou);return $u("/",Ou)},parse:function(Ou){Au(Ou);var Pu={root:"",dir:"",base:"",ext:"",name:""};if(Ou.length===0)return Pu;var Du=Ou.charCodeAt(0),Lu=Du===47,ju;Lu?(Pu.root="/",ju=1):ju=0;for(var Bu=-1,Fu=0,zu=-1,qu=!0,Uu=Ou.length-1,Hu=0;Uu>=ju;--Uu){if(Du=Ou.charCodeAt(Uu),Du===47){if(!qu){Fu=Uu+1;break}continue}zu===-1&&(qu=!1,zu=Uu+1),Du===46?Bu===-1?Bu=Uu:Hu!==1&&(Hu=1):Bu!==-1&&(Hu=-1)}return Bu===-1||zu===-1||Hu===0||Hu===1&&Bu===zu-1&&Bu===Fu+1?zu!==-1&&(Fu===0&&Lu?Pu.base=Pu.name=Ou.slice(1,zu):Pu.base=Pu.name=Ou.slice(Fu,zu)):(Fu===0&&Lu?(Pu.name=Ou.slice(1,Bu),Pu.base=Ou.slice(1,zu)):(Pu.name=Ou.slice(Fu,Bu),Pu.base=Ou.slice(Fu,zu)),Pu.ext=Ou.slice(Bu,zu)),Fu>0?Pu.dir=Ou.slice(0,Fu-1):Lu&&(Pu.dir="/"),Pu},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(Pu){try{return decodeURIComponent(Pu.replace(/\+/g," "))}catch{return null}}function Ru(Pu){try{return encodeURIComponent(Pu)}catch{return null}}function Iu(Pu){for(var Du=/([^=?#&]+)=?([^&]*)/g,Lu={},ju;ju=Du.exec(Pu);){var Bu=$u(ju[1]),Fu=$u(ju[2]);Bu===null||Fu===null||Bu in Lu||(Lu[Bu]=Fu)}return Lu}function Ou(Pu,Du){Du=Du||"";var Lu=[],ju,Bu;typeof Du!="string"&&(Du="?");for(Bu in Pu)if(Au.call(Pu,Bu)){if(ju=Pu[Bu],!ju&&(ju===null||ju===lo||isNaN(ju))&&(ju=""),Bu=Ru(Bu),ju=Ru(ju),Bu===null||ju===null)continue;Lu.push(Bu+"="+ju)}return Lu.length?Du+Lu.join("&"):""}return querystringify.stringify=Ou,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+-.]*:\/\//,Ou=/:\d+$/,Pu=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,Du=/^[a-zA-Z]:/;function Lu(Ku){return(Ku||"").toString().replace($u,"")}var ju=[["#","hash"],["?","query"],function(Zu,Qu){return zu(Qu.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 Fu(Ku){var Zu;typeof window<"u"?Zu=window:typeof globalThis<"u"?Zu=globalThis:typeof self<"u"?Zu=self:Zu={};var Qu=Zu.location||{};Ku=Ku||Qu;var Yu={},ed=typeof Ku,Xu;if(Ku.protocol==="blob:")Yu=new Hu(unescape(Ku.pathname),{});else if(ed==="string"){Yu=new Hu(Ku,{});for(Xu in Bu)delete Yu[Xu]}else if(ed==="object"){for(Xu in Ku)Xu in Bu||(Yu[Xu]=Ku[Xu]);Yu.slashes===void 0&&(Yu.slashes=Iu.test(Ku.href))}return Yu}function zu(Ku){return Ku==="file:"||Ku==="ftp:"||Ku==="http:"||Ku==="https:"||Ku==="ws:"||Ku==="wss:"}function qu(Ku,Zu){Ku=Lu(Ku),Ku=Ku.replace(Ru,""),Zu=Zu||{};var Qu=Pu.exec(Ku),Yu=Qu[1]?Qu[1].toLowerCase():"",ed=!!Qu[2],Xu=!!Qu[3],rd=0,nd;return ed?Xu?(nd=Qu[2]+Qu[3]+Qu[4],rd=Qu[2].length+Qu[3].length):(nd=Qu[2]+Qu[4],rd=Qu[2].length):Xu?(nd=Qu[3]+Qu[4],rd=Qu[3].length):nd=Qu[4],Yu==="file:"?rd>=2&&(nd=nd.slice(2)):zu(Yu)?nd=Qu[4]:Yu?ed&&(nd=nd.slice(2)):rd>=2&&zu(Zu.protocol)&&(nd=Qu[4]),{protocol:Yu,slashes:ed||zu(Yu),slashesCount:rd,rest:nd}}function Uu(Ku,Zu){if(Ku==="")return Zu;for(var Qu=(Zu||"/").split("/").slice(0,-1).concat(Ku.split("/")),Yu=Qu.length,ed=Qu[Yu-1],Xu=!1,rd=0;Yu--;)Qu[Yu]==="."?Qu.splice(Yu,1):Qu[Yu]===".."?(Qu.splice(Yu,1),rd++):rd&&(Yu===0&&(Xu=!0),Qu.splice(Yu,1),rd--);return Xu&&Qu.unshift(""),(ed==="."||ed==="..")&&Qu.push(""),Qu.join("/")}function Hu(Ku,Zu,Qu){if(Ku=Lu(Ku),Ku=Ku.replace(Ru,""),!(this instanceof Hu))return new Hu(Ku,Zu,Qu);var Yu,ed,Xu,rd,nd,od,ad=ju.slice(),ld=typeof Zu,fd=this,pd=0;for(ld!=="object"&&ld!=="string"&&(Qu=Zu,Zu=null),Qu&&typeof Qu!="function"&&(Qu=lo.parse),Zu=Fu(Zu),ed=qu(Ku||"",Zu),Yu=!ed.protocol&&!ed.slashes,fd.slashes=ed.slashes||Yu&&Zu.slashes,fd.protocol=ed.protocol||Zu.protocol||"",Ku=ed.rest,(ed.protocol==="file:"&&(ed.slashesCount!==2||Du.test(Ku))||!ed.slashes&&(ed.protocol||ed.slashesCount<2||!zu(fd.protocol)))&&(ad[3]=[/(.*)/,"pathname"]);pd<ad.length;pd++){if(rd=ad[pd],typeof rd=="function"){Ku=rd(Ku,fd);continue}Xu=rd[0],od=rd[1],Xu!==Xu?fd[od]=Ku:typeof Xu=="string"?(nd=Xu==="@"?Ku.lastIndexOf(Xu):Ku.indexOf(Xu),~nd&&(typeof rd[2]=="number"?(fd[od]=Ku.slice(0,nd),Ku=Ku.slice(nd+rd[2])):(fd[od]=Ku.slice(nd),Ku=Ku.slice(0,nd)))):(nd=Xu.exec(Ku))&&(fd[od]=nd[1],Ku=Ku.slice(0,nd.index)),fd[od]=fd[od]||Yu&&rd[3]&&Zu[od]||"",rd[4]&&(fd[od]=fd[od].toLowerCase())}Qu&&(fd.query=Qu(fd.query)),Yu&&Zu.slashes&&fd.pathname.charAt(0)!=="/"&&(fd.pathname!==""||Zu.pathname!=="")&&(fd.pathname=Uu(fd.pathname,Zu.pathname)),fd.pathname.charAt(0)!=="/"&&zu(fd.protocol)&&(fd.pathname="/"+fd.pathname),Au(fd.port,fd.protocol)||(fd.host=fd.hostname,fd.port=""),fd.username=fd.password="",fd.auth&&(nd=fd.auth.indexOf(":"),~nd?(fd.username=fd.auth.slice(0,nd),fd.username=encodeURIComponent(decodeURIComponent(fd.username)),fd.password=fd.auth.slice(nd+1),fd.password=encodeURIComponent(decodeURIComponent(fd.password))):fd.username=encodeURIComponent(decodeURIComponent(fd.auth)),fd.auth=fd.password?fd.username+":"+fd.password:fd.username),fd.origin=fd.protocol!=="file:"&&zu(fd.protocol)&&fd.host?fd.protocol+"//"+fd.host:"null",fd.href=fd.toString()}function Vu(Ku,Zu,Qu){var Yu=this;switch(Ku){case"query":typeof Zu=="string"&&Zu.length&&(Zu=(Qu||lo.parse)(Zu)),Yu[Ku]=Zu;break;case"port":Yu[Ku]=Zu,Au(Zu,Yu.protocol)?Zu&&(Yu.host=Yu.hostname+":"+Zu):(Yu.host=Yu.hostname,Yu[Ku]="");break;case"hostname":Yu[Ku]=Zu,Yu.port&&(Zu+=":"+Yu.port),Yu.host=Zu;break;case"host":Yu[Ku]=Zu,Ou.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=!Qu;break;case"pathname":case"hash":if(Zu){var ed=Ku==="pathname"?"/":"#";Yu[Ku]=Zu.charAt(0)!==ed?ed+Zu:Zu}else Yu[Ku]=Zu;break;case"username":case"password":Yu[Ku]=encodeURIComponent(Zu);break;case"auth":var Xu=Zu.indexOf(":");~Xu?(Yu.username=Zu.slice(0,Xu),Yu.username=encodeURIComponent(decodeURIComponent(Yu.username)),Yu.password=Zu.slice(Xu+1),Yu.password=encodeURIComponent(decodeURIComponent(Yu.password))):Yu.username=encodeURIComponent(decodeURIComponent(Zu))}for(var rd=0;rd<ju.length;rd++){var nd=ju[rd];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:"&&zu(Yu.protocol)&&Yu.host?Yu.protocol+"//"+Yu.host:"null",Yu.href=Yu.toString(),Yu}function Gu(Ku){(!Ku||typeof Ku!="function")&&(Ku=lo.stringify);var Zu,Qu=this,Yu=Qu.host,ed=Qu.protocol;ed&&ed.charAt(ed.length-1)!==":"&&(ed+=":");var Xu=ed+(Qu.protocol&&Qu.slashes||zu(Qu.protocol)?"//":"");return Qu.username?(Xu+=Qu.username,Qu.password&&(Xu+=":"+Qu.password),Xu+="@"):Qu.password?(Xu+=":"+Qu.password,Xu+="@"):Qu.protocol!=="file:"&&zu(Qu.protocol)&&!Yu&&Qu.pathname!=="/"&&(Xu+="@"),(Yu[Yu.length-1]===":"||Ou.test(Qu.hostname)&&!Qu.port)&&(Yu+=":"),Xu+=Yu+Qu.pathname,Zu=typeof Qu.query=="object"?Ku(Qu.query):Qu.query,Zu&&(Xu+=Zu.charAt(0)!=="?"?"?"+Zu:Zu),Qu.hash&&(Xu+=Qu.hash),Xu}return Hu.prototype={set:Vu,toString:Gu},Hu.extractProtocol=qu,Hu.location=Fu,Hu.trimLeft=Lu,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 Ou(qu){if(typeof document<"u"&&document){const Uu=document.createElement("a");return Uu.href=qu,Uu}return(0,$u.default)(qu)}Iu.parse=Ou;function Pu(qu){return(0,$u.default)(qu).hostname}Iu.getHostName=Pu;function Du(qu){return qu&&Ou(qu).toString()}Iu.normalize=Du;function Lu(...qu){let Uu=(0,$u.default)(qu[0],{});const Hu=Uu.protocol===""&&Uu.slashes;Hu&&(Uu=(0,$u.default)(qu[0],"https:"+qu[0]));const Vu=`${Hu?"":Uu.protocol}${Uu.slashes?"//":""}${Uu.auth}${Uu.auth?"@":""}${Uu.host}`,Gu=lo.posix.join(`${Vu&&Uu.pathname[0]!=="/"?"/":""}${Uu.pathname}`,...qu.slice(1));return`${Vu}${Gu==="."?"":Gu}`}Iu.join=Lu;function ju(qu){return Lu(...qu.split("/").map(encodeURIComponent))}Iu.encodeParts=ju;function Bu(qu){const Uu=Object.keys(qu).filter(Hu=>Hu.length>0);return Uu.length?"?"+Uu.map(Hu=>{const Vu=encodeURIComponent(String(qu[Hu]));return Hu+(Vu?"="+Vu:"")}).join("&"):""}Iu.objectToQueryString=Bu;function Fu(qu){return qu.replace(/^\?/,"").split("&").reduce((Uu,Hu)=>{const[Vu,Gu]=Hu.split("=");return Vu.length>0&&(Uu[Vu]=decodeURIComponent(Gu||"")),Uu},{})}Iu.queryStringToObject=Fu;function zu(qu,Uu=!1){const{protocol:Hu}=Ou(qu);return(!Hu||qu.toLowerCase().indexOf(Hu)!==0)&&(Uu?qu.indexOf("//")!==0:qu.indexOf("/")!==0)}Iu.isLocal=zu})(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 Ou=(lo=Au.mode)!==null&&lo!==void 0?lo:getOption("mode"),Pu=($u=Au.workspace)!==null&&$u!==void 0?$u:getOption("workspace"),Du=Ou==="single-document"?"doc":"lab";Iu=url_1.URLExt.join(Iu,Du),Pu!==PageConfig.defaultWorkspace&&(Iu=url_1.URLExt.join(Iu,"workspaces",encodeURIComponent(Pu)));const Lu=(Ru=Au.treePath)!==null&&Ru!==void 0?Ru:getOption("treePath");return Lu&&(Iu=url_1.URLExt.join(Iu,"tree",url_1.URLExt.encodeParts(Lu))),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 Ou=getOption(Iu);if(Ou)return JSON.parse(Ou)}catch(Ou){console.warn(`Unable to parse ${Iu}.`,Ou)}return[]}Au.deferred=lo("deferredExtensions"),Au.disabled=lo("disabledExtensions");function $u(Iu){const Ou=Iu.indexOf(":");let Pu="";return Ou!==-1&&(Pu=Iu.slice(0,Ou)),Au.deferred.some(Du=>Du===Iu||Pu&&Du===Pu)}Au.isDeferred=$u;function Ru(Iu){const Ou=Iu.indexOf(":");let Pu="";return Ou!==-1&&(Pu=Iu.slice(0,Ou)),Au.disabled.some(Du=>Du===Iu||Pu&&Du===Pu)}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(...qu){const Uu=Au.posix.join(...qu);return Uu==="."?"":zu(Uu)}$u.join=Ru;function Iu(...qu){const Uu=Au.posix.join(...qu);return Uu==="."?"":Uu}$u.joinWithLeadingSlash=Iu;function Ou(qu,Uu){return Au.posix.basename(qu,Uu)}$u.basename=Ou;function Pu(qu){const Uu=zu(Au.posix.dirname(qu));return Uu==="."?"":Uu}$u.dirname=Pu;function Du(qu){return Au.posix.extname(qu)}$u.extname=Du;function Lu(qu){return qu===""?"":zu(Au.posix.normalize(qu))}$u.normalize=Lu;function ju(...qu){return zu(Au.posix.resolve(...qu))}$u.resolve=ju;function Bu(qu,Uu){return zu(Au.posix.relative(qu,Uu))}$u.relative=Bu;function Fu(qu){return qu.length>0&&qu.indexOf(".")!==0&&(qu=`.${qu}`),qu}$u.normalizeExtension=Fu;function zu(qu){return qu.indexOf("/")===0&&(qu=qu.slice(1)),qu}$u.removeSlash=zu})(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 Ou(){$u.disconnect(Pu)}function Pu(Du,Lu){Ou(),Iu.resolve([Du,Lu])}return $u.connect(Pu),(Ru??0)>0&&setTimeout(()=>{Ou(),Iu.reject(`Signal not emitted within ${Ru} ms.`)},Ru),Iu.promise}return signal$1}var text$i={},hasRequiredText;function requireText(){if(hasRequiredText)return text$i;hasRequiredText=1,Object.defineProperty(text$i,"__esModule",{value:!0}),text$i.Text=void 0;var Au;return(function(lo){function Ru(Du,Lu){let ju=Du;for(let Bu=0;Bu+1<Lu.length&&Bu<Du;Bu++){const Fu=Lu.charCodeAt(Bu);if(Fu>=55296&&Fu<=56319){const zu=Lu.charCodeAt(Bu+1);zu>=56320&&zu<=57343&&(ju--,Bu++)}}return ju}lo.jsIndexToCharIndex=Ru;function Iu(Du,Lu){let ju=Du;for(let Bu=0;Bu+1<Lu.length&&Bu<ju;Bu++){const Fu=Lu.charCodeAt(Bu);if(Fu>=55296&&Fu<=56319){const zu=Lu.charCodeAt(Bu+1);zu>=56320&&zu<=57343&&(ju++,Bu++)}}return ju}lo.charIndexToJsIndex=Iu;function Ou(Du,Lu=!1){return Du.replace(/^(\w)|[\s-_:]+(\w)/g,function(ju,Bu,Fu){return Fu?Fu.toUpperCase():Lu?Bu.toUpperCase():Bu.toLowerCase()})}lo.camelCase=Ou;function Pu(Du){return(Du||"").toLowerCase().split(" ").map(Lu=>Lu.charAt(0).toUpperCase()+Lu.slice(1)).join(" ")}lo.titleCase=Pu})(Au||(text$i.Text=Au={})),text$i}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(Ou,Pu="long"){const Du=document.documentElement.lang||"en",Lu=new Intl.RelativeTimeFormat(Du,{numeric:"auto",style:Pu}),ju=new Date(Ou).getTime()-Date.now();for(let Bu of Au){const Fu=Math.ceil(ju/Bu.milliseconds);if(Fu!==0)return Lu.format(Fu,Bu.name)}return Lu.format(0,"seconds")}$u.formatHuman=Ru;function Iu(Ou){const Pu=document.documentElement.lang||"en";return new Intl.DateTimeFormat(Pu,{dateStyle:"short",timeStyle:"short"}).format(new Date(Ou))}$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 Ou;super(Iu),this._pluginData=new Map,this._expectedActivationTime=(Ou=Iu?.expectedActivationTime)!==null&&Ou!==void 0?Ou:lo}registerPlugin(Iu){return this._pluginData.set(Iu.id,Iu),super.registerPlugin(Iu)}async activatePlugin(Iu){const Ou=performance.now();let Pu=setTimeout(()=>{console.warn(`Plugin ${Iu} is taking too long to activate.`)},this._expectedActivationTime);try{const Du=await super.activatePlugin(Iu);clearTimeout(Pu);const ju=performance.now()-Ou;if(ju>=this._expectedActivationTime){const Bu=this._getDependentCount(Iu);console.warn(`Plugin ${Iu} (with ${Bu} dependants) took ${ju.toFixed(2)}ms to activate.`)}return Du}catch(Du){throw clearTimeout(Pu),console.error(`Error activating plugin: ${Iu}`,Du),Du}}_getDependentCount(Iu){var Ou;const Pu=this._pluginData.get(Iu);if(!Pu?.provides)return 0;const Du=Pu.provides.name;let Lu=0;for(const[ju,Bu]of this._pluginData.entries()){if(ju===Iu)continue;!((Ou=Bu.requires)===null||Ou===void 0)&&Ou.filter(zu=>!!zu).some(zu=>zu.name===Du)&&Lu++}return Lu}}return pluginregistry.JupyterPluginRegistry=$u,pluginregistry}var hasRequiredLib$c;function requireLib$c(){return hasRequiredLib$c||(hasRequiredLib$c=1,(function(Au){var lo=lib$e&&lib$e.__createBinding||(Object.create?(function(Ru,Iu,Ou,Pu){Pu===void 0&&(Pu=Ou);var Du=Object.getOwnPropertyDescriptor(Iu,Ou);(!Du||("get"in Du?!Iu.__esModule:Du.writable||Du.configurable))&&(Du={enumerable:!0,get:function(){return Iu[Ou]}}),Object.defineProperty(Ru,Pu,Du)}):(function(Ru,Iu,Ou,Pu){Pu===void 0&&(Pu=Ou),Ru[Pu]=Iu[Ou]})),$u=lib$e&&lib$e.__exportStar||function(Ru,Iu){for(var Ou in Ru)Ou!=="default"&&!Object.prototype.hasOwnProperty.call(Iu,Ou)&&lo(Iu,Ru,Ou)};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$e)),lib$e}var libExports$5=requireLib$c();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((Ou,Pu)=>Ou+(Number.isFinite(Pu.credits)?Pu.credits:0),0);return Math.max(0,Ru-Iu)};function asIAMProviderLinked(Au){const lo=Au.linkedAccount.replaceAll("'",'"');return{iamProviderName:Au.iam_ProviderName,linkedAccount:JSON.parse(lo===""?"{}":lo),linkedAccountUrl:Au.linkedAccountUrl,linkedAccountId:Au.linkedAccountId}}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"}}},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??[];let Ru=[];try{Ru=(lo.iam_providers??[]).map(Ou=>asIAMProviderLinked(Ou))}catch{}this.iamProviders=Ru,this.settings=new UserSettings(lo.settings??{}),this.unsubscribedFromOutbounds=lo.unsubscribed_from_outbounds_b??!1,this.mfaUrl=lo.mfa_url_s,this.onboarding=lo.onboarding_s?JSON.parse(lo.onboarding_s):BOOTSTRAP_USER_ONBOARDING,this.linkedContactId=lo.linked_contact_uid,this.subscription=lo.subscription;let Iu=lo.events??[];Array.isArray(Iu)||(Iu=[Iu]),this.events=Iu.map(Ou=>asUserEvent(Ou)),this.events.sort((Ou,Pu)=>Ou.eventDate<Pu.eventDate?1:-1)}setRoles(lo){this.roles=lo}}function asUser(Au){return new User(Au)}var lib$d={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 Ou=0,Pu,Du,Lu=0,ju="";Du=Iu.charAt(Lu++);~Du&&(Pu=Ou%4?Pu*64+Du:Du,Ou++%4)?ju+=String.fromCharCode(255&Pu>>(-2*Ou&6)):0)Du=Au.indexOf(Du);return ju}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 Ou=Iu.charCodeAt(0).toString(16).toUpperCase();return Ou.length<2&&(Ou="0"+Ou),"%"+Ou}))}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$b;function requireLib$b(){if(hasRequiredLib$b)return lib$d.exports;hasRequiredLib$b=1;var Au=requireBase64_url_decode();function lo($u){this.message=$u}return lo.prototype=new Error,lo.prototype.name="InvalidTokenError",lib$d.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(Ou){throw new lo("Invalid token specified: "+Ou.message)}},lib$d.exports.InvalidTokenError=lo,lib$d.exports}var libExports$4=requireLib$b();const jwt_decode=getDefaultExportFromCjs(libExports$4);let _localStorageAvailable;function isLocalStorageAvailable(){if(_localStorageAvailable!==void 0)return _localStorageAvailable;try{if(typeof window>"u"||!window.localStorage)return _localStorageAvailable=!1,!1;const Au="__datalayer_ls_test__";return window.localStorage.setItem(Au,"test"),window.localStorage.removeItem(Au),_localStorageAvailable=!0,!0}catch{return _localStorageAvailable=!1,!1}}const JWT_DATALAYER_ISSUER="https://id.datalayer.run",DATALAYER_IAM_USER_KEY="@datalayer/iam:user",DATALAYER_IAM_TOKEN_KEY="@datalayer/iam:token",JWT_REFRESH_TOKEN_COOKIE_NAME="refresh_token",getStoredUser=()=>{if(!isLocalStorageAvailable())return ANONYMOUS_USER;const Au=window.localStorage.getItem(DATALAYER_IAM_USER_KEY);if(Au)try{const lo=JSON.parse(Au);return lo.joinDate=new Date(lo.joinDate),lo}catch{return ANONYMOUS_USER}return ANONYMOUS_USER},storeUser=Au=>{isLocalStorageAvailable()&&(Au?window.localStorage.setItem(DATALAYER_IAM_USER_KEY,JSON.stringify(Au)):window.localStorage.removeItem(DATALAYER_IAM_USER_KEY))},getStoredToken=()=>{if(!isLocalStorageAvailable())return ANONYMOUS_USER_TOKEN;const Au=window.localStorage.getItem(DATALAYER_IAM_TOKEN_KEY);return Au||ANONYMOUS_USER_TOKEN},storeToken=Au=>{if(isLocalStorageAvailable())if(Au){if(Au!==ANONYMOUS_USER_TOKEN)try{const lo=jwt_decode(Au);console.debug("JWT Token",lo)}catch(lo){throw console.error("Error while decoding JWT Token.",lo),lo}window.localStorage.setItem(DATALAYER_IAM_TOKEN_KEY,Au)}else window.localStorage.removeItem(DATALAYER_IAM_TOKEN_KEY)};function loadRefreshTokenFromCookie(){return getCookie$1(JWT_REFRESH_TOKEN_COOKIE_NAME)}function bind$1(Au,lo){return function(){return Au.apply(lo,arguments)}}const{toString:toString$4}=Object.prototype,{getPrototypeOf:getPrototypeOf$2}=Object,{iterator,toStringTag}=Symbol,hasOwnProperty$3=(({hasOwnProperty:Au})=>(lo,$u)=>Au.call(lo,$u))(Object.prototype),isUnsafeObjectKey=Au=>typeof Au=="string"&&(Au==="__proto__"||Au==="constructor"||Au==="prototype"),isPrototypeBoundary=(Au,lo,$u)=>Au===Object.prototype||!$u&&lo===null,isSafeAndFullyMutable=Au=>{if(!Object.isExtensible(Au))return!1;const lo=Object.getOwnPropertyNames(Au);return Object.getOwnPropertySymbols&&lo.push(...Object.getOwnPropertySymbols(Au)),lo.every($u=>{if(isUnsafeObjectKey($u))return!1;const Ru=Object.getOwnPropertyDescriptor(Au,$u);return!!Ru&&Ru.configurable&&Ru.writable===!0})},hasOwnInPrototypeChain=(Au,lo)=>{let $u=Au;const Ru=[];for(;$u!=null;){if(Ru.indexOf($u)!==-1)return!1;Ru.push($u);const Iu=getPrototypeOf$2($u);if(isPrototypeBoundary($u,Iu,$u===Au))return!1;if(hasOwnProperty$3($u,lo))return!0;$u=Iu}return!1},getSafeProp=(Au,lo)=>Au!=null&&hasOwnInPrototypeChain(Au,lo)?Au[lo]:void 0,toSafeFlatObject=Au=>{if(Au==null||typeof Au!="object"&&typeof Au!="function")return Au;const lo=getPrototypeOf$2(Au);if(lo===null&&isSafeAndFullyMutable(Au))return Au;const $u=Object.create(null),Ru=Object.create(null),Iu=[];let Ou=Au;for(;Ou!=null&&Iu.indexOf(Ou)===-1;){Iu.push(Ou);const Pu=Ou===Au?lo:getPrototypeOf$2(Ou);if(isPrototypeBoundary(Ou,Pu,Ou===Au))break;const Du=Object.getOwnPropertyNames(Ou);Object.getOwnPropertySymbols&&Du.push(...Object.getOwnPropertySymbols(Ou));for(const Lu of Du)isUnsafeObjectKey(Lu)||hasOwnProperty$3(Ru,Lu)||($u[Lu]=Au[Lu],Ru[Lu]=!0);Ou=Pu}return $u},kindOf$1=(Au=>lo=>{const $u=toString$4.call(lo);return Au[$u]||(Au[$u]=$u.slice(8,-1).toLowerCase())})(Object.create(null)),kindOfTest=Au=>(Au=Au.toLowerCase(),lo=>kindOf$1(lo)===Au),typeOfTest=Au=>lo=>typeof lo===Au,{isArray:isArray$2}=Array,isUndefined$1=typeOfTest("undefined");function isBuffer$2(Au){return Au!==null&&!isUndefined$1(Au)&&Au.constructor!==null&&!isUndefined$1(Au.constructor)&&isFunction$3(Au.constructor.isBuffer)&&Au.constructor.isBuffer(Au)}const isArrayBuffer$1=kindOfTest("ArrayBuffer");function isArrayBufferView(Au){let lo;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?lo=ArrayBuffer.isView(Au):lo=Au&&Au.buffer&&isArrayBuffer$1(Au.buffer),lo}const isString$4=typeOfTest("string"),isFunction$3=typeOfTest("function"),isNumber$6=typeOfTest("number"),isObject$8=Au=>Au!==null&&typeof Au=="object",isBoolean$1=Au=>Au===!0||Au===!1,isPlainObject$7=Au=>{if(!isObject$8(Au))return!1;const lo=getPrototypeOf$2(Au);return(lo===null||lo===Object.prototype||getPrototypeOf$2(lo)===null)&&!hasOwnInPrototypeChain(Au,toStringTag)&&!hasOwnInPrototypeChain(Au,iterator)},isEmptyObject$1=Au=>{if(!isObject$8(Au)||isBuffer$2(Au))return!1;try{return Object.keys(Au).length===0&&Object.getPrototypeOf(Au)===Object.prototype}catch{return!1}},isDate$1=kindOfTest("Date"),isFile=kindOfTest("File"),isReactNativeBlob=Au=>!!(Au&&typeof Au.uri<"u"),isReactNative$1=Au=>Au&&typeof Au.getParts<"u",isBlob=kindOfTest("Blob"),isFileList=kindOfTest("FileList"),isSet$1=kindOfTest("Set"),isStream$1=Au=>isObject$8(Au)&&isFunction$3(Au.pipe);function getGlobal$2(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof globalThis<"u"?globalThis:{}}const G$3=getGlobal$2(),FormDataCtor=typeof G$3.FormData<"u"?G$3.FormData:void 0,isFormData=Au=>{if(!Au)return!1;if(FormDataCtor&&Au instanceof FormDataCtor)return!0;const lo=getPrototypeOf$2(Au);if(!lo||lo===Object.prototype||!isFunction$3(Au.append))return!1;const $u=kindOf$1(Au);return $u==="formdata"||$u==="object"&&isFunction$3(Au.toString)&&Au.toString()==="[object FormData]"},isURLSearchParams=kindOfTest("URLSearchParams"),[isReadableStream,isRequest,isResponse,isHeaders]=["ReadableStream","Request","Response","Headers"].map(kindOfTest),trim$1=Au=>Au.trim?Au.trim():Au.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function forEach$1(Au,lo,{allOwnKeys:$u=!1}={}){if(Au===null||typeof Au>"u")return;let Ru,Iu;if(typeof Au!="object"&&(Au=[Au]),isArray$2(Au))for(Ru=0,Iu=Au.length;Ru<Iu;Ru++)lo.call(null,Au[Ru],Ru,Au);else{if(isBuffer$2(Au))return;const Ou=$u?Object.getOwnPropertyNames(Au):Object.keys(Au),Pu=Ou.length;let Du;for(Ru=0;Ru<Pu;Ru++)Du=Ou[Ru],lo.call(null,Au[Du],Du,Au)}}function findKey$1(Au,lo){if(isBuffer$2(Au))return null;lo=lo.toLowerCase();const $u=Object.keys(Au);let Ru=$u.length,Iu;for(;Ru-- >0;)if(Iu=$u[Ru],lo===Iu.toLowerCase())return Iu;return null}const _global=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:globalThis,isContextDefined=Au=>!isUndefined$1(Au)&&Au!==_global;function merge$3(...Au){const{caseless:lo,skipUndefined:$u}=isContextDefined(this)&&this||{},Ru={},Iu=(Ou,Pu)=>{if(Pu==="__proto__"||Pu==="constructor"||Pu==="prototype")return;const Du=lo&&typeof Pu=="string"&&findKey$1(Ru,Pu)||Pu,Lu=hasOwnProperty$3(Ru,Du)?Ru[Du]:void 0;isPlainObject$7(Lu)&&isPlainObject$7(Ou)?Ru[Du]=merge$3(Lu,Ou):isPlainObject$7(Ou)?Ru[Du]=merge$3({},Ou):isArray$2(Ou)?Ru[Du]=Ou.slice():(!$u||!isUndefined$1(Ou))&&(Ru[Du]=Ou)};for(let Ou=0,Pu=Au.length;Ou<Pu;Ou++){const Du=Au[Ou];if(!Du||isBuffer$2(Du)||(forEach$1(Du,Iu),typeof Du!="object"||isArray$2(Du)))continue;const Lu=Object.getOwnPropertySymbols(Du);for(let ju=0;ju<Lu.length;ju++){const Bu=Lu[ju];propertyIsEnumerable.call(Du,Bu)&&Iu(Du[Bu],Bu)}}return Ru}const extend$5=(Au,lo,$u,{allOwnKeys:Ru}={})=>(forEach$1(lo,(Iu,Ou)=>{$u&&isFunction$3(Iu)?Object.defineProperty(Au,Ou,{__proto__:null,value:bind$1(Iu,$u),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(Au,Ou,{__proto__:null,value:Iu,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:Ru}),Au),stripBOM=Au=>(Au.charCodeAt(0)===65279&&(Au=Au.slice(1)),Au),inherits=(Au,lo,$u,Ru)=>{Au.prototype=Object.create(lo.prototype,Ru),Object.defineProperty(Au.prototype,"constructor",{__proto__:null,value:Au,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(Au,"super",{__proto__:null,value:lo.prototype}),$u&&Object.assign(Au.prototype,$u)},toFlatObject=(Au,lo,$u,Ru)=>{let Iu,Ou,Pu;const Du={};if(lo=lo||{},Au==null)return lo;do{for(Iu=Object.getOwnPropertyNames(Au),Ou=Iu.length;Ou-- >0;)Pu=Iu[Ou],(!Ru||Ru(Pu,Au,lo))&&!Du[Pu]&&(lo[Pu]=Au[Pu],Du[Pu]=!0);Au=$u!==!1&&getPrototypeOf$2(Au)}while(Au&&(!$u||$u(Au,lo))&&Au!==Object.prototype);return lo},endsWith=(Au,lo,$u)=>{Au=String(Au),($u===void 0||$u>Au.length)&&($u=Au.length),$u-=lo.length;const Ru=Au.indexOf(lo,$u);return Ru!==-1&&Ru===$u},toArray$1=Au=>{if(!Au)return null;if(isArray$2(Au))return Au;let lo=Au.length;if(!isNumber$6(lo))return null;const $u=new Array(lo);for(;lo-- >0;)$u[lo]=Au[lo];return $u},isTypedArray$2=(Au=>lo=>Au&&lo instanceof Au)(typeof Uint8Array<"u"&&getPrototypeOf$2(Uint8Array)),forEachEntry=(Au,lo)=>{const Ru=(Au&&Au[iterator]).call(Au);let Iu;for(;(Iu=Ru.next())&&!Iu.done;){const Ou=Iu.value;lo.call(Au,Ou[0],Ou[1])}},matchAll=(Au,lo)=>{let $u;const Ru=[];for(;($u=Au.exec(lo))!==null;)Ru.push($u);return Ru},isHTMLForm=kindOfTest("HTMLFormElement"),toCamelCase$1=Au=>Au.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function($u,Ru,Iu){return Ru.toUpperCase()+Iu}),{propertyIsEnumerable}=Object.prototype,isRegExp$2=kindOfTest("RegExp"),reduceDescriptors=(Au,lo)=>{const $u=Object.getOwnPropertyDescriptors(Au),Ru={};forEach$1($u,(Iu,Ou)=>{let Pu;(Pu=lo(Iu,Ou,Au))!==!1&&(Ru[Ou]=Pu||Iu)}),Object.defineProperties(Au,Ru)},freezeMethods=Au=>{reduceDescriptors(Au,(lo,$u)=>{if(isFunction$3(Au)&&["arguments","caller","callee"].includes($u))return!1;const Ru=Au[$u];if(isFunction$3(Ru)){if(lo.enumerable=!1,"writable"in lo){lo.writable=!1;return}lo.set||(lo.set=()=>{throw Error("Can not rewrite read-only method '"+$u+"'")})}})},toObjectSet=(Au,lo)=>{const $u={},Ru=Iu=>{Iu.forEach(Ou=>{$u[Ou]=!0})};return isArray$2(Au)?Ru(Au):Ru(String(Au).split(lo)),$u},noop$2=()=>{},toFiniteNumber=(Au,lo)=>Au!=null&&Number.isFinite(Au=+Au)?Au:lo;function isSpecCompliantForm(Au){return!!(Au&&isFunction$3(Au.append)&&Au[toStringTag]==="FormData"&&Au[iterator])}const toJSONObject=Au=>{const lo=new WeakSet,$u=Ru=>{if(isObject$8(Ru)){if(lo.has(Ru))return;if(isBuffer$2(Ru))return Ru;if(!("toJSON"in Ru)){lo.add(Ru);let Iu;if(isSet$1(Ru)){Iu=[];for(const Ou of Ru){const Pu=$u(Ou);!isUndefined$1(Pu)&&Iu.push(Pu)}}else Iu=isArray$2(Ru)?[]:{},forEach$1(Ru,(Ou,Pu)=>{const Du=$u(Ou);!isUndefined$1(Du)&&(Iu[Pu]=Du)});return lo.delete(Ru),Iu}}return Ru};return $u(Au)},isAsyncFn=kindOfTest("AsyncFunction"),isThenable=Au=>Au&&(isObject$8(Au)||isFunction$3(Au))&&isFunction$3(Au.then)&&isFunction$3(Au.catch),_setImmediate=((Au,lo)=>Au?setImmediate:lo?(($u,Ru)=>(_global.addEventListener("message",({source:Iu,data:Ou})=>{Iu===_global&&Ou===$u&&Ru.length&&Ru.shift()()},!1),Iu=>{Ru.push(Iu),_global.postMessage($u,"*")}))(`axios@${Math.random()}`,[]):$u=>setTimeout($u))(typeof setImmediate=="function",isFunction$3(_global.postMessage)),asap=typeof queueMicrotask<"u"?queueMicrotask.bind(_global):typeof process<"u"&&process.nextTick||_setImmediate,isIterable=Au=>Au!=null&&isFunction$3(Au[iterator]),isSafeIterable=Au=>Au!=null&&hasOwnInPrototypeChain(Au,iterator)&&isIterable(Au),utils$3={isArray:isArray$2,isArrayBuffer:isArrayBuffer$1,isBuffer:isBuffer$2,isFormData,isArrayBufferView,isString:isString$4,isNumber:isNumber$6,isBoolean:isBoolean$1,isObject:isObject$8,isPlainObject:isPlainObject$7,isEmptyObject:isEmptyObject$1,isReadableStream,isRequest,isResponse,isHeaders,isUndefined:isUndefined$1,isDate:isDate$1,isFile,isReactNativeBlob,isReactNative:isReactNative$1,isBlob,isRegExp:isRegExp$2,isFunction:isFunction$3,isStream:isStream$1,isURLSearchParams,isTypedArray:isTypedArray$2,isFileList,forEach:forEach$1,merge:merge$3,extend:extend$5,trim:trim$1,stripBOM,inherits,toFlatObject,kindOf:kindOf$1,kindOfTest,endsWith,toArray:toArray$1,forEachEntry,matchAll,isHTMLForm,hasOwnProperty:hasOwnProperty$3,hasOwnProp:hasOwnProperty$3,hasOwnInPrototypeChain,getSafeProp,toSafeFlatObject,reduceDescriptors,freezeMethods,toObjectSet,toCamelCase:toCamelCase$1,noop:noop$2,toFiniteNumber,findKey:findKey$1,global:_global,isContextDefined,isSpecCompliantForm,toJSONObject,isAsyncFn,isThenable,setImmediate:_setImmediate,asap,isIterable,isSafeIterable},ignoreDuplicateOf=utils$3.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),parseHeaders=Au=>{const lo={};let $u,Ru,Iu;return Au&&Au.split(`
245
245
  `).forEach(function(Pu){Iu=Pu.indexOf(":"),$u=Pu.substring(0,Iu).trim().toLowerCase(),Ru=Pu.substring(Iu+1).trim();const Du=utils$3.hasOwnProp(lo,$u);!$u||Du&&utils$3.hasOwnProp(ignoreDuplicateOf,$u)||($u==="set-cookie"?Du?lo[$u].push(Ru):lo[$u]=[Ru]:lo[$u]=Du?lo[$u]+", "+Ru:Ru)}),lo};function trimSPorHTAB(Au){let lo=0,$u=Au.length;for(;lo<$u;){const Ru=Au.charCodeAt(lo);if(Ru!==9&&Ru!==32)break;lo+=1}for(;$u>lo;){const Ru=Au.charCodeAt($u-1);if(Ru!==9&&Ru!==32)break;$u-=1}return lo===0&&$u===Au.length?Au:Au.slice(lo,$u)}const INVALID_UNICODE_HEADER_VALUE_CHARS=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),INVALID_BYTE_STRING_HEADER_VALUE_CHARS=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function sanitizeValue(Au,lo){return utils$3.isArray(Au)?Au.map($u=>sanitizeValue($u,lo)):trimSPorHTAB(String(Au).replace(lo,""))}const sanitizeHeaderValue=Au=>sanitizeValue(Au,INVALID_UNICODE_HEADER_VALUE_CHARS),sanitizeByteStringHeaderValue=Au=>sanitizeValue(Au,INVALID_BYTE_STRING_HEADER_VALUE_CHARS);function toByteStringHeaderObject(Au){const lo=Object.create(null);return utils$3.forEach(Au.toJSON(),($u,Ru)=>{lo[Ru]=sanitizeByteStringHeaderValue($u)}),lo}const $internals$1=Symbol("internals");function normalizeHeader(Au){return Au&&String(Au).trim().toLowerCase()}function normalizeValue$1(Au){return Au===!1||Au==null?Au:utils$3.isArray(Au)?Au.map(normalizeValue$1):sanitizeHeaderValue(String(Au))}function parseTokens$1(Au){const lo=Object.create(null),$u=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let Ru;for(;Ru=$u.exec(Au);)lo[Ru[1]]=Ru[2];return lo}const parameterNameRE=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function trimOWS(Au){let lo=0,$u=Au.length;for(;lo<$u;){const Ru=Au.charCodeAt(lo);if(Ru!==9&&Ru!==32)break;lo+=1}for(;$u>lo;){const Ru=Au.charCodeAt($u-1);if(Ru!==9&&Ru!==32)break;$u-=1}return lo===0&&$u===Au.length?Au:Au.slice(lo,$u)}function decodeQuotedString(Au){const lo=Au.length-1;if(lo<1||Au.charCodeAt(0)!==34||Au.charCodeAt(lo)!==34)return Au;let $u="";for(let Ru=1;Ru<lo;Ru++){const Iu=Au.charCodeAt(Ru);if(Iu===34||Iu===92&&(Ru+=1,Ru>=lo))return Au;$u+=Au[Ru]}return $u}function parseParameters(Au){const lo=Object.create(null),$u=String(Au);let Ru=0,Iu=!1,Ou=!1;function Pu(Du){const Lu=trimOWS($u.slice(Ru,Du)),ju=Lu.indexOf("=");if(ju<1)return;const Bu=trimOWS(Lu.slice(0,ju));if(!parameterNameRE.test(Bu))return;const Fu=Bu.toLowerCase();if(Fu==="__proto__"||Fu==="constructor"||Fu==="prototype")return;const zu=trimOWS(Lu.slice(ju+1));lo[Fu]=decodeQuotedString(zu)}for(let Du=0;Du<$u.length;Du++){const Lu=$u.charCodeAt(Du);Iu?Ou?Ou=!1:Lu===92?Ou=!0:Lu===34&&(Iu=!1):Lu===34?Iu=!0:(Lu===44||Lu===59)&&(Pu(Du),Ru=Du+1)}return Pu($u.length),lo}const isValidHeaderName=Au=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(Au.trim());function matchHeaderValue(Au,lo,$u,Ru,Iu){if(utils$3.isFunction(Ru))return Ru.call(this,lo,$u);if(Iu&&(lo=$u),!!utils$3.isString(lo)){if(utils$3.isString(Ru))return lo.indexOf(Ru)!==-1;if(utils$3.isRegExp(Ru))return Ru.test(lo)}}function formatHeader$1(Au){return Au.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(lo,$u,Ru)=>$u.toUpperCase()+Ru)}function buildAccessors(Au,lo){const $u=utils$3.toCamelCase(" "+lo);["get","set","has"].forEach(Ru=>{Object.defineProperty(Au,Ru+$u,{__proto__:null,value:function(Iu,Ou,Pu){return this[Ru].call(this,lo,Iu,Ou,Pu)},configurable:!0})})}let AxiosHeaders$1=class{constructor(lo){lo&&this.set(lo)}set(lo,$u,Ru){const Iu=this;function Ou(Du,Lu,ju){const Bu=normalizeHeader(Lu);if(!Bu)return;const Fu=utils$3.findKey(Iu,Bu);(!Fu||Iu[Fu]===void 0||ju===!0||ju===void 0&&Iu[Fu]!==!1)&&(Iu[Fu||Lu]=normalizeValue$1(Du))}const Pu=(Du,Lu)=>utils$3.forEach(Du,(ju,Bu)=>Ou(ju,Bu,Lu));if(utils$3.isPlainObject(lo)||lo instanceof this.constructor)Pu(lo,$u);else if(utils$3.isString(lo)&&(lo=lo.trim())&&!isValidHeaderName(lo))Pu(parseHeaders(lo),$u);else if(utils$3.isObject(lo)&&utils$3.isSafeIterable(lo)){let Du=Object.create(null),Lu,ju;for(const Bu of lo){if(!utils$3.isArray(Bu))throw new TypeError("Object iterator must return a key-value pair");ju=Bu[0],utils$3.hasOwnProp(Du,ju)?(Lu=Du[ju],Du[ju]=utils$3.isArray(Lu)?[...Lu,Bu[1]]:[Lu,Bu[1]]):Du[ju]=Bu[1]}Pu(Du,$u)}else lo!=null&&Ou($u,lo,Ru);return this}get(lo,$u){if(lo=normalizeHeader(lo),lo){const Ru=utils$3.findKey(this,lo);if(Ru){const Iu=this[Ru];if(!$u)return Iu;if($u===!0)return parseTokens$1(Iu);if(utils$3.isFunction($u))return $u.call(this,Iu,Ru);if(utils$3.isRegExp($u))return $u.exec(Iu);throw new TypeError("parser must be boolean|regexp|function")}}}has(lo,$u){if(lo=normalizeHeader(lo),lo){const Ru=utils$3.findKey(this,lo);return!!(Ru&&this[Ru]!==void 0&&(!$u||matchHeaderValue(this,this[Ru],Ru,$u)))}return!1}delete(lo,$u){const Ru=this;let Iu=!1;function Ou(Pu){if(Pu=normalizeHeader(Pu),Pu){const Du=utils$3.findKey(Ru,Pu);Du&&(!$u||matchHeaderValue(Ru,Ru[Du],Du,$u))&&(delete Ru[Du],Iu=!0)}}return utils$3.isArray(lo)?lo.forEach(Ou):Ou(lo),Iu}clear(lo){const $u=Object.keys(this);let Ru=$u.length,Iu=!1;for(;Ru--;){const Ou=$u[Ru];(!lo||matchHeaderValue(this,this[Ou],Ou,lo,!0))&&(delete this[Ou],Iu=!0)}return Iu}normalize(lo){const $u=this,Ru={};return utils$3.forEach(this,(Iu,Ou)=>{const Pu=utils$3.findKey(Ru,Ou);if(Pu){$u[Pu]=normalizeValue$1(Iu),delete $u[Ou];return}const Du=lo?formatHeader$1(Ou):String(Ou).trim();Du!==Ou&&delete $u[Ou],$u[Du]=normalizeValue$1(Iu),Ru[Du]=!0}),this}concat(...lo){return this.constructor.concat(this,...lo)}toJSON(lo){const $u=Object.create(null);return utils$3.forEach(this,(Ru,Iu)=>{Ru!=null&&Ru!==!1&&($u[Iu]=lo&&utils$3.isArray(Ru)?Ru.join(", "):Ru)}),$u}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([lo,$u])=>lo+": "+$u).join(`
@@ -3437,7 +3437,7 @@ Tech
3437
3437
  Sales`,value:zu,onChange:ld=>qu(ld.target.value)})]}),Bu==="score"&&jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,children:[jsxRuntimeExports.jsxs(FormControl$1,{sx:{flex:1},children:[jsxRuntimeExports.jsx(FormControl$1.Label,{children:"From"}),jsxRuntimeExports.jsx(TextInput$1,{block:!0,size:"small",type:"number",name:"from",value:Uu,onChange:ld=>Hu(ld.target.value)})]}),jsxRuntimeExports.jsxs(FormControl$1,{sx:{flex:1},children:[jsxRuntimeExports.jsx(FormControl$1.Label,{children:"To"}),jsxRuntimeExports.jsx(TextInput$1,{block:!0,size:"small",type:"number",name:"to",value:Vu,onChange:ld=>Gu(ld.target.value)})]})]}),Ku?jsxRuntimeExports.jsx(Text$5,{as:"p",role:"alert",sx:{m:0,color:"danger.fg",fontSize:0},children:Ku}):null,jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",type:"submit",disabled:Qu,children:Qu?DECISION_WORDS.asking:DECISION_WORDS.submit}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",type:"button",onClick:od,disabled:Qu,children:DECISION_WORDS.cancel})]})]})}const DEFAULT_BALLOON_DISPLAY="history";let displayNames=null;function toolDisplayName(Au){if(!displayNames){displayNames=new Map;for(const Ru of Object.values(BACKEND_TOOL_CATALOG)){const Iu=Ru.runtime?.method;Iu&&Ru.name&&!displayNames.has(Iu)&&displayNames.set(Iu,Ru.name)}}const lo=displayNames.get(Au);if(lo)return lo;const $u=Au.indexOf("__");return $u>0?Au.slice($u+2):Au}function toolLineParts(Au,lo=ENGLISH_CHAT_WORDS){if(Au.phase==="running"&&Au.words)return{before:"",name:"",after:Au.words};switch(Au.phase){case"running":return{...lo.toolRunning,name:Au.name};case"done":return{...lo.toolDone,name:Au.name};case"failed":return{...lo.toolFailedLine,name:Au.name}}}function toolLineText(Au,lo=ENGLISH_CHAT_WORDS){const{before:$u,name:Ru,after:Iu}=toolLineParts(Au,lo);return`${$u}${Ru}${Iu}`}function newestToolLine(Au){const lo=Au[Au.length-1];if(!lo||typeof lo.toolName!="string"||!lo.toolName)return;const $u=lo.status==="error"||typeof lo.error=="string"&&lo.error?"failed":lo.status==="complete"?"done":"running";return{id:String(lo.toolCallId??lo.id??lo.toolName),tool:lo.toolName,name:toolDisplayName(lo.toolName),phase:$u}}function toolAnnouncement(Au,lo,$u=ENGLISH_CHAT_WORDS){if(Au&&!(lo&&lo.id===Au.id&&lo.phase===Au.phase))return toolLineText(Au,$u)}function conversationCount(Au){return Au.filter(lo=>{const $u=lo;return($u.role==="user"||$u.role==="assistant")&&typeof $u.toolName!="string"}).length}function displayItemOfLine(Au){return!Au.tool&&!Au.name?{id:`balloon-activity:${Au.id}`,role:"assistant",content:Au.words??"",createdAt:new Date(0)}:toolCallOfLine(Au)}function toolCallOfLine(Au){return{id:`balloon-tool:${Au.id}`,type:"tool-call",toolCallId:Au.id,toolName:Au.tool||Au.name,args:{},status:Au.phase==="failed"?"error":Au.phase==="done"?"complete":"executing",...Au.words?{summary:Au.words}:{}}}function withToolCall(Au,lo){return!lo||Au.some($u=>$u.toolCallId===lo.id||$u.id===lo.id)?Au:[...Au,displayItemOfLine(lo)]}const VISUALLY_HIDDEN={position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap"},BALLOON_AVATARS={userAvatar:null,assistantAvatar:null,showAvatars:!1,avatarSize:0,userAvatarBg:"neutral.muted",assistantAvatarBg:"accent.emphasis"};async function respondInBalloon(Au,lo){if(lo&&typeof lo=="object"){const $u=lo;$u.type==="tool-approval-decision"&&typeof $u.approved=="boolean"&&typeof $u.approvalId=="string"&&agentRuntimeStore.getState().sendDecision($u.approvalId,$u.approved)}}function BalloonChatItems({items:Au,density:lo="compact",waiting:$u=!1}){const Ru=reactExports.useRef(null);return jsxRuntimeExports.jsx(Box,{"data-balloon-chat-items":"",minWidth:0,children:jsxRuntimeExports.jsx(ChatMessageList,{displayItems:Au,isLoading:$u,isStreaming:!1,showLoadingIndicator:$u,hideMessagesAfterToolUI:!1,avatarConfig:BALLOON_AVATARS,padding:0,onRespond:respondInBalloon,messagesEndRef:Ru,emptyContent:$u?jsxRuntimeExports.jsx(TypingDots,{size:6}):null,density:lo})})}function BalloonToolCall({line:Au,waiting:lo=!1}){return jsxRuntimeExports.jsx(Box,{"aria-hidden":"true","data-balloon-tool":Au.phase,"data-balloon-tool-name":Au.tool||void 0,minWidth:0,width:"100%",children:jsxRuntimeExports.jsx(BalloonChatItems,{items:[displayItemOfLine(Au)],waiting:lo})})}function ToolLineAnnouncer({line:Au}){const lo=useChatWords(),$u=reactExports.useRef(void 0),[Ru,Iu]=reactExports.useState("");return reactExports.useEffect(()=>{const Ou=toolAnnouncement(Au,$u.current,lo);Au&&Ou&&($u.current={id:Au.id,phase:Au.phase},Iu(Ou))},[Au?.id,Au?.phase]),jsxRuntimeExports.jsx(Box,{as:"span",role:"status","aria-live":"polite","data-balloon-announce":"",...VISUALLY_HIDDEN,children:Ru})}function BalloonNow({busy:Au=!1}){const lo=useChatWords();return jsxRuntimeExports.jsxs(Box,{as:"span","data-balloon-now":Au?"busy":"",display:"inline-flex",alignItems:"center",gap:"6px",fontSize:0,fontWeight:"semibold",color:"accent.fg",textTransform:"uppercase",letterSpacing:"0.04em",sx:{"@keyframes balloonNowBreathe":{"0%, 100%":{opacity:1,transform:"scale(1)"},"50%":{opacity:.35,transform:"scale(0.7)"}},"& [data-balloon-now-dot]":{width:6,height:6,borderRadius:"50%",bg:"accent.emphasis",animation:Au?"balloonNowBreathe 1.2s ease-in-out infinite":"none"},"@media (prefers-reduced-motion: reduce)":{"& [data-balloon-now-dot]":{animation:"none"}}},children:[jsxRuntimeExports.jsx(Box,{as:"span","data-balloon-now-dot":"","aria-hidden":"true"}),lo.now]})}function conversationHeaderText(Au,lo=ENGLISH_CHAT_WORDS){return Au>0?`${lo.conversation} · ${Au}`:lo.conversation}function ConversationBalloonHeader({count:Au}){const lo=useChatWords();return jsxRuntimeExports.jsx(Box,{"data-balloon-header":"",flexShrink:0,display:"flex",alignItems:"center",gap:2,pl:3,pr:6,py:2,borderBottom:"1px solid",borderColor:"border.muted",bg:"canvas.default",borderTopLeftRadius:"var(--theme-radius-bubble, 16px)",borderTopRightRadius:"var(--theme-radius-bubble, 16px)",children:jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,fontWeight:"semibold",color:"fg.muted"},children:conversationHeaderText(Au,lo)})})}function CurrentBalloonBody({text:Au,tool:lo,busy:$u=!1,speaking:Ru=!1,attachment:Iu,waiting:Ou=!1,whole:Pu=!1,fullText:Du,onOverflow:Lu}){const ju=reactExports.useRef(null);return reactExports.useLayoutEffect(()=>{const Bu=ju.current;!Bu||Pu||!Lu||Lu(Bu.scrollHeight>Bu.clientHeight+1)},[Au,Pu,Lu]),jsxRuntimeExports.jsxs(Box,{"data-balloon-current":"",display:"flex",flexDirection:"column",gap:1,minWidth:0,children:[jsxRuntimeExports.jsx(BalloonNow,{busy:$u}),lo?jsxRuntimeExports.jsx(BalloonToolCall,{line:lo,waiting:Ou}):Au?jsxRuntimeExports.jsxs(Box,{"aria-live":"polite","aria-busy":Ru,ref:ju,"data-balloon-current-text":Pu?"whole":"",maxHeight:Pu?240:"5.6em",overflowY:Pu?"auto":void 0,overflowWrap:"anywhere",pr:Pu?1:void 0,overflow:Pu?void 0:"hidden",children:[jsxRuntimeExports.jsx(ChatMarkdown,{density:"compact",text:Pu?Du??Au:Au}),Ou&&jsxRuntimeExports.jsx(Box,{as:"span",ml:2,display:"inline-flex",children:jsxRuntimeExports.jsx(TypingDots,{size:5})})]}):Ou?jsxRuntimeExports.jsx(TypingDots,{size:6}):null,Iu,jsxRuntimeExports.jsx(ToolLineAnnouncer,{line:lo})]})}const BalloonExpandContext=reactExports.createContext(null);function BalloonExpandButton({title:Au,onExpand:lo}){const $u=useChatWords();return jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",leadingVisual:ScreenFullIcon,"aria-label":$u.expandWhat(Au),"data-balloon-expand":"",onClick:lo,sx:{alignSelf:"flex-start",px:1},children:$u.expand})}const EXPANDED_DIALOG_SIZE={width:"80vw",height:"80vh"};function ExpandedVisual({visual:Au,target:lo,onClose:$u}){const Ru=lo?.current;return lo?Ru?reactDomExports.createPortal(jsxRuntimeExports.jsxs(Box,{"data-balloon-expanded":"target","data-balloon-visual":Au.id,position:"relative",minWidth:0,children:[jsxRuntimeExports.jsx(Box,{position:"absolute",top:0,right:0,zIndex:1,children:jsxRuntimeExports.jsx(IconButton,{icon:Au.shrink?ScreenNormalIcon:XIcon,size:"small",variant:"invisible","aria-label":`${Au.shrink?"Shrink":"Close"} ${Au.title}`,"data-balloon-expanded-close":"",...Au.shrink?{"data-balloon-shrink":""}:{},onClick:$u})}),Au.render("target")]}),Ru):null:jsxRuntimeExports.jsx(Dialog$1,{title:Au.title,onClose:$u,sx:{width:EXPANDED_DIALOG_SIZE.width,maxWidth:EXPANDED_DIALOG_SIZE.width,height:EXPANDED_DIALOG_SIZE.height,maxHeight:EXPANDED_DIALOG_SIZE.height},children:jsxRuntimeExports.jsx(Box,{"data-balloon-expanded":"overlay","data-balloon-visual":Au.id,minWidth:0,children:Au.render("overlay")})})}function focusExpanded(Au){const lo=Au?.current;if(!lo)return;const $u=typeof window<"u"&&!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;lo.scrollIntoView?.({behavior:$u?"auto":"smooth",block:"start"}),(lo.querySelector('[tabindex="-1"]')??lo).focus?.({preventScroll:!0})}function BalloonSuggestions({suggestions:Au,onSuggestion:lo}){const $u=useChatWords();return jsxRuntimeExports.jsx(Box,{role:"group","aria-label":$u.suggestions,"data-balloon-suggestions":"",display:"flex",flexWrap:"wrap",gap:1,mt:2,children:Au.map(Ru=>jsxRuntimeExports.jsx(ButtonComponent,{size:"small","data-balloon-suggestion":Ru.label,"aria-label":`Ask: ${Ru.prompt}`,title:Ru.prompt,onClick:()=>lo(Ru),sx:{borderRadius:999},children:Ru.label},Ru.label))})}const BALLOON_HISTORY_MAX_HEIGHT=220,BALLOON_HISTORY_WITH_ATTACHMENT_MAX_HEIGHT=120;function BalloonHistoryLarge({history:Au,tool:lo,attachment:$u}){const Ru=useChatWords();return jsxRuntimeExports.jsxs(Box,{role:"log","aria-label":Ru.conversation,"data-balloon-history-large":"",display:"flex",flexDirection:"column",gap:2,children:[jsxRuntimeExports.jsx(BalloonChatItems,{items:withToolCall(Au,lo),density:"comfortable"}),$u?jsxRuntimeExports.jsx(Box,{children:$u}):null]})}function BalloonHistory({history:Au,onOpen:lo,maxHeight:$u=BALLOON_HISTORY_MAX_HEIGHT,onExpand:Ru,tool:Iu,waiting:Ou=!1}){const Pu=useChatWords(),Du=reactExports.useRef(null),Lu=Au[Au.length-1]?.id;return reactExports.useEffect(()=>{const ju=Du.current;ju&&(ju.scrollTop=ju.scrollHeight)},[Au.length,Lu,Ou,Iu?.id,Iu?.phase]),reactExports.useEffect(()=>{const ju=Du.current,Bu=ju?.firstElementChild;if(!ju||!Bu||typeof ResizeObserver>"u")return;const Fu=new ResizeObserver(()=>{ju.scrollTop=ju.scrollHeight});return Fu.observe(Bu),()=>Fu.disconnect()},[]),jsxRuntimeExports.jsxs(Box,{"data-balloon-history":"",flex:1,minWidth:0,display:"flex",flexDirection:"column",children:[jsxRuntimeExports.jsx(Box,{as:"button",type:"button","data-balloon-peek":"","data-balloon-header":"",onClick:lo,m:0,p:0,pb:1,border:0,bg:"transparent",font:"inherit",textAlign:"left",cursor:"pointer",fontSize:0,fontWeight:"semibold",color:"fg.muted",hover:{textDecoration:"underline"},children:conversationHeaderText(conversationCount(Au),Pu)}),Ru?jsxRuntimeExports.jsx(IconButton,{icon:ScreenFullIcon,size:"small",variant:"invisible","aria-label":Pu.expandConversation,"data-balloon-history-expand":"",onClick:Ru,sx:{position:"absolute",top:"4px",right:"28px"}}):null,jsxRuntimeExports.jsx(Box,{ref:Du,role:"log","aria-label":Pu.conversation,"data-balloon-history-list":"",maxHeight:$u,overflowY:"auto",display:"flex",flexDirection:"column",pr:1,children:jsxRuntimeExports.jsx(BalloonChatItems,{items:withToolCall(Au,Iu),waiting:Ou})})]})}function SpeechBalloon({text:Au,more:lo=!1,onOpen:$u,above:Ru,side:Iu="above",align:Ou,tailAt:Pu,approval:Du,decide:Lu,onDecisionActive:ju,wide:Bu=!1,onDismissPeek:Fu,display:zu="history",tool:qu,speaking:Uu=!1,busy:Hu=!1,attachment:Vu,history:Gu,onExpand:Ku,expandTitle:Zu,suggestions:Qu,onSuggestion:Yu,waiting:ed=!1,fullText:Xu,onExpandHistory:rd}){const nd=useChatWords(),[od,ad]=reactExports.useState(!1),[ld,fd]=reactExports.useState(!1),pd=!!Xu&&Xu!==Au||!!lo&&Au.endsWith("…"),Sd=Xu??Au;reactExports.useEffect(()=>{ad(!1)},[Sd.slice(0,40)]);const wd=Qu&&Qu.length>0&&Yu&&!Du?Qu:null,bd=zu==="current",Td=!bd&&Gu&&Gu.length>0?Gu:null;return jsxRuntimeExports.jsxs(Box,{"data-speech-balloon":"","data-balloon-display":zu,maxWidth:Bu||Td||wd||od||bd&&Vu?300:bd?260:280,px:3,py:2,color:"fg.default",border:"1px solid",borderRadius:"bubble",boxShadow:"shadow.medium",fontSize:1,textAlign:"left",bottom:Iu==="above"?`${Ru}px`:void 0,top:Iu==="above"?void 0:`${Ru}px`,sx:{position:"absolute",[Ou]:0,width:Bu||Td||wd||od||bd&&Vu?300:"max-content",bg:"canvas.default",borderColor:bd?"accent.muted":"border.default","&::after":{content:'""',position:"absolute",...Iu==="above"?{bottom:"-7px"}:{top:"-7px"},[Ou]:`${Pu-6}px`,width:12,height:12,bg:"canvas.default",borderRight:"1px solid",borderBottom:"1px solid",borderColor:bd?"accent.muted":"border.default",transform:Iu==="above"?"rotate(45deg)":"rotate(225deg)"}},children:[jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"flex-start",gap:1,children:[bd&&!Du?jsxRuntimeExports.jsx(Box,{role:"button",tabIndex:0,"data-balloon-peek":"",onClick:Pd=>{const ud=Pd.target.closest("button");ud&&Pd.currentTarget.contains(ud)||$u()},onKeyDown:Pd=>{Pd.target===Pd.currentTarget&&(Pd.key==="Enter"||Pd.key===" ")&&(Pd.preventDefault(),$u())},flex:1,minWidth:0,m:0,p:0,border:0,bg:"transparent",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer",children:jsxRuntimeExports.jsx(CurrentBalloonBody,{text:Au,tool:qu,busy:Hu,speaking:Uu,waiting:ed,whole:od,fullText:Sd,onOverflow:fd})}):Td?jsxRuntimeExports.jsx(BalloonHistory,{history:Td,onOpen:$u,onExpand:rd,tool:qu,waiting:ed,maxHeight:Vu?BALLOON_HISTORY_WITH_ATTACHMENT_MAX_HEIGHT:BALLOON_HISTORY_MAX_HEIGHT}):qu?jsxRuntimeExports.jsx(Box,{flex:1,minWidth:0,children:jsxRuntimeExports.jsx(BalloonToolCall,{line:qu})}):jsxRuntimeExports.jsx(Box,{as:"button",type:"button","data-balloon-peek":"","data-balloon-more":lo?"":void 0,onClick:$u,flex:1,minWidth:0,m:0,p:0,border:0,bg:"transparent",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer",hover:{textDecoration:"underline"},children:jsxRuntimeExports.jsx(Box,{as:"span",role:"status","aria-live":"polite",children:Au})}),Fu&&!Du?jsxRuntimeExports.jsx(IconButton,{icon:XIcon,size:"small",variant:"invisible","aria-label":nd.dismiss,"data-balloon-dismiss":"",onClick:Fu,sx:{mt:"-4px",mr:"-8px",flexShrink:0}}):null]}),bd&&!Du&&!qu&&(pd||ld||od)?jsxRuntimeExports.jsx(Box,{as:"button",type:"button","aria-expanded":od,"data-balloon-whole":od?"less":"more",onClick:()=>ad(!od),m:0,mt:1,p:0,border:0,bg:"transparent",color:"accent.fg",font:"inherit",fontSize:0,cursor:"pointer",hover:{textDecoration:"underline"},children:od?nd.showLess:nd.showMore}):null,!bd&&!Td&&ed?jsxRuntimeExports.jsx(Box,{"data-balloon-waiting":"",mt:1,children:jsxRuntimeExports.jsx(BalloonChatItems,{items:[],waiting:!0})}):null,Du&&jsxRuntimeExports.jsxs(Box,{"data-balloon-approval":Du.id,mt:1,children:[jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{m:0,fontWeight:"semibold"},children:Du.asks}),Du.why?jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:Du.why}):null,jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,mt:2,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",disabled:Du.deciding,onClick:Du.onApprove,children:nd.approve}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Du.deciding,onClick:Du.onDeny,children:nd.deny})]}),Du.others>0?jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{m:0,mt:1,color:"fg.muted",fontSize:0},children:nd.moreWaiting(Du.others)}):null]}),wd&&Yu?jsxRuntimeExports.jsx(BalloonSuggestions,{suggestions:wd,onSuggestion:Yu}):null,Vu?jsxRuntimeExports.jsxs(Box,{"data-balloon-attachment":"",mt:2,display:"flex",flexDirection:"column",gap:1,children:[Vu,Ku?jsxRuntimeExports.jsx(BalloonExpandButton,{title:Zu??nd.theVisual,onExpand:Ku}):null]}):null,bd?null:jsxRuntimeExports.jsx(ToolLineAnnouncer,{line:qu}),Lu&&jsxRuntimeExports.jsx(DecisionAsk,{ask:Lu,onActiveChange:ju})]})}const MENU_DESCRIPTION_MAX=60;function shortDescription(Au){const lo=Au.replace(/\s+/g," ").trim();if(lo.length<=MENU_DESCRIPTION_MAX)return lo;const $u=lo.slice(0,MENU_DESCRIPTION_MAX),Ru=$u.lastIndexOf(" ");return`${(Ru>MENU_DESCRIPTION_MAX/2?$u.slice(0,Ru):$u).replace(/[\s,.;:!?—-]+$/,"")}…`}function menuGroups(Au){const lo=[];for(const $u of Au){const Ru=lo.find(Iu=>Iu.group===$u.group);Ru?Ru.items.push($u):lo.push({group:$u.group,items:[$u]})}return[...lo.filter($u=>$u.group===void 0),...lo.filter($u=>$u.group!==void 0)]}function opensContextMenu(Au){return Au.key==="ContextMenu"||Au.key==="F10"&&Au.shiftKey}const LONG_PRESS_MS=550;function AssistantContextMenu({at:Au,items:lo,onClose:$u,returnFocusRef:Ru,label:Iu}){const Ou=reactExports.useRef(null),Pu=Au!==null;if(reactExports.useEffect(()=>{if(!Pu)return;const Lu=()=>$u();return window.addEventListener("scroll",Lu,!0),()=>window.removeEventListener("scroll",Lu,!0)},[Pu,$u]),!Au||typeof document>"u")return null;const Du=menuGroups(lo);return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[reactDomExports.createPortal(jsxRuntimeExports.jsx("div",{ref:Ou,"aria-hidden":"true","data-assistant-menu-anchor":"",style:{position:"fixed",left:Au.x,top:Au.y,width:1,height:1,pointerEvents:"none"}}),document.body),jsxRuntimeExports.jsx(ActionMenu,{open:!0,anchorRef:Ou,onOpenChange:Lu=>{Lu||($u(),requestAnimationFrame(()=>Ru?.current?.focus()))},children:jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"auto","data-assistant-menu":"",children:jsxRuntimeExports.jsx(ActionList,{"aria-label":Iu,children:Du.map(({group:Lu,items:ju},Bu)=>{const Fu=ju.some(qu=>qu.checked!==void 0),zu=ju.map(qu=>jsxRuntimeExports.jsxs(ActionList.Item,{"data-assistant-menu-item":qu.id,disabled:qu.disabled,variant:qu.danger?"danger":"default",...Fu?{selected:!!qu.checked}:{},onSelect:()=>{qu.onSelect(),$u(),requestAnimationFrame(()=>Ru?.current?.focus())},children:[qu.icon&&jsxRuntimeExports.jsx(ActionList.LeadingVisual,{children:jsxRuntimeExports.jsx(qu.icon,{})}),qu.label,qu.description&&jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:jsxRuntimeExports.jsx("span",{title:qu.description,children:shortDescription(qu.description)})})]},qu.id));return jsxRuntimeExports.jsxs(ActionList.Group,{...Fu?{selectionVariant:"single"}:{},children:[Lu&&jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:Lu}),zu]},Lu??`ungrouped-${Bu}`)})})})})]})}const NAMES={idle:[],thinking:["Thinking","Think","CheckingSomething","Searching","Search","Uncertain"],working:["Processing","Working","Writing","Write","Searching","Search","GetTechy","CheckingSomething","Read","Reading"],waiting:["GetAttention","Alert","Suggest","LookDown","GestureDown","Acknowledge"],paused:["IdleSnooze","Sleep","Sleeping","Snooze","Rest","RestPose"],greeting:["Greeting","Greet","Show","Wave"],speaking:["Explain","Speak","Speaking","Announce","GestureRight","GestureLeft"],goodbye:["GoodBye","Goodbye","Hide","Wave"]},AUTHORED={idle:["IdlingLevel1","IdlingLevel2","IdlingLevel3"],thinking:[],working:[],waiting:["Listening"],paused:[],greeting:["Showing"],speaking:["Speaking"],goodbye:["Hiding"]},IDLE$1=/^(idle|rest ?pose)/i,STATES=["idle","thinking","working","waiting","paused","greeting","speaking","goodbye"];function stateAnimations(Au){const lo=Object.keys(Au.animations);if(lo.length===0)throw new Error(`The character ${Au.name} has no animations.`);const $u=new Map;for(const Bu of lo)$u.has(Bu.toLowerCase())||$u.set(Bu.toLowerCase(),Bu);const Ru=new Map;for(const[Bu,Fu]of Object.entries(Au.authoredStates??{}))Ru.set(Bu.toLowerCase().replace(/\s+/g,""),Fu);const Iu=Bu=>{const Fu=[];for(const zu of Bu){const qu=$u.get(zu.toLowerCase());qu&&!Fu.includes(qu)&&Fu.push(qu)}return Fu},Ou=lo.filter(Bu=>IDLE$1.test(Bu)),Pu=Iu(AUTHORED.idle.flatMap(Bu=>Ru.get(Bu.toLowerCase())??[])),Du=[...new Set([...Ou,...Pu])],Lu=Du.length>0?Du:[lo[0]],ju={};for(const Bu of STATES){if(Bu==="idle"){ju.idle=Lu;continue}const Fu=[...new Set([...Iu(NAMES[Bu]),...Iu(AUTHORED[Bu].flatMap(zu=>Ru.get(zu.toLowerCase())??[]))])];ju[Bu]=Fu.length>0?Fu:Lu}return ju}function assistantStateOf(Au,lo={}){return lo.leaving?"goodbye":Au==="paused"?"paused":lo.arriving?"greeting":Au==="waiting"?"waiting":lo.speaking&&Au!=="idle"||lo.voicing?"speaking":Au}function newestIsAnswer(Au){const lo=Au[Au.length-1];return!!lo&&lo.role==="assistant"&&typeof lo.toolName!="string"}const SAYING_LIMIT=220;function plainWordsOf(Au){return(typeof Au=="string"?Au:Array.isArray(Au)?Au.map($u=>$u&&typeof $u=="object"&&$u.type==="text"?String($u.text??""):"").join(" "):"").replace(/```[\s\S]*?```/g," ").replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/[*_`#>]+/g,"").replace(/\s+/g," ").trim()}function markdownOf(Au){return typeof Au=="string"?Au:Array.isArray(Au)?Au.map(lo=>lo&&typeof lo=="object"&&lo.type==="text"?String(lo.text??""):"").join(`
3438
3438
 
3439
3439
  `):""}function latestSaying(Au){for(let lo=Au.length-1;lo>=0;lo-=1){const $u=Au[lo];if($u.role!=="assistant"||typeof $u.toolName=="string")continue;const Ru=plainWordsOf($u.content);if(!Ru)continue;const Iu=markdownOf($u.content);if(Ru.length<=SAYING_LIMIT)return{id:String($u.id??lo),text:Ru,more:!1,markdown:Iu};const Ou=Ru.slice(0,SAYING_LIMIT),Pu=Ou.slice(0,Math.max(Ou.lastIndexOf(" "),SAYING_LIMIT*.6));return{id:String($u.id??lo),text:`${Pu.trimEnd()}…`,more:!0,markdown:Iu}}}function mouthOpening(Au){return Au<.08?0:Au<.3?1:Au<.6?2:3}const ASSISTANT_AWAY_KEY="datalayer-assistant-away";function keptAway(){try{if(window.localStorage.getItem(ASSISTANT_AWAY_KEY)==="always")return"always";if(window.sessionStorage.getItem(ASSISTANT_AWAY_KEY)==="session")return"session"}catch{}return"none"}function keepAway(Au){try{window.localStorage.removeItem(ASSISTANT_AWAY_KEY),window.sessionStorage.removeItem(ASSISTANT_AWAY_KEY),Au==="always"?window.localStorage.setItem(ASSISTANT_AWAY_KEY,"always"):Au==="session"&&window.sessionStorage.setItem(ASSISTANT_AWAY_KEY,"session")}catch{}}const ASSISTANT_OBSTACLES=['[role="dialog"]','[role="alertdialog"]',"dialog[open]",'[class*="prc-Overlay-Overlay"]',"[data-chat-composer]"].join(", "),POINTER_ROOM=24,POINTER_CALM_MS=1500;function boxesMeet(Au,lo,$u=0){return Au.left-$u<lo.right&&lo.left<Au.right+$u&&Au.top-$u<lo.bottom&&lo.top<Au.bottom+$u}function pointerNear(Au,lo,$u=POINTER_ROOM){return boxesMeet(Au,{left:lo.x,top:lo.y,right:lo.x,bottom:lo.y},$u)}const MOUTH_STEP_MS=110,WIDE=["wide1","wide2","wide3","wide4"],BY_OPENING={0:["closed","narrow"],1:["narrow","medium","closed"],2:["medium","narrow",...WIDE],3:[...WIDE,"medium"]};function mouthFor(Au,lo,$u=Math.random()){const Ru=Object.keys(Au?.mouths??{});if(Ru.length===0)return;if(lo===void 0)return Ru[Math.min(Ru.length-1,Math.floor($u*Ru.length))];const Iu=BY_OPENING[mouthOpening(lo)],Ou=WIDE.filter(Pu=>Ru.includes(Pu));return mouthOpening(lo)===3&&Ou.length>0?Ou[Math.min(Ou.length-1,Math.floor($u*Ou.length))]:Iu.find(Pu=>Ru.includes(Pu))??Ru[0]}function playCharacterSound(Au){const lo=new Audio(Au);Promise.resolve(lo.play()).catch($u=>{console.warn(`A sound of the character was not played: ${String($u)}`)})}function nextFrameIndex(Au,lo,$u=Math.random()){const Ru=Au.frames[lo];let Iu=$u*100;for(const Ou of Ru?.branching??[]){if(Iu<Ou.weight)return Ou.frameIndex;Iu-=Ou.weight}return lo+1<Au.frames.length?lo+1:void 0}function animationFor(Au,lo,$u=Math.random()){const Ru=stateAnimations(Au)[lo];return Ru[Math.min(Ru.length-1,Math.floor($u*Ru.length))]}const reducedMotion=()=>typeof window<"u"&&!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;function SpriteCharacter({character:Au,state:lo,size:$u,sounds:Ru=!1,mouthLevel:Iu,playSound:Ou=playCharacterSound}){const[Pu,Du]=reactExports.useState(()=>({name:animationFor(Au,lo),index:0}));reactExports.useEffect(()=>{Du({name:animationFor(Au,lo),index:0})},[Au,lo]);const Lu=Au.animations[Pu.name],ju=Lu?.frames[Pu.index],Bu=reactExports.useMemo(reducedMotion,[]);reactExports.useEffect(()=>{if(!Lu||!ju||Bu)return;const Qu=setTimeout(()=>{const Yu=nextFrameIndex(Lu,Pu.index);Du(Yu===void 0?{name:animationFor(Au,lo),index:0}:{name:Pu.name,index:Yu})},Math.max(ju.duration,16));return()=>clearTimeout(Qu)},[Lu,ju,Pu,Au,lo,Bu]);const Fu=Ru&&ju?.sound!==void 0?Au.sounds?.[ju.sound]:void 0;reactExports.useEffect(()=>{Fu&&Ou(Fu)},[Fu,Pu,Ou]);const zu=lo==="speaking"&&!Bu&&!!ju?.mouths,[qu,Uu]=reactExports.useState();reactExports.useEffect(()=>{if(!zu){Uu(void 0);return}const Qu=()=>Uu(mouthFor(ju,Iu?.()));Qu();const Yu=setInterval(Qu,MOUTH_STEP_MS);return()=>clearInterval(Yu)},[zu,ju,Iu]);const Hu=zu&&qu?ju?.mouths?.[qu]:void 0,Vu=Hu?[Hu]:ju?.images??[],{width:Gu,height:Ku}=Au.frameSize,Zu=$u/Math.max(Gu,Ku);return jsxRuntimeExports.jsx("span",{className:"assistant-sprite",role:"img","aria-label":Au.name,"data-sprite-animation":Pu.name,...Hu?{"data-sprite-mouth":qu}:{},style:{position:"relative",display:"block",width:$u,height:$u},children:Vu.map((Qu,Yu)=>jsxRuntimeExports.jsx("span",{"aria-hidden":!0,style:{position:"absolute",left:($u-Gu*Zu)/2,top:($u-Ku*Zu)/2,width:Gu,height:Ku,transform:`scale(${Zu})`,transformOrigin:"top left",backgroundImage:`url(${Au.sprite})`,backgroundPosition:`-${Qu.x}px -${Qu.y}px`,backgroundRepeat:"no-repeat",imageRendering:"pixelated"}},Yu))})}const MOTIONS={"@keyframes assistantFloat":{"0%, 100%":{transform:"translateY(0)"},"50%":{transform:"translateY(-3px)"}},"@keyframes assistantBlink":{"0%, 94%, 100%":{transform:"scaleY(0)"},"97%":{transform:"scaleY(1)"}},"@keyframes assistantTilt":{"0%, 100%":{transform:"rotate(-5deg)"},"50%":{transform:"rotate(-8deg) translateY(-2px)"}},"@keyframes assistantWork":{"0%, 100%":{transform:"rotate(-3deg) translateY(0)"},"50%":{transform:"rotate(3deg) translateY(-4px)"}},"@keyframes assistantAttention":{"0%, 100%":{transform:"scale(1) rotate(0)"},"20%":{transform:"scale(1.08) rotate(-6deg)"},"40%":{transform:"scale(1.08) rotate(6deg)"},"60%":{transform:"scale(1)"}},"@keyframes assistantHop":{"0%, 100%":{transform:"translateY(0)"},"30%":{transform:"translateY(-14px)"},"55%":{transform:"translateY(0)"},"75%":{transform:"translateY(-6px)"}},"@keyframes assistantTalk":{"0%, 100%":{transform:"scaleY(1)"},"50%":{transform:"scaleY(2.2)"}},"@keyframes assistantDoze":{"0%, 100%":{transform:"translateY(2px) scale(1, 0.97)"},"50%":{transform:"translateY(3px) scale(1.02, 0.95)"}},"@keyframes assistantLeave":{from:{transform:"scale(1)",opacity:1},to:{transform:"scale(0.2) translateY(20px)",opacity:0}}},BODY="& .assistant-body",AWAY_CHOICES=[{away:"page",label:"Hide for now"},{away:"session",label:"Hide for this session"},{away:"always",label:"Don’t show again"}],AgentInspectorDialog=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/AgentInspectorDialog-zGMiFR5z.js"),[],import.meta.url)),AgentDetailsDialog=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/AgentDetailsDialog-DQfL7V4R.js"),[],import.meta.url)),SandboxDetailsDialog=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/SandboxDetailsDialog-22wdG0V-.js"),[],import.meta.url));function assistantMenuItems(Au){const lo=[];if(Au.inspect&&lo.push({id:"inspect",label:"Inspect the agent…",icon:PulseIcon,onSelect:Au.inspect}),Au.agentDetails&&lo.push({id:"agent-details",label:"Agent Details…",icon:DependabotIcon,onSelect:Au.agentDetails}),Au.sandboxDetails&&lo.push({id:"sandbox-details",label:"Code Sandbox Details…",icon:CodeIcon,onSelect:Au.sandboxDetails}),Au.conversationLabel!==!1&&lo.push({id:"conversation",label:Au.conversationLabel??(Au.open?"Close the conversation":"Open the conversation"),icon:CommentDiscussionIcon,onSelect:Au.onToggle}),Au.busy&&Au.onStop&&lo.push({id:"stop",label:"Stop the turn",icon:SquareFillIcon,onSelect:Au.onStop}),Au.onNewChat&&lo.push({id:"new-chat",label:"New conversation",icon:PlusIcon,onSelect:Au.onNewChat}),Au.onClear&&lo.push({id:"clear",label:"Clear the conversation",icon:TrashIcon,onSelect:Au.onClear}),Au.suggestions?.length&&Au.onSuggestion){const $u=Au.onSuggestion;for(const Ru of Au.suggestions)lo.push({id:`suggestion:${Ru.label}`,label:Ru.label,description:Ru.prompt,group:"Suggestions",disabled:Au.busy,onSelect:()=>$u(Ru)})}if(Au.onBalloonDisplayChange){const $u=Au.onBalloonDisplayChange;lo.push({id:"balloon-history",label:"History",group:"Balloon",checked:Au.balloonDisplay!=="current",onSelect:()=>$u("history")},{id:"balloon-current",label:"Current",group:"Balloon",checked:Au.balloonDisplay==="current",onSelect:()=>$u("current")})}Au.onChangeCharacter&&lo.push({id:"character",label:"Change character…",icon:PencilIcon,onSelect:Au.onChangeCharacter}),Au.speech&&lo.push({id:"speech",label:Au.speech.muted?"Unmute speech":"Mute speech",icon:Au.speech.muted?UnmuteIcon:MuteIcon,onSelect:Au.speech.onToggle}),Au.characterSounds&&lo.push({id:"character-sounds",label:Au.characterSounds.on?"Mute its sounds":"Play its sounds",icon:Au.characterSounds.on?MuteIcon:UnmuteIcon,onSelect:Au.characterSounds.onToggle}),Au.onResetPosition&&lo.push({id:"reset-position",label:"Reset position",icon:ScreenNormalIcon,onSelect:Au.onResetPosition}),Au.about&&lo.push({id:"about",label:`About ${Au.name}`,icon:InfoIcon,onSelect:Au.about}),lo.push(...Au.extra??[]);for(const $u of AWAY_CHOICES)lo.push({id:`away:${$u.away}`,label:$u.label,group:"Send away",icon:XIcon,onSelect:()=>Au.onDismiss($u.away)});return lo}const BALLOON_ROOM=200;function pixels(Au){if(typeof Au=="number")return Au;const lo=typeof Au=="string"?/^(-?\d+(?:\.\d+)?)px$/.exec(Au):null;return lo?Number(lo[1]):void 0}function balloonSide(Au,lo={width:typeof window>"u"?1280:window.innerWidth,height:typeof window>"u"?800:window.innerHeight}){const $u=pixels(Au.left),Ru=pixels(Au.top),Iu=$u!==void 0?$u<lo.width/2?"left":"right":Au.left!==void 0&&Au.right===void 0?"left":"right";return{side:Ru!==void 0?Ru<BALLOON_ROOM?"below":"above":Au.top!==void 0&&Au.bottom===void 0?"below":"above",align:Iu}}const CLEAR_CHECK_MS=400;function useKeepClear(Au,lo,$u){const[Ru,Iu]=reactExports.useState(!1),[Ou,Pu]=reactExports.useState(!1);return reactExports.useEffect(()=>{if($u){Iu(!1);return}const Du=()=>{const ju=Au.current;if(!ju)return;const Bu=ju.getBoundingClientRect(),Fu=lo?.current,zu=Array.from(document.querySelectorAll(ASSISTANT_OBSTACLES)).some(qu=>{if(ju.contains(qu)||qu.contains(ju)||Fu?.contains(qu))return!1;const Uu=qu.getBoundingClientRect();return Uu.width>0&&Uu.height>0&&boxesMeet(Bu,Uu)});Iu(zu)};Du();const Lu=window.setInterval(Du,CLEAR_CHECK_MS);return()=>window.clearInterval(Lu)},[Au,lo,$u]),reactExports.useEffect(()=>{if($u){Pu(!1);return}let Du,Lu=!1;const ju=Bu=>{const Fu=Au.current,zu=Bu.target;!Fu||zu&&(Fu.contains(zu)||lo?.current?.contains(zu))||Bu.type==="pointermove"&&Bu.buttons===0&&!Lu||pointerNear(Fu.getBoundingClientRect(),{x:Bu.clientX,y:Bu.clientY})&&(Lu=!0,Pu(!0),clearTimeout(Du),Du=setTimeout(()=>{Lu=!1,Pu(!1)},POINTER_CALM_MS))};return document.addEventListener("pointerdown",ju,!0),document.addEventListener("pointermove",ju,!0),()=>{clearTimeout(Du),document.removeEventListener("pointerdown",ju,!0),document.removeEventListener("pointermove",ju,!0)}},[Au,lo,$u]),Ru?"obstacle":Ou?"pointer":void 0}function useMouth(Au,lo,$u){reactExports.useEffect(()=>{const Ru=Au.current,Iu=typeof window<"u"&&!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if(!Ru||!lo||!$u||Iu){Ru?.removeAttribute("data-assistant-mouth");return}let Ou=0;const Pu=()=>{Ru.setAttribute("data-assistant-mouth",String(mouthOpening(lo()))),Ou=requestAnimationFrame(Pu)};return Ou=requestAnimationFrame(Pu),()=>{cancelAnimationFrame(Ou),Ru.removeAttribute("data-assistant-mouth")}},[Au,lo,$u])}function AssistantStage({character:Au,state:lo,size:$u=88,place:Ru,stageRef:Iu,onDragStart:Ou,open:Pu,onToggle:Du,onCharacterClick:Lu,onCharacterKeyDown:ju,balloon:Bu,insist:Fu=!1,onDismiss:zu,ownRef:qu,decide:Uu,mouthLevel:Hu,stayPut:Vu=!1,balloonDisplay:Gu="history",expandTarget:Ku,expandOnArrival:Zu=!1,suggestions:Qu,onSuggestion:Yu,inspector:ed,inspectAgent:Xu,conversationLabel:rd,onBalloonDisplayChange:nd,onStop:od,onNewChat:ad,onClear:ld,onChangeCharacter:fd,speech:pd,onResetPosition:Sd,about:wd,sandbox:bd,contextMenu:Td,agentName:Pd,label:ud}){const md=useChatWords(),_d=typeof Au=="string"?assistantCharacter(Au):"Drawing"in Au?Au:void 0,hd=_d?_d.name:Au.name,gd=Pd??hd,Ed=reactExports.useId(),xd=!!(Pd||ud),{colorScheme:Od}=useTheme(),Bd=Od?.startsWith("dark")?"dark":"light",[Gd,Ud]=reactExports.useState(!1),[Md,zd]=reactExports.useState(!1),[Vd,kd]=reactExports.useState(null),[Rd,Ld]=reactExports.useState(!1),[Jd,Xd]=reactExports.useState(!1),[uh,xh]=reactExports.useState(null),Mh=reactExports.useRef(null),Rh=reactExports.useRef(void 0),bh=reactExports.useCallback(()=>kd(null),[]),[_h,eh]=reactExports.useState(!1),Sh=!_d&&Object.keys(Au.sounds??{}).length>0;reactExports.useEffect(()=>()=>clearTimeout(Rh.current),[]);const Dd=reactExports.useRef(null),$d=useKeepClear(Iu,qu,Md||Vd!==null||Rd||Jd||uh!==null||Vu);useMouth(Iu,Hu,lo==="speaking");const[jd,Fd]=reactExports.useState(!1),rh=!$d&&!Pu&&!!Bu&&(Gd||Fu||jd),Yd=(lo==="idle"||lo==="greeting")&&!Bu?.tool&&!Bu?.approval&&!Bu?.busy,ah=assistantMenuItems({name:gd,open:Pu,onToggle:Du,onDismiss:zu,conversationLabel:rd,inspect:ed?()=>Ld(!0):void 0,agentDetails:wd?()=>xh("agent"):void 0,sandboxDetails:bd?()=>xh("sandbox"):void 0,balloonDisplay:Gu,onBalloonDisplayChange:nd,suggestions:Qu,onSuggestion:Yu,busy:lo==="thinking"||lo==="working"||lo==="speaking",onStop:od,onNewChat:ad,onClear:ld,onChangeCharacter:fd,speech:pd,characterSounds:Sh?{on:_h,onToggle:()=>eh(ih=>!ih)}:void 0,onResetPosition:Sd,about:wd?()=>Xd(!0):void 0,extra:Td}),Ah=Bu?.visual,[Dh,zh]=reactExports.useState(null),mf=Ah?()=>{zh(Ah),Ku&&requestAnimationFrame(()=>focusExpanded(Ku))}:null,Zd=Bu?.history,Ad=Gu!=="current"&&Zd&&Zd.length>0?{id:"balloon-history",title:conversationHeaderText(conversationCount(Zd),md),shrink:!0,render:()=>jsxRuntimeExports.jsx(BalloonHistoryLarge,{history:Zd,tool:Bu?.tool,attachment:Bu?.attachment})}:null,sh=Dh?.id==="balloon-history"?Ad:Dh;return reactExports.useEffect(()=>{Ah&&Zu&&Ku&&zh(Ah)},[Ah?.id,Zu,!!Ku]),jsxRuntimeExports.jsxs(Box,{ref:Iu,"data-assistant-state":lo,"data-assistant-aside":$d,"data-assistant-balloon":Gu,sx:{position:"fixed",zIndex:1002,...Ru,width:$u,height:$u,opacity:$d?0:1,visibility:$d?"hidden":"visible",pointerEvents:$d?"none":void 0,transition:$d?"opacity 150ms ease, visibility 0s linear 150ms":"opacity 150ms ease",...MOTIONS,"& .assistant-lids ellipse":{transformBox:"fill-box",transformOrigin:"top",transform:"scaleY(0)",animation:"assistantBlink 5.2s ease-in-out infinite"},[BODY]:{transformBox:"fill-box",transformOrigin:"50% 100%"},"& .assistant-pupils":{transition:"transform var(--theme-motion-status, 120ms) var(--theme-motion-easing, ease)"},"& .assistant-mouth":{transformBox:"fill-box",transformOrigin:"center"},'&[data-assistant-state="idle"] .assistant-body':{animation:"assistantFloat 3.2s ease-in-out infinite"},'&[data-assistant-state="thinking"] .assistant-body':{animation:"assistantTilt 2.4s ease-in-out infinite"},'&[data-assistant-state="thinking"] .assistant-pupils':{transform:"translate(-1px, -3px)"},'&[data-assistant-state="working"] .assistant-body':{animation:"assistantWork 0.7s ease-in-out infinite"},'&[data-assistant-state="working"] .assistant-pupils':{transform:"translate(2px, 2px)"},'&[data-assistant-state="waiting"] .assistant-body':{animation:"assistantAttention 1.4s ease-in-out infinite"},'&[data-assistant-state="greeting"] .assistant-body':{animation:"assistantHop 0.9s ease-out 2"},'&[data-assistant-state="speaking"] .assistant-mouth':{animation:"assistantTalk 0.24s ease-in-out infinite"},'&[data-assistant-state="speaking"] .assistant-body':{animation:"assistantFloat 1.6s ease-in-out infinite"},"&[data-assistant-mouth] .assistant-mouth":{animation:"none",transition:"transform 60ms linear"},'&[data-assistant-mouth="0"] .assistant-mouth':{transform:"scaleY(1)"},'&[data-assistant-mouth="1"] .assistant-mouth':{transform:"scaleY(1.5)"},'&[data-assistant-mouth="2"] .assistant-mouth':{transform:"scaleY(2.1)"},'&[data-assistant-mouth="3"] .assistant-mouth':{transform:"scaleY(2.8)"},'&[data-assistant-state="paused"] .assistant-body':{animation:"assistantDoze 4.8s ease-in-out infinite",filter:"grayscale(0.5)",opacity:.8},'&[data-assistant-state="paused"] .assistant-lids ellipse':{animation:"none",transform:"scaleY(1)"},'&[data-assistant-state="goodbye"] .assistant-body':{animation:"assistantLeave 0.6s ease-in forwards"},'&[data-assistant-state="goodbye"] .assistant-sprite':{animation:"assistantLeave 0.6s ease-in forwards"},"@media (prefers-reduced-motion: reduce)":{"& *":{animation:"none !important"}}},onMouseEnter:()=>Ud(!0),onMouseLeave:()=>Ud(!1),children:[sh&&jsxRuntimeExports.jsx(ExpandedVisual,{visual:sh,target:Ku,onClose:()=>zh(null)}),rh&&Bu&&jsxRuntimeExports.jsx(BalloonExpandContext.Provider,{value:mf,children:jsxRuntimeExports.jsx(SpeechBalloon,{text:Bu.text,more:Bu.more,approval:Bu.approval,onDismissPeek:Bu.onDismiss,display:Gu,tool:Bu.tool,speaking:Bu.speaking,busy:Bu.busy,attachment:Bu.attachment,history:Bu.history,onExpand:mf??void 0,expandTitle:Ah?.title,onExpandHistory:Ad?()=>{zh(Ad),Ku&&requestAnimationFrame(()=>focusExpanded(Ku))}:void 0,suggestions:Yd?Qu:void 0,fullText:Bu.fullText,waiting:(lo==="thinking"||lo==="working"||lo==="waiting")&&!Bu.speaking,onSuggestion:Yu,decide:Uu,onDecisionActive:Fd,wide:jd,onOpen:Du,above:$u+8,side:balloonSide(Ru).side,align:balloonSide(Ru).align,tailAt:$u/2})}),jsxRuntimeExports.jsxs(Box,{as:"button",type:"button","aria-label":ud??(Pu?`Close the conversation with ${gd}`:`Talk to ${gd}`),"aria-describedby":xd?Ed:void 0,"aria-expanded":Pu,"aria-haspopup":"menu",ref:Mh,"data-assistant-figure":"",onContextMenu:ih=>{ih.preventDefault(),clearTimeout(Rh.current),kd({x:ih.clientX,y:ih.clientY})},onKeyDown:ih=>{if(opensContextMenu(ih)){ih.preventDefault();const Bh=ih.currentTarget.getBoundingClientRect();kd({x:Bh.left+Bh.width/2,y:Bh.bottom});return}ju?.(ih)},onPointerUp:()=>clearTimeout(Rh.current),onPointerCancel:()=>clearTimeout(Rh.current),onPointerMove:ih=>{const Bh=Dd.current;Bh&&Math.hypot(ih.clientX-Bh.x,ih.clientY-Bh.y)>8&&clearTimeout(Rh.current)},onPointerDown:ih=>{if(Dd.current={x:ih.clientX,y:ih.clientY},ih.pointerType==="touch"){const Bh={x:ih.clientX,y:ih.clientY};clearTimeout(Rh.current),Rh.current=setTimeout(()=>{Dd.current={x:-1e6,y:-1e6},kd(Bh)},LONG_PRESS_MS)}Ou(ih)},onClick:ih=>{const Bh=Dd.current;Dd.current=null,!(Bh&&Math.hypot(ih.clientX-Bh.x,ih.clientY-Bh.y)>4)&&(Lu??Du)()},display:"block",width:$u,height:$u,p:0,border:0,bg:"transparent",cursor:"grab",filter:"drop-shadow(0 6px 10px rgba(0, 0, 0, 0.18))",active:{cursor:"grabbing"},focusVisible:{outline:"2px solid",outlineColor:"var(--focus-outlineColor, var(--fgColor-accent))",outlineOffset:2,borderRadius:"50%"},touchAction:"none",children:[xd&&jsxRuntimeExports.jsx(Box,{as:"span",id:Ed,position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",children:`Its character: ${hd}`}),_d?jsxRuntimeExports.jsx(_d.Drawing,{size:$u,mode:Bd}):jsxRuntimeExports.jsx(SpriteCharacter,{character:Au,state:lo,size:$u,sounds:_h,mouthLevel:Hu})]}),(Gd||Md)&&!$d&&lo!=="goodbye"&&jsxRuntimeExports.jsx(Box,{position:"absolute",top:"-6px",right:"-6px",children:jsxRuntimeExports.jsxs(ActionMenu,{open:Md,onOpenChange:zd,children:[jsxRuntimeExports.jsx(ActionMenu.Anchor,{children:jsxRuntimeExports.jsx(IconButton,{icon:XIcon,"aria-label":`Send ${gd} away`,size:"small",variant:"invisible","data-assistant-dismiss":"",sx:{bg:"canvas.default",borderRadius:"50%",boxShadow:"shadow.small"}})}),jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"auto",children:jsxRuntimeExports.jsx(ActionList,{children:AWAY_CHOICES.map(ih=>jsxRuntimeExports.jsx(ActionList.Item,{"data-assistant-away":ih.away,onSelect:()=>zu(ih.away),children:ih.label},ih.away))})})]})}),jsxRuntimeExports.jsx(AssistantContextMenu,{at:Vd,items:ah,onClose:bh,returnFocusRef:Mh,label:`${gd}’s menu`}),Rd&&jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(AgentInspectorDialog,{tracer:ed??null,agent:Xu,title:`${wd?.name??gd} · Agent Inspector`,onClose:()=>{Ld(!1),Mh.current?.focus()}})}),uh==="agent"&&wd&&jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(AgentDetailsDialog,{about:wd,name:gd,onClose:()=>{xh(null),Mh.current?.focus()}})}),uh==="sandbox"&&bd&&jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(SandboxDetailsDialog,{sandbox:bd,name:wd?.name??gd,onClose:()=>{xh(null),Mh.current?.focus()}})}),Jd&&wd&&jsxRuntimeExports.jsx(Dialog$1,{title:`About ${wd.name??gd}`,onClose:()=>{Xd(!1),Mh.current?.focus()},"data-assistant-about":"",children:[["Agent",wd.name],["Spec",wd.spec],["Model",wd.model],["Runs",wd.where],["Character",hd]].filter(([,ih])=>ih).map(([ih,Bh])=>jsxRuntimeExports.jsxs(Text$5,{as:"p",sx:{m:0,mb:1},children:[jsxRuntimeExports.jsxs(Text$5,{sx:{color:"fg.muted"},children:[ih,": "]}),Bh]},ih))})]})}const SYNTHESES_PATH="/api/ai-agents/v1/speech/syntheses";class ServerSpeaker{constructor(lo){this.options=lo}options;context;analyser;buffer;queue=[];playing;running=!1;generation=0;state={speaking:!1};update(lo){this.options={...this.options,...lo}}unlock(){this.audio(),this.context?.resume()}audio(){return this.context||(this.context=new AudioContext,this.analyser=this.context.createAnalyser(),this.analyser.fftSize=512,this.analyser.connect(this.context.destination),this.buffer=new Float32Array(this.analyser.fftSize)),this.context}level(){if(!this.analyser||!this.buffer||!this.state.speaking)return 0;this.analyser.getFloatTimeDomainData(this.buffer);let lo=0;for(const $u of this.buffer)lo+=$u*$u;return Math.min(1,Math.sqrt(lo/this.buffer.length)*6)}set(lo){this.state={...this.state,...lo},this.options.onState?.(this.state)}say(lo){const $u=lo.trim();$u&&(this.queue.push({text:$u,audio:this.fetch($u),asked:performance.now()}),this.running||this.run(this.generation))}async fetch(lo){const{speechUrl:$u,voice:Ru,language:Iu,token:Ou,fetcher:Pu=fetch}=this.options;try{const Du=await Pu(`${$u.replace(/\/+$/,"")}${SYNTHESES_PATH}`,{method:"POST",headers:{"Content-Type":"application/json",...Ou?{Authorization:`Bearer ${Ou}`}:{}},body:JSON.stringify({text:lo,voice:Ru,language:Iu,format:"opus"})});if(!Du.ok){const Lu=await Du.json().catch(()=>({}));return typeof Lu?.detail=="string"?Lu.detail:`The answer could not be spoken (${Du.status}).`}return await Du.arrayBuffer()}catch{return"Datalayer’s speech service could not be reached: the answer is still written here."}}async run(lo){this.running=!0;try{for(;this.queue.length&&lo===this.generation;){const $u=this.queue.shift(),Ru=await $u.audio;if(lo!==this.generation)return;if(typeof Ru=="string"){this.queue=[],this.set({speaking:!1,sentence:void 0,refused:Ru});return}const Iu=this.audio(),Ou=await Iu.decodeAudioData(Ru);if(lo!==this.generation)return;await new Promise(Pu=>{const Du=Iu.createBufferSource();Du.buffer=Ou,Du.connect(this.analyser),Du.onended=()=>Pu(),this.playing=Du,this.set({speaking:!0,sentence:$u.text,refused:void 0}),this.options.onFirstSound?.(Math.round(performance.now()-$u.asked)),Du.start()}),this.playing=void 0}}finally{lo===this.generation&&(this.running=!1,this.state.speaking&&this.set({speaking:!1,sentence:void 0}))}}stop(){this.generation+=1,this.queue=[],this.running=!1;try{this.playing?.stop()}catch{}this.playing=void 0,this.set({speaking:!1,sentence:void 0})}close(){this.stop(),this.context?.close(),this.context=void 0}}function plainWords(Au){return Au.replace(/```[\s\S]*?(```|$)/g," A code block. ").replace(/(^|\n)(\|[^\n]*\|[ \t]*(\n|$))+/g,`$1 A table.
3440
- `).replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/`([^`]*)`/g,"$1").replace(/^\s{0,3}#{1,6}\s+(.*)$/gm,"$1.").replace(/^\s*(?:[-*+]|\d+[.)])\s+/gm,"").replace(/^\s*>\s?/gm,"").replace(/[*_~]+/g,"").replace(/\.\s*\./g,".").replace(/\s+/g," ").trim()}const END=/[.!?…:;](?=["'»)\]]*(\s|$))/g,SHORTEST=12;class SentenceCutter{said=0;feed(lo){const $u=plainWords(lo),Ru=[];END.lastIndex=this.said;let Iu;for(;(Iu=END.exec($u))!==null;){const Ou=Iu.index+Iu[0].length;if(Ou>=$u.length)break;const Pu=$u.slice(this.said,Ou).trim();Pu.length>=SHORTEST&&(Ru.push(Pu),this.said=Ou)}return Ru}end(lo){const $u=plainWords(lo).slice(this.said).trim();return this.said=plainWords(lo).length,$u?[$u]:[]}}function answerText(Au){const lo=Au;if(!(!lo||lo.role!=="assistant"||typeof lo.toolName=="string")){if(typeof lo.content=="string")return lo.content;if(Array.isArray(lo.content))return lo.content.map($u=>$u&&typeof $u=="object"&&$u.type==="text"?String($u.text??""):"").join(" ")}}function useSpokenAnswers(Au,lo,$u,Ru){const Iu=reactExports.useRef(new Set),Ou=reactExports.useRef(void 0),Pu=reactExports.useRef(!1);reactExports.useEffect(()=>{if(!$u||!Ru){Pu.current=!1,Ou.current=void 0;return}const Du=Au.map((Bu,Fu)=>({id:String(Bu?.id??Fu),text:answerText(Bu)})).filter(Bu=>Bu.text!==void 0);if(!Pu.current){Pu.current=!0,Du.forEach(Bu=>Iu.current.add(Bu.id));return}const Lu=Du[Du.length-1];if(!Lu||Iu.current.has(Lu.id)&&Ou.current?.id!==Lu.id)return;Ou.current?.id!==Lu.id&&(Iu.current.add(Lu.id),Ou.current={id:Lu.id,cutter:new SentenceCutter,ended:!1});const ju=Ou.current;if(!ju.ended){for(const Bu of ju.cutter.feed(Lu.text??""))Ru.say(Bu);if(!lo){for(const Bu of ju.cutter.end(Lu.text??""))Ru.say(Bu);ju.ended=!0}}},[Au,lo,$u,Ru])}const CONVERSATION_BALLOON_WIDTH=380,CONVERSATION_BALLOON_MAX_HEIGHT=560,CONVERSATION_BALLOON_VIEWPORT_SHARE=.6,CURRENT_BALLOON_HEIGHT=230;function conversationBalloonHeight(Au){return Math.max(240,Math.min(CONVERSATION_BALLOON_MAX_HEIGHT,Math.round(Au*CONVERSATION_BALLOON_VIEWPORT_SHARE)))}const TAIL=7;function balloonTailAt(Au,lo,$u=CONVERSATION_BALLOON_WIDTH){return Math.min($u-24-TAIL,Math.max(24,Au-lo-TAIL))}function conversationBalloonSx(Au,lo="canvas.default"){return{borderRadius:"var(--theme-radius-bubble, 16px)",overflow:"visible",...Au.edge==="none"?{}:{"&::after":{content:'""',position:"absolute",...Au.edge==="bottom"?{bottom:`-${TAIL}px`}:{top:`-${TAIL}px`},left:`${Au.at}px`,width:`${TAIL*2}px`,height:`${TAIL*2}px`,bg:lo,borderRight:"1px solid",borderBottom:"1px solid",borderColor:"border.default",transform:Au.edge==="bottom"?"rotate(45deg)":"rotate(225deg)",pointerEvents:"none"}}}}function ConversationBalloonClose({name:Au,onClose:lo}){return jsxRuntimeExports.jsx(Box,{"data-conversation-balloon-close":"",position:"absolute",top:"6px",right:"6px",zIndex:30,children:jsxRuntimeExports.jsx(IconButton,{icon:XIcon,size:"small",variant:"invisible","aria-label":Au?`Close the conversation with ${Au}`:"Close the conversation",onClick:lo,sx:{bg:"canvas.default",borderRadius:"50%"}})})}function BalloonApprovalMessage({approval:Au}){const lo=useChatWords(),$u=reactExports.useRef(null);return reactExports.useEffect(()=>{$u.current?.scrollIntoView?.({block:"nearest"})},[Au.id]),jsxRuntimeExports.jsx(Box,{ref:$u,"data-balloon-approval":Au.id,px:3,py:2,display:"flex",children:jsxRuntimeExports.jsxs(Box,{maxWidth:"90%",px:3,py:2,bg:"attention.subtle",border:"1px solid",borderColor:"attention.muted",borderRadius:"var(--theme-radius-bubble, 16px)",fontSize:1,children:[jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:lo.waitingForYou}),jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{m:0,fontWeight:"semibold"},children:Au.asks}),Au.why?jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:Au.why}):null,jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,mt:2,alignItems:"center",children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",disabled:Au.deciding,onClick:Au.onApprove,children:lo.approve}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Au.deciding,onClick:Au.onDeny,children:lo.deny}),Au.others>0?jsxRuntimeExports.jsx(Text$5,{sx:{color:"fg.muted",fontSize:0},children:lo.moreWaiting(Au.others)}):null]})]})})}const PEEK_LIMIT=60;function peekLine(Au,lo=PEEK_LIMIT){const $u=Au.replace(/\s+/g," ").trim();if($u.length<=lo)return{text:$u,more:!1};const Ru=$u.slice(0,lo);return{text:`${Ru.slice(0,Math.max(Ru.lastIndexOf(" "),lo*.6)).trimEnd()}…`,more:!0}}const PRESENCE_LINES={idle:"Ready",thinking:"Thinking…",working:"Working…",waiting:"Waiting for you",paused:"Paused"};function presenceState(Au,lo,$u=!1){return $u?"paused":lo?.open&&lo.pendingApproval?"waiting":Au?lo?.open?"working":"thinking":"idle"}function presenceToolOf(Au){for(let lo=Au.length-1;lo>=0;lo-=1){const $u=Au[lo];if(typeof $u.toolName=="string"&&$u.toolCallId){const Ru=$u.status!=="complete"&&$u.status!=="error",Iu=Ru&&$u.result?.pending_approval===!0;return{open:Ru,pendingApproval:Iu}}}return{open:!1,pendingApproval:!1}}const LIVE=new Set(["running","idle","busy","starting"]);function sandboxIsLive(Au){return Au.status===void 0||LIVE.has(Au.status)}const NO_SANDBOX_YET="No sandbox is running yet: run a cell or ask the agent to execute code.",SANDBOX_KIND_LABELS={browser:"Python in your browser (Pyodide)",local:"Local Jupyter server",jupyter:"Jupyter server",cloud:"Datalayer cloud runtime",runtime:"In the agent runtime"};function isLocalUrl(Au){if(!Au)return!1;try{const lo=new URL(Au).hostname;return lo==="localhost"||lo==="127.0.0.1"||lo==="::1"||lo==="[::1]"||lo.endsWith(".localhost")}catch{return!1}}const SECRET_PARAMS=/^(token|access_token|api_key|apikey|key|auth|password|secret|signature|sig|jwt)$/i;function displayUrl(Au){if(Au)try{const lo=new URL(Au);lo.username="",lo.password="";for(const $u of[...lo.searchParams.keys()])SECRET_PARAMS.test($u)&&lo.searchParams.delete($u);return lo.toString()}catch{return Au.split("?")[0]}}const text$3=Au=>typeof Au=="string"&&Au?Au:void 0;function assistantSandboxOf(Au,lo={}){if(!Au)return;const $u=text$3(Au.variant),Ru=text$3(Au.jupyter_url)??text$3(Au.agent_base_url),Iu=Au.sandbox_running===!0||Au.jupyter_connected===!0;return!$u&&!Iu?void 0:{kind:$u==="datalayer"?"cloud":$u==="jupyter-server"||$u==="jupyter"?isLocalUrl(text$3(Au.jupyter_url))?"local":"jupyter":"runtime",status:lo.state??(Iu?"running":"stopped"),variant:$u,url:Ru,token:text$3(Au.jupyter_token),kernelId:text$3(Au.kernel_id),agentId:lo.agentId,environment:text$3(Au.environment_name),serverUrl:lo.serverUrl}}function sandboxExecuteOverHttp(Au,lo){const $u=Au.replace(/\/+$/,"").replace(/\/api\/v1$/,"");return async Ru=>{const Iu=await fetch(`${$u}/api/v1/sandbox/execute`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:Ru,agent_id:lo})});if(!Iu.ok)return{stdout:"",error:`The sandbox did not run the code (HTTP ${Iu.status}).`};const Ou=await Iu.json();return{stdout:Ou.stdout??"",error:Ou.error??void 0}}}function timeLeft(Au,lo=Date.now()){if(Au===null)return"never";if(Au===void 0||Au==="")return;const $u=typeof Au=="number"?Au<1e12?Au*1e3:Au:Date.parse(Au);if(!Number.isFinite($u))return;const Ru=Math.round(($u-lo)/6e4);if(Ru<=0)return"ended";const Iu=Math.floor(Ru/60);return Iu?`${Iu} h ${Ru%60} min`:`${Ru} min`}function useIsMobile(Au=640){const[lo,$u]=reactExports.useState(!1);return reactExports.useEffect(()=>{const Ru=()=>{$u(window.innerWidth<Au)};return Ru(),window.addEventListener("resize",Ru),()=>window.removeEventListener("resize",Ru)},[Au]),lo}const px=Au=>`${Math.round(Au)}px`,clamp=(Au,lo)=>Math.max(8,Math.min(Au,Math.max(8,lo)));function ChatFloating({endpoint:Au,protocol:lo,useStore:$u=!0,title:Ru="Chat",description:Iu="Start a conversation with the AI agent.",position:Ou="bottom-right",defaultOpen:Pu=!1,width:Du=400,height:Lu=550,showHeader:ju=!0,showButton:Bu=!0,showNewChatButton:Fu=!0,showClearButton:zu=!0,showSettingsButton:qu=!1,enableKeyboardShortcuts:Uu=!0,toggleShortcut:Hu="/",showPoweredBy:Vu=!0,promptVariant:Gu,mentionableAgents:Ku,poweredByProps:Zu,clickOutsideToClose:Qu=!1,escapeToClose:Yu=!0,className:ed,onSettingsClick:Xu,onNewChat:rd,onOpen:nd,onClose:od,onStateUpdate:ad,children:ld,brandIcon:fd,buttonIcon:pd,buttonTooltip:Sd="Chat with AI",brandColor:wd,buttonGlow:bd=!0,offset:Td=20,animationDuration:Pd=200,renderToolResult:ud,frontendTools:md,initialState:_d,suggestions:hd,submitOnSuggestionClick:gd=!0,hideMessagesAfterToolUI:Ed=!1,defaultViewMode:xd="floating",onViewModeChange:Od,sidebarMountPoint:Bd=null,showPanelBackdrop:Gd=!1,availableModels:Ud,showModelSelector:Md=!1,showToolsMenu:zd=!1,showSkillsMenu:Vd=!1,showTokenUsage:kd=!0,showContextRing:Rd=!1,themeVariant:Ld,themeOverrides:Jd,colorMode:Xd,runtimeId:uh,historyEndpoint:xh,authToken:Mh,historyAuthToken:Rh,pendingPrompt:bh,showInformation:_h=!1,onInformationClick:eh,onToolCallStart:Sh,onToolCallComplete:Dd,showToolApprovalBanner:$d,pendingApprovals:jd,onApproveApproval:Fd,onRejectApproval:rh,panelProps:Yd,launching:th=!1,launchingMessage:ah,assistantCharacter:Ah=DEFAULT_ASSISTANT_CHARACTER,balloonDisplay:Dh=DEFAULT_BALLOON_DISPLAY,expandTarget:zh,conversation:mf,decisions:Zd,voice:Ad,inspector:sh,onBalloonDisplayChange:ih,onChangeCharacter:Bh,about:Yh,sandbox:Kh,contextMenu:rf}){const hf=useChatWords(),Rf=reactExports.useRef(null),[Cf,Df]=reactExports.useState(),[sf,qf]=reactExports.useState(!1),[Uf,mh]=reactExports.useState();reactExports.useEffect(()=>mh(void 0),[Dh]);const oh=Uf??Dh,ph=reactExports.useCallback(xf=>{mh(xf),ih?.(xf)},[ih]),Lh=useChatOpen(),kh=useChatMessages(),vf=useChatStore(xf=>xf.setOpen),Jh=useChatStore(xf=>xf.clearMessages),[lf,Yf]=reactExports.useState(Pu),Tf=$u?Lh:lf,Nf=$u?vf:Yf,Qh=kh,kf=reactExports.useRef(null),yf=useIsMobile(),[rp,up]=reactExports.useState(!1),[np,kp]=reactExports.useState(!1),[Bf,zp]=reactExports.useState(xd),[Zp,sm]=reactExports.useState(0),[pp,qp]=reactExports.useState(!1),[Jf,gp]=reactExports.useState(null),dp=Bf==="panel"?"sidebar":Bf,[Cp,Tp]=reactExports.useState(null);reactExports.useLayoutEffect(()=>{Tp(resolveMountPoint(Bd))},[Bd,Tf,Bf]);const hp=disabledChatViewModes({sidebarMountPoint:Cp,viewMode:dp}),Rp=hp.includes("sidebar"),Qf=Bf==="panel"&&!yf&&!!Cp,cm=useViewportDrag(kf),um=cm.reset;reactExports.useEffect(()=>{Bf!=="floating-draggable"&&um()},[Bf,um]);const Mp=88,Np=Bf==="assistant"&&!yf,[Em,nm]=reactExports.useState(!1),[qm,Km]=reactExports.useState({open:!1,pendingApproval:!1}),[Lp,Sf]=reactExports.useState(!1),[hh,jh]=reactExports.useState(),[Ef,wf]=reactExports.useState(0),[gf,$f]=reactExports.useState([]),[vh,Th]=reactExports.useState([]),[gh,Kd]=reactExports.useState({speaking:!1}),dh=reactExports.useMemo(()=>Ad&&Ad.output==="always"&&Ad.speechUrl?new ServerSpeaker({speechUrl:Ad.speechUrl,voice:Ad.voice,language:Ad.language,token:Ad.token,onState:Kd}):void 0,[Ad?.output,Ad?.speechUrl]);reactExports.useEffect(()=>{dh?.update({voice:Ad?.voice,language:Ad?.language,token:Ad?.token})},[dh,Ad?.voice,Ad?.language,Ad?.token]),reactExports.useEffect(()=>()=>dh?.close(),[dh]),reactExports.useEffect(()=>{if(!dh)return;const xf=()=>dh.unlock();return window.addEventListener("pointerdown",xf,{once:!0}),window.addEventListener("keydown",xf,{once:!0}),()=>{window.removeEventListener("pointerdown",xf),window.removeEventListener("keydown",xf)}},[dh]),useSpokenAnswers(vh,Em,!!dh&&!sf,dh);const $h=reactExports.useCallback(()=>dh?.stop(),[dh]),Uh=reactExports.useMemo(()=>dh?()=>dh.level():void 0,[dh]),[cf,Pf]=reactExports.useState(!1),[Ff,Vf]=reactExports.useState(!1),[Ip,ep]=reactExports.useState(keptAway),_p=Np&&Ip==="none",Jp=reactExports.useCallback(()=>{keepAway("none"),ep("none")},[]),[sp,xp]=reactExports.useState(),$p=mf?mf.saying:sp,am=mf?mf.answering:Lp,Cm=mf?mf.tool:hh,Dm=oh==="current",[Lf,Up]=reactExports.useState(),[lm,ym]=reactExports.useState(!1);reactExports.useEffect(()=>{if(!$p||Tf)return;ym(!0);const xf=setTimeout(()=>ym(!1),12e3);return()=>clearTimeout(xf)},[$p?.id,$p?.text,Tf]),reactExports.useEffect(()=>{Tf&&$p&&Up($p.id)},[Tf,$p?.id]);const Zm=reactExports.useRef(null),Bm=useViewportDrag(Zm,{whole:!0});reactExports.useEffect(()=>{if(!_p)return;Pf(!0);const xf=setTimeout(()=>Pf(!1),1800);return()=>clearTimeout(xf)},[_p]);const Um=assistantStateOf(mf?mf.presence:presenceState(Em,qm),{arriving:cf,leaving:Ff,speaking:am,voicing:gh.speaking}),Hp=!!$p&&$p.id!==Lf,[cg,Ym]=reactExports.useState(!1),gm=jd?.[0],Gf=gm&&Fd&&rh?{id:gm.id,asks:gm.toolDescription||gm.toolName,others:(jd?.length??1)-1,deciding:cg,onApprove:()=>{Ym(!0),Promise.resolve(Fd(gm.id)).finally(()=>Ym(!1))},onDeny:()=>{Ym(!0),Promise.resolve(rh(gm.id)).finally(()=>Ym(!1))}}:void 0,Yp=reactExports.useMemo(()=>Zd?.serverUrl?decisionsAskerAt(Zd.serverUrl,Zd.token):void 0,[Zd?.serverUrl,Zd?.token]),cd=Um==="thinking"||Um==="working"||Um==="speaking",yd=Cm&&(Cm.phase==="running"||cd)?Cm:void 0,Id=cd&&!am?hf.thinking:($p?.more?$p.text:$p?.markdown)||void 0,Nd=cd&&!am?void 0:$p?.more?$p.markdown:void 0,Hd=!Dm&&!mf&&gf.length>0?gf:void 0,Wd=xf=>Hd?{...xf,history:Hd}:xf,Qd=Um==="paused"?{text:hf.paused}:gh.sentence?{text:gh.sentence}:gh.refused?{text:gh.refused}:Gf?Wd({text:hf.waitingForYou,approval:Gf}):Um==="waiting"?{text:hf.waitingOpen}:yd?Wd({text:toolLineText(yd,hf),tool:yd,busy:cd}):Dm&&(Hp||cd)?{text:Id??Iu,fullText:Nd,more:$p?.more,speaking:am&&cd,busy:cd,onDismiss:$p?()=>{Up($p.id),ym(!1)}:void 0}:Wd(Hp&&$p?{...peekLine($p.text),onDismiss:()=>{Up($p.id),ym(!1)}}:{text:Iu}),wh=!!gh.sentence||Um==="greeting"||Um==="waiting"||!!Gf||!!yd||Dm&&cd||Hp&&(Um==="speaking"||lm),yh=reactExports.useMemo(()=>mf||!hd?.length?void 0:hd.map(xf=>({label:xf.title,prompt:xf.message})),[mf,hd]),Nh=reactExports.useCallback(xf=>{Rf.current?Rf.current.send(xf.prompt):Df(xf.prompt)},[]),tf=Yd?.onSendReady,df=reactExports.useCallback(xf=>{Rf.current=xf,tf?.(xf)},[tf]),Hh=Yd?.onLoadingChange,Af=Yd?.onDisplayItemsChange,bp=reactExports.useCallback(xf=>{nm(xf),Hh?.(xf)},[Hh]),Mf=reactExports.useCallback(xf=>{const Vp=presenceToolOf(xf);Km(vm=>vm.open===Vp.open&&vm.pendingApproval===Vp.pendingApproval?vm:Vp),Sf(newestIsAnswer(xf));const Lm=newestToolLine(xf);jh(vm=>vm?.id===Lm?.id&&vm?.phase===Lm?.phase?vm:Lm),wf(conversationCount(xf)),$f(xf),Th(xf);const _m=latestSaying(xf);xp(vm=>vm?.id===_m?.id&&vm?.text===_m?.text?vm:_m),Af?.(xf)},[Af]),Pp=reactExports.useCallback(xf=>{if(!(xf==="sidebar"&&Rp))if(xf==="sidebar"){if(Od){Od(xf);return}zp("panel"),sm(Vp=>Vp+1)}else xf==="assistant"&&Jp(),zp(xf),sm(Vp=>Vp+1),Od?.(xf)},[Od,Rp,Jp]);reactExports.useLayoutEffect(()=>{if(Bf!=="panel"||yf){qp(!1);return}if(Cp){qp(!0);return}const xf=kf.current?.parentElement;if(!xf){qp(!1);return}const Vp=window.getComputedStyle(xf),Lm=Vp.display.includes("flex")&&(Vp.flexDirection==="row"||Vp.flexDirection==="row-reverse"),_m=Vp.display.includes("grid");qp(Lm||_m)},[Bf,yf,Tf,Cp]);const Pm=typeof Du=="number"?Du:typeof Du=="string"&&Number.parseInt(Du,10)||420;reactExports.useLayoutEffect(()=>{if(yf||Bf!=="panel"||pp||!Tf){gp(null);return}const xf=kf.current?.parentElement;if(!xf){gp(null);return}const Vp=xf.style.paddingRight,Lm=xf.style.boxSizing,_m=window.getComputedStyle(xf).paddingRight;xf.style.boxSizing="border-box",xf.style.paddingRight=`calc(${_m} + ${Pm}px)`;const vm=()=>{const Ng=xf.getBoundingClientRect();gp(ig=>{const Xm=Ng.height<1?{top:0,height:window.innerHeight,right:0}:{top:Ng.top,height:Ng.height,right:Math.max(0,window.innerWidth-Ng.right)};return ig&&Math.abs(ig.top-Xm.top)<1&&Math.abs(ig.height-Xm.height)<1&&Math.abs(ig.right-Xm.right)<1?ig:Xm})};vm(),window.addEventListener("resize",vm),window.addEventListener("scroll",vm,!0);const yg=new ResizeObserver(vm);return yg.observe(xf),()=>{window.removeEventListener("resize",vm),window.removeEventListener("scroll",vm,!0),yg.disconnect(),xf.style.paddingRight=Vp,xf.style.boxSizing=Lm}},[yf,Bf,pp,Tf,Pm]);const Xp=reactExports.useMemo(()=>{if(lo&&typeof lo=="object")return lo;if(!Au)return;const xf=typeof lo=="string"?lo:void 0,Vp=Au.match(/^(.*?)\/api\/v1\//)?.[1]||Au.match(/^(https?:\/\/[^/]+)/)?.[1]||"",Lm=Au.match(/\/api\/v1\/(ag-ui|vercel-ai|a2a|acp)\//),_m=xf??Lm?.[1]??"vercel-ai",vm=Au.match(/\/api\/v1\/(?:ag-ui|vercel-ai|a2a\/agents|acp\/ws)\/([^/]+)/),yg=vm?vm[1]:void 0;return{type:_m,endpoint:Au,agentId:yg,authToken:Mh,enableConfigQuery:Md||zd||Vd||kd,configEndpoint:Md||zd||Vd||kd?`${Vp}/api/v1/configure`:void 0}},[lo,Au,Mh,Md,zd,Vd,kd]),og=Au?.match(/^(.*?)\/api\/v1\//)?.[1],dm=reactExports.useMemo(()=>Yh||Xp?.agentId?{name:Ru,protocol:Xp?.type,url:Xp?.endpoint,agentId:Xp?.agentId,apiBase:og,...Yh}:void 0,[Yh,Xp,Ru,og]),Hf=useAgentRuntimeCodemodeStatus(),ug=reactExports.useMemo(()=>Kh??assistantSandboxOf(Hf?.sandbox,{agentId:Xp?.agentId,serverUrl:og})??(Xp?.agentId&&og?{kind:"runtime",status:"not running",agentId:Xp.agentId,serverUrl:og}:void 0),[Kh,Hf,Xp?.agentId,og]);reactExports.useEffect(()=>{Jh()},[Au,lo]),reactExports.useEffect(()=>{Nf(Pu)},[]);const yp=reactExports.useCallback(()=>{const xf=!Tf;up(!0),xf?(Nf(xf),nd?.()):setTimeout(()=>{Nf(xf),od?.(),up(!1)},Pd),setTimeout(()=>up(!1),Pd)},[Tf,Nf,nd,od,Pd]),Tm=reactExports.useCallback(xf=>{Tf&&yp(),keepAway(xf),Vf(!0),setTimeout(()=>{Vf(!1),ep(xf)},600)},[Tf,yp]),jg=typeof window>"u"?1280:window.innerWidth,mg=typeof window>"u"?800:window.innerHeight,Hm=conversationBalloonHeight(mg),Rg=Dm&&!mf,vg=Rg?CURRENT_BALLOON_HEIGHT:Hm,Bg=()=>{const xf=CONVERSATION_BALLOON_WIDTH,Vp=vg;if(Bm.position){const{left:ig,top:Xm}=Bm.position,y0=ig+Mp/2<jg/2,jp=Xm-Vp-16,Tg=Xm+Mp+16,km=jp<8&&Tg+Vp>mg-8,Yg=km?y0?ig+Mp+16:ig-xf-16:y0?ig:ig+Mp-xf,_0=km?Xm+Mp-Vp:jp>=8?jp:Tg,x0=clamp(Yg,jg-xf-8);return{place:{left:px(x0),top:px(clamp(_0,mg-Vp-8)),right:"auto",bottom:"auto"},tail:km?{edge:"none"}:{edge:jp>=8?"bottom":"top",at:balloonTailAt(ig+Mp/2,x0)}}}const Lm=Ou.endsWith("right"),_m=Lm?jg-Td-Mp/2:Td+Mp/2,vm=Lm?jg-Td-xf:Td,yg={edge:Ou.startsWith("bottom")?"bottom":"top",at:balloonTailAt(_m,vm)},Ng=Nm();return{place:Ou.startsWith("bottom")?{...Ng,bottom:px(Td+Mp+16)}:{...Ng,top:px(Td+Mp+16)},tail:yg}},Jm=reactExports.useCallback(()=>{$u&&Jh(),rd?.()},[$u,Jh,rd]),Qm=reactExports.useCallback(()=>{window.confirm("Clear all messages?")&&$u&&Jh()},[$u,Jh]);useChatKeyboardShortcuts({onToggle:Uu?yp:void 0,onNewChat:Uu?Jm:void 0,onClear:Uu&&Qh.length>0?Qm:void 0,enabled:Uu}),reactExports.useEffect(()=>{if(!Yu||!Tf)return;const xf=Vp=>{Vp.key==="Escape"&&yp()};return document.addEventListener("keydown",xf),()=>document.removeEventListener("keydown",xf)},[Yu,Tf,yp]);const Fg=!!mf;reactExports.useEffect(()=>{if(!Fg||!Tf)return;const xf=setTimeout(()=>{kf.current?.querySelector('[data-chat-composer] textarea, [data-chat-composer] [contenteditable="true"], textarea')?.focus()},Pd);return()=>clearTimeout(xf)},[Fg,Tf,Pd,Zp]),reactExports.useEffect(()=>{if(!_p||!Tf)return;const xf=setTimeout(()=>{const Vp=kf.current?.querySelector("[data-chat-history]");Vp?.scrollTo?.({top:Vp.scrollHeight})},Pd);return()=>clearTimeout(xf)},[_p,Tf,Pd]),reactExports.useEffect(()=>{if(!Qu||!Tf)return;const xf=Lm=>{kf.current&&!kf.current.contains(Lm.target)&&yp()},Vp=setTimeout(()=>{document.addEventListener("mousedown",xf)},100);return()=>{clearTimeout(Vp),document.removeEventListener("mousedown",xf)}},[Qu,Tf,yp]),reactExports.useEffect(()=>{if(yf&&Tf)return document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.width="100%",document.body.style.touchAction="none",()=>{document.body.style.overflow="",document.body.style.position="",document.body.style.width="",document.body.style.touchAction=""}},[yf,Tf]);const Nm=()=>{const xf={position:"fixed",zIndex:1e3};switch(Ou){case"bottom-right":xf.bottom=Td,xf.right=Td;break;case"bottom-left":xf.bottom=Td,xf.left=Td;break;case"top-right":xf.top=Td,xf.right=Td;break;case"top-left":xf.top=Td,xf.left=Td;break}return xf},Vm=xf=>{if(xf)return"scale(1) translateY(0)";switch(Ou){case"bottom-right":case"bottom-left":return"scale(0.95) translateY(20px)";case"top-right":case"top-left":return"scale(0.95) translateY(-20px)";default:return"scale(0.95)"}},F0=Uu?getShortcutDisplay({key:Hu}):void 0,Am=_p?Bg():void 0,zg=yf?"100%":Am?CONVERSATION_BALLOON_WIDTH:Du,Wp=yf?"100%":Am?vg:Lu,qg=yf?{position:"fixed",top:0,left:0,right:0,bottom:0,width:"100%",height:"100%",borderRadius:0}:{},Fm=jsxRuntimeExports.jsx(Tooltip,{text:`Close${Yu?" (Esc)":""}`,direction:"s",children:jsxRuntimeExports.jsx(IconButton,{icon:XIcon,"aria-label":"Close",onClick:yp,variant:"invisible",size:"small"})}),Dg=Am?{showHeader:!1,showPoweredBy:!1,promptVariant:"lexical",showModelSelector:!1,showToolsMenu:!1,showSkillsMenu:!1,showTokenUsage:!1,showContextRing:!1,showInformation:!1,showToolApprovalBanner:!1,showAgentsMenu:!1,showTurnFooter:!1,compact:!0,welcome:Iu,backgroundColor:"canvas.default",borderRadius:"var(--theme-radius-bubble, 16px)",trailingContent:Gf?jsxRuntimeExports.jsx(BalloonApprovalMessage,{approval:Gf}):void 0,footerContent:Yp?jsxRuntimeExports.jsx(Box,{"data-balloon-decisions":"",px:3,pb:1,display:"flex",flexDirection:"column",alignItems:"flex-end",fontSize:0,sx:{"& form":{alignSelf:"stretch"},'& [data-balloon-decision="answered"]':{alignSelf:"stretch"}},children:jsxRuntimeExports.jsx(DecisionAsk,{ask:Yp})}):void 0}:void 0,O0=jsxRuntimeExports.jsxs(Box,{ref:kf,className:ed,sx:{position:Bf==="panel"&&!yf&&(pp||Qf)?"relative":"fixed",...Bf==="floating"&&!yf?{top:0,right:0,bottom:0,left:"auto"}:{},...Bf==="floating-small"&&!yf?Nm():{},...Bf==="floating-draggable"&&!yf?cm.position?{left:px(cm.position.left),top:px(cm.position.top),right:"auto",bottom:"auto"}:Nm():{},...Am?Am.place:Np&&!yf?Nm():{},...Bf==="panel"&&!yf?{...pp||Qf?{top:"auto",right:"auto",bottom:"auto",left:"auto",marginLeft:"auto",alignSelf:"stretch"}:{top:Jf?`${Jf.top}px`:0,right:Jf?`${Jf.right}px`:0,bottom:Jf?"auto":0,left:"auto"}}:{},width:Bf==="panel"&&!yf?Tf||rp?`${Pm}px`:"0px":Bf==="floating"&&!yf?typeof zg=="number"?`${zg}px`:zg:(Bf==="floating-small"||Bf==="floating-draggable"||Bf==="assistant")&&!yf?typeof zg=="number"?`${zg}px`:zg:yf?"100%":typeof zg=="number"?`${zg}px`:zg,height:Bf==="panel"&&!yf?pp||Qf?"100%":Jf?`${Jf.height}px`:"100%":Bf==="floating"&&!yf?"100%":(Bf==="floating-small"||Bf==="floating-draggable"||Bf==="assistant")&&!yf?typeof Wp=="number"?`${Wp}px`:Wp:yf?"100%":typeof Wp=="number"?`${Wp}px`:Wp,display:"flex",flexDirection:"column",bg:"canvas.default",border:"1px solid",borderColor:"border.default",borderRadius:Bf==="panel"||yf?0:Np?"var(--theme-radius-bubble, 16px)":"12px",boxShadow:Bf==="panel"?"shadow.none":"shadow.extra-large",overflow:"hidden",transform:Bf==="panel"?Tf?"translateX(0)":"translateX(100%)":Vm(Tf),opacity:Bf==="panel"||Tf?1:0,transition:`transform ${Pd}ms ease, opacity ${Pd}ms ease, width ${Pd}ms ease`,zIndex:Bf==="panel"&&!yf&&(pp||Qf)?"auto":1001,visibility:Tf||rp?"visible":"hidden",pointerEvents:Tf?"auto":"none",...qg,...Am?conversationBalloonSx(Am.tail,Am.tail.edge==="bottom"?"canvas.subtle":"canvas.default"):{}},"data-conversation-balloon":Am?"":void 0,"data-balloon-display":Am?oh:void 0,children:[Am?jsxRuntimeExports.jsx(ConversationBalloonClose,{onClose:yp}):null,Am&&!Rg?jsxRuntimeExports.jsx(ConversationBalloonHeader,{count:Ef}):null,Bf==="floating-draggable"&&!yf&&jsxRuntimeExports.jsx(Box,{onPointerDown:cm.onHandlePointerDown,"aria-label":"Move the chat",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,height:18,cursor:"grab",color:"fg.subtle",bg:"canvas.subtle",borderBottom:"1px solid",borderColor:"border.muted",active:{cursor:"grabbing"},touchAction:"none",children:jsxRuntimeExports.jsx(GrabberIcon,{size:16})}),mf?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[ju&&!Am?jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,flexShrink:0,px:3,py:2,borderBottom:"1px solid",borderColor:"border.default",children:[fd||jsxRuntimeExports.jsx(ForwardRef$3,{colored:!0,size:20}),jsxRuntimeExports.jsx(Text$5,{sx:{flex:1,minWidth:0,fontWeight:"semibold",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Ru}),Fm]}):null,jsxRuntimeExports.jsx(Box,{"data-floating-conversation":!0,flex:"1 1 auto",minHeight:0,display:"flex",borderRadius:Am?"bubble":void 0,overflow:Am?"hidden":void 0,children:mf.body})]}):jsxRuntimeExports.jsx(ChatBase,{title:Ru,showHeader:ju,useStore:$u,protocol:Xp,themeVariant:Ld,themeOverrides:Jd,colorMode:Xd,autoFocus:Tf,focusTrigger:Zp,launching:th,launchingMessage:ah,brandIcon:fd||jsxRuntimeExports.jsx(ForwardRef$3,{colored:!0,size:20}),headerButtons:{showNewChat:Fu,showClear:zu&&Qh.length>0,showSettings:qu&&!!Xu,onNewChat:Jm,onClear:Qm,onSettings:Xu},headerActions:jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Fm}),chatViewMode:dp,onChatViewModeChange:Pp,disabledViewModes:hp,showPoweredBy:Vu,promptVariant:Gu,mentionableAgents:Ku,poweredByProps:{brandName:"Datalayer",brandUrl:"https://datalayer.ai",...Zu},renderToolResult:ud,description:Iu,onStateUpdate:ad,onNewChat:rd,suggestions:hd,submitOnSuggestionClick:gd,hideMessagesAfterToolUI:Ed,avatarConfig:{showAvatars:!0},placeholder:"Type a message...",backgroundColor:"canvas.subtle",frontendTools:md,showModelSelector:Md,availableModels:Ud,showToolsMenu:zd,showSkillsMenu:Vd,showTokenUsage:kd,showContextRing:Rd,runtimeId:uh,historyEndpoint:xh,historyAuthToken:Rh,pendingPrompt:bh??Cf,inspector:sh,showInformation:_h,onInformationClick:eh,onToolCallStart:Sh,onToolCallComplete:Dd,showToolApprovalBanner:$d,pendingApprovals:jd,onApproveApproval:Fd,onRejectApproval:rh,voice:Ad,voiceSpeaking:gh.speaking,onStopSpeaking:dh?$h:void 0,...Yd,...Dg,onLoadingChange:bp,onDisplayItemsChange:Mf,onSendReady:df,children:Am&&Rg?jsxRuntimeExports.jsx(Box,{px:3,pt:3,pb:2,overflow:"hidden",children:jsxRuntimeExports.jsx(CurrentBalloonBody,{text:yd?void 0:Id??Iu,fullText:yd?void 0:Nd,tool:yd,busy:cd,speaking:am&&cd,waiting:cd&&!am})}):ld})]}),bg=jsxRuntimeExports.jsx(IconButton,{icon:pd||CommentDiscussionIcon,"aria-label":Sd,unsafeDisableTooltip:!!$p,onClick:Np&&Ip==="page"?Jp:yp,size:"large",sx:{width:56,height:56,borderRadius:"50%",bg:wd||"accent.emphasis",color:"fg.onEmphasis",boxShadow:"shadow.large",transition:"transform 0.2s ease, box-shadow 0.2s ease",transform:np?"scale(1.1)":"scale(1)",...Hp?{animation:"chatFloatingBlink 1.1s ease-in-out infinite","@keyframes chatFloatingBlink":{"0%, 100%":{filter:"brightness(1)",boxShadow:"0 0 0 0 rgba(0,0,0,0)"},"50%":{filter:"brightness(1.25)",boxShadow:"0 0 0 6px var(--bgColor-accent-muted, rgba(84,174,255,0.4))"}},"@media (prefers-reduced-motion: reduce)":{animation:"none"}}:{},"&:hover":{bg:wd||"accent.emphasis",boxShadow:"shadow.extra-large"}}});return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[_p&&jsxRuntimeExports.jsx(AssistantStage,{character:Ah,state:Um,size:Mp,place:Bm.position?{left:px(Bm.position.left),top:px(Bm.position.top)}:Nm(),stageRef:Zm,onDragStart:Bm.onHandlePointerDown,open:Tf,onToggle:yp,balloon:Qd,balloonDisplay:oh,expandTarget:zh,insist:wh,onDismiss:Tm,ownRef:kf,mouthLevel:Uh,suggestions:yh,onSuggestion:Nh,inspector:sh,onBalloonDisplayChange:ph,onStop:Em&&Rf.current?()=>Rf.current?.stop():void 0,onNewChat:!mf&&Fu?Jm:void 0,onClear:!mf&&$u?Qm:void 0,onChangeCharacter:Bh,speech:dh?{muted:sf,onToggle:()=>{sf||dh.stop(),qf(!sf)}}:void 0,onResetPosition:Bm.position?Bm.reset:void 0,about:dm,sandbox:ug,contextMenu:rf}),Bu&&!Tf&&!_p&&jsxRuntimeExports.jsx(Box,{sx:{...Nm()},children:jsxRuntimeExports.jsxs(Box,{position:"relative",display:"inline-flex",isolation:"isolate",onMouseEnter:()=>kp(!0),onMouseLeave:()=>kp(!1),children:[bd&&jsxRuntimeExports.jsx(ButtonGlow,{color:wd}),np&&$p?jsxRuntimeExports.jsx(SpeechBalloon,{text:$p.text,more:$p.more,onOpen:yp,above:64,side:Ou.startsWith("bottom")?"above":"below",align:Ou.includes("right")?"right":"left",tailAt:28}):null,$p?bg:jsxRuntimeExports.jsx(Tooltip,{text:`${Sd}${F0?` (${F0})`:""}`,direction:Ou.includes("right")?"w":"e",children:bg}),Qh.length>0&&jsxRuntimeExports.jsx(Box,{position:"absolute",top:0,right:0,minWidth:18,height:18,px:1,display:"flex",alignItems:"center",justifyContent:"center",bg:"danger.emphasis",color:"fg.onEmphasis",borderRadius:"50%",fontSize:0,fontWeight:"bold",pointerEvents:"none",children:jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0},children:Qh.length>99?"99+":Qh.length})}),Hp&&jsxRuntimeExports.jsx(Box,{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:"50%",border:"2px solid",borderColor:wd||"accent.emphasis",animation:"pulse 2s infinite",pointerEvents:"none",reducedMotion:{animation:"none",transform:"scale(1.15)",opacity:.6},sx:{"@keyframes pulse":{"0%":{transform:"scale(1)",opacity:1},"100%":{transform:"scale(1.5)",opacity:0}}}})]})}),yf&&Tf&&jsxRuntimeExports.jsx(Box,{position:"fixed",top:0,left:0,right:0,bottom:0,bg:"neutral.muted",opacity:.5,zIndex:999,onClick:yp}),Gd&&Bf==="panel"&&Tf&&!yf&&jsxRuntimeExports.jsx(Box,{position:"fixed",top:0,left:0,right:0,bottom:0,bg:"neutral.muted",opacity:.3,zIndex:1e3,onClick:yp}),Qf&&Cp?reactDomExports.createPortal(O0,Cp):O0]})}const LoopCanvasBlock=defineContributionPoint("loop.canvas.block"),LoopA2uiComponent=defineContributionPoint("loop.a2ui.component"),listeners$2=new Set;function requestSurface(Au){if(listeners$2.size===0)return!1;for(const lo of[...listeners$2])lo(Au);return!0}function onSurfaceRequest(Au){return listeners$2.add(Au),()=>{listeners$2.delete(Au)}}const listeners$1=new Set;function focusPrompt(){if(listeners$1.size===0)return!1;for(const Au of[...listeners$1])Au();return!0}function onPromptFocusRequest(Au){return listeners$1.add(Au),()=>{listeners$1.delete(Au)}}function agentServerOf(Au,lo){return Au.target==="datalayer"?Au.agentBaseUrl||void 0:Au.agentBaseUrl||lo}function noRuntimeSaid(Au,lo){return Au.state==="error"?lo.noRuntime(Au.errorReason??""):lo.runtimeStarting}const IDLE_SANDBOX_SNAPSHOT=Object.freeze({state:"idle"}),IDLE_SANDBOX_SNAPSHOT_SIGNAL={value:IDLE_SANDBOX_SNAPSHOT,peek:()=>IDLE_SANDBOX_SNAPSHOT},IDLE_SANDBOX_TARGET_SIGNAL={value:void 0,peek:()=>{}};function loopSurfaceId(Au){return`loop-${Au||"default"}`}function createPromptChannel(){const Au=new Set,lo=[];return{submit($u){if(Au.size===0)return lo.push($u),!0;for(const Ru of[...Au])Ru($u);return!0},subscribe($u){if(Au.add($u),lo.length>0){const Ru=lo.splice(0,lo.length);queueMicrotask(()=>{for(const Iu of Ru)$u(Iu)})}return()=>{Au.delete($u)}}}}const LoopViewType=defineContributionPoint("loop.viewType"),LoopEditorView=defineContributionPoint("loop.chat.surface"),LoopChatSurface=LoopEditorView,LoopFrontendTool=defineContributionPoint("loop.frontendTool"),LoopChatComposer=defineContributionPoint("loop.chat.composer"),LoopChatHeader=defineContributionPoint("loop.chat.header"),LoopAgentBlueprint=defineContributionPoint("loop.agent.blueprint"),LoopChatSuggestion=defineContributionPoint("loop.chat.suggestion"),LoopAssistantCharacter=defineContributionPoint("loop.assistant.character");defineContributionPoint("loop.assistant.menu");const LoopChatExtras=defineContributionPoint("loop.chat.extras"),LoopOpeningNotebook=defineContributionPoint("loop.notebook.opening"),LoopOpeningDocument=defineContributionPoint("loop.document.opening"),LoopAgentGate=defineGate("loop.agent.available"),LoopNotebookToolbar=defineContributionPoint("loop.notebook.toolbar"),LoopNotebookToolbarItem=defineContributionPoint("loop.notebook.toolbar.item"),LoopDocumentToolbar=defineContributionPoint("loop.document.toolbar"),LoopDocumentToolbarItem=defineContributionPoint("loop.document.toolbar.item"),LoopCommand=defineContributionPoint("loop.command"),LoopRunProps=defineContributionPoint("loop.runProps");function runForwardedProps(Au,lo){let $u;for(const Ru of[...Au.map(Iu=>Iu.props()),lo]){if(!Ru)continue;const Iu={...$u?.loop??{},...Ru.loop??{}};$u={...$u,...Ru},Object.keys(Iu).length>0&&($u.loop=Iu)}return $u}defineContributionPoint("loop.mention");const LoopSlots={header:"loop.header",chatHeader:"loop.chatHeader",promptAction:"loop.promptAction",inpromptMenu:"loop.inpromptMenu",footer:"loop.footer",status:"loop.status",root:"root",sidebar:"loop.sidebar"};function sandboxIndicatorState(Au,lo,$u){return Au==="error"?"connected-dead":Au==="starting"?"connected-starting":Au==="stopping"?"disconnecting":Au!=="running"?"disconnected":lo==="busy"||$u?"connected-busy":"connected-idle"}function canOpenView(Au,lo){return Au.canOpen?Au.canOpen(lo):!0}function parseCommand(Au){const lo=Au.trimStart();if(!lo.startsWith("/"))return;const[$u,...Ru]=lo.slice(1).split(/\s+/);if($u)return{name:$u.toLowerCase(),argv:Ru.join(" ").trim()}}const LoopChatLayout=defineContributionPoint("loop.chat.layout"),LoopPromptPanel=defineContributionPoint("loop.prompt.panel"),LoopChatTurn=defineContributionPoint("loop.chat.turn");function defineAgentCapacityPlugin(Au){const{key:lo,displayName:$u,description:Ru,specId:Iu,octicon:Ou,emoji:Pu,codemode:Du,createPayload:Lu,suggestions:ju,instructions:Bu,model:Fu,modeEffect:zu,name:qu,requiredBackendPlugins:Uu}=Au;return{name:qu??`@datalayer/loop-plugin-agent-${lo}`,...Uu?{requiredBackendPlugins:Uu}:{},displayName:$u,description:Ru,octicon:Ou??"dependabot",emoji:Pu,contributes:[contribution(LoopAgentBlueprint,{id:lo,specId:Iu,createPayload:{description:Ru,agent_library:"pydantic-ai",enable_codemode:Du??!1,...Lu},...Bu?{instructions:Bu}:{},...Fu?{model:Fu}:{},...zu?{modeEffect:zu}:{}},{id:lo}),...ju&&ju.length>0?[contribution(LoopChatSuggestion,{id:lo,suggestions:ju},{id:lo})]:[]]}}var util;(function(Au){Au.assertEqual=Iu=>{};function lo(Iu){}Au.assertIs=lo;function $u(Iu){throw new Error}Au.assertNever=$u,Au.arrayToEnum=Iu=>{const Ou={};for(const Pu of Iu)Ou[Pu]=Pu;return Ou},Au.getValidEnumValues=Iu=>{const Ou=Au.objectKeys(Iu).filter(Du=>typeof Iu[Iu[Du]]!="number"),Pu={};for(const Du of Ou)Pu[Du]=Iu[Du];return Au.objectValues(Pu)},Au.objectValues=Iu=>Au.objectKeys(Iu).map(function(Ou){return Iu[Ou]}),Au.objectKeys=typeof Object.keys=="function"?Iu=>Object.keys(Iu):Iu=>{const Ou=[];for(const Pu in Iu)Object.prototype.hasOwnProperty.call(Iu,Pu)&&Ou.push(Pu);return Ou},Au.find=(Iu,Ou)=>{for(const Pu of Iu)if(Ou(Pu))return Pu},Au.isInteger=typeof Number.isInteger=="function"?Iu=>Number.isInteger(Iu):Iu=>typeof Iu=="number"&&Number.isFinite(Iu)&&Math.floor(Iu)===Iu;function Ru(Iu,Ou=" | "){return Iu.map(Pu=>typeof Pu=="string"?`'${Pu}'`:Pu).join(Ou)}Au.joinValues=Ru,Au.jsonStringifyReplacer=(Iu,Ou)=>typeof Ou=="bigint"?Ou.toString():Ou})(util||(util={}));var objectUtil;(function(Au){Au.mergeShapes=(lo,$u)=>({...lo,...$u})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=Au=>{switch(typeof Au){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(Au)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(Au)?ZodParsedType.array:Au===null?ZodParsedType.null:Au.then&&typeof Au.then=="function"&&Au.catch&&typeof Au.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&Au instanceof Map?ZodParsedType.map:typeof Set<"u"&&Au instanceof Set?ZodParsedType.set:typeof Date<"u"&&Au instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ZodError extends Error{get errors(){return this.issues}constructor(lo){super(),this.issues=[],this.addIssue=Ru=>{this.issues=[...this.issues,Ru]},this.addIssues=(Ru=[])=>{this.issues=[...this.issues,...Ru]};const $u=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,$u):this.__proto__=$u,this.name="ZodError",this.issues=lo}format(lo){const $u=lo||function(Ou){return Ou.message},Ru={_errors:[]},Iu=Ou=>{for(const Pu of Ou.issues)if(Pu.code==="invalid_union")Pu.unionErrors.map(Iu);else if(Pu.code==="invalid_return_type")Iu(Pu.returnTypeError);else if(Pu.code==="invalid_arguments")Iu(Pu.argumentsError);else if(Pu.path.length===0)Ru._errors.push($u(Pu));else{let Du=Ru,Lu=0;for(;Lu<Pu.path.length;){const ju=Pu.path[Lu];Lu===Pu.path.length-1?(Du[ju]=Du[ju]||{_errors:[]},Du[ju]._errors.push($u(Pu))):Du[ju]=Du[ju]||{_errors:[]},Du=Du[ju],Lu++}}};return Iu(this),Ru}static assert(lo){if(!(lo instanceof ZodError))throw new Error(`Not a ZodError: ${lo}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(lo=$u=>$u.message){const $u={},Ru=[];for(const Iu of this.issues)if(Iu.path.length>0){const Ou=Iu.path[0];$u[Ou]=$u[Ou]||[],$u[Ou].push(lo(Iu))}else Ru.push(lo(Iu));return{formErrors:Ru,fieldErrors:$u}}get formErrors(){return this.flatten()}}ZodError.create=Au=>new ZodError(Au);const errorMap=(Au,lo)=>{let $u;switch(Au.code){case ZodIssueCode.invalid_type:Au.received===ZodParsedType.undefined?$u="Required":$u=`Expected ${Au.expected}, received ${Au.received}`;break;case ZodIssueCode.invalid_literal:$u=`Invalid literal value, expected ${JSON.stringify(Au.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:$u=`Unrecognized key(s) in object: ${util.joinValues(Au.keys,", ")}`;break;case ZodIssueCode.invalid_union:$u="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:$u=`Invalid discriminator value. Expected ${util.joinValues(Au.options)}`;break;case ZodIssueCode.invalid_enum_value:$u=`Invalid enum value. Expected ${util.joinValues(Au.options)}, received '${Au.received}'`;break;case ZodIssueCode.invalid_arguments:$u="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:$u="Invalid function return type";break;case ZodIssueCode.invalid_date:$u="Invalid date";break;case ZodIssueCode.invalid_string:typeof Au.validation=="object"?"includes"in Au.validation?($u=`Invalid input: must include "${Au.validation.includes}"`,typeof Au.validation.position=="number"&&($u=`${$u} at one or more positions greater than or equal to ${Au.validation.position}`)):"startsWith"in Au.validation?$u=`Invalid input: must start with "${Au.validation.startsWith}"`:"endsWith"in Au.validation?$u=`Invalid input: must end with "${Au.validation.endsWith}"`:util.assertNever(Au.validation):Au.validation!=="regex"?$u=`Invalid ${Au.validation}`:$u="Invalid";break;case ZodIssueCode.too_small:Au.type==="array"?$u=`Array must contain ${Au.exact?"exactly":Au.inclusive?"at least":"more than"} ${Au.minimum} element(s)`:Au.type==="string"?$u=`String must contain ${Au.exact?"exactly":Au.inclusive?"at least":"over"} ${Au.minimum} character(s)`:Au.type==="number"?$u=`Number must be ${Au.exact?"exactly equal to ":Au.inclusive?"greater than or equal to ":"greater than "}${Au.minimum}`:Au.type==="bigint"?$u=`Number must be ${Au.exact?"exactly equal to ":Au.inclusive?"greater than or equal to ":"greater than "}${Au.minimum}`:Au.type==="date"?$u=`Date must be ${Au.exact?"exactly equal to ":Au.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(Au.minimum))}`:$u="Invalid input";break;case ZodIssueCode.too_big:Au.type==="array"?$u=`Array must contain ${Au.exact?"exactly":Au.inclusive?"at most":"less than"} ${Au.maximum} element(s)`:Au.type==="string"?$u=`String must contain ${Au.exact?"exactly":Au.inclusive?"at most":"under"} ${Au.maximum} character(s)`:Au.type==="number"?$u=`Number must be ${Au.exact?"exactly":Au.inclusive?"less than or equal to":"less than"} ${Au.maximum}`:Au.type==="bigint"?$u=`BigInt must be ${Au.exact?"exactly":Au.inclusive?"less than or equal to":"less than"} ${Au.maximum}`:Au.type==="date"?$u=`Date must be ${Au.exact?"exactly":Au.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(Au.maximum))}`:$u="Invalid input";break;case ZodIssueCode.custom:$u="Invalid input";break;case ZodIssueCode.invalid_intersection_types:$u="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:$u=`Number must be a multiple of ${Au.multipleOf}`;break;case ZodIssueCode.not_finite:$u="Number must be finite";break;default:$u=lo.defaultError,util.assertNever(Au)}return{message:$u}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=Au=>{const{data:lo,path:$u,errorMaps:Ru,issueData:Iu}=Au,Ou=[...$u,...Iu.path||[]],Pu={...Iu,path:Ou};if(Iu.message!==void 0)return{...Iu,path:Ou,message:Iu.message};let Du="";const Lu=Ru.filter(ju=>!!ju).slice().reverse();for(const ju of Lu)Du=ju(Pu,{data:lo,defaultError:Du}).message;return{...Iu,path:Ou,message:Du}};function addIssueToContext(Au,lo){const $u=getErrorMap(),Ru=makeIssue({issueData:lo,data:Au.data,path:Au.path,errorMaps:[Au.common.contextualErrorMap,Au.schemaErrorMap,$u,$u===errorMap?void 0:errorMap].filter(Iu=>!!Iu)});Au.common.issues.push(Ru)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(lo,$u){const Ru=[];for(const Iu of $u){if(Iu.status==="aborted")return INVALID;Iu.status==="dirty"&&lo.dirty(),Ru.push(Iu.value)}return{status:lo.value,value:Ru}}static async mergeObjectAsync(lo,$u){const Ru=[];for(const Iu of $u){const Ou=await Iu.key,Pu=await Iu.value;Ru.push({key:Ou,value:Pu})}return ParseStatus.mergeObjectSync(lo,Ru)}static mergeObjectSync(lo,$u){const Ru={};for(const Iu of $u){const{key:Ou,value:Pu}=Iu;if(Ou.status==="aborted"||Pu.status==="aborted")return INVALID;Ou.status==="dirty"&&lo.dirty(),Pu.status==="dirty"&&lo.dirty(),Ou.value!=="__proto__"&&(typeof Pu.value<"u"||Iu.alwaysSet)&&(Ru[Ou.value]=Pu.value)}return{status:lo.value,value:Ru}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=Au=>({status:"dirty",value:Au}),OK=Au=>({status:"valid",value:Au}),isAborted=Au=>Au.status==="aborted",isDirty=Au=>Au.status==="dirty",isValid=Au=>Au.status==="valid",isAsync=Au=>typeof Promise<"u"&&Au instanceof Promise;var errorUtil;(function(Au){Au.errToObj=lo=>typeof lo=="string"?{message:lo}:lo||{},Au.toString=lo=>typeof lo=="string"?lo:lo?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(lo,$u,Ru,Iu){this._cachedPath=[],this.parent=lo,this.data=$u,this._path=Ru,this._key=Iu}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(Au,lo)=>{if(isValid(lo))return{success:!0,data:lo.value};if(!Au.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const $u=new ZodError(Au.common.issues);return this._error=$u,this._error}}};function processCreateParams(Au){if(!Au)return{};const{errorMap:lo,invalid_type_error:$u,required_error:Ru,description:Iu}=Au;if(lo&&($u||Ru))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return lo?{errorMap:lo,description:Iu}:{errorMap:(Pu,Du)=>{const{message:Lu}=Au;return Pu.code==="invalid_enum_value"?{message:Lu??Du.defaultError}:typeof Du.data>"u"?{message:Lu??Ru??Du.defaultError}:Pu.code!=="invalid_type"?{message:Du.defaultError}:{message:Lu??$u??Du.defaultError}},description:Iu}}class ZodType{get description(){return this._def.description}_getType(lo){return getParsedType(lo.data)}_getOrReturnCtx(lo,$u){return $u||{common:lo.parent.common,data:lo.data,parsedType:getParsedType(lo.data),schemaErrorMap:this._def.errorMap,path:lo.path,parent:lo.parent}}_processInputParams(lo){return{status:new ParseStatus,ctx:{common:lo.parent.common,data:lo.data,parsedType:getParsedType(lo.data),schemaErrorMap:this._def.errorMap,path:lo.path,parent:lo.parent}}}_parseSync(lo){const $u=this._parse(lo);if(isAsync($u))throw new Error("Synchronous parse encountered promise.");return $u}_parseAsync(lo){const $u=this._parse(lo);return Promise.resolve($u)}parse(lo,$u){const Ru=this.safeParse(lo,$u);if(Ru.success)return Ru.data;throw Ru.error}safeParse(lo,$u){const Ru={common:{issues:[],async:$u?.async??!1,contextualErrorMap:$u?.errorMap},path:$u?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:lo,parsedType:getParsedType(lo)},Iu=this._parseSync({data:lo,path:Ru.path,parent:Ru});return handleResult(Ru,Iu)}"~validate"(lo){const $u={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:lo,parsedType:getParsedType(lo)};if(!this["~standard"].async)try{const Ru=this._parseSync({data:lo,path:[],parent:$u});return isValid(Ru)?{value:Ru.value}:{issues:$u.common.issues}}catch(Ru){Ru?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),$u.common={issues:[],async:!0}}return this._parseAsync({data:lo,path:[],parent:$u}).then(Ru=>isValid(Ru)?{value:Ru.value}:{issues:$u.common.issues})}async parseAsync(lo,$u){const Ru=await this.safeParseAsync(lo,$u);if(Ru.success)return Ru.data;throw Ru.error}async safeParseAsync(lo,$u){const Ru={common:{issues:[],contextualErrorMap:$u?.errorMap,async:!0},path:$u?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:lo,parsedType:getParsedType(lo)},Iu=this._parse({data:lo,path:Ru.path,parent:Ru}),Ou=await(isAsync(Iu)?Iu:Promise.resolve(Iu));return handleResult(Ru,Ou)}refine(lo,$u){const Ru=Iu=>typeof $u=="string"||typeof $u>"u"?{message:$u}:typeof $u=="function"?$u(Iu):$u;return this._refinement((Iu,Ou)=>{const Pu=lo(Iu),Du=()=>Ou.addIssue({code:ZodIssueCode.custom,...Ru(Iu)});return typeof Promise<"u"&&Pu instanceof Promise?Pu.then(Lu=>Lu?!0:(Du(),!1)):Pu?!0:(Du(),!1)})}refinement(lo,$u){return this._refinement((Ru,Iu)=>lo(Ru)?!0:(Iu.addIssue(typeof $u=="function"?$u(Ru,Iu):$u),!1))}_refinement(lo){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:lo}})}superRefine(lo){return this._refinement(lo)}constructor(lo){this.spa=this.safeParseAsync,this._def=lo,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:$u=>this["~validate"]($u)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(lo){return ZodUnion.create([this,lo],this._def)}and(lo){return ZodIntersection.create(this,lo,this._def)}transform(lo){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:lo}})}default(lo){const $u=typeof lo=="function"?lo:()=>lo;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:$u,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(lo){const $u=typeof lo=="function"?lo:()=>lo;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:$u,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(lo){const $u=this.constructor;return new $u({...this._def,description:lo})}pipe(lo){return ZodPipeline.create(this,lo)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(Au){let lo="[0-5]\\d";Au.precision?lo=`${lo}\\.\\d{${Au.precision}}`:Au.precision==null&&(lo=`${lo}(\\.\\d+)?`);const $u=Au.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${lo})${$u}`}function timeRegex(Au){return new RegExp(`^${timeRegexSource(Au)}$`)}function datetimeRegex(Au){let lo=`${dateRegexSource}T${timeRegexSource(Au)}`;const $u=[];return $u.push(Au.local?"Z?":"Z"),Au.offset&&$u.push("([+-]\\d{2}:?\\d{2})"),lo=`${lo}(${$u.join("|")})`,new RegExp(`^${lo}$`)}function isValidIP(Au,lo){return!!((lo==="v4"||!lo)&&ipv4Regex.test(Au)||(lo==="v6"||!lo)&&ipv6Regex.test(Au))}function isValidJWT(Au,lo){if(!jwtRegex.test(Au))return!1;try{const[$u]=Au.split(".");if(!$u)return!1;const Ru=$u.replace(/-/g,"+").replace(/_/g,"/").padEnd($u.length+(4-$u.length%4)%4,"="),Iu=JSON.parse(atob(Ru));return!(typeof Iu!="object"||Iu===null||"typ"in Iu&&Iu?.typ!=="JWT"||!Iu.alg||lo&&Iu.alg!==lo)}catch{return!1}}function isValidCidr(Au,lo){return!!((lo==="v4"||!lo)&&ipv4CidrRegex.test(Au)||(lo==="v6"||!lo)&&ipv6CidrRegex.test(Au))}class ZodString extends ZodType{_parse(lo){if(this._def.coerce&&(lo.data=String(lo.data)),this._getType(lo)!==ZodParsedType.string){const Ou=this._getOrReturnCtx(lo);return addIssueToContext(Ou,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:Ou.parsedType}),INVALID}const Ru=new ParseStatus;let Iu;for(const Ou of this._def.checks)if(Ou.kind==="min")lo.data.length<Ou.value&&(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.too_small,minimum:Ou.value,type:"string",inclusive:!0,exact:!1,message:Ou.message}),Ru.dirty());else if(Ou.kind==="max")lo.data.length>Ou.value&&(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.too_big,maximum:Ou.value,type:"string",inclusive:!0,exact:!1,message:Ou.message}),Ru.dirty());else if(Ou.kind==="length"){const Pu=lo.data.length>Ou.value,Du=lo.data.length<Ou.value;(Pu||Du)&&(Iu=this._getOrReturnCtx(lo,Iu),Pu?addIssueToContext(Iu,{code:ZodIssueCode.too_big,maximum:Ou.value,type:"string",inclusive:!0,exact:!0,message:Ou.message}):Du&&addIssueToContext(Iu,{code:ZodIssueCode.too_small,minimum:Ou.value,type:"string",inclusive:!0,exact:!0,message:Ou.message}),Ru.dirty())}else if(Ou.kind==="email")emailRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"email",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty());else if(Ou.kind==="emoji")emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"emoji",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty());else if(Ou.kind==="uuid")uuidRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"uuid",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty());else if(Ou.kind==="nanoid")nanoidRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty());else if(Ou.kind==="cuid")cuidRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"cuid",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty());else if(Ou.kind==="cuid2")cuid2Regex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty());else if(Ou.kind==="ulid")ulidRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"ulid",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty());else if(Ou.kind==="url")try{new URL(lo.data)}catch{Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"url",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty()}else Ou.kind==="regex"?(Ou.regex.lastIndex=0,Ou.regex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"regex",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty())):Ou.kind==="trim"?lo.data=lo.data.trim():Ou.kind==="includes"?lo.data.includes(Ou.value,Ou.position)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:{includes:Ou.value,position:Ou.position},message:Ou.message}),Ru.dirty()):Ou.kind==="toLowerCase"?lo.data=lo.data.toLowerCase():Ou.kind==="toUpperCase"?lo.data=lo.data.toUpperCase():Ou.kind==="startsWith"?lo.data.startsWith(Ou.value)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:{startsWith:Ou.value},message:Ou.message}),Ru.dirty()):Ou.kind==="endsWith"?lo.data.endsWith(Ou.value)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:{endsWith:Ou.value},message:Ou.message}),Ru.dirty()):Ou.kind==="datetime"?datetimeRegex(Ou).test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:"datetime",message:Ou.message}),Ru.dirty()):Ou.kind==="date"?dateRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:"date",message:Ou.message}),Ru.dirty()):Ou.kind==="time"?timeRegex(Ou).test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:"time",message:Ou.message}),Ru.dirty()):Ou.kind==="duration"?durationRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"duration",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty()):Ou.kind==="ip"?isValidIP(lo.data,Ou.version)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"ip",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty()):Ou.kind==="jwt"?isValidJWT(lo.data,Ou.alg)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"jwt",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty()):Ou.kind==="cidr"?isValidCidr(lo.data,Ou.version)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"cidr",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty()):Ou.kind==="base64"?base64Regex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"base64",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty()):Ou.kind==="base64url"?base64urlRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"base64url",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty()):util.assertNever(Ou);return{status:Ru.value,value:lo.data}}_regex(lo,$u,Ru){return this.refinement(Iu=>lo.test(Iu),{validation:$u,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(Ru)})}_addCheck(lo){return new ZodString({...this._def,checks:[...this._def.checks,lo]})}email(lo){return this._addCheck({kind:"email",...errorUtil.errToObj(lo)})}url(lo){return this._addCheck({kind:"url",...errorUtil.errToObj(lo)})}emoji(lo){return this._addCheck({kind:"emoji",...errorUtil.errToObj(lo)})}uuid(lo){return this._addCheck({kind:"uuid",...errorUtil.errToObj(lo)})}nanoid(lo){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(lo)})}cuid(lo){return this._addCheck({kind:"cuid",...errorUtil.errToObj(lo)})}cuid2(lo){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(lo)})}ulid(lo){return this._addCheck({kind:"ulid",...errorUtil.errToObj(lo)})}base64(lo){return this._addCheck({kind:"base64",...errorUtil.errToObj(lo)})}base64url(lo){return this._addCheck({kind:"base64url",...errorUtil.errToObj(lo)})}jwt(lo){return this._addCheck({kind:"jwt",...errorUtil.errToObj(lo)})}ip(lo){return this._addCheck({kind:"ip",...errorUtil.errToObj(lo)})}cidr(lo){return this._addCheck({kind:"cidr",...errorUtil.errToObj(lo)})}datetime(lo){return typeof lo=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:lo}):this._addCheck({kind:"datetime",precision:typeof lo?.precision>"u"?null:lo?.precision,offset:lo?.offset??!1,local:lo?.local??!1,...errorUtil.errToObj(lo?.message)})}date(lo){return this._addCheck({kind:"date",message:lo})}time(lo){return typeof lo=="string"?this._addCheck({kind:"time",precision:null,message:lo}):this._addCheck({kind:"time",precision:typeof lo?.precision>"u"?null:lo?.precision,...errorUtil.errToObj(lo?.message)})}duration(lo){return this._addCheck({kind:"duration",...errorUtil.errToObj(lo)})}regex(lo,$u){return this._addCheck({kind:"regex",regex:lo,...errorUtil.errToObj($u)})}includes(lo,$u){return this._addCheck({kind:"includes",value:lo,position:$u?.position,...errorUtil.errToObj($u?.message)})}startsWith(lo,$u){return this._addCheck({kind:"startsWith",value:lo,...errorUtil.errToObj($u)})}endsWith(lo,$u){return this._addCheck({kind:"endsWith",value:lo,...errorUtil.errToObj($u)})}min(lo,$u){return this._addCheck({kind:"min",value:lo,...errorUtil.errToObj($u)})}max(lo,$u){return this._addCheck({kind:"max",value:lo,...errorUtil.errToObj($u)})}length(lo,$u){return this._addCheck({kind:"length",value:lo,...errorUtil.errToObj($u)})}nonempty(lo){return this.min(1,errorUtil.errToObj(lo))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(lo=>lo.kind==="datetime")}get isDate(){return!!this._def.checks.find(lo=>lo.kind==="date")}get isTime(){return!!this._def.checks.find(lo=>lo.kind==="time")}get isDuration(){return!!this._def.checks.find(lo=>lo.kind==="duration")}get isEmail(){return!!this._def.checks.find(lo=>lo.kind==="email")}get isURL(){return!!this._def.checks.find(lo=>lo.kind==="url")}get isEmoji(){return!!this._def.checks.find(lo=>lo.kind==="emoji")}get isUUID(){return!!this._def.checks.find(lo=>lo.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(lo=>lo.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(lo=>lo.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(lo=>lo.kind==="cuid2")}get isULID(){return!!this._def.checks.find(lo=>lo.kind==="ulid")}get isIP(){return!!this._def.checks.find(lo=>lo.kind==="ip")}get isCIDR(){return!!this._def.checks.find(lo=>lo.kind==="cidr")}get isBase64(){return!!this._def.checks.find(lo=>lo.kind==="base64")}get isBase64url(){return!!this._def.checks.find(lo=>lo.kind==="base64url")}get minLength(){let lo=null;for(const $u of this._def.checks)$u.kind==="min"&&(lo===null||$u.value>lo)&&(lo=$u.value);return lo}get maxLength(){let lo=null;for(const $u of this._def.checks)$u.kind==="max"&&(lo===null||$u.value<lo)&&(lo=$u.value);return lo}}ZodString.create=Au=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:Au?.coerce??!1,...processCreateParams(Au)});function floatSafeRemainder(Au,lo){const $u=(Au.toString().split(".")[1]||"").length,Ru=(lo.toString().split(".")[1]||"").length,Iu=$u>Ru?$u:Ru,Ou=Number.parseInt(Au.toFixed(Iu).replace(".","")),Pu=Number.parseInt(lo.toFixed(Iu).replace(".",""));return Ou%Pu/10**Iu}class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(lo){if(this._def.coerce&&(lo.data=Number(lo.data)),this._getType(lo)!==ZodParsedType.number){const Ou=this._getOrReturnCtx(lo);return addIssueToContext(Ou,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:Ou.parsedType}),INVALID}let Ru;const Iu=new ParseStatus;for(const Ou of this._def.checks)Ou.kind==="int"?util.isInteger(lo.data)||(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:Ou.message}),Iu.dirty()):Ou.kind==="min"?(Ou.inclusive?lo.data<Ou.value:lo.data<=Ou.value)&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.too_small,minimum:Ou.value,type:"number",inclusive:Ou.inclusive,exact:!1,message:Ou.message}),Iu.dirty()):Ou.kind==="max"?(Ou.inclusive?lo.data>Ou.value:lo.data>=Ou.value)&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.too_big,maximum:Ou.value,type:"number",inclusive:Ou.inclusive,exact:!1,message:Ou.message}),Iu.dirty()):Ou.kind==="multipleOf"?floatSafeRemainder(lo.data,Ou.value)!==0&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.not_multiple_of,multipleOf:Ou.value,message:Ou.message}),Iu.dirty()):Ou.kind==="finite"?Number.isFinite(lo.data)||(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.not_finite,message:Ou.message}),Iu.dirty()):util.assertNever(Ou);return{status:Iu.value,value:lo.data}}gte(lo,$u){return this.setLimit("min",lo,!0,errorUtil.toString($u))}gt(lo,$u){return this.setLimit("min",lo,!1,errorUtil.toString($u))}lte(lo,$u){return this.setLimit("max",lo,!0,errorUtil.toString($u))}lt(lo,$u){return this.setLimit("max",lo,!1,errorUtil.toString($u))}setLimit(lo,$u,Ru,Iu){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:lo,value:$u,inclusive:Ru,message:errorUtil.toString(Iu)}]})}_addCheck(lo){return new ZodNumber({...this._def,checks:[...this._def.checks,lo]})}int(lo){return this._addCheck({kind:"int",message:errorUtil.toString(lo)})}positive(lo){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(lo)})}negative(lo){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(lo)})}nonpositive(lo){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(lo)})}nonnegative(lo){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(lo)})}multipleOf(lo,$u){return this._addCheck({kind:"multipleOf",value:lo,message:errorUtil.toString($u)})}finite(lo){return this._addCheck({kind:"finite",message:errorUtil.toString(lo)})}safe(lo){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(lo)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(lo)})}get minValue(){let lo=null;for(const $u of this._def.checks)$u.kind==="min"&&(lo===null||$u.value>lo)&&(lo=$u.value);return lo}get maxValue(){let lo=null;for(const $u of this._def.checks)$u.kind==="max"&&(lo===null||$u.value<lo)&&(lo=$u.value);return lo}get isInt(){return!!this._def.checks.find(lo=>lo.kind==="int"||lo.kind==="multipleOf"&&util.isInteger(lo.value))}get isFinite(){let lo=null,$u=null;for(const Ru of this._def.checks){if(Ru.kind==="finite"||Ru.kind==="int"||Ru.kind==="multipleOf")return!0;Ru.kind==="min"?($u===null||Ru.value>$u)&&($u=Ru.value):Ru.kind==="max"&&(lo===null||Ru.value<lo)&&(lo=Ru.value)}return Number.isFinite($u)&&Number.isFinite(lo)}}ZodNumber.create=Au=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:Au?.coerce||!1,...processCreateParams(Au)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(lo){if(this._def.coerce)try{lo.data=BigInt(lo.data)}catch{return this._getInvalidInput(lo)}if(this._getType(lo)!==ZodParsedType.bigint)return this._getInvalidInput(lo);let Ru;const Iu=new ParseStatus;for(const Ou of this._def.checks)Ou.kind==="min"?(Ou.inclusive?lo.data<Ou.value:lo.data<=Ou.value)&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.too_small,type:"bigint",minimum:Ou.value,inclusive:Ou.inclusive,message:Ou.message}),Iu.dirty()):Ou.kind==="max"?(Ou.inclusive?lo.data>Ou.value:lo.data>=Ou.value)&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.too_big,type:"bigint",maximum:Ou.value,inclusive:Ou.inclusive,message:Ou.message}),Iu.dirty()):Ou.kind==="multipleOf"?lo.data%Ou.value!==BigInt(0)&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.not_multiple_of,multipleOf:Ou.value,message:Ou.message}),Iu.dirty()):util.assertNever(Ou);return{status:Iu.value,value:lo.data}}_getInvalidInput(lo){const $u=this._getOrReturnCtx(lo);return addIssueToContext($u,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:$u.parsedType}),INVALID}gte(lo,$u){return this.setLimit("min",lo,!0,errorUtil.toString($u))}gt(lo,$u){return this.setLimit("min",lo,!1,errorUtil.toString($u))}lte(lo,$u){return this.setLimit("max",lo,!0,errorUtil.toString($u))}lt(lo,$u){return this.setLimit("max",lo,!1,errorUtil.toString($u))}setLimit(lo,$u,Ru,Iu){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:lo,value:$u,inclusive:Ru,message:errorUtil.toString(Iu)}]})}_addCheck(lo){return new ZodBigInt({...this._def,checks:[...this._def.checks,lo]})}positive(lo){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(lo)})}negative(lo){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(lo)})}nonpositive(lo){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(lo)})}nonnegative(lo){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(lo)})}multipleOf(lo,$u){return this._addCheck({kind:"multipleOf",value:lo,message:errorUtil.toString($u)})}get minValue(){let lo=null;for(const $u of this._def.checks)$u.kind==="min"&&(lo===null||$u.value>lo)&&(lo=$u.value);return lo}get maxValue(){let lo=null;for(const $u of this._def.checks)$u.kind==="max"&&(lo===null||$u.value<lo)&&(lo=$u.value);return lo}}ZodBigInt.create=Au=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:Au?.coerce??!1,...processCreateParams(Au)});class ZodBoolean extends ZodType{_parse(lo){if(this._def.coerce&&(lo.data=!!lo.data),this._getType(lo)!==ZodParsedType.boolean){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:Ru.parsedType}),INVALID}return OK(lo.data)}}ZodBoolean.create=Au=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:Au?.coerce||!1,...processCreateParams(Au)});class ZodDate extends ZodType{_parse(lo){if(this._def.coerce&&(lo.data=new Date(lo.data)),this._getType(lo)!==ZodParsedType.date){const Ou=this._getOrReturnCtx(lo);return addIssueToContext(Ou,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:Ou.parsedType}),INVALID}if(Number.isNaN(lo.data.getTime())){const Ou=this._getOrReturnCtx(lo);return addIssueToContext(Ou,{code:ZodIssueCode.invalid_date}),INVALID}const Ru=new ParseStatus;let Iu;for(const Ou of this._def.checks)Ou.kind==="min"?lo.data.getTime()<Ou.value&&(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.too_small,message:Ou.message,inclusive:!0,exact:!1,minimum:Ou.value,type:"date"}),Ru.dirty()):Ou.kind==="max"?lo.data.getTime()>Ou.value&&(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.too_big,message:Ou.message,inclusive:!0,exact:!1,maximum:Ou.value,type:"date"}),Ru.dirty()):util.assertNever(Ou);return{status:Ru.value,value:new Date(lo.data.getTime())}}_addCheck(lo){return new ZodDate({...this._def,checks:[...this._def.checks,lo]})}min(lo,$u){return this._addCheck({kind:"min",value:lo.getTime(),message:errorUtil.toString($u)})}max(lo,$u){return this._addCheck({kind:"max",value:lo.getTime(),message:errorUtil.toString($u)})}get minDate(){let lo=null;for(const $u of this._def.checks)$u.kind==="min"&&(lo===null||$u.value>lo)&&(lo=$u.value);return lo!=null?new Date(lo):null}get maxDate(){let lo=null;for(const $u of this._def.checks)$u.kind==="max"&&(lo===null||$u.value<lo)&&(lo=$u.value);return lo!=null?new Date(lo):null}}ZodDate.create=Au=>new ZodDate({checks:[],coerce:Au?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(Au)});class ZodSymbol extends ZodType{_parse(lo){if(this._getType(lo)!==ZodParsedType.symbol){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:Ru.parsedType}),INVALID}return OK(lo.data)}}ZodSymbol.create=Au=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(Au)});class ZodUndefined extends ZodType{_parse(lo){if(this._getType(lo)!==ZodParsedType.undefined){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:Ru.parsedType}),INVALID}return OK(lo.data)}}ZodUndefined.create=Au=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(Au)});class ZodNull extends ZodType{_parse(lo){if(this._getType(lo)!==ZodParsedType.null){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:Ru.parsedType}),INVALID}return OK(lo.data)}}ZodNull.create=Au=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(Au)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(lo){return OK(lo.data)}}ZodAny.create=Au=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(Au)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(lo){return OK(lo.data)}}ZodUnknown.create=Au=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(Au)});class ZodNever extends ZodType{_parse(lo){const $u=this._getOrReturnCtx(lo);return addIssueToContext($u,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:$u.parsedType}),INVALID}}ZodNever.create=Au=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(Au)});class ZodVoid extends ZodType{_parse(lo){if(this._getType(lo)!==ZodParsedType.undefined){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:Ru.parsedType}),INVALID}return OK(lo.data)}}ZodVoid.create=Au=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(Au)});class ZodArray extends ZodType{_parse(lo){const{ctx:$u,status:Ru}=this._processInputParams(lo),Iu=this._def;if($u.parsedType!==ZodParsedType.array)return addIssueToContext($u,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:$u.parsedType}),INVALID;if(Iu.exactLength!==null){const Pu=$u.data.length>Iu.exactLength.value,Du=$u.data.length<Iu.exactLength.value;(Pu||Du)&&(addIssueToContext($u,{code:Pu?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:Du?Iu.exactLength.value:void 0,maximum:Pu?Iu.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:Iu.exactLength.message}),Ru.dirty())}if(Iu.minLength!==null&&$u.data.length<Iu.minLength.value&&(addIssueToContext($u,{code:ZodIssueCode.too_small,minimum:Iu.minLength.value,type:"array",inclusive:!0,exact:!1,message:Iu.minLength.message}),Ru.dirty()),Iu.maxLength!==null&&$u.data.length>Iu.maxLength.value&&(addIssueToContext($u,{code:ZodIssueCode.too_big,maximum:Iu.maxLength.value,type:"array",inclusive:!0,exact:!1,message:Iu.maxLength.message}),Ru.dirty()),$u.common.async)return Promise.all([...$u.data].map((Pu,Du)=>Iu.type._parseAsync(new ParseInputLazyPath($u,Pu,$u.path,Du)))).then(Pu=>ParseStatus.mergeArray(Ru,Pu));const Ou=[...$u.data].map((Pu,Du)=>Iu.type._parseSync(new ParseInputLazyPath($u,Pu,$u.path,Du)));return ParseStatus.mergeArray(Ru,Ou)}get element(){return this._def.type}min(lo,$u){return new ZodArray({...this._def,minLength:{value:lo,message:errorUtil.toString($u)}})}max(lo,$u){return new ZodArray({...this._def,maxLength:{value:lo,message:errorUtil.toString($u)}})}length(lo,$u){return new ZodArray({...this._def,exactLength:{value:lo,message:errorUtil.toString($u)}})}nonempty(lo){return this.min(1,lo)}}ZodArray.create=(Au,lo)=>new ZodArray({type:Au,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(lo)});function deepPartialify(Au){if(Au instanceof ZodObject){const lo={};for(const $u in Au.shape){const Ru=Au.shape[$u];lo[$u]=ZodOptional.create(deepPartialify(Ru))}return new ZodObject({...Au._def,shape:()=>lo})}else return Au instanceof ZodArray?new ZodArray({...Au._def,type:deepPartialify(Au.element)}):Au instanceof ZodOptional?ZodOptional.create(deepPartialify(Au.unwrap())):Au instanceof ZodNullable?ZodNullable.create(deepPartialify(Au.unwrap())):Au instanceof ZodTuple?ZodTuple.create(Au.items.map(lo=>deepPartialify(lo))):Au}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const lo=this._def.shape(),$u=util.objectKeys(lo);return this._cached={shape:lo,keys:$u},this._cached}_parse(lo){if(this._getType(lo)!==ZodParsedType.object){const ju=this._getOrReturnCtx(lo);return addIssueToContext(ju,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ju.parsedType}),INVALID}const{status:Ru,ctx:Iu}=this._processInputParams(lo),{shape:Ou,keys:Pu}=this._getCached(),Du=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const ju in Iu.data)Pu.includes(ju)||Du.push(ju);const Lu=[];for(const ju of Pu){const Bu=Ou[ju],Fu=Iu.data[ju];Lu.push({key:{status:"valid",value:ju},value:Bu._parse(new ParseInputLazyPath(Iu,Fu,Iu.path,ju)),alwaysSet:ju in Iu.data})}if(this._def.catchall instanceof ZodNever){const ju=this._def.unknownKeys;if(ju==="passthrough")for(const Bu of Du)Lu.push({key:{status:"valid",value:Bu},value:{status:"valid",value:Iu.data[Bu]}});else if(ju==="strict")Du.length>0&&(addIssueToContext(Iu,{code:ZodIssueCode.unrecognized_keys,keys:Du}),Ru.dirty());else if(ju!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const ju=this._def.catchall;for(const Bu of Du){const Fu=Iu.data[Bu];Lu.push({key:{status:"valid",value:Bu},value:ju._parse(new ParseInputLazyPath(Iu,Fu,Iu.path,Bu)),alwaysSet:Bu in Iu.data})}}return Iu.common.async?Promise.resolve().then(async()=>{const ju=[];for(const Bu of Lu){const Fu=await Bu.key,zu=await Bu.value;ju.push({key:Fu,value:zu,alwaysSet:Bu.alwaysSet})}return ju}).then(ju=>ParseStatus.mergeObjectSync(Ru,ju)):ParseStatus.mergeObjectSync(Ru,Lu)}get shape(){return this._def.shape()}strict(lo){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...lo!==void 0?{errorMap:($u,Ru)=>{const Iu=this._def.errorMap?.($u,Ru).message??Ru.defaultError;return $u.code==="unrecognized_keys"?{message:errorUtil.errToObj(lo).message??Iu}:{message:Iu}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(lo){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...lo})})}merge(lo){return new ZodObject({unknownKeys:lo._def.unknownKeys,catchall:lo._def.catchall,shape:()=>({...this._def.shape(),...lo._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(lo,$u){return this.augment({[lo]:$u})}catchall(lo){return new ZodObject({...this._def,catchall:lo})}pick(lo){const $u={};for(const Ru of util.objectKeys(lo))lo[Ru]&&this.shape[Ru]&&($u[Ru]=this.shape[Ru]);return new ZodObject({...this._def,shape:()=>$u})}omit(lo){const $u={};for(const Ru of util.objectKeys(this.shape))lo[Ru]||($u[Ru]=this.shape[Ru]);return new ZodObject({...this._def,shape:()=>$u})}deepPartial(){return deepPartialify(this)}partial(lo){const $u={};for(const Ru of util.objectKeys(this.shape)){const Iu=this.shape[Ru];lo&&!lo[Ru]?$u[Ru]=Iu:$u[Ru]=Iu.optional()}return new ZodObject({...this._def,shape:()=>$u})}required(lo){const $u={};for(const Ru of util.objectKeys(this.shape))if(lo&&!lo[Ru])$u[Ru]=this.shape[Ru];else{let Ou=this.shape[Ru];for(;Ou instanceof ZodOptional;)Ou=Ou._def.innerType;$u[Ru]=Ou}return new ZodObject({...this._def,shape:()=>$u})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(Au,lo)=>new ZodObject({shape:()=>Au,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(lo)});ZodObject.strictCreate=(Au,lo)=>new ZodObject({shape:()=>Au,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(lo)});ZodObject.lazycreate=(Au,lo)=>new ZodObject({shape:Au,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(lo)});class ZodUnion extends ZodType{_parse(lo){const{ctx:$u}=this._processInputParams(lo),Ru=this._def.options;function Iu(Ou){for(const Du of Ou)if(Du.result.status==="valid")return Du.result;for(const Du of Ou)if(Du.result.status==="dirty")return $u.common.issues.push(...Du.ctx.common.issues),Du.result;const Pu=Ou.map(Du=>new ZodError(Du.ctx.common.issues));return addIssueToContext($u,{code:ZodIssueCode.invalid_union,unionErrors:Pu}),INVALID}if($u.common.async)return Promise.all(Ru.map(async Ou=>{const Pu={...$u,common:{...$u.common,issues:[]},parent:null};return{result:await Ou._parseAsync({data:$u.data,path:$u.path,parent:Pu}),ctx:Pu}})).then(Iu);{let Ou;const Pu=[];for(const Lu of Ru){const ju={...$u,common:{...$u.common,issues:[]},parent:null},Bu=Lu._parseSync({data:$u.data,path:$u.path,parent:ju});if(Bu.status==="valid")return Bu;Bu.status==="dirty"&&!Ou&&(Ou={result:Bu,ctx:ju}),ju.common.issues.length&&Pu.push(ju.common.issues)}if(Ou)return $u.common.issues.push(...Ou.ctx.common.issues),Ou.result;const Du=Pu.map(Lu=>new ZodError(Lu));return addIssueToContext($u,{code:ZodIssueCode.invalid_union,unionErrors:Du}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(Au,lo)=>new ZodUnion({options:Au,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(lo)});function mergeValues(Au,lo){const $u=getParsedType(Au),Ru=getParsedType(lo);if(Au===lo)return{valid:!0,data:Au};if($u===ZodParsedType.object&&Ru===ZodParsedType.object){const Iu=util.objectKeys(lo),Ou=util.objectKeys(Au).filter(Du=>Iu.indexOf(Du)!==-1),Pu={...Au,...lo};for(const Du of Ou){const Lu=mergeValues(Au[Du],lo[Du]);if(!Lu.valid)return{valid:!1};Pu[Du]=Lu.data}return{valid:!0,data:Pu}}else if($u===ZodParsedType.array&&Ru===ZodParsedType.array){if(Au.length!==lo.length)return{valid:!1};const Iu=[];for(let Ou=0;Ou<Au.length;Ou++){const Pu=Au[Ou],Du=lo[Ou],Lu=mergeValues(Pu,Du);if(!Lu.valid)return{valid:!1};Iu.push(Lu.data)}return{valid:!0,data:Iu}}else return $u===ZodParsedType.date&&Ru===ZodParsedType.date&&+Au==+lo?{valid:!0,data:Au}:{valid:!1}}class ZodIntersection extends ZodType{_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo),Iu=(Ou,Pu)=>{if(isAborted(Ou)||isAborted(Pu))return INVALID;const Du=mergeValues(Ou.value,Pu.value);return Du.valid?((isDirty(Ou)||isDirty(Pu))&&$u.dirty(),{status:$u.value,value:Du.data}):(addIssueToContext(Ru,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return Ru.common.async?Promise.all([this._def.left._parseAsync({data:Ru.data,path:Ru.path,parent:Ru}),this._def.right._parseAsync({data:Ru.data,path:Ru.path,parent:Ru})]).then(([Ou,Pu])=>Iu(Ou,Pu)):Iu(this._def.left._parseSync({data:Ru.data,path:Ru.path,parent:Ru}),this._def.right._parseSync({data:Ru.data,path:Ru.path,parent:Ru}))}}ZodIntersection.create=(Au,lo,$u)=>new ZodIntersection({left:Au,right:lo,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams($u)});class ZodTuple extends ZodType{_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo);if(Ru.parsedType!==ZodParsedType.array)return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:Ru.parsedType}),INVALID;if(Ru.data.length<this._def.items.length)return addIssueToContext(Ru,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&Ru.data.length>this._def.items.length&&(addIssueToContext(Ru,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),$u.dirty());const Ou=[...Ru.data].map((Pu,Du)=>{const Lu=this._def.items[Du]||this._def.rest;return Lu?Lu._parse(new ParseInputLazyPath(Ru,Pu,Ru.path,Du)):null}).filter(Pu=>!!Pu);return Ru.common.async?Promise.all(Ou).then(Pu=>ParseStatus.mergeArray($u,Pu)):ParseStatus.mergeArray($u,Ou)}get items(){return this._def.items}rest(lo){return new ZodTuple({...this._def,rest:lo})}}ZodTuple.create=(Au,lo)=>{if(!Array.isArray(Au))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:Au,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(lo)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo);if(Ru.parsedType!==ZodParsedType.object)return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:Ru.parsedType}),INVALID;const Iu=[],Ou=this._def.keyType,Pu=this._def.valueType;for(const Du in Ru.data)Iu.push({key:Ou._parse(new ParseInputLazyPath(Ru,Du,Ru.path,Du)),value:Pu._parse(new ParseInputLazyPath(Ru,Ru.data[Du],Ru.path,Du)),alwaysSet:Du in Ru.data});return Ru.common.async?ParseStatus.mergeObjectAsync($u,Iu):ParseStatus.mergeObjectSync($u,Iu)}get element(){return this._def.valueType}static create(lo,$u,Ru){return $u instanceof ZodType?new ZodRecord({keyType:lo,valueType:$u,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(Ru)}):new ZodRecord({keyType:ZodString.create(),valueType:lo,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams($u)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo);if(Ru.parsedType!==ZodParsedType.map)return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:Ru.parsedType}),INVALID;const Iu=this._def.keyType,Ou=this._def.valueType,Pu=[...Ru.data.entries()].map(([Du,Lu],ju)=>({key:Iu._parse(new ParseInputLazyPath(Ru,Du,Ru.path,[ju,"key"])),value:Ou._parse(new ParseInputLazyPath(Ru,Lu,Ru.path,[ju,"value"]))}));if(Ru.common.async){const Du=new Map;return Promise.resolve().then(async()=>{for(const Lu of Pu){const ju=await Lu.key,Bu=await Lu.value;if(ju.status==="aborted"||Bu.status==="aborted")return INVALID;(ju.status==="dirty"||Bu.status==="dirty")&&$u.dirty(),Du.set(ju.value,Bu.value)}return{status:$u.value,value:Du}})}else{const Du=new Map;for(const Lu of Pu){const ju=Lu.key,Bu=Lu.value;if(ju.status==="aborted"||Bu.status==="aborted")return INVALID;(ju.status==="dirty"||Bu.status==="dirty")&&$u.dirty(),Du.set(ju.value,Bu.value)}return{status:$u.value,value:Du}}}}ZodMap.create=(Au,lo,$u)=>new ZodMap({valueType:lo,keyType:Au,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams($u)});class ZodSet extends ZodType{_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo);if(Ru.parsedType!==ZodParsedType.set)return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:Ru.parsedType}),INVALID;const Iu=this._def;Iu.minSize!==null&&Ru.data.size<Iu.minSize.value&&(addIssueToContext(Ru,{code:ZodIssueCode.too_small,minimum:Iu.minSize.value,type:"set",inclusive:!0,exact:!1,message:Iu.minSize.message}),$u.dirty()),Iu.maxSize!==null&&Ru.data.size>Iu.maxSize.value&&(addIssueToContext(Ru,{code:ZodIssueCode.too_big,maximum:Iu.maxSize.value,type:"set",inclusive:!0,exact:!1,message:Iu.maxSize.message}),$u.dirty());const Ou=this._def.valueType;function Pu(Lu){const ju=new Set;for(const Bu of Lu){if(Bu.status==="aborted")return INVALID;Bu.status==="dirty"&&$u.dirty(),ju.add(Bu.value)}return{status:$u.value,value:ju}}const Du=[...Ru.data.values()].map((Lu,ju)=>Ou._parse(new ParseInputLazyPath(Ru,Lu,Ru.path,ju)));return Ru.common.async?Promise.all(Du).then(Lu=>Pu(Lu)):Pu(Du)}min(lo,$u){return new ZodSet({...this._def,minSize:{value:lo,message:errorUtil.toString($u)}})}max(lo,$u){return new ZodSet({...this._def,maxSize:{value:lo,message:errorUtil.toString($u)}})}size(lo,$u){return this.min(lo,$u).max(lo,$u)}nonempty(lo){return this.min(1,lo)}}ZodSet.create=(Au,lo)=>new ZodSet({valueType:Au,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(lo)});class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(lo){const{ctx:$u}=this._processInputParams(lo);return this._def.getter()._parse({data:$u.data,path:$u.path,parent:$u})}}ZodLazy.create=(Au,lo)=>new ZodLazy({getter:Au,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(lo)});class ZodLiteral extends ZodType{_parse(lo){if(lo.data!==this._def.value){const $u=this._getOrReturnCtx(lo);return addIssueToContext($u,{received:$u.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:lo.data}}get value(){return this._def.value}}ZodLiteral.create=(Au,lo)=>new ZodLiteral({value:Au,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(lo)});function createZodEnum(Au,lo){return new ZodEnum({values:Au,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(lo)})}class ZodEnum extends ZodType{_parse(lo){if(typeof lo.data!="string"){const $u=this._getOrReturnCtx(lo),Ru=this._def.values;return addIssueToContext($u,{expected:util.joinValues(Ru),received:$u.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(lo.data)){const $u=this._getOrReturnCtx(lo),Ru=this._def.values;return addIssueToContext($u,{received:$u.data,code:ZodIssueCode.invalid_enum_value,options:Ru}),INVALID}return OK(lo.data)}get options(){return this._def.values}get enum(){const lo={};for(const $u of this._def.values)lo[$u]=$u;return lo}get Values(){const lo={};for(const $u of this._def.values)lo[$u]=$u;return lo}get Enum(){const lo={};for(const $u of this._def.values)lo[$u]=$u;return lo}extract(lo,$u=this._def){return ZodEnum.create(lo,{...this._def,...$u})}exclude(lo,$u=this._def){return ZodEnum.create(this.options.filter(Ru=>!lo.includes(Ru)),{...this._def,...$u})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(lo){const $u=util.getValidEnumValues(this._def.values),Ru=this._getOrReturnCtx(lo);if(Ru.parsedType!==ZodParsedType.string&&Ru.parsedType!==ZodParsedType.number){const Iu=util.objectValues($u);return addIssueToContext(Ru,{expected:util.joinValues(Iu),received:Ru.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(lo.data)){const Iu=util.objectValues($u);return addIssueToContext(Ru,{received:Ru.data,code:ZodIssueCode.invalid_enum_value,options:Iu}),INVALID}return OK(lo.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(Au,lo)=>new ZodNativeEnum({values:Au,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(lo)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(lo){const{ctx:$u}=this._processInputParams(lo);if($u.parsedType!==ZodParsedType.promise&&$u.common.async===!1)return addIssueToContext($u,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:$u.parsedType}),INVALID;const Ru=$u.parsedType===ZodParsedType.promise?$u.data:Promise.resolve($u.data);return OK(Ru.then(Iu=>this._def.type.parseAsync(Iu,{path:$u.path,errorMap:$u.common.contextualErrorMap})))}}ZodPromise.create=(Au,lo)=>new ZodPromise({type:Au,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(lo)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo),Iu=this._def.effect||null,Ou={addIssue:Pu=>{addIssueToContext(Ru,Pu),Pu.fatal?$u.abort():$u.dirty()},get path(){return Ru.path}};if(Ou.addIssue=Ou.addIssue.bind(Ou),Iu.type==="preprocess"){const Pu=Iu.transform(Ru.data,Ou);if(Ru.common.async)return Promise.resolve(Pu).then(async Du=>{if($u.value==="aborted")return INVALID;const Lu=await this._def.schema._parseAsync({data:Du,path:Ru.path,parent:Ru});return Lu.status==="aborted"?INVALID:Lu.status==="dirty"||$u.value==="dirty"?DIRTY(Lu.value):Lu});{if($u.value==="aborted")return INVALID;const Du=this._def.schema._parseSync({data:Pu,path:Ru.path,parent:Ru});return Du.status==="aborted"?INVALID:Du.status==="dirty"||$u.value==="dirty"?DIRTY(Du.value):Du}}if(Iu.type==="refinement"){const Pu=Du=>{const Lu=Iu.refinement(Du,Ou);if(Ru.common.async)return Promise.resolve(Lu);if(Lu instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return Du};if(Ru.common.async===!1){const Du=this._def.schema._parseSync({data:Ru.data,path:Ru.path,parent:Ru});return Du.status==="aborted"?INVALID:(Du.status==="dirty"&&$u.dirty(),Pu(Du.value),{status:$u.value,value:Du.value})}else return this._def.schema._parseAsync({data:Ru.data,path:Ru.path,parent:Ru}).then(Du=>Du.status==="aborted"?INVALID:(Du.status==="dirty"&&$u.dirty(),Pu(Du.value).then(()=>({status:$u.value,value:Du.value}))))}if(Iu.type==="transform")if(Ru.common.async===!1){const Pu=this._def.schema._parseSync({data:Ru.data,path:Ru.path,parent:Ru});if(!isValid(Pu))return INVALID;const Du=Iu.transform(Pu.value,Ou);if(Du instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:$u.value,value:Du}}else return this._def.schema._parseAsync({data:Ru.data,path:Ru.path,parent:Ru}).then(Pu=>isValid(Pu)?Promise.resolve(Iu.transform(Pu.value,Ou)).then(Du=>({status:$u.value,value:Du})):INVALID);util.assertNever(Iu)}}ZodEffects.create=(Au,lo,$u)=>new ZodEffects({schema:Au,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:lo,...processCreateParams($u)});ZodEffects.createWithPreprocess=(Au,lo,$u)=>new ZodEffects({schema:lo,effect:{type:"preprocess",transform:Au},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams($u)});class ZodOptional extends ZodType{_parse(lo){return this._getType(lo)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(lo)}unwrap(){return this._def.innerType}}ZodOptional.create=(Au,lo)=>new ZodOptional({innerType:Au,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(lo)});class ZodNullable extends ZodType{_parse(lo){return this._getType(lo)===ZodParsedType.null?OK(null):this._def.innerType._parse(lo)}unwrap(){return this._def.innerType}}ZodNullable.create=(Au,lo)=>new ZodNullable({innerType:Au,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(lo)});class ZodDefault extends ZodType{_parse(lo){const{ctx:$u}=this._processInputParams(lo);let Ru=$u.data;return $u.parsedType===ZodParsedType.undefined&&(Ru=this._def.defaultValue()),this._def.innerType._parse({data:Ru,path:$u.path,parent:$u})}removeDefault(){return this._def.innerType}}ZodDefault.create=(Au,lo)=>new ZodDefault({innerType:Au,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof lo.default=="function"?lo.default:()=>lo.default,...processCreateParams(lo)});class ZodCatch extends ZodType{_parse(lo){const{ctx:$u}=this._processInputParams(lo),Ru={...$u,common:{...$u.common,issues:[]}},Iu=this._def.innerType._parse({data:Ru.data,path:Ru.path,parent:{...Ru}});return isAsync(Iu)?Iu.then(Ou=>({status:"valid",value:Ou.status==="valid"?Ou.value:this._def.catchValue({get error(){return new ZodError(Ru.common.issues)},input:Ru.data})})):{status:"valid",value:Iu.status==="valid"?Iu.value:this._def.catchValue({get error(){return new ZodError(Ru.common.issues)},input:Ru.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(Au,lo)=>new ZodCatch({innerType:Au,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof lo.catch=="function"?lo.catch:()=>lo.catch,...processCreateParams(lo)});class ZodNaN extends ZodType{_parse(lo){if(this._getType(lo)!==ZodParsedType.nan){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:Ru.parsedType}),INVALID}return{status:"valid",value:lo.data}}}ZodNaN.create=Au=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(Au)});class ZodBranded extends ZodType{_parse(lo){const{ctx:$u}=this._processInputParams(lo),Ru=$u.data;return this._def.type._parse({data:Ru,path:$u.path,parent:$u})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo);if(Ru.common.async)return(async()=>{const Ou=await this._def.in._parseAsync({data:Ru.data,path:Ru.path,parent:Ru});return Ou.status==="aborted"?INVALID:Ou.status==="dirty"?($u.dirty(),DIRTY(Ou.value)):this._def.out._parseAsync({data:Ou.value,path:Ru.path,parent:Ru})})();{const Iu=this._def.in._parseSync({data:Ru.data,path:Ru.path,parent:Ru});return Iu.status==="aborted"?INVALID:Iu.status==="dirty"?($u.dirty(),{status:"dirty",value:Iu.value}):this._def.out._parseSync({data:Iu.value,path:Ru.path,parent:Ru})}}static create(lo,$u){return new ZodPipeline({in:lo,out:$u,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(lo){const $u=this._def.innerType._parse(lo),Ru=Iu=>(isValid(Iu)&&(Iu.value=Object.freeze(Iu.value)),Iu);return isAsync($u)?$u.then(Iu=>Ru(Iu)):Ru($u)}unwrap(){return this._def.innerType}}ZodReadonly.create=(Au,lo)=>new ZodReadonly({innerType:Au,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(lo)});var ZodFirstPartyTypeKind;(function(Au){Au.ZodString="ZodString",Au.ZodNumber="ZodNumber",Au.ZodNaN="ZodNaN",Au.ZodBigInt="ZodBigInt",Au.ZodBoolean="ZodBoolean",Au.ZodDate="ZodDate",Au.ZodSymbol="ZodSymbol",Au.ZodUndefined="ZodUndefined",Au.ZodNull="ZodNull",Au.ZodAny="ZodAny",Au.ZodUnknown="ZodUnknown",Au.ZodNever="ZodNever",Au.ZodVoid="ZodVoid",Au.ZodArray="ZodArray",Au.ZodObject="ZodObject",Au.ZodUnion="ZodUnion",Au.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Au.ZodIntersection="ZodIntersection",Au.ZodTuple="ZodTuple",Au.ZodRecord="ZodRecord",Au.ZodMap="ZodMap",Au.ZodSet="ZodSet",Au.ZodFunction="ZodFunction",Au.ZodLazy="ZodLazy",Au.ZodLiteral="ZodLiteral",Au.ZodEnum="ZodEnum",Au.ZodEffects="ZodEffects",Au.ZodNativeEnum="ZodNativeEnum",Au.ZodOptional="ZodOptional",Au.ZodNullable="ZodNullable",Au.ZodDefault="ZodDefault",Au.ZodCatch="ZodCatch",Au.ZodPromise="ZodPromise",Au.ZodBranded="ZodBranded",Au.ZodPipeline="ZodPipeline",Au.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,numberType=ZodNumber.create;ZodBigInt.create;const booleanType=ZodBoolean.create;ZodDate.create;const anyType=ZodAny.create,unknownType=ZodUnknown.create;ZodNever.create;const arrayType=ZodArray.create,objectType=ZodObject.create,unionType=ZodUnion.create,intersectionType=ZodIntersection.create;ZodTuple.create;const recordType=ZodRecord.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create;ZodPromise.create;ZodOptional.create;ZodNullable.create;const coerce={string:(Au=>ZodString.create({...Au,coerce:!0})),number:(Au=>ZodNumber.create({...Au,coerce:!0})),boolean:(Au=>ZodBoolean.create({...Au,coerce:!0})),bigint:(Au=>ZodBigInt.create({...Au,coerce:!0})),date:(Au=>ZodDate.create({...Au,coerce:!0}))};class A2uiError extends Error{constructor(lo,$u="UNKNOWN_ERROR"){super(lo),this.name=this.constructor.name,this.code=$u,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}class A2uiValidationError extends A2uiError{constructor(lo,$u,Ru="VALIDATION_ERROR"){super(lo,Ru),this.details=$u}}class A2uiDataError extends A2uiError{constructor(lo,$u){super(lo,"DATA_ERROR"),this.path=$u}}class A2uiExpressionError extends A2uiError{constructor(lo,$u,Ru){super(lo,"EXPRESSION_ERROR"),this.expression=$u,this.details=Ru}}class A2uiStateError extends A2uiError{constructor(lo){super(lo,"STATE_ERROR")}}class A2uiCatalogError extends A2uiError{constructor(lo,$u="CATALOG_ERROR"){super(lo,$u)}}class A2uiIntegrityError extends A2uiValidationError{constructor(lo,$u,Ru="INTEGRITY_ERROR"){super(lo,$u,Ru),this.name="A2uiIntegrityError"}}class A2uiRecursionError extends A2uiValidationError{constructor(lo,$u,Ru="RECURSION_ERROR"){super(lo,$u,Ru),this.name="A2uiRecursionError"}}var RpcErrorCode;(function(Au){Au.INVALID_FUNCTION_CALL="INVALID_FUNCTION_CALL",Au.EXECUTION_ERROR="EXECUTION_ERROR",Au.UNKNOWN_FUNCTION="UNKNOWN_FUNCTION",Au.UNKNOWN_ERROR="UNKNOWN_ERROR",Au.TIMEOUT="TIMEOUT",Au.CANCELLED="CANCELLED",Au.DISPOSED="DISPOSED",Au.DUPLICATE="DUPLICATE",Au.NO_LISTENER="NO_LISTENER"})(RpcErrorCode||(RpcErrorCode={}));class A2uiRpcError extends A2uiError{constructor(lo,$u=RpcErrorCode.UNKNOWN_ERROR,Ru,Iu){const Ou=$u||RpcErrorCode.UNKNOWN_ERROR;super(`[${Ou}] ${lo}`,Ou),this.functionCallId=Ru,this.details=Iu,this.name="A2uiRpcError"}}function markChildRef(Au,lo){return Au._def.a2uiChildRef=lo,Au}function childRefKindOf(Au){return Au?._def?.a2uiChildRef}const MAX_FUNCTION_CALL_ARGS=1e3;objectType({component:stringType().describe("The type name of the component."),id:lazyType(()=>ComponentIdSchema$2).optional(),weight:numberType().optional()}).passthrough().describe("A generic A2UI component definition.");const ComponentIdSchema$2=markChildRef(stringType().describe("REF:common_types.json#/$defs/ComponentId|The unique identifier for a component, used for both definitions and references within the same surface."),"component-id"),DataBindingSchema$2=objectType({path:stringType().describe("A JSON Pointer path to a value in the data model.")}).describe("REF:common_types.json#/$defs/DataBinding"),FunctionCallSchema$2=objectType({call:stringType().describe("The name of the function to call."),args:recordType(stringType(),unknownType()).describe("Arguments passed to the function.").optional(),returnType:enumType(["string","number","boolean","array","object","any","void"]).describe("The expected return type of the function call.").optional(),catalogId:stringType().describe("The catalog ID for this function, overriding any surface-level default catalogId.").optional()}).describe("REF:common_types.json#/$defs/FunctionCall|Invokes a named function, combining common function properties with the catalog function definition."),DynamicStringSchema$2=unionType([stringType(),DataBindingSchema$2,FunctionCallSchema$2]).describe("REF:common_types.json#/$defs/DynamicString|Represents a string"),DynamicBooleanSchema$2=unionType([booleanType(),DataBindingSchema$2,FunctionCallSchema$2]).describe("REF:common_types.json#/$defs/DynamicBoolean|A boolean value that can be a literal, a path, or a function call returning a boolean."),AccessibilityAttributesSchema$2=objectType({label:DynamicStringSchema$2.optional(),description:DynamicStringSchema$2.optional(),live:enumType(["off","polite","assertive"]).default("off").describe("Controls screen reader announcements for dynamic updates (WAI-ARIA aria-live). 'polite' waits for user pause; 'assertive' interrupts immediately for alerts.").optional(),hidden:DynamicBooleanSchema$2.optional()}).describe("REF:common_types.json#/$defs/AccessibilityAttributes|Attributes to enhance accessibility when using assistive technologies like screen readers or model understanding."),ExtensionsSchema$1=recordType(stringType(),unknownType()).superRefine((Au,lo)=>{for(const $u in Au)$u.match(/^[\p{XID_Start}_][\p{XID_Continue}]*$/u)||lo.addIssue({path:[$u],code:ZodIssueCode.custom,message:`Invalid extension key "${$u}": Keys MUST be Unicode identifiers (UAX #31).`})}).describe("REF:#/$defs/Extensions|Optional extension metadata. Keys MUST be Unicode identifiers (UAX #31). Keys starting with 'a2ui_' are reserved for official extensions.");objectType({id:ComponentIdSchema$2,accessibility:AccessibilityAttributesSchema$2.optional(),catalogId:stringType().describe("The catalog ID for this component, overriding any surface-level default catalogId.").optional(),metadata:objectType({extensions:ExtensionsSchema$1.optional()}).strict().describe("Optional component-level metadata for vendor extensions.").optional()}).describe("REF:common_types.json#/$defs/ComponentCommon");const ChildListSchema$1=markChildRef(unionType([arrayType(ComponentIdSchema$2).describe("A static list of child component IDs."),objectType({componentId:ComponentIdSchema$2,path:stringType().describe("The path to the list of component property objects in the data model.")}).describe("A template for generating a dynamic list of children.")]).describe("REF:common_types.json#/$defs/ChildList"),"child-list"),DynamicValueSchema$2=unionType([stringType(),numberType(),booleanType(),arrayType(unknownType()),DataBindingSchema$2,FunctionCallSchema$2,recordType(stringType(),unknownType()).refine(Au=>!Au||!("path"in Au)&&!("call"in Au))]).describe("REF:common_types.json#/$defs/DynamicValue|A value that can be a literal, a path, or a function call returning any type."),DynamicNumberSchema$2=unionType([numberType(),DataBindingSchema$2,FunctionCallSchema$2]).describe("REF:common_types.json#/$defs/DynamicNumber|Represents a value that can be either a literal number, a path to a number in the data model, or a function call returning a number."),DynamicStringListSchema$1=unionType([arrayType(stringType()),DataBindingSchema$2,FunctionCallSchema$2]).describe("REF:common_types.json#/$defs/DynamicStringList|Represents a value that can be either a literal array of strings, a path to a string array in the data model, or a function call returning a string array."),CheckRuleSchema$2=objectType({condition:unionType([DynamicBooleanSchema$2,DataBindingSchema$2,FunctionCallSchema$2]).describe("Path or function call evaluating to a structured validation result object."),message:stringType().describe("Optional fallback error message.").optional()}).describe("REF:common_types.json#/$defs/CheckRule|A single validation check rule applied to an input component. The condition function or path evaluates to a structured validation result object."),CheckableSchema=objectType({checks:arrayType(CheckRuleSchema$2).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional()}).describe("REF:common_types.json#/$defs/Checkable|Properties for components that support renderer-side checks."),ActionSchema$2=unionType([objectType({event:objectType({name:stringType().describe("The name of the action to be dispatched to the server."),context:recordType(stringType(),unknownType()).describe("A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.").optional()}).strict().describe("The event to dispatch to the server.")}).strict().describe("Triggers a server-side event."),objectType({functionCall:FunctionCallSchema$2}).strict().describe("Executes a local client-side function."),objectType({event:objectType({name:stringType().describe("The name of the action to be dispatched to the agent."),userMessage:DynamicStringSchema$2.optional(),context:recordType(stringType(),unknownType()).describe("A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.").optional()}).strict().describe("The event to dispatch to the agent.")}).strict().describe("Triggers an agent-side event."),objectType({functionCall:FunctionCallSchema$2}).strict().describe("Executes a renderer or agent-side function.")]).describe("REF:common_types.json#/$defs/Action|Defines an interaction handler that can either trigger an agent-side event or execute a local renderer-side function."),CallIdSchema$1=stringType().describe("REF:common_types.json#/$defs/CallId|The unique identifier for a function call.");objectType({call:stringType().describe("The name of the function to call."),catalogId:stringType().describe("The catalog ID for this function, overriding any surface-level default catalogId.").optional()}).describe("REF:common_types.json#/$defs/FunctionCommon|Baseline envelope properties common to all function calls. Function-specific argument schemas (\\'args\\') are defined individually by each function in the active catalog.");objectType({call:literalType("@index"),args:objectType({offset:DynamicNumberSchema$2.optional()}).strict().optional()}).strict().describe("REF:common_types.json#/$defs/IndexSystemFunction|Returns the 0-based index of the current item when rendering a dynamic list from a template. This function MUST ONLY be available when evaluating template items within a list context.");objectType({component:literalType("Surface").optional(),child:literalType("root").optional()}).strict().describe("REF:common_types.json#/$defs/Surface|The reserved canonical container component representing an A2UI surface. The Surface component is immutable and always has \\'child\\': \\'root\\'.");objectType({functionCallId:CallIdSchema$1,value:unknownType().describe("The return value of the function.").optional(),error:objectType({code:stringType(),message:stringType()}).strict().describe("An error object indicating failure of the function execution.").optional()}).strict().describe("REF:common_types.json#/$defs/FunctionResponse|The return response matching a callAgentFunction or callRendererFunction invocation.");const SEMVER_REGEX=/^[vV]?(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*))?(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;function normalizeVersionString(Au){if(!Au||typeof Au!="string")return"";const lo=Au.trim().replace(/^[vV]/,""),$u=lo.indexOf("-"),Ru=lo.indexOf("+");let Iu=lo.length;return $u!==-1&&Ru!==-1?Iu=Math.min($u,Ru):$u!==-1?Iu=$u:Ru!==-1&&(Iu=Ru),`${lo.slice(0,Iu).replace(/_/g,".")}${lo.slice(Iu)}`}function parseSemVer(Au){if(!Au||typeof Au!="string")return null;const lo=Au.trim().match(SEMVER_REGEX);return lo?{major:parseInt(lo[1],10),minor:parseInt(lo[2],10),patch:lo[3]!==void 0?parseInt(lo[3],10):0,prerelease:lo[4]?lo[4].split("."):[],build:lo[5]?lo[5].split("."):[]}:null}function toSemVer(Au){if(!Au)return null;if(typeof Au=="object"){const lo=Au;return typeof lo.major!="number"||!Number.isInteger(lo.major)||lo.major<0||typeof lo.minor=="number"&&(!Number.isInteger(lo.minor)||lo.minor<0)||typeof lo.patch=="number"&&(!Number.isInteger(lo.patch)||lo.patch<0)?null:{major:lo.major,minor:typeof lo.minor=="number"?lo.minor:0,patch:typeof lo.patch=="number"?lo.patch:0,prerelease:Array.isArray(lo.prerelease)?lo.prerelease:[],build:Array.isArray(lo.build)?lo.build:[]}}return parseSemVer(normalizeVersionString(Au))}function toCanonicalVersion(Au){if(!Au)return null;const lo=toSemVer(Au);if(!lo)return null;if(lo.patch===0&&lo.prerelease.length===0&&lo.build.length===0)return`${lo.major}.${lo.minor}`;const $u=lo.prerelease.length>0?`-${lo.prerelease.join(".")}`:"",Ru=lo.build.length>0?`+${lo.build.join(".")}`:"";return`${lo.major}.${lo.minor}.${lo.patch}${$u}${Ru}`}function comparePrereleaseId(Au,lo){const $u=/^\d+$/.test(Au),Ru=/^\d+$/.test(lo);return $u&&Ru?Au.length!==lo.length?Au.length-lo.length:Au<lo?-1:Au>lo?1:0:$u?-1:Ru?1:Au<lo?-1:Au>lo?1:0}function comparePrereleaseLists(Au,lo){if(Au.length===0&&lo.length===0)return 0;if(Au.length===0)return 1;if(lo.length===0)return-1;const $u=Math.min(Au.length,lo.length);for(let Ru=0;Ru<$u;Ru++){const Iu=comparePrereleaseId(Au[Ru],lo[Ru]);if(Iu!==0)return Iu}return Au.length-lo.length}function compareSemVer(Au,lo){const $u=toSemVer(Au),Ru=toSemVer(lo);return!$u&&!Ru?0:$u?Ru?$u.major!==Ru.major?$u.major-Ru.major:$u.minor!==Ru.minor?$u.minor-Ru.minor:$u.patch!==Ru.patch?$u.patch-Ru.patch:comparePrereleaseLists($u.prerelease,Ru.prerelease):1:-1}function isAtLeastVersion(Au,lo){if(!Au)return!1;const $u=toSemVer(Au),Ru=toSemVer(lo);return!$u||!Ru?!1:compareSemVer($u,Ru)>=0}const UAX31_IDENTIFIER=/^[\p{XID_Start}_][\p{XID_Continue}]*$/u;function isValidUax31Identifier(Au){if(!Au)return!1;const lo=Au.startsWith("@")?Au.slice(1):Au;return UAX31_IDENTIFIER.test(lo)}function assertUax31Identifier(Au,lo){if(!isValidUax31Identifier(Au))throw new A2uiCatalogError(`Invalid UAX #31 ${lo}`)}const DEFAULT_PROTOCOL_VERSION="0.9",COMMON_TYPE_SCHEMAS={DynamicString:DynamicStringSchema$2,DynamicNumber:DynamicNumberSchema$2,DynamicBoolean:DynamicBooleanSchema$2,DynamicStringList:DynamicStringListSchema$1,DynamicValue:DynamicValueSchema$2,ComponentId:ComponentIdSchema$2,ChildList:ChildListSchema$1,Action:ActionSchema$2,CheckRule:CheckRuleSchema$2,Checkable:CheckableSchema,AccessibilityAttributes:AccessibilityAttributesSchema$2,DataBinding:DataBindingSchema$2,FunctionCall:FunctionCallSchema$2};function resolveJsonPointer(Au,lo){if(!lo.startsWith("#/"))return;const $u=lo.slice(2).split("/").map(Iu=>Iu.replace(/~1/g,"/").replace(/~0/g,"~"));let Ru=Au;for(const Iu of $u)if(Ru&&typeof Ru=="object"&&Iu in Ru)Ru=Ru[Iu];else return;return typeof Ru=="object"&&Ru!==null?Ru:void 0}function resolveProtocolRef(Au){const lo=Au.split(/#\/(?:\$defs|definitions)\//)[1];return lo?COMMON_TYPE_SCHEMAS[lo]:void 0}function convertEnumToZod(Au){return Au.length===0?unknownType():Au.every(lo=>typeof lo=="string")?enumType(Au):Au.length===1?literalType(Au[0]):unionType(Au.map(lo=>literalType(lo)))}function canonicalJsonStringify(Au){return Au===null||typeof Au!="object"?JSON.stringify(Au):Array.isArray(Au)?`[${Au.map(canonicalJsonStringify).join(",")}]`:`{${Object.keys(Au).sort().map(Ru=>`${JSON.stringify(Ru)}:${canonicalJsonStringify(Au[Ru])}`).join(",")}}`}function finalizePropertyZod(Au,lo,$u,Ru,Iu){let Ou=Au;if(lo.not&&typeof lo.not=="object"){const Pu=convertPropertyToZod(lo.not,$u,new Set(Ru),Iu);Ou=Ou.refine(Du=>!Pu.safeParse(Du).success,{message:'Value matched prohibited "not" schema'})}return lo.default!==void 0&&(Ou=Ou.default(lo.default)),typeof lo.description=="string"&&(Ou=Ou.describe(lo.description)),Ou}function convertRefToZod(Au,lo,$u,Ru,Iu){const Ou=resolveProtocolRef(Au);if(Ou){const Pu=Au.split(/#\/(?:\$defs|definitions)\//)[1],Du=typeof lo.description=="string"?`REF:common_types.json#/$defs/${Pu}|${lo.description}`:Ou.description;return Du?Ou.describe(Du):Ou}if($u&&Au.startsWith("#/")){const Pu=resolveJsonPointer($u,Au);if(!Pu)return unknownType().superRefine((Lu,ju)=>{ju.addIssue({code:ZodIssueCode.custom,message:`Unresolvable schema reference: '${Au}'`})});if(Ru.has(Au)){let Lu=Iu.get(Au);return lazyType(()=>(Lu||(Lu=Iu.get(Au)??convertPropertyToZod(Pu,$u,new Set([Au]),Iu),Iu.set(Au,Lu)),Lu))}let Du=Iu.get(Au);if(!Du){const Lu=new Set(Ru);Lu.add(Au),Du=convertPropertyToZod(Pu,$u,Lu,Iu),Iu.set(Au,Du)}return typeof lo.description=="string"&&(Du=Du.describe(lo.description)),Du}}function convertUnionToZod(Au,lo,$u,Ru){const Iu=Array.isArray(Au.oneOf),Pu=(Au.oneOf||Au.anyOf).filter(zu=>typeof zu=="object"&&zu!==null);if(Pu.length===0)return;const Du=Pu.find(zu=>Array.isArray(zu.enum)),Lu=Pu.some(zu=>typeof zu.$ref=="string"&&zu.$ref.includes("DataBinding")),ju=Pu.map(zu=>convertPropertyToZod(zu,lo,new Set($u),Ru));let Bu;if(ju.length===1)Bu=ju[0];else{const zu=unionType([ju[0],ju[1],...ju.slice(2)]);Bu=Iu?anyType().superRefine((qu,Uu)=>{let Hu=0;for(const Vu of ju)if(Vu.safeParse(qu).success&&++Hu>1){Uu.addIssue({code:ZodIssueCode.custom,message:"Value matched more than one schema in oneOf"});return}}).pipe(zu):zu}Au.default!==void 0&&(Bu=Bu.default(Au.default));const Fu=(typeof Au.description=="string"?Au.description:void 0)||(Du&&Lu?"REF:common_types.json#/$defs/DynamicString":void 0);return Fu?Bu.describe(Fu):Bu}function convertPropertyToZod(Au,lo,$u=new Set,Ru=new Map){if(!Au||typeof Au!="object")return unknownType();if(Au.$ref&&typeof Au.$ref=="string"){const Iu=convertRefToZod(Au.$ref,Au,lo,$u,Ru);if(Iu)return Iu}if(Array.isArray(Au.oneOf)||Array.isArray(Au.anyOf)){const Iu=convertUnionToZod(Au,lo,$u,Ru);if(Iu)return Iu}if(Au.const!==void 0){const Iu=literalType(Au.const);return finalizePropertyZod(Iu,Au,lo,$u,Ru)}if(Array.isArray(Au.enum)&&Au.enum.length>0){const Iu=convertEnumToZod(Au.enum);return finalizePropertyZod(Iu,Au,lo,$u,Ru)}if(Au.type==="array"){const Iu=Au.items&&typeof Au.items=="object"?convertPropertyToZod(Au.items,lo,new Set($u),Ru):unknownType();let Ou=arrayType(Iu);return typeof Au.minItems=="number"&&(Ou=Ou.min(Au.minItems)),typeof Au.maxItems=="number"&&(Ou=Ou.max(Au.maxItems)),Au.uniqueItems===!0&&(Ou=Ou.refine(Pu=>new Set(Pu.map(canonicalJsonStringify)).size===Pu.length,{message:"Array items must be unique"})),finalizePropertyZod(Ou,Au,lo,$u,Ru)}switch(Au.type){case"string":{let Iu=stringType();if(typeof Au.minLength=="number"&&(Iu=Iu.min(Au.minLength)),typeof Au.maxLength=="number"&&(Iu=Iu.max(Au.maxLength)),typeof Au.pattern=="string")try{Iu=Iu.regex(new RegExp(Au.pattern,"u"))}catch{}return finalizePropertyZod(Iu,Au,lo,$u,Ru)}case"integer":case"number":{let Iu=Au.type==="integer"?numberType().int():numberType();return typeof Au.minimum=="number"&&(Iu=Iu.min(Au.minimum)),typeof Au.maximum=="number"&&(Iu=Iu.max(Au.maximum)),typeof Au.exclusiveMinimum=="number"&&(Iu=Iu.gt(Au.exclusiveMinimum)),typeof Au.exclusiveMaximum=="number"&&(Iu=Iu.lt(Au.exclusiveMaximum)),typeof Au.multipleOf=="number"&&(Iu=Iu.multipleOf(Au.multipleOf)),finalizePropertyZod(Iu,Au,lo,$u,Ru)}case"boolean":return finalizePropertyZod(booleanType(),Au,lo,$u,Ru);case"object":{const Iu=Au.properties;let Ou;if(typeof Iu=="object"&&Iu!==null){const Pu=Array.isArray(Au.required)?new Set(Au.required.filter(ju=>typeof ju=="string")):new Set,Du=objectType(convertPropertiesToShape(Iu,Pu,!1,lo,$u,Ru));Ou=Au.additionalProperties===!1||Au.unevaluatedProperties===!1?Du.strict():Du.passthrough()}else Ou=recordType(unknownType());return finalizePropertyZod(Ou,Au,lo,$u,Ru)}default:return finalizePropertyZod(unknownType(),Au,lo,$u,Ru)}}function convertPropertiesToShape(Au,lo,$u=!1,Ru,Iu,Ou=new Map){const Pu={};for(const[Du,Lu]of Object.entries(Au)){if($u&&(Du==="component"||Du==="id"))continue;const ju=convertPropertyToZod(typeof Lu=="object"&&Lu!==null?Lu:{},Ru,Iu?new Set(Iu):new Set,Ou);Pu[Du]=lo.has(Du)?ju:ju.optional()}return Pu}function collectComponentSubSchemas(Au,lo,$u=new Set){const Ru=[];if(!Au||typeof Au!="object")return Ru;if(Array.isArray(Au.allOf)){for(const Iu of Au.allOf)if(!(!Iu||typeof Iu!="object"))if(typeof Iu.$ref=="string"){const Ou=Iu.$ref;if(Ou.includes("common_types.json")&&Ou.includes("ComponentCommon"))Ru.push({properties:{accessibility:AccessibilityAttributesSchema$2.optional()}});else if(Ou.startsWith("#/")&&!$u.has(Ou)){$u.add(Ou);const Pu=resolveJsonPointer(lo,Ou);Pu&&Ru.push(...collectComponentSubSchemas(Pu,lo,$u))}}else Ru.push(...collectComponentSubSchemas(Iu,lo,$u))}return Au.properties&&Ru.push(Au),Ru}function convertComponentJsonSchemaToZod(Au,lo,$u=!0,Ru=new Map){const Iu={},Ou=collectComponentSubSchemas(Au,lo),Pu=new Set;for(const ju of Ou)Array.isArray(ju.required)&&ju.required.forEach(Bu=>{typeof Bu=="string"&&Pu.add(Bu)});for(const ju of Ou){const Bu=convertPropertiesToShape(ju.properties||{},Pu,$u,lo,void 0,Ru);Object.assign(Iu,Bu)}const Du=objectType(Iu);return Au.unevaluatedProperties===!0||typeof Au.unevaluatedProperties=="object"&&Au.unevaluatedProperties!==null||Au.additionalProperties===!0||typeof Au.additionalProperties=="object"&&Au.additionalProperties!==null?Du.passthrough():Du.strict()}function convertFunctionArgsJsonSchemaToZod(Au,lo,$u=new Map){const Ru=new Set(Array.isArray(Au.required)?Au.required.filter(Du=>typeof Du=="string"):[]),Iu=convertPropertiesToShape(Au.properties||{},Ru,!1,lo,void 0,$u),Ou=objectType(Iu);return Au.unevaluatedProperties===!0||typeof Au.unevaluatedProperties=="object"&&Au.unevaluatedProperties!==null||Au.additionalProperties===!0||typeof Au.additionalProperties=="object"&&Au.additionalProperties!==null?Ou.passthrough():Ou.strict()}function parseFunctionDefinitions(Au,lo,$u,Ru=!1){const Iu=[];if(!Au)return Iu;const Ou=new Map,Pu=(Du,Lu)=>{if(Ru&&(assertUax31Identifier(Du,`function identifier: '${Du}'`),Lu&&typeof Lu=="object"))for(const ju of Object.keys(Lu))assertUax31Identifier(ju,`argument identifier: '${ju}' in function '${Du}'`)};if(Array.isArray(Au)){for(const Du of Au)if(Du&&typeof Du=="object"&&typeof Du.name=="string"){if(Pu(Du.name,Du.parameters),$u&&!$u.has(Du.name))continue;const Lu=Du.parameters&&typeof Du.parameters=="object"?convertFunctionArgsJsonSchemaToZod(Du.parameters,lo,Ou):recordType(unknownType());Iu.push({name:Du.name,description:typeof Du.description=="string"?Du.description:void 0,returnType:typeof Du.returnType=="string"?Du.returnType:"any",allowedCallers:Du.allowedCallers,requiresUserActivation:Du.requiresUserActivation,schema:Lu})}return Iu}if(typeof Au=="object"&&Au!==null)for(const[Du,Lu]of Object.entries(Au)){const ju=Lu&&typeof Lu=="object"?Lu:{};if(Pu(Du,ju.properties&&typeof ju.properties=="object"?ju.properties:ju.parameters),$u&&!$u.has(Du)||!Lu||typeof Lu!="object")continue;const Bu=Lu,Fu=Bu.properties;let zu=Fu?.args??Bu.args??Bu.parameters;!zu&&Fu&&!("call"in Fu)&&!("function"in Fu)?zu=Bu:zu&&typeof zu=="object"&&!("properties"in zu)&&!("type"in zu)&&(zu={type:"object",properties:zu,required:Bu.required,additionalProperties:Bu.additionalProperties});const qu=zu&&typeof zu=="object"?convertFunctionArgsJsonSchemaToZod(zu,lo,Ou):recordType(unknownType()),Uu=(typeof Bu.returnType=="string"?Bu.returnType:void 0)??(typeof Fu?.returnType?.const=="string"?(Fu?.returnType).const:"any"),Hu=Bu.allowedCallers??Fu?.allowedCallers?.const,Vu=Bu.requiresUserActivation??Fu?.requiresUserActivation?.const;Iu.push({name:Du,description:typeof Bu.description=="string"?Bu.description:void 0,returnType:Uu,allowedCallers:Hu,requiresUserActivation:Vu,schema:qu})}return Iu}function extractPermittedNames(Au,lo){if(!Array.isArray(Au))return;const $u=new Set;for(const Ru of Au)if(typeof Ru?.$ref=="string"&&Ru.$ref.startsWith(lo)){const Ou=Ru.$ref.slice(lo.length).replace(/~([01])/g,(Pu,Du)=>Du==="1"?"/":"~");$u.add(Ou)}return $u}function parseCatalogComponents(Au,lo,$u,Ru){const Iu=[],Ou=new Map;for(const[Pu,Du]of Object.entries(Au)){const Lu=Du||{};if($u){assertUax31Identifier(Pu,`component identifier: '${Pu}'`);const Bu=Lu.properties;if(Bu&&typeof Bu=="object")for(const Fu of Object.keys(Bu))assertUax31Identifier(Fu,`property identifier: '${Fu}' in component '${Pu}'`)}if(Ru&&!Ru.has(Pu))continue;const ju=convertComponentJsonSchemaToZod(Lu,lo,!0,Ou);Iu.push({name:Pu,schema:ju,allowedParents:Array.isArray(Lu.allowedParents)?Lu.allowedParents.filter(Bu=>typeof Bu=="string"):void 0,allowedChildren:Array.isArray(Lu.allowedChildren)?Lu.allowedChildren.filter(Bu=>typeof Bu=="string"):void 0})}return Iu}function parseThemeSchema(Au,lo){const $u=Au.theme??Au.themeSchema??Au.styles??lo?.theme;if($u&&typeof $u=="object")return convertComponentJsonSchemaToZod($u,Au,!1)}function loadCatalogFromSchema(Au,lo){const $u=Au.catalogId??Au.$id??Au.id;if(!$u||typeof $u!="string")throw new Error("Catalog ID must be specified via catalog metadata ('catalogId' or '$id').");const Ru=Au.$defs,Iu=Ru?.anyComponent,Ou=extractPermittedNames(Iu?.oneOf,"#/components/"),Pu=lo??Au.protocolVersion??DEFAULT_PROTOCOL_VERSION,Du=isAtLeastVersion(Pu,"1.0"),Lu=Au.components??{},ju=parseCatalogComponents(Lu,Au,Du,Ou),Bu=Ru?.anyFunction,Fu=extractPermittedNames(Bu?.oneOf,"#/functions/"),zu=parseFunctionDefinitions(Au.functions,Au,Fu,Du),qu=parseThemeSchema(Au,Ru),Uu=typeof Au.instructions=="string"?Au.instructions:void 0;return new Catalog($u,Pu,ju,zu,qu,Uu)}const V08_STANDARD_DEFS={ComponentId:{description:"The unique identifier for a component, used for both definitions and references within the same surface.",type:"string"},TextItem:{additionalProperties:!1,description:"The value of the text field. This can be a literal string or a reference to a value in the data model ('path', e.g. '/user/name').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},UrlItem:{additionalProperties:!1,description:"The URL of the audio to be played. This can be a literal string ('literal') or a reference to a value in the data model ('path', e.g. '/song/url').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},AltTextItem:{additionalProperties:!1,description:"The alt text for the image. This can be a literal string ('literal') or a reference to a value in the data model ('path', e.g. '/thumbnail/altText').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},NameItem:{additionalProperties:!1,description:"The name of the icon to display. This can be a literal string or a reference to a value in the data model ('path', e.g. '/form/submit').",properties:{literalString:{enum:["accountCircle","add","arrowBack","arrowForward","attachFile","calendarToday","call","camera","check","close","delete","download","edit","event","error","favorite","favoriteOff","folder","help","home","info","locationOn","lock","lockOpen","mail","menu","moreVert","moreHoriz","notificationsOff","notifications","payment","person","phone","photo","print","refresh","search","send","settings","share","shoppingCart","star","starHalf","starOff","upload","visibility","visibilityOff","warning"],type:"string"},path:{type:"string"}},type:"object"},DescriptionItem:{additionalProperties:!1,description:"A description of the audio, such as a title or summary. This can be a literal string or a reference to a value in the data model ('path', e.g. '/song/title').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},ChildrenItem:{additionalProperties:!1,description:"Defines the children. Use 'explicitList' for a fixed set of children, or 'template' to generate children from a data list.",properties:{explicitList:{items:{type:"string"},type:"array"},template:{$ref:"#/$defs/TemplateItem",description:"A template for generating a dynamic list of children from a data model list. `componentId` is the component to use as a template, and `dataBinding` is the path to the map of components in the data model. Values in the map will define the list of children."}},type:"object"},TemplateItem:{additionalProperties:!1,description:"A template for generating a dynamic list of children from a data model list. `componentId` is the component to use as a template, and `dataBinding` is the path to the map of components in the data model. Values in the map will define the list of children.",properties:{componentId:{type:"string"},dataBinding:{type:"string"}},required:["componentId","dataBinding"],type:"object"},TabItemItem:{additionalProperties:!1,properties:{child:{type:"string"},title:{$ref:"#/$defs/TitleItem"}},required:["title","child"],type:"object"},TitleItem:{additionalProperties:!1,description:"The tab title. Defines the value as either a literal value or a path to data model value (e.g. '/options/title').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},ActionItem:{additionalProperties:!1,description:"The client-side action to be dispatched when the button is clicked. It includes the action's name and an optional context payload.",properties:{context:{items:{$ref:"#/$defs/ContextItem"},type:"array"},name:{type:"string"}},required:["name"],type:"object"},ContextItem:{additionalProperties:!1,properties:{key:{type:"string"},value:{$ref:"#/$defs/ValueItem",description:"Defines the value to be included in the context as either a literal value or a path to a data model value (e.g. '/user/name')."}},required:["key","value"],type:"object"},ValueItem:{additionalProperties:!1,description:"The current value of the slider. This can be a literal number ('literalNumber') or a reference to a value in the data model ('path', e.g. '/restaurant/cost').",properties:{literalNumber:{type:"number"},path:{type:"string"}},type:"object"},LabelItem:{additionalProperties:!1,description:"The label for the slider. This can be a literal string or a reference to a value in the data model ('path').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},OptionItem:{additionalProperties:!1,properties:{label:{$ref:"#/$defs/LabelItem",description:"The text to display for this option. This can be a literal string or a reference to a value in the data model (e.g. '/option/label')."},value:{description:"The value to be associated with this option when selected.",type:"string"}},required:["label","value"],type:"object"},SelectionItem:{additionalProperties:!1,description:"The currently selected values for the component. This can be a literal array of strings or a path to an array in the data model('path', e.g. '/hotel/options').",properties:{literalArray:{items:{type:"string"},type:"array"},path:{type:"string"}},type:"object"}},V09_CHILD_REF_OPTIONS={childRefNames:new Set(["ComponentId","Child","ChildComponentId"]),childListRefNames:new Set(["ChildList","TemplateChildList","ChildrenItem","TemplateItem"])},V09_STANDARD_DEFS={ComponentId:{type:"string",description:"The unique identifier for a component, used for both definitions and references within the same surface."},AccessibilityAttributes:{type:"object",description:"Attributes to enhance accessibility when using assistive technologies like screen readers.",properties:{label:{$ref:"#/$defs/DynamicString",description:"A short string, typically 1 to 3 words, used by assistive technologies to convey the purpose or intent of an element. For example, an input field might have an accessible label of 'User ID' or a button might be labeled 'Submit'."},description:{$ref:"#/$defs/DynamicString",description:"Additional information provided by assistive technologies about an element such as instructions, format requirements, or result of an action. For example, a mute button might have a label of 'Mute' and a description of 'Silences notifications about this conversation'."}}},ComponentCommon:{type:"object",properties:{id:{$ref:"#/$defs/ComponentId"},accessibility:{$ref:"#/$defs/AccessibilityAttributes"}},required:["id"]},ChildList:{oneOf:[{type:"array",items:{$ref:"#/$defs/ComponentId"},description:"A static list of child component IDs."},{type:"object",description:"A template for generating a dynamic list of children from a data model list. The `componentId` is the component to use as a template.",properties:{componentId:{$ref:"#/$defs/ComponentId"},path:{type:"string",description:"The path to the list of component property objects in the data model."}},required:["componentId","path"],additionalProperties:!1}]},DataBinding:{type:"object",properties:{path:{type:"string",description:"A JSON Pointer path to a value in the data model."}},required:["path"],additionalProperties:!1},DynamicValue:{description:"A value that can be a literal, a path, or a function call returning any type.",oneOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"array"},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},DynamicString:{description:"Represents a string",oneOf:[{type:"string"},{$ref:"#/$defs/DataBinding"},{allOf:[{$ref:"#/$defs/FunctionCall"},{properties:{returnType:{const:"string"}}}]}]},DynamicNumber:{description:"Represents a value that can be either a literal number, a path to a number in the data model, or a function call returning a number.",oneOf:[{type:"number"},{$ref:"#/$defs/DataBinding"},{allOf:[{$ref:"#/$defs/FunctionCall"},{properties:{returnType:{const:"number"}}}]}]},DynamicBoolean:{description:"A boolean value that can be a literal, a path, or a function call returning a boolean.",oneOf:[{type:"boolean"},{$ref:"#/$defs/DataBinding"},{allOf:[{$ref:"#/$defs/FunctionCall"},{properties:{returnType:{const:"boolean"}}}]}]},DynamicStringList:{description:"Represents a value that can be either a literal array of strings, a path to a string array in the data model, or a function call returning a string array.",oneOf:[{type:"array",items:{type:"string"}},{$ref:"#/$defs/DataBinding"},{allOf:[{$ref:"#/$defs/FunctionCall"},{properties:{returnType:{const:"array"}}}]}]},FunctionCall:{type:"object",description:"Invokes a named function on the client.",properties:{call:{type:"string",description:"The name of the function to call."},args:{type:"object",description:"Arguments passed to the function.",additionalProperties:{anyOf:[{$ref:"#/$defs/DynamicValue"},{type:"object",description:"A literal object argument (e.g. configuration)."}]}},returnType:{type:"string",description:"The expected return type of the function call.",enum:["string","number","boolean","array","object","any","void"],default:"boolean"}},required:["call"],oneOf:[{$ref:"catalog.json#/$defs/anyFunction"}]},CheckRule:{type:"object",description:"A single validation rule applied to an input component.",properties:{condition:{$ref:"#/$defs/DynamicBoolean"},message:{type:"string",description:"The error message to display if the check fails."}},required:["condition","message"],additionalProperties:!1},Checkable:{description:"Properties for components that support client-side checks.",type:"object",properties:{checks:{type:"array",description:"A list of checks to perform. These are function calls that must return a boolean indicating validity.",items:{$ref:"#/$defs/CheckRule"}}}},Action:{description:"Defines an interaction handler that can either trigger a server-side event or execute a local client-side function.",oneOf:[{type:"object",description:"Triggers a server-side event.",properties:{event:{type:"object",description:"The event to dispatch to the server.",properties:{name:{type:"string",description:"The name of the action to be dispatched to the server."},context:{type:"object",description:"A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.",additionalProperties:{$ref:"#/$defs/DynamicValue"}}},required:["name"],additionalProperties:!1}},required:["event"],additionalProperties:!1},{type:"object",description:"Executes a local client-side function.",properties:{functionCall:{$ref:"#/$defs/FunctionCall"}},required:["functionCall"],additionalProperties:!1}]}},V10_STANDARD_DEFS={ComponentId:{type:"string",description:"The unique identifier for a component, used for both definitions and references within the same surface."},CallId:{type:"string",description:"The unique identifier for a function call."},AccessibilityAttributes:{type:"object",description:"Attributes to enhance accessibility when using assistive technologies like screen readers or model understanding.",properties:{label:{$ref:"#/$defs/DynamicString",description:"A short string, typically 1 to 3 words, used by assistive technologies to convey the purpose or intent of an element. For example, an input field might have an accessible label of 'User ID' or a button might be labeled 'Submit'."},description:{$ref:"#/$defs/DynamicString",description:"Additional information provided by assistive technologies about an element such as instructions, format requirements, or result of an action. For example, a mute button might have a label of 'Mute' and a description of 'Silences notifications about this conversation'."},live:{type:"string",enum:["off","polite","assertive"],default:"off",description:"Controls screen reader announcements for dynamic updates (WAI-ARIA aria-live). 'polite' waits for user pause; 'assertive' interrupts immediately for alerts."},hidden:{$ref:"#/$defs/DynamicBoolean",description:"Hides the element and its children from assistive technologies when true. Default is false."}},additionalProperties:!1},Extensions:{type:"object",description:"Optional extension metadata. Keys MUST be Unicode identifiers (UAX #31). Keys starting with 'a2ui_' are reserved for official extensions.",patternProperties:{"^[\\p{XID_Start}_][\\p{XID_Continue}]*$":{}},additionalProperties:!1},ComponentCommon:{type:"object",properties:{id:{$ref:"#/$defs/ComponentId"},catalogId:{type:"string",description:"The catalog ID for this component, overriding any surface-level default catalogId."},accessibility:{$ref:"#/$defs/AccessibilityAttributes"},metadata:{type:"object",description:"Optional component-level metadata for vendor extensions.",properties:{extensions:{$ref:"#/$defs/Extensions"}},additionalProperties:!1}},required:["id"]},Child:{$ref:"#/$defs/ComponentId",description:"A reference to a single child component ID."},ChildList:{oneOf:[{type:"array",items:{$ref:"#/$defs/ComponentId"},description:"A static list of child component IDs."},{type:"object",description:"A template for generating a dynamic list of children from a data model list. The `componentId` is the component to use as a template.",properties:{componentId:{$ref:"#/$defs/ComponentId"},path:{type:"string",description:"The path to the list of component property objects in the data model."}},required:["componentId","path"],additionalProperties:!1}]},DataBinding:{type:"object",properties:{path:{type:"string",description:"A JSON Pointer path to a value in the data model."}},required:["path"],additionalProperties:!1},DynamicValue:{description:"A value that can be a literal, a path, or a function call returning any type.",oneOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"array"},{type:"object",not:{anyOf:[{required:["path"]},{required:["call"]}]}},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},DynamicString:{description:"Represents a string",oneOf:[{type:"string"},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},DynamicNumber:{description:"Represents a value that can be either a literal number, a path to a number in the data model, or a function call returning a number.",oneOf:[{type:"number"},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},DynamicBoolean:{description:"A boolean value that can be a literal, a path, or a function call returning a boolean.",oneOf:[{type:"boolean"},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},DynamicStringList:{description:"Represents a value that can be either a literal array of strings, a path to a string array in the data model, or a function call returning a string array.",oneOf:[{type:"array",items:{type:"string"}},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},FunctionCommon:{type:"object",description:"Baseline envelope properties common to all function calls. Function-specific argument schemas ('args') are defined individually by each function in the active catalog.",properties:{call:{type:"string",description:"The name of the function to call."},catalogId:{type:"string",description:"The catalog ID for this function, overriding any surface-level default catalogId."}},required:["call"]},IndexSystemFunction:{type:"object",description:"Returns the 0-based index of the current item when rendering a dynamic list from a template. This function MUST ONLY be available when evaluating template items within a list context.",returnType:"number",properties:{call:{const:"@index"},args:{type:"object",properties:{offset:{$ref:"#/$defs/DynamicNumber",description:"Optional. An offset to add to the 0-based index (e.g., 1 for 1-based indexing). Defaults to 0.",default:0}},unevaluatedProperties:!1}},required:["call"],unevaluatedProperties:!1},FunctionCall:{type:"object",description:"Invokes a named function, combining common function properties with the catalog function definition.",allOf:[{$ref:"#/$defs/FunctionCommon"},{oneOf:[{$ref:"catalog.json#/$defs/anyFunction"},{$ref:"#/$defs/IndexSystemFunction"}]}],unevaluatedProperties:!1},CheckRule:{type:"object",description:"A single validation check rule applied to an input component. The condition function or path evaluates to a structured validation result object.",properties:{condition:{oneOf:[{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}],description:"Path or function call evaluating to a structured validation result object."},message:{type:"string",description:"Optional fallback error message."}},required:["condition"],additionalProperties:!1},Checkable:{description:"Properties for components that support renderer-side checks.",type:"object",properties:{checks:{type:"array",description:"A list of checks to perform. These are function calls that must return a boolean indicating validity.",items:{$ref:"#/$defs/CheckRule"}}}},Action:{description:"Defines an interaction handler that can either trigger an agent-side event or execute a local renderer-side function.",oneOf:[{type:"object",description:"Triggers an agent-side event.",properties:{event:{type:"object",description:"The event to dispatch to the agent.",properties:{name:{type:"string",description:"The name of the action to be dispatched to the agent."},userMessage:{$ref:"#/$defs/DynamicString",description:"An optional human-readable message describing the action performed by the user, to present in conversation history or user feedback."},context:{type:"object",description:"A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.",additionalProperties:{$ref:"#/$defs/DynamicValue"}}},required:["name"],additionalProperties:!1}},required:["event"],additionalProperties:!1},{type:"object",description:"Executes a renderer or agent-side function.",properties:{functionCall:{$ref:"#/$defs/FunctionCall"}},required:["functionCall"],additionalProperties:!1}]},Surface:{title:"Surface Container Component",description:"The reserved canonical container component representing an A2UI surface. The Surface component is immutable and always has 'child': 'root'.",type:"object",allowedParents:[],properties:{component:{const:"Surface"},child:{const:"root"}},additionalProperties:!1},FunctionResponse:{type:"object",description:"The return response matching a callAgentFunction or callRendererFunction invocation.",properties:{functionCallId:{$ref:"#/$defs/CallId",description:"The unique ID matching the initiating function call."},value:{description:"The return value of the function."},error:{type:"object",description:"An error object indicating failure of the function execution.",properties:{code:{type:"string"},message:{type:"string"}},required:["code","message"],additionalProperties:!1}},required:["functionCallId"],oneOf:[{required:["value"]},{required:["error"]}],additionalProperties:!1}};const STANDARD_DEFS_BY_VERSION={"0.8":V08_STANDARD_DEFS,"0.9":V09_STANDARD_DEFS,"0.9.1":V09_STANDARD_DEFS,"1.0":V10_STANDARD_DEFS};function getStandardDefsForCatalog(Au,lo){if(lo?.standardDefs)return lo.standardDefs;if(lo?.protocolVersion){const $u=toCanonicalVersion(lo.protocolVersion)??normalizeVersionString(lo.protocolVersion);if($u in STANDARD_DEFS_BY_VERSION)return STANDARD_DEFS_BY_VERSION[$u]}return V09_STANDARD_DEFS}function transformRefDescriptionNode(Au){if(typeof Au.description!="string"||!Au.description.startsWith("REF:"))return!1;const lo=Au.description.substring(4),$u=lo.indexOf("|"),Ru=$u===-1?lo:lo.substring(0,$u),Iu=$u===-1?"":lo.substring($u+1),Ou=Au.default;for(const Pu of Object.keys(Au))delete Au[Pu];return Au.$ref=Ru.startsWith("#")?Ru:`#/$defs/${Ru.split("/").pop()}`,Ou!==void 0&&(Au.default=Ou),Iu&&(Au.description=Iu),!0}function cleanSchemaProperties(Au){Array.isArray(Au.anyOf)&&(Au.oneOf=Au.anyOf,delete Au.anyOf),Au.additionalProperties&&typeof Au.additionalProperties=="object"&&Object.keys(Au.additionalProperties).length===0&&(Au.additionalProperties=!0),Au.unevaluatedProperties&&typeof Au.unevaluatedProperties=="object"&&Object.keys(Au.unevaluatedProperties).length===0&&(Au.unevaluatedProperties=!0),"$schema"in Au&&delete Au.$schema}function cleanSchemaNode(Au,lo=new Set){if(typeof Au!="object"||Au===null||lo.has(Au))return;if(lo.add(Au),Array.isArray(Au)){for(const Ru of Au)cleanSchemaNode(Ru,lo);return}const $u=Au;if(!transformRefDescriptionNode($u)){cleanSchemaProperties($u);for(const Ru of Object.keys($u))cleanSchemaNode($u[Ru],lo)}}function processTheme(Au,lo){if(!Au.themeSchema)return;const $u=zodToJsonSchema(Au.themeSchema,{target:"jsonSchema2019-09",$refStrategy:"none"});cleanSchemaNode($u),$u.definitions&&typeof $u.definitions=="object"?(Object.assign(lo,$u.definitions),delete $u.definitions):$u.$defs&&typeof $u.$defs=="object"&&(Object.assign(lo,$u.$defs),delete $u.$defs);const Ru=Au.id.includes("v0_8")||Au.id.includes("v0.8"),Iu={type:"object",properties:$u.properties||{},...Array.isArray($u.required)&&$u.required.length>0?{required:$u.required}:{},...Ru?{}:{additionalProperties:$u.additionalProperties!==void 0?$u.additionalProperties:!0}};lo.theme=Iu}function extractZodComponentSchema(Au,lo){if(!Au.schema||typeof Au.schema!="object"||!("safeParse"in Au.schema))return{props:{},reqList:[],additionalProps:void 0};const $u=zodToJsonSchema(Au.schema,{target:"jsonSchema2019-09",$refStrategy:"none"});cleanSchemaNode($u),$u.definitions&&typeof $u.definitions=="object"?Object.assign(lo,$u.definitions):$u.$defs&&typeof $u.$defs=="object"&&Object.assign(lo,$u.$defs);const Ru=$u.properties||{},Iu=Array.isArray($u.required)?$u.required.filter(Du=>Du!=="component"&&Du!=="id"):[],Ou=$u.unevaluatedProperties??$u.additionalProperties;return{props:Ru,reqList:Iu,additionalProps:typeof Ou=="boolean"||typeof Ou=="object"&&Ou!==null?Ou:void 0}}function processSingleComponent(Au,lo,$u,Ru,Iu){const{props:Ou,reqList:Pu,additionalProps:Du}=extractZodComponentSchema(lo,$u),{component:Lu,id:ju,...Bu}=Ou,Fu={id:{$ref:"#/$defs/ComponentId"},...Bu,component:{const:Au}},zu=["id",...Pu,"component"];let qu;return Iu?.componentEnvelopeRef?qu={allOf:[{$ref:Iu.componentEnvelopeRef},{type:"object",properties:Fu,required:zu}],unevaluatedProperties:Du!==void 0?Du:!1}:qu={type:"object",properties:Fu,required:zu,unevaluatedProperties:Du!==void 0?Du:!1},lo.allowedParents&&lo.allowedParents.length>0&&(qu.allowedParents=lo.allowedParents),lo.allowedChildren&&lo.allowedChildren.length>0&&(qu.allowedChildren=lo.allowedChildren),qu}function processComponents(Au,lo,$u,Ru){if(Au.components.size===0){lo.components={};return}const Iu={};for(const[Ou,Pu]of Au.components.entries())Iu[Ou]=processSingleComponent(Ou,Pu,$u,Au,Ru);lo.components=Iu,$u.anyComponent={oneOf:Array.from(Au.components.keys()).map(Ou=>({$ref:`#/components/${Ou}`})),discriminator:{propertyName:"component"}}}function processSingleFunction(Au,lo,$u){let Ru;if(lo.schema&&typeof lo.schema=="object"&&"safeParse"in lo.schema){const Iu=zodToJsonSchema(lo.schema,{target:"jsonSchema2019-09",$refStrategy:"none"});cleanSchemaNode(Iu),Iu.definitions&&typeof Iu.definitions=="object"?(Object.assign($u,Iu.definitions),delete Iu.definitions):Iu.$defs&&typeof Iu.$defs=="object"&&(Object.assign($u,Iu.$defs),delete Iu.$defs),Ru=Iu}else Ru={type:"object",properties:{}};if(lo.description&&Ru.description===void 0&&(Ru.description=lo.description),Ru.type==="object"){const Iu=Ru.unevaluatedProperties??Ru.additionalProperties,Ou=typeof Iu=="boolean"||typeof Iu=="object"&&Iu!==null?Iu:void 0;Ru.additionalProperties!==void 0&&delete Ru.additionalProperties,Ru.unevaluatedProperties=Ou!==void 0?Ou:!1}return Ru}function processFunctions(Au,lo,$u){if(Au.functions.size===0)return;const Ru={};for(const[Iu,Ou]of Au.functions.entries())Ru[Iu]=processSingleFunction(Iu,Ou,$u);lo.functions=Ru,$u.anyFunction={oneOf:Array.from(Au.functions.keys()).map(Iu=>({$ref:`#/functions/${Iu}`}))}}function collectReferencedDefs(Au,lo,$u=new Set){if(!(typeof Au!="object"||Au===null)&&!$u.has(Au)){if($u.add(Au),typeof Au.$ref=="string"){const Ru=Au.$ref;Ru.startsWith("#/$defs/")&&lo.add(Ru.substring(8))}if(Array.isArray(Au))for(const Ru of Au)collectReferencedDefs(Ru,lo,$u);else for(const Ru of Object.values(Au))collectReferencedDefs(Ru,lo,$u)}}function generateCatalogSchema(Au,lo){const $u={$schema:"https://json-schema.org/draft/2020-12/schema",catalogId:Au.id};Au.instructions&&($u.instructions=Au.instructions);const Ru={};processTheme(Au,Ru),processComponents(Au,$u,Ru,lo),processFunctions(Au,$u,Ru);const Iu=getStandardDefsForCatalog(Au,lo);let Ou;do{Ou=Object.keys(Ru).length;const Pu=new Set;collectReferencedDefs($u,Pu),collectReferencedDefs(Ru,Pu),(Pu.has("DynamicString")||Pu.has("DynamicNumber")||Pu.has("DynamicBoolean")||Pu.has("DynamicValue"))&&(Pu.add("DataBinding"),Pu.add("FunctionCall"));for(const Du of Pu)Du in Iu&&!(Du in Ru)&&(Ru[Du]=Iu[Du])}while(Object.keys(Ru).length>Ou);return Object.keys(Ru).length>0&&($u.$defs=Ru),$u}function extractRefDefName(Au){if(!Au)return"";const lo=Au.lastIndexOf("#");return(lo!==-1?Au.slice(lo+1):Au).split("/").filter(Boolean).pop()??""}function unwrapNextZodLayer(Au,lo){if(!Au?._def)return null;if(lo){if(lo.has(Au))return null;lo.add(Au)}switch(Au._def.typeName){case"ZodOptional":case"ZodNullable":case"ZodDefault":case"ZodReadonly":return Au._def.innerType;case"ZodBranded":return Au._def.type;case"ZodEffects":return Au._def.schema;case"ZodLazy":return Au._def.getter();default:return null}}function getDescriptions(Au){const lo=[],$u=new Set;let Ru=Au;for(;Ru;){Ru.description&&lo.push(Ru.description),Ru._def?.description&&lo.push(Ru._def.description);const Iu=unwrapNextZodLayer(Ru,$u);if(!Iu)break;Ru=Iu}return lo}function unwrapZodType(Au){const lo=new Set;let $u=Au;for(;$u;){const Ru=unwrapNextZodLayer($u,lo);if(!Ru)break;$u=Ru}return $u}function checkDirectJsonRef(Au,lo){if(!Au)return null;const $u=extractRefDefName(Au),Ru=lo.childListRefNames,Iu=lo.childRefNames;return Ru.has($u)?{isChild:!1,isChildList:!0}:Iu.has($u)?{isChild:!0,isChildList:!1}:null}function checkCombinerList(Au,lo){let $u=!1;for(const Ru of Au){if(typeof Ru!="object"||Ru===null)continue;const Iu=checkJsonSchemaRef(Ru,lo);if(Iu.isChildList)return{isChild:!1,isChildList:!0};Iu.isChild&&($u=!0)}return $u?{isChild:!0,isChildList:!1}:null}function checkCombinerRefs(Au,lo){let $u=!1;for(const Ru of["oneOf","anyOf","allOf"]){const Iu=Au[Ru];if(!Array.isArray(Iu))continue;const Ou=checkCombinerList(Iu,lo);if(Ou?.isChildList)return Ou;Ou?.isChild&&($u=!0)}return $u?{isChild:!0,isChildList:!1}:null}function checkJsonSchemaRef(Au,lo){const $u=typeof Au.$ref=="string"?Au.$ref:"",Ru=checkDirectJsonRef($u,lo);if(Ru)return Ru;if(Au.type==="array"&&Au.items){const Ou=checkJsonSchemaRef(Au.items,lo);if(Ou.isChild||Ou.isChildList)return{isChild:!1,isChildList:!0}}const Iu=checkCombinerRefs(Au,lo);return Iu||(Au.type==="object"&&Au.properties&&("componentId"in Au.properties&&("path"in Au.properties||"dataBinding"in Au.properties)||"explicitList"in Au.properties||"template"in Au.properties)?{isChild:!1,isChildList:!0}:{isChild:!1,isChildList:!1})}function isTemplateShape(Au){if(Au?._def?.typeName==="ZodObject"&&typeof Au._def.shape=="function"){const lo=Au._def.shape();return!!(lo.componentId&&(lo.path||lo.dataBinding)||lo.explicitList||lo.template)}return!1}function isArrayOfChild(Au,lo){if(Au?._def?.typeName==="ZodArray"){const $u=unwrapZodType(Au._def.type);return analyzeChildRefSchema($u,lo).isChild}return!1}function analyzeUnionOptions(Au,lo){let $u=!1,Ru=!1,Iu=!1;for(const Ou of Au){const Pu=unwrapZodType(Ou);isTemplateShape(Pu)&&($u=!0),isArrayOfChild(Pu,lo)&&(Ru=!0);const Du=analyzeChildRefSchema(Pu,lo);if(Du.isChildList)return{isChild:!1,isChildList:!0};Du.isChild&&(Iu=!0)}return $u||Ru?{isChild:!1,isChildList:!0}:Iu?{isChild:!0,isChildList:!1}:{isChild:!1,isChildList:!1}}function isChildListDescription(Au,lo){if(!Au)return!1;if(Au.startsWith("REF:")){const Iu=extractRefDefName(Au.substring(4).split("|")[0]);if(lo.has(Iu))return!0}const $u=extractRefDefName(Au.split("|")[0]);if($u&&lo.has($u))return!0;const Ru=Au.trim();return!!lo.has(Ru)}function isChildDescription(Au,lo){if(!Au)return!1;if(Au.startsWith("REF:")){const Iu=extractRefDefName(Au.substring(4).split("|")[0]);if(lo.has(Iu))return!0}const $u=extractRefDefName(Au.split("|")[0]);if($u&&lo.has($u))return!0;const Ru=Au.trim();return!!lo.has(Ru)}function checkDescriptionChildRef(Au,lo){const $u=lo.childListRefNames,Ru=lo.childRefNames;for(const Iu of Au){if(isChildListDescription(Iu,$u))return{isChild:!1,isChildList:!0};if(isChildDescription(Iu,Ru))return{isChild:!0,isChildList:!1}}return null}function analyzeZodArray(Au,lo){const $u=analyzeChildRefSchema(Au,lo);return $u.isChild||$u.isChildList?{isChild:!1,isChildList:!0}:{isChild:!1,isChildList:!1}}function analyzeChildRefSchema(Au,lo){if(!Au||typeof Au!="object")return{isChild:!1,isChildList:!1};const $u=childRefKindOf(Au);if($u==="component-id")return{isChild:!0,isChildList:!1};if($u==="child-list")return{isChild:!1,isChildList:!0};const Ru=checkDescriptionChildRef(getDescriptions(Au),lo);if(Ru)return Ru;const Iu=unwrapZodType(Au);if(!Iu?._def)return checkJsonSchemaRef(Au,lo);const Ou=childRefKindOf(Iu);if(Ou==="component-id")return{isChild:!0,isChildList:!1};if(Ou==="child-list")return{isChild:!1,isChildList:!0};const Pu=Iu._def.typeName;if(Pu==="ZodArray"){const Du=unwrapZodType(Iu._def.type);return analyzeZodArray(Du,lo)}if(Pu==="ZodUnion"){const Du=Iu._def.options??[];return analyzeUnionOptions(Du,lo)}if(Pu==="ZodObject"&&typeof Iu._def.shape=="function"){const Du=Iu._def.shape();if(Du.componentId&&(Du.path||Du.dataBinding)||Du.explicitList||Du.template)return{isChild:!1,isChildList:!0}}return{isChild:!1,isChildList:!1}}function addNestedRef(Au,lo,$u){const Ru=Au.nestedRefs[lo];if(Ru){Ru.add($u);return}Au.nestedRefs[lo]=new Set([$u])}function inspectShapeField(Au,lo,$u,Ru){const Iu=analyzeChildRefSchema(lo,Ru);if(Iu.isChildList){$u.listRefs.add(Au);return}if(Iu.isChild){$u.singleRefs.add(Au);return}const Ou=unwrapZodType(lo);if(Ou?._def?.typeName!=="ZodArray")return;const Pu=unwrapZodType(Ou._def.type);if(Pu?._def?.typeName!=="ZodObject"||typeof Pu._def.shape!="function")return;const Du=Pu._def.shape();for(const[Lu,ju]of Object.entries(Du)){const Bu=analyzeChildRefSchema(ju,Ru);(Bu.isChild||Bu.isChildList)&&($u.listRefs.add(Au),addNestedRef($u,Au,Lu))}}function rawArrayItemProperties(Au){if(typeof Au!="object"||Au===null)return null;const lo=Au;if(lo.type!=="array"&&!("items"in lo))return null;const $u=lo.items;if(typeof $u!="object"||$u===null)return null;const Ru=$u.properties;return typeof Ru!="object"||Ru===null?null:Ru}function inspectRawProperties(Au,lo,$u){for(const[Ru,Iu]of Object.entries(Au)){const Ou=analyzeChildRefSchema(Iu,$u);if(Ou.isChildList){lo.listRefs.add(Ru);continue}if(Ou.isChild){lo.singleRefs.add(Ru);continue}const Pu=rawArrayItemProperties(Iu);if(Pu)for(const[Du,Lu]of Object.entries(Pu)){const ju=analyzeChildRefSchema(Lu,$u);(ju.isChild||ju.isChildList)&&(lo.listRefs.add(Ru),addNestedRef(lo,Ru,Du))}}}function inspectComponentSchema(Au,lo,$u){if(!Au)return;const Ru=unwrapZodType(Au);if(Ru?._def?.typeName==="ZodObject"&&typeof Ru._def.shape=="function"){const Iu=Ru._def.shape();for(const[Ou,Pu]of Object.entries(Iu))inspectShapeField(Ou,Pu,lo,$u);return}if(typeof Au=="object"&&Au!==null&&"properties"in Au){const Iu=Au.properties;typeof Iu=="object"&&Iu!==null&&inspectRawProperties(Iu,lo,$u)}}function buildComponentRefMap(Au,lo){const $u={},Ru=typeof Au?.components?.values=="function"?Array.from(Au.components.values()):Array.isArray(Au)?Au:Array.from(Au.values());for(const Iu of Ru){const Ou={singleRefs:new Set,listRefs:new Set,nestedRefs:{}};inspectComponentSchema(Iu.schema,Ou,lo),$u[Iu.name]={singleRefs:Ou.singleRefs,listRefs:Ou.listRefs,nestedRefs:Ou.nestedRefs}}return $u}function createFunctionImplementation(Au,lo){return{name:Au.name,returnType:Au.returnType,schema:Au.schema,allowedCallers:Au.allowedCallers,requiresUserActivation:Au.requiresUserActivation,description:Au.description,execute:lo}}class Catalog{get catalogSchema(){return this.cachedCatalogSchema||(this.cachedCatalogSchema=generateCatalogSchema(this)),this.cachedCatalogSchema}get componentRefMap(){return this._componentRefMap||(this._componentRefMap=buildComponentRefMap(this,V09_CHILD_REF_OPTIONS)),this._componentRefMap}constructor(lo,$u,Ru=[],Iu=[],Ou,Pu){if(!$u)throw new A2uiCatalogError("protocolVersion must be provided.");this.id=lo,this.protocolVersion=$u;const Du=new Map;for(const ju of Ru)Du.set(ju.name,ju);this.components=Du;const Lu=new Map;for(const ju of Iu)Lu.set(ju.name,ju);this.functions=Lu,this.themeSchema=Ou,this.instructions=Pu,this.invoker=(ju,Bu,Fu,zu)=>{const qu=this.functions.get(ju);if(!qu)throw new A2uiExpressionError(`Function not found in catalog '${this.id}': ${ju}`,ju);const Uu=qu.execute;if(typeof Uu!="function")throw new A2uiExpressionError(`Function '${ju}' in catalog '${this.id}' is schema-only and has no implementation.`,ju);try{const Hu=qu.schema.parse(Bu);return Uu.call(qu,Hu,Fu,zu)}catch(Hu){throw Hu?.name==="ZodError"||Hu instanceof ZodError?new A2uiExpressionError(`Validation failed for function '${ju}': ${Hu.message}`,ju,Hu.errors??Hu.issues):Hu}}}static fromSchema(lo,$u){return loadCatalogFromSchema(lo,$u)}}class EventEmitter{constructor(){this.listeners=new Set}subscribe(lo){return this.listeners.add(lo),{unsubscribe:()=>this.listeners.delete(lo)}}async emit(lo){for(const $u of this.listeners)try{await $u(lo)}catch(Ru){console.error("EventEmitter error:",Ru)}}dispose(){this.listeners.clear()}}var i=Symbol.for("preact-signals");function t(){if(v>1)v--;else{var Au,lo=!1;for((function(){var Iu=c;for(c=void 0;Iu!==void 0;){var Ou=Iu.S;if(Ou.v===Iu.v)for(var Pu=Ou.t;Pu!==void 0;Pu=Pu.x)Pu.i===Iu.i&&(Pu.i=Ou.i);Iu=Iu.o}})();h!==void 0;){var $u=h;for(h=void 0,s++;$u!==void 0;){var Ru=$u.u;if($u.u=void 0,$u.f&=-3,!(8&$u.f)&&w($u))try{$u.c()}catch(Iu){lo||(Au=Iu,lo=!0)}$u=Ru}}if(s=0,v--,lo)throw Au}}function n(Au){if(v>0)return Au();e=++u,v++;try{return Au()}finally{t()}}var r,o=void 0;function f(Au){var lo=o,$u=r;o=void 0,r=void 0;try{return Au()}finally{o=lo,r=$u}}var h=void 0,v=0,s=0,u=0,e=0,c=void 0,d=0;function a(Au){if(o!==void 0){var lo=Au.n;if(lo===void 0||lo.t!==o)return lo={i:0,S:Au,p:o.s,n:void 0,t:o,e:void 0,x:void 0,r:lo},o.s!==void 0&&(o.s.n=lo),o.s=lo,Au.n=lo,32&o.f&&Au.S(lo),lo;if(lo.i===-1)return lo.i=0,lo.n!==void 0&&(lo.n.p=lo.p,lo.p!==void 0&&(lo.p.n=lo.n),lo.p=o.s,lo.n=void 0,o.s.n=lo,o.s=lo),lo}}function l(Au,lo){this.v=Au,this.i=0,this.n=void 0,this.t=void 0,this.l=0,this.W=lo?.watched,this.Z=lo?.unwatched,this.name=lo?.name}l.prototype.brand=i;l.prototype.h=function(){return!0};l.prototype.S=function(Au){var lo=this,$u=this.t;$u!==Au&&Au.e===void 0&&(Au.x=$u,this.t=Au,$u!==void 0?$u.e=Au:f(function(){var Ru;(Ru=lo.W)==null||Ru.call(lo)}))};l.prototype.U=function(Au){var lo=this;if(this.t!==void 0){var $u=Au.e,Ru=Au.x;$u!==void 0&&($u.x=Ru,Au.e=void 0),Ru!==void 0&&(Ru.e=$u,Au.x=void 0),Au===this.t&&(this.t=Ru,Ru===void 0&&f(function(){var Iu;(Iu=lo.Z)==null||Iu.call(lo)}))}};l.prototype.subscribe=function(Au){var lo=this;return j(function(){var $u=lo.value;f(function(){return Au($u)})},{name:"sub"})};l.prototype.valueOf=function(){return this.value};l.prototype.toString=function(){return this.value+""};l.prototype.toJSON=function(){return this.value};l.prototype.peek=function(){var Au=this;return f(function(){return Au.value})};Object.defineProperty(l.prototype,"value",{get:function(){var Au=a(this);return Au!==void 0&&(Au.i=this.i),this.v},set:function(Au){if(Au!==this.v){if(s>100)throw new Error("Cycle detected");(function($u){v!==0&&s===0&&$u.l!==e&&($u.l=e,c={S:$u,v:$u.v,i:$u.i,o:c})})(this),this.v=Au,this.i++,d++,v++;try{for(var lo=this.t;lo!==void 0;lo=lo.x)lo.t.N()}finally{t()}}}});function y(Au,lo){return new l(Au,lo)}function w(Au){for(var lo=Au.s;lo!==void 0;lo=lo.n)if(lo.S.i!==lo.i||!lo.S.h()||lo.S.i!==lo.i)return!0;return!1}function _(Au){for(var lo=Au.s;lo!==void 0;lo=lo.n){var $u=lo.S.n;if($u!==void 0&&(lo.r=$u),lo.S.n=lo,lo.i=-1,lo.n===void 0){Au.s=lo;break}}}function b(Au){for(var lo=Au.s,$u=void 0;lo!==void 0;){var Ru=lo.p;lo.i===-1?(lo.S.U(lo),Ru!==void 0&&(Ru.n=lo.n),lo.n!==void 0&&(lo.n.p=Ru)):$u=lo,lo.S.n=lo.r,lo.r!==void 0&&(lo.r=void 0),lo=Ru}Au.s=$u}function p(Au,lo){l.call(this,void 0,lo),this.x=Au,this.s=void 0,this.g=d-1,this.f=4}p.prototype=new l;p.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===d))return!0;if(this.g=d,this.f|=1,this.i>0&&!w(this))return this.f&=-2,!0;var Au=o;try{_(this),o=this;var lo=this.x();(16&this.f||this.v!==lo||this.i===0)&&(this.v=lo,this.f&=-17,this.i++)}catch($u){this.v=$u,this.f|=16,this.i++}return o=Au,b(this),this.f&=-2,!0};p.prototype.S=function(Au){if(this.t===void 0){this.f|=36;for(var lo=this.s;lo!==void 0;lo=lo.n)lo.S.S(lo)}l.prototype.S.call(this,Au)};p.prototype.U=function(Au){if(this.t!==void 0&&(l.prototype.U.call(this,Au),this.t===void 0)){this.f&=-33;for(var lo=this.s;lo!==void 0;lo=lo.n)lo.S.U(lo)}};p.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var Au=this.t;Au!==void 0;Au=Au.x)Au.t.N()}};Object.defineProperty(p.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var Au=a(this);if(this.h(),Au!==void 0&&(Au.i=this.i),16&this.f)throw this.v;return this.v}});function g(Au,lo){return new p(Au,lo)}function S(Au){var lo=Au.m;if(Au.m=void 0,typeof lo=="function"){v++;var $u=o;o=void 0;try{lo()}catch(Ru){throw Au.f&=-2,Au.f|=8,m(Au),Ru}finally{o=$u,t()}}}function m(Au){for(var lo=Au.s;lo!==void 0;lo=lo.n)lo.S.U(lo);Au.x=void 0,Au.s=void 0,S(Au)}function x(Au){if(o!==this)throw new Error("Out-of-order effect");b(this),o=Au,this.f&=-2,8&this.f&&m(this),t()}function E(Au,lo){this.x=Au,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=lo?.name,r&&r.push(this)}E.prototype.c=function(){var Au=this.S();try{if(8&this.f||this.x===void 0)return;var lo=this.x();typeof lo=="function"&&(this.m=lo)}finally{Au()}};E.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,S(this),_(this),v++;var Au=o;return o=this,x.bind(this,Au)};E.prototype.N=function(){2&this.f||(this.f|=2,this.u=h,h=this)};E.prototype.d=function(){this.f|=8,1&this.f||m(this)};E.prototype.dispose=function(){this.d()};function j(Au,lo){var $u=new E(Au,lo);try{$u.c()}catch(Iu){throw $u.d(),Iu}var Ru=$u.d.bind($u);return Ru[Symbol.dispose]=Ru,Ru}let signalImpl,computedImpl,effectImpl,batchWriteImpl,isSignalImpl,getValueImpl,setValueImpl,peekValueImpl;const _PRIVATE_DEFAULT_SIGNAL_IMPLEMENTATION={signal:y,computed:g,effect:j,batchWrite:n,isSignal:Au=>!!Au&&typeof Au=="object"&&"value"in Au&&"peek"in Au,getValue:Au=>Au.value,setValue:(Au,lo)=>{Au instanceof p||(Au.value=lo)},peekValue:Au=>Au.peek()};setSignalImplementation(_PRIVATE_DEFAULT_SIGNAL_IMPLEMENTATION);function setSignalImplementation(Au){signalImpl=Au.signal,computedImpl=Au.computed,effectImpl=Au.effect,batchWriteImpl=Au.batchWrite,isSignalImpl=Au.isSignal,getValueImpl=Au.getValue,setValueImpl=Au.setValue,peekValueImpl=Au.peekValue}function signal(Au){return signalImpl(Au)}function computed(Au){return computedImpl(Au)}function effect(Au){return effectImpl(Au)}function batchWrite(Au){return batchWriteImpl(Au)}function isSignal(Au){return isSignalImpl(Au)}function getValue(Au){return getValueImpl(Au)}function setValue(Au,lo){setValueImpl(Au,lo)}function peekValue(Au){return peekValueImpl(Au)}function isNumeric(Au){return/^(0|[1-9]\d*)$/.test(Au)}const MAX_ARRAY_INDEX=1e4,FORBIDDEN_KEYS=new Set(["__proto__","constructor","prototype"]);class DataModel{constructor(lo={}){this.data={},this.signals=new Map,this.subscriptions=new Set,this.data=lo}getSignal(lo){const $u=this.normalizePath(lo);return this.signals.has($u)||this.signals.set($u,signal(this.get($u))),this.signals.get($u)}set(lo,$u){if(lo==null)throw new A2uiDataError("Path cannot be null or undefined.");if(lo==="/"||lo==="")return this.data=$u??{},this.notifyAllSignals(),this;const Ru=this.parsePath(lo),Iu=Ru.pop();if($u==null&&this.get(lo)===void 0)return this;if(this.data===void 0||this.data===null)this.data={};else if(typeof this.data!="object")throw new A2uiDataError(`Cannot set path '${lo}': the data model root is a primitive value.`,lo);let Ou=this.data;for(let Pu=0;Pu<Ru.length;Pu++){const Du=Ru[Pu];if(Array.isArray(Ou)){if(!isNumeric(Du))throw new A2uiDataError(`Cannot use non-numeric segment '${Du}' on an array in path '${lo}'.`,lo);const Lu=parseInt(Du,10);if(Lu>MAX_ARRAY_INDEX)throw new A2uiDataError(`Cannot set path '${lo}': array index '${Du}' exceeds maximum supported index (${MAX_ARRAY_INDEX}).`,lo);const ju=Ou[Lu];if(ju!=null&&typeof ju!="object")throw new A2uiDataError(`Cannot set path '${lo}': segment '${Du}' is a primitive value.`,lo);if(ju==null){const Bu=Pu<Ru.length-1?Ru[Pu+1]:Iu;if(isNumeric(Bu)){if(parseInt(Bu,10)>MAX_ARRAY_INDEX)throw new A2uiDataError(`Cannot set path '${lo}': array index '${Bu}' exceeds maximum supported index (${MAX_ARRAY_INDEX}).`,lo);Ou[Lu]=[]}else Ou[Lu]={}}}else{const Lu=Object.prototype.hasOwnProperty.call(Ou,Du);if(Lu){const ju=Ou[Du];if(ju!=null&&typeof ju!="object")throw new A2uiDataError(`Cannot set path '${lo}': segment '${Du}' is a primitive value.`,lo)}if(!Lu||Ou[Du]===void 0||Ou[Du]===null){const ju=Pu<Ru.length-1?Ru[Pu+1]:Iu;if(isNumeric(ju)){if(parseInt(ju,10)>MAX_ARRAY_INDEX)throw new A2uiDataError(`Cannot set path '${lo}': array index '${ju}' exceeds maximum supported index (${MAX_ARRAY_INDEX}).`,lo);Ou[Du]=[]}else Ou[Du]={}}}Ou=Ou[Du]}if(Array.isArray(Ou)){if(!isNumeric(Iu))throw new A2uiDataError(`Cannot use non-numeric segment '${Iu}' on an array in path '${lo}'.`,lo);if(parseInt(Iu,10)>MAX_ARRAY_INDEX)throw new A2uiDataError(`Cannot set path '${lo}': array index '${Iu}' exceeds maximum supported index (${MAX_ARRAY_INDEX}).`,lo)}if($u==null)if(Array.isArray(Ou)){const Pu=parseInt(Iu,10);Pu<Ou.length&&(Ou[Pu]=void 0)}else delete Ou[Iu];else Ou[Iu]=$u;return this.notifySignals(lo),this}delete(lo){return this.set(lo,void 0)}static resolvePath(lo,$u){return lo.startsWith("/")?lo:$u?`${$u.endsWith("/")?$u:`${$u}/`}${lo}`:`/${lo}`}get(lo){if(lo==null)throw new A2uiDataError("Path cannot be null or undefined.");if(lo==="/"||lo==="")return this.data;const $u=this.parsePath(lo);let Ru=this.data;for(const Iu of $u){if(Ru==null||typeof Ru!="object")return;if(Array.isArray(Ru)){if(!isNumeric(Iu))return;const Ou=parseInt(Iu,10);if(Ou<0||Ou>=Ru.length)return;Ru=Ru[Ou]}else{if(!Object.prototype.hasOwnProperty.call(Ru,Iu))return;Ru=Ru[Iu]}}return Ru}hasPath(lo){return lo==null?!1:this.get(lo)!==void 0}subscribe(lo,$u){const Ru=this.getSignal(lo);let Iu=!0,Ou=peekValue(Ru);const Pu=effect(()=>{const Du=getValue(Ru);Ou=Du,Iu||$u(Du)});return Iu=!1,this.subscriptions.add(Pu),{get value(){return Ou},unsubscribe:()=>{Pu(),this.subscriptions.delete(Pu)}}}dispose(){for(const lo of this.subscriptions)lo();this.subscriptions.clear(),this.signals.clear()}normalizePath(lo){return lo.length>1&&lo.endsWith("/")?lo.slice(0,-1):lo||"/"}parsePath(lo){return lo.split("/").filter($u=>$u.length>0).map($u=>{const Ru=$u.replace(/~([01])/g,(Iu,Ou)=>Ou==="1"?"/":"~");if(FORBIDDEN_KEYS.has(Ru))throw new A2uiDataError(`Forbidden path segment '${Ru}' in path '${lo}'.`,lo);return Ru})}notifySignals(lo){const $u=this.normalizePath(lo);batchWrite(()=>{this.updateSignal($u);let Ru=$u;for(;Ru!=="/"&&Ru!=="";)Ru=Ru.substring(0,Ru.lastIndexOf("/"))||"/",this.updateSignal(Ru);for(const Iu of this.signals.keys())this.isDescendant(Iu,$u)&&this.updateSignal(Iu)})}updateSignal(lo){const $u=this.signals.get(lo);if($u){const Ru=this.get(lo);Array.isArray(Ru)?setValue($u,Ru.slice()):typeof Ru=="object"&&Ru!==null?setValue($u,{...Ru}):setValue($u,Ru)}}notifyAllSignals(){batchWrite(()=>{for(const lo of this.signals.keys())this.updateSignal(lo)})}isDescendant(lo,$u){return $u==="/"||$u===""?lo!=="/":lo.startsWith($u+"/")}}const MAX_GLOBAL_DEPTH=50,MAX_FUNC_CALL_DEPTH=5,RELAXED_PATH_PATTERN=/^(?:(?:\/(?:[^~/]|~[01])*)*|(?:[^~/]|~[01])+(?:\/(?:[^~/]|~[01])*)*)$/;function*extractPointers(Au,lo,$u){if(typeof Au=="string")yield[Au,lo];else if(Array.isArray(Au))for(let Ru=0;Ru<Au.length;Ru++){const Iu=Au[Ru],Ou=`${lo}[${Ru}]`;yield*extractPointers(Iu,Ou,$u)}else if(typeof Au=="object"&&Au!==null){const Ru=Au;if("componentId"in Ru&&typeof Ru.componentId=="string"&&("path"in Ru||"dataBinding"in Ru))yield[Ru.componentId,`${lo}.componentId`];else if($u?.size)for(const Iu of $u)Iu in Ru&&(yield*extractPointers(Ru[Iu],`${lo}.${Iu}`));else for(const[Iu,Ou]of Object.entries(Ru))yield*extractPointers(Ou,`${lo}.${Iu}`)}}function getOrCreateRefMap(Au){return Au.componentRefMap}function*getComponentReferences(Au,lo){if(!Au||typeof Au!="object")return;const $u=lo instanceof Catalog?getOrCreateRefMap(lo):lo,Ru=Au.component;let Iu="",Ou=Au;if(typeof Ru=="string")Iu=Ru;else if(typeof Ru=="object"&&Ru!==null){const Bu=Ru;Iu=Object.keys(Bu)[0]??"",Ou=Bu[Iu]??{}}if(!Iu||typeof Ou!="object"||Ou===null)return;const Pu=$u[Iu],Du=Pu?Pu.singleRefs:new Set,Lu=Pu?Pu.listRefs:new Set,ju=Pu?.nestedRefs;for(const[Bu,Fu]of Object.entries(Ou))(Du.has(Bu)||Lu.has(Bu))&&(yield*extractPointers(Fu,Bu,ju?.[Bu]))}function traverseRecursionAndPaths(Au,lo,$u){if(lo>MAX_GLOBAL_DEPTH)throw new A2uiRecursionError(`Global recursion limit exceeded: Depth > ${MAX_GLOBAL_DEPTH}`);if(Array.isArray(Au)){for(const Ru of Au)traverseRecursionAndPaths(Ru,lo+1,$u);return}if(typeof Au=="object"&&Au!==null){const Ru=Au;if("path"in Ru&&typeof Ru.path=="string"){const Pu=Ru.path;if(!RELAXED_PATH_PATTERN.test(Pu))throw new A2uiValidationError(`Invalid path syntax: '${Pu}'`)}const Iu="functionCall"in Ru&&typeof Ru.functionCall=="object"&&Ru.functionCall!==null,Ou="call"in Ru&&"args"in Ru;if(Iu){if($u>=MAX_FUNC_CALL_DEPTH)throw new A2uiRecursionError(`Recursion limit exceeded: functionCall depth > ${MAX_FUNC_CALL_DEPTH}`);for(const[Pu,Du]of Object.entries(Ru))Pu==="functionCall"?traverseRecursionAndPaths(Du,lo+1,$u+1):traverseRecursionAndPaths(Du,lo+1,$u)}else if(Ou){if($u>=MAX_FUNC_CALL_DEPTH)throw new A2uiRecursionError(`Recursion limit exceeded: functionCall depth > ${MAX_FUNC_CALL_DEPTH}`);for(const[Pu,Du]of Object.entries(Ru))Pu==="args"?traverseRecursionAndPaths(Du,lo+1,$u+1):traverseRecursionAndPaths(Du,lo+1,$u)}else for(const Pu of Object.values(Ru))traverseRecursionAndPaths(Pu,lo+1,$u)}}function validateRecursionAndPaths(Au){traverseRecursionAndPaths(Au,0,0)}class SurfaceComponentsModel{constructor(lo){this.components=new Map,this._onCreated=new EventEmitter,this._onDeleted=new EventEmitter,this.onCreated=this._onCreated,this.onDeleted=this._onDeleted,lo&&this.setCatalog(lo)}setCatalog(lo){this.refMap=lo instanceof Catalog?lo.componentRefMap:lo}get(lo){return this.components.get(lo)}getAll(){return new Map(this.components)}has(lo){return this.components.has(lo)}get entries(){return this.components.entries()}get keys(){return this.components.keys()}get values(){return this.components.values()}get size(){return this.components.size}get componentsMap(){return this.components}addComponent(lo){if(this.components.has(lo.id))throw new A2uiStateError(`Component with id '${lo.id}' already exists.`);this.components.set(lo.id,lo),this._onCreated.emit(lo)}removeComponent(lo){const $u=this.components.get(lo);$u&&(this.components.delete(lo),$u.dispose(),this._onDeleted.emit(lo))}getChildReferences(lo){const $u=this.components.get(lo);if(!$u)return[];const Ru=$u.catalog?.components.size?$u.catalog.componentRefMap:this.refMap??$u.catalog?.componentRefMap??{};return Array.from(getComponentReferences({id:$u.id,component:$u.type,...$u.properties},Ru))}getChildIds(lo){return this.getChildReferences(lo).map(([$u])=>$u)}detectCycles(lo={}){const $u=lo.rootId??"root",Ru=lo.maxDepth??MAX_GLOBAL_DEPTH,Iu=lo.allowMissingRoot??!1;for(const Lu of this.components.values())for(const[ju,Bu]of this.getChildReferences(Lu.id))if(ju===Lu.id)throw new A2uiRecursionError(`Circular reference detected: Component '${Lu.id}' references itself in field '${Bu}' (Self-reference detected)`);const Ou=new Set,Pu=new Set,Du=(Lu,ju)=>{if(ju>Ru)throw new A2uiRecursionError(`Global recursion limit exceeded: logical depth > ${Ru}`);Ou.add(Lu),Pu.add(Lu);const Bu=this.getChildIds(Lu);for(const Fu of Bu)if(this.components.has(Fu)){if(!Ou.has(Fu))Du(Fu,ju+1);else if(Pu.has(Fu))throw new A2uiRecursionError(`Circular reference detected involving component '${Fu}'`)}Pu.delete(Lu)};if(Iu){const Lu=Array.from(this.components.keys()).sort();for(const ju of Lu)Ou.has(ju)||Du(ju,0)}else this.components.has($u)&&Du($u,0);return Ou}validateTopology(lo={}){if(this.components.size===0)return;const $u=lo.rootId??"root",Ru=lo.allowMissingRoot??!1,Iu=lo.allowDanglingReferences??!1,Ou=lo.allowOrphanComponents??!1;if(!Ru&&!this.components.has($u))throw new A2uiIntegrityError(`Missing root component: No component has id='${$u}'`);if(!Iu){for(const Du of this.components.values())for(const[Lu,ju]of this.getChildReferences(Du.id))if(!this.components.has(Lu))throw new A2uiIntegrityError(`Component '${Du.id}' references non-existent component '${Lu}' in field '${ju}' (Dangling reference '${Lu}' in component '${Du.id}')`)}const Pu=this.detectCycles({rootId:$u,allowMissingRoot:Ru,maxDepth:lo.maxDepth});if(!Ou&&!Ru&&Pu.size<this.components.size){const Du=Array.from(this.components.keys()).filter(Lu=>!Pu.has(Lu)).sort();if(Du.length>0)throw new A2uiIntegrityError(`Component '${Du[0]}' is not reachable from '${$u}' (Orphaned component '${Du[0]}' is not reachable from root)`)}}validateReferences(lo={}){const $u=[];try{this.validateTopology(lo)}catch(Ru){Ru instanceof A2uiValidationError?$u.push(Ru):Ru instanceof Error&&$u.push(new A2uiValidationError(Ru.message))}return $u}dispose(){for(const lo of this.components.values())lo.dispose();this.components.clear(),this._onCreated.dispose(),this._onDeleted.dispose()}}class SurfaceModel{constructor(lo,$u,Ru=new Map,Iu={},Ou=!1,Pu,Du="root"){if(this.id=lo,this.defaultCatalog=$u,this.theme=Iu,this.sendDataModel=Ou,this.rootId=Du,this._onAction=new EventEmitter,this._onError=new EventEmitter,this._onWarning=new EventEmitter,this.onAction=this._onAction,this.onError=this._onError,this.onWarning=this._onWarning,Ru!=null&&!(Ru instanceof Map))throw new TypeError("availableCatalogs must be a Map, or undefined/null. Note that availableCatalogs is now the 3rd argument to SurfaceModel and theme is the 4th argument.");const Lu=new Map(Ru??[]);$u?.id&&!Lu.has($u.id)&&Lu.set($u.id,$u),this.availableCatalogs=Lu,this.dataModel=Pu??new DataModel({}),this.componentsModel=new SurfaceComponentsModel($u)}get catalog(){return this.defaultCatalog}async dispatchAction(lo,$u){if(!lo||typeof lo!="object")return;const Ru=extractActionTarget(lo);if(!Ru)return;const Iu=Ru.name;if(!Iu||typeof Iu!="string")return;const Ou=Ru.context,Pu=Ou&&typeof Ou=="object"&&!Array.isArray(Ou)?Ou:{},Du={name:Iu,surfaceId:this.id,sourceComponentId:$u,timestamp:new Date().toISOString(),context:Pu},Lu=Ru.catalogId??lo.catalogId;typeof Lu=="string"&&Lu&&(Du.catalogId=Lu),typeof Ru.userMessage=="string"&&Ru.userMessage.length>0&&(Du.userMessage=Ru.userMessage),await this._onAction.emit(Du)}async dispatchError(lo){await this._onError.emit({...lo,surfaceId:this.id})}async dispatchWarning(lo){await this._onWarning.emit({...lo,surfaceId:this.id})}dispose(){this.dataModel.dispose(),this.componentsModel.dispose(),this._onAction.dispose(),this._onError.dispose(),this._onWarning.dispose()}}function extractActionTarget(Au){return"event"in Au&&Au.event&&typeof Au.event=="object"?Au.event:"name"in Au&&typeof Au.name=="string"?Au:null}class SurfaceGroupModel{constructor(){this.surfaces=new Map,this.surfaceUnsubscribers=new Map,this._onSurfaceCreated=new EventEmitter,this._onSurfaceDeleted=new EventEmitter,this._onAction=new EventEmitter,this.onSurfaceCreated=this._onSurfaceCreated,this.onSurfaceDeleted=this._onSurfaceDeleted,this.onAction=this._onAction}addSurface(lo){if(this.surfaces.has(lo.id)){console.warn(`Surface ${lo.id} already exists. Ignoring.`);return}this.surfaces.set(lo.id,lo);const $u=lo.onAction.subscribe(Ru=>this._onAction.emit(Ru));this.surfaceUnsubscribers.set(lo.id,$u),this._onSurfaceCreated.emit(lo)}deleteSurface(lo){const $u=this.surfaces.get(lo);if($u){const Ru=this.surfaceUnsubscribers.get(lo);Ru&&(Ru.unsubscribe(),this.surfaceUnsubscribers.delete(lo)),this.surfaces.delete(lo),$u.dispose(),this._onSurfaceDeleted.emit(lo)}}getSurface(lo){return this.surfaces.get(lo)}get surfacesMap(){return this.surfaces}dispose(){for(const lo of Array.from(this.surfaces.keys()))this.deleteSurface(lo);this._onSurfaceCreated.dispose(),this._onSurfaceDeleted.dispose(),this._onAction.dispose()}}class ComponentModel{constructor(lo,$u,Ru,Iu){this.id=lo,this.type=$u,this.catalog=Iu,this._onUpdated=new EventEmitter,this.onUpdated=this._onUpdated,this._properties=Ru}get properties(){return this._properties}set properties(lo){this._properties=lo,this._onUpdated.emit(this)}dispose(){this._onUpdated.dispose()}get componentTree(){return{id:this.id,type:this.type,...this._properties}}}function formatZodIssue(Au){const lo=Au.path.join(".")||"root";switch(Au.code){case ZodIssueCode.invalid_union:{const $u=Au.unionErrors?.flatMap(Ru=>Ru.issues);return $u&&$u.length>0?$u.map(formatZodIssue).join("; "):`${lo}: Invalid union`}case ZodIssueCode.unrecognized_keys:{const $u=Au.keys.map(Ru=>`'${Ru}'`).join(", ");return`${lo}: Unrecognized key(s) in object: ${$u}`}case ZodIssueCode.invalid_enum_value:{const $u=Au,Ru=$u.options.map(Iu=>String(Iu)).join(" | ");return`${lo}: Invalid enum value. Expected ${Ru}, received '${String($u.received)}'`}case ZodIssueCode.invalid_type:{const $u=Au;return`${lo}: Expected ${$u.expected}, received ${$u.received}`}case ZodIssueCode.custom:return`${lo}: ${Au.message}`;default:return Au.message?`${lo}: ${Au.message}`:`${lo}: Validation error (${Au.code})`}}const DEFAULT_CATALOG_COMPATIBILITY={"0.8":new Set(["0.8"]),"0.9":new Set(["0.9","0.9.1"]),"0.9.1":new Set(["0.9.1","0.9"]),"1.0":new Set(["1.0"])};function isCatalogVersionCompatible(Au,lo,$u=DEFAULT_CATALOG_COMPATIBILITY){if(!Au||!lo)return!1;const Ru=toCanonicalVersion(Au),Iu=toCanonicalVersion(lo);if(Ru&&Iu){if(Ru===Iu)return!0;const Du=$u[Iu];if(Du&&Du.has(Ru))return!0;const Lu=toSemVer(Au),ju=toSemVer(lo);return!!(Lu&&ju&&Lu.major>=1&&Lu.major===ju.major)}if(typeof Au!="string"||typeof lo!="string")return!1;const Ou=normalizeVersionString(Au),Pu=normalizeVersionString(lo);return Ou.length>0&&Ou===Pu}let globalKnownActionsProvider;function registerKnownActionsProvider(Au){globalKnownActionsProvider=Au}function validateActionSurfaceIds(Au,lo){for(const $u of lo){const Ru=Au[$u];if(Ru&&typeof Ru=="object"){const Iu=Ru;if("surfaceId"in Iu&&Iu.surfaceId!==void 0&&typeof Iu.surfaceId!="string")throw new A2uiValidationError("surfaceId must be a string")}}}class BaseVersionAdapter{get compatibleCatalogVersions(){const lo=toCanonicalVersion(this.version);return lo?new Set([lo]):new Set}get validActions(){return new Set(this.getNativeActionKeys())}isCatalogCompatible(lo){return lo?isCatalogVersionCompatible(lo,this.version):!1}extractOperations(lo){if(!lo||typeof lo!="object")return[];if(Array.isArray(lo))return lo.flatMap(Du=>this.extractOperations(Du));const $u=lo;if(Array.isArray($u.messages))return this.extractOperations($u.messages);const Ru=this.getNativeActionKeys();validateActionSurfaceIds($u,Ru);const Iu=Ru.filter(Du=>Du in $u).sort();if(Iu.length>1)throw new A2uiValidationError(`Message contains multiple conflicting update actions: ${Iu.join(", ")}.`);if(Iu.length===0){const Du=globalKnownActionsProvider?globalKnownActionsProvider():new Set(Ru),Lu=Object.keys($u).find(Bu=>Du.has(Bu)&&!Ru.includes(Bu)),ju=Ru.slice().sort().join(", ");throw Lu?new A2uiValidationError(`Invalid ${this.version} message: action '${Lu}' is not supported in protocol version ${this.version}. Allowed actions: ${ju}.`):new A2uiValidationError(`Invalid ${this.version} message: message must contain exactly one update action: ${ju}.`)}const Ou=this.preparePayloadForValidation($u),Pu=this.schema.safeParse(Ou);if(!Pu.success){const Du=Pu.error.errors.map(formatZodIssue).join("; ");throw new A2uiValidationError(`Invalid ${this.version} message: ${Du}`,Pu.error)}return this.extractOperationsFromObject($u)}preparePayloadForValidation(lo){return"version"in lo?lo:{version:this.version,...lo}}}const exactlyOneKey=(Au,lo)=>{const $u=Object.keys(Au).filter(Ru=>Au[Ru]!==void 0);$u.length!==1&&lo.addIssue({code:ZodIssueCode.custom,message:`Must define exactly one property, found ${$u.length} (${$u.join(", ")}).`})},StringValueSchema=objectType({path:stringType().optional(),literalString:stringType().optional(),literal:stringType().optional()}).strict().superRefine(exactlyOneKey),DataValueMapItemSchema=lazyType(()=>objectType({key:stringType(),valueString:stringType().optional(),valueNumber:numberType().optional(),valueBoolean:booleanType().optional(),valueMap:arrayType(DataValueMapItemSchema).optional()}).strict().superRefine((Au,lo)=>{let $u=0;Au.valueString!==void 0&&$u++,Au.valueNumber!==void 0&&$u++,Au.valueBoolean!==void 0&&$u++,Au.valueMap!==void 0&&$u++,$u!==1&&lo.addIssue({code:ZodIssueCode.custom,message:`Value map item must have exactly one value property (valueString, valueNumber, valueBoolean, valueMap), found ${$u}.`})}));function createDataValueSchema(Au={}){const lo=Au.maxDepth??5;return DataValueMapItemSchema.superRefine(($u,Ru)=>{const Iu=(Ou,Pu)=>{if(Pu>lo){Ru.addIssue({code:ZodIssueCode.custom,message:`valueMap recursion exceeded maximum depth of ${lo}.`});return}if(Ou.valueMap&&Array.isArray(Ou.valueMap))for(const Du of Ou.valueMap)Iu(Du,Pu+1)};Iu($u,1)})}const DataValueSchema=createDataValueSchema();objectType({path:stringType().optional(),literalNumber:numberType().optional(),literal:numberType().optional()}).strict().superRefine(exactlyOneKey);objectType({path:stringType().optional(),literalBoolean:booleanType().optional(),literal:booleanType().optional()}).strict().superRefine(exactlyOneKey);const ActionSchema$1=objectType({name:stringType().describe("A unique name identifying the action (e.g., 'submitForm')."),context:arrayType(objectType({key:stringType(),value:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalString:stringType().describe("A fixed, hardcoded string value.").optional(),literalNumber:numberType().optional(),literalBoolean:booleanType().optional()}).describe("The dynamic value. Define EXACTLY ONE of the nested properties.").strict().superRefine(exactlyOneKey)})).describe("A key-value map of data bindings to be resolved when the action is triggered.").optional()});objectType({text:StringValueSchema,usageHint:enumType(["h1","h2","h3","h4","h5","caption","body"]).optional()});objectType({url:StringValueSchema,usageHint:enumType(["icon","avatar","smallFeature","mediumFeature","largeFeature","header"]).optional(),fit:enumType(["contain","cover","fill","none","scale-down"]).optional(),altText:StringValueSchema.optional()});objectType({name:StringValueSchema});objectType({url:StringValueSchema});objectType({url:StringValueSchema,description:StringValueSchema.optional().describe("A label, title, or placeholder text.")});objectType({tabItems:arrayType(objectType({title:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalString:stringType().describe("A fixed, hardcoded string value.").optional()}),child:stringType().describe("A reference to a component instance by its unique ID.")}).strict().superRefine((Au,lo)=>{Au.title||lo.addIssue({code:ZodIssueCode.custom,message:"Tab item is missing 'title'."}),Au.child||lo.addIssue({code:ZodIssueCode.custom,message:"Tab item is missing 'child'."}),Au.title&&exactlyOneKey(Au.title,lo)})).describe("A list of tabs, each with a title and a child component ID.")});objectType({axis:enumType(["horizontal","vertical"]).optional().describe("The orientation."),color:stringType().optional().describe("The color of the divider (e.g., hex code or semantic name)."),thickness:numberType().optional().describe("The thickness of the divider.")});objectType({entryPointChild:stringType().describe("The ID of the component (e.g., a button) that triggers the modal."),contentChild:stringType().describe("The ID of the component to display as the modal's content.")});objectType({child:stringType().describe("The ID of the component to display as the button's content."),action:ActionSchema$1.describe("Represents a user-initiated action."),primary:booleanType().optional().describe("Indicates if this button should be styled as the primary action.")});objectType({label:StringValueSchema,value:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalBoolean:booleanType().optional()}).strict().superRefine(exactlyOneKey)});objectType({text:StringValueSchema.optional(),label:StringValueSchema.describe("A label, title, or placeholder text."),textFieldType:enumType(["shortText","number","date","longText","obscured"]).optional(),validationRegexp:stringType().optional().describe("A regex string to validate the input.")});objectType({value:StringValueSchema,enableDate:booleanType().optional(),enableTime:booleanType().optional(),outputFormat:stringType().optional().describe("The string format for the output (e.g., 'YYYY-MM-DD').")});objectType({selections:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalArray:arrayType(stringType()).optional()}).strict().superRefine(exactlyOneKey),options:arrayType(objectType({label:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalString:stringType().describe("A fixed, hardcoded string value.").optional()}).strict().superRefine(exactlyOneKey),value:stringType()})).optional(),maxAllowedSelections:numberType().optional(),type:enumType(["checkbox","chips"]).optional(),filterable:booleanType().optional()});objectType({value:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalNumber:numberType().optional()}).strict().superRefine(exactlyOneKey),minValue:numberType().optional(),maxValue:numberType().optional(),label:StringValueSchema.optional()});const ComponentArrayTemplateSchema=objectType({componentId:stringType(),dataBinding:stringType()}),ComponentArrayReferenceSchema=objectType({explicitList:arrayType(stringType()).optional(),template:ComponentArrayTemplateSchema.describe("A template for generating a dynamic list of children from a data model list. `componentId` is the component to use as a template, and `dataBinding` is the path to the map of components in the data model. Values in the map will define the list of children.").optional()}).strict().superRefine(exactlyOneKey);objectType({children:ComponentArrayReferenceSchema,distribution:enumType(["start","center","end","spaceBetween","spaceAround","spaceEvenly"]).optional(),alignment:enumType(["start","center","end","stretch"]).optional()});objectType({children:ComponentArrayReferenceSchema,distribution:enumType(["start","center","end","spaceBetween","spaceAround","spaceEvenly"]).optional(),alignment:enumType(["start","center","end","stretch"]).optional()});objectType({children:ComponentArrayReferenceSchema,direction:enumType(["vertical","horizontal"]).optional(),alignment:enumType(["start","center","end","stretch"]).optional()});objectType({child:stringType().describe("The ID of the component to be rendered inside the card.")});const ValueMapSchema=DataValueSchema.describe("A single data entry. Exactly one 'value*' property should be provided alongside the key."),ComponentPropertiesSchema=recordType(anyType()).refine(Au=>Object.keys(Au).length===1,"A wrapper object that MUST contain exactly one key, which is the name of the component type (e.g., 'Heading')."),ComponentInstanceSchema=objectType({id:stringType().describe("The unique identifier for this component."),weight:numberType().optional().describe("The relative weight of this component within a Row or Column. This corresponds to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column."),component:ComponentPropertiesSchema.describe("A wrapper object that MUST contain exactly one key, which is the name of the component type (e.g., 'Heading'). The value is an object containing the properties for that specific component.")}).strict().describe("Represents a *single* component in a UI widget tree. This component could be one of many supported types."),BeginRenderingMessageSchema=objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be rendered."),catalogId:stringType().optional().describe("The identifier of the component catalog to use for this surface. If omitted, the client MUST default to the standard catalog for this A2UI version (https://a2ui.org/specification/v0_8/standard_catalog_definition.json)."),root:stringType().describe("The ID of the root component to render."),styles:objectType({font:stringType().optional().describe("The primary font for the UI."),primaryColor:stringType().regex(/^#[0-9a-fA-F]{6}$/).optional().describe("The primary UI color as a hexadecimal code (e.g., '#00BFFF').")}).strict().optional().describe("Styling information for the UI.")}).strict().describe("Signals the client to begin rendering a surface with a root component and specific styles."),SurfaceUpdateMessageSchema=objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be updated. If you are adding a new surface this *must* be a new, unique identified that has never been used for any existing surfaces shown."),components:arrayType(ComponentInstanceSchema).min(1).describe("A list containing all UI components for the surface.")}).strict().superRefine((Au,lo)=>{const $u=new Set;for(const Iu of Au.components)Iu.id&&($u.has(Iu.id)&&lo.addIssue({code:ZodIssueCode.custom,message:`Duplicate component ID found: ${Iu.id}`,path:["components"]}),$u.add(Iu.id));const Ru=(Iu,Ou)=>{for(const Pu of Iu)Pu&&!$u.has(Pu)&&lo.addIssue({code:ZodIssueCode.custom,message:`Component '${Ou}' references non-existent component ID '${Pu}'.`,path:["components"]})};for(const Iu of Au.components){if(!Iu.id||!Iu.component)continue;const Ou=Object.keys(Iu.component);if(Ou.length!==1)continue;const Pu=Ou[0],Du=Iu.component[Pu];switch(Pu){case"Row":case"Column":case"List":if(Du.children&&!Array.isArray(Du.children)){const Lu=!!Du.children.explicitList,ju=!!Du.children.template;(Lu&&ju||!Lu&&!ju)&&lo.addIssue({code:ZodIssueCode.custom,message:`Component '${Iu.id}' must have either 'explicitList' or 'template' in children, but not both or neither.`}),Lu&&Ru(Du.children.explicitList,Iu.id),ju&&Ru([Du.children.template?.componentId],Iu.id)}break;case"Card":Du.child&&Ru([Du.child],Iu.id);break;case"Tabs":Du.tabItems&&Array.isArray(Du.tabItems)&&Du.tabItems.forEach(Lu=>{Lu.child&&Ru([Lu.child],Iu.id)});break;case"Modal":Ru([Du.entryPointChild,Du.contentChild],Iu.id);break;case"Button":Du.child&&Ru([Du.child],Iu.id);break}}}).describe("Updates a surface with a new set of components."),DataModelUpdateMessageSchema=objectType({surfaceId:stringType().describe("The unique identifier for the UI surface this data model update applies to."),path:stringType().optional().describe("An optional path to a location within the data model (e.g., '/user/name'). If omitted, or set to '/', the entire data model will be replaced."),contents:arrayType(ValueMapSchema).describe("An array of data entries. Each entry must contain a 'key' and exactly one corresponding typed 'value*' property.")}).strict().describe("Updates the data model for a surface."),DeleteSurfaceMessageSchema$2=objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be deleted.")}).strict().describe("Signals the client to delete the surface identified by 'surfaceId'."),A2uiMessageSchema$1=objectType({beginRendering:BeginRenderingMessageSchema.optional(),surfaceUpdate:SurfaceUpdateMessageSchema.optional(),dataModelUpdate:DataModelUpdateMessageSchema.optional(),deleteSurface:DeleteSurfaceMessageSchema$2.optional()}).strict().superRefine((Au,lo)=>{Object.keys(Au).filter(Ru=>["beginRendering","surfaceUpdate","dataModelUpdate","deleteSurface"].includes(Ru)).length!==1&&lo.addIssue({code:ZodIssueCode.custom,message:"A2UI Protocol message must have exactly one of: surfaceUpdate, dataModelUpdate, beginRendering, deleteSurface."})}).describe("Describes a JSON payload for an A2UI (Agent to UI) message, which is used to dynamically construct and update user interfaces. A message MUST contain exactly ONE of the action properties: 'beginRendering', 'surfaceUpdate', 'dataModelUpdate', or 'deleteSurface'.");function normalizeV08Component(Au){if(!Au||typeof Au!="object")return{id:"",component:""};const lo=Au;let $u=typeof lo.component=="string"?lo.component:"";const Ru={};for(const[Iu,Ou]of Object.entries(lo))Iu!=="component"&&Iu!=="id"&&(Ru[Iu]=Ou);if(lo.component&&typeof lo.component=="object"){const Iu=lo.component,Ou=Object.keys(Iu);if(Ou.length>0){$u=Ou[0];const Pu=Iu[Ou[0]];Pu&&typeof Pu=="object"&&Pu!==null&&!Array.isArray(Pu)&&Object.assign(Ru,Pu)}}return{...Ru,id:String(lo.id??""),component:$u}}class V0Point8Adapter extends BaseVersionAdapter{constructor(){super(...arguments),this.version="v0.8",this.schema=A2uiMessageSchema$1}getNativeActionKeys(){return["beginRendering","surfaceUpdate","dataModelUpdate","deleteSurface"]}preparePayloadForValidation(lo){const $u={...lo};return delete $u.version,$u}extractOperationsFromObject(lo){const $u=[];if("beginRendering"in lo){const Ru=lo.beginRendering;$u.push({type:"createSurface",surfaceId:String(Ru?.surfaceId??""),catalogId:typeof Ru?.catalogId=="string"?Ru.catalogId:void 0,theme:Ru?.theme??Ru?.styles,sendDataModel:!!Ru?.sendDataModel,components:Array.isArray(Ru?.components)?Ru.components.map(normalizeV08Component):void 0,dataModel:Ru?.dataModel&&typeof Ru.dataModel=="object"&&!Array.isArray(Ru.dataModel)?Ru.dataModel:void 0,version:typeof lo.version=="string"?lo.version:this.version,rootId:typeof Ru?.root=="string"&&Ru.root?Ru.root:void 0})}if("surfaceUpdate"in lo){const Ru=lo.surfaceUpdate;$u.push({type:"updateComponents",surfaceId:String(Ru?.surfaceId??""),components:Array.isArray(Ru?.components)?Ru.components.map(normalizeV08Component):[]})}if("dataModelUpdate"in lo){const Ru=lo.dataModelUpdate,Iu=String(Ru?.surfaceId??"");if(Array.isArray(Ru?.contents)){for(const Ou of Ru.contents)if(Ou&&typeof Ou=="object"&&typeof Ou.key=="string"){const Pu="valueNumber"in Ou?Ou.valueNumber:"valueString"in Ou?Ou.valueString:"valueBoolean"in Ou?Ou.valueBoolean:"valueObject"in Ou?Ou.valueObject:"valueArray"in Ou?Ou.valueArray:Ou.value;$u.push({type:"updateDataModel",surfaceId:Iu,path:Ou.key,value:Pu})}}else $u.push({type:"updateDataModel",surfaceId:Iu,path:typeof Ru?.path=="string"?Ru.path:void 0,value:Ru?.value})}if("deleteSurface"in lo){const Ru=lo.deleteSurface;$u.push({type:"deleteSurface",surfaceId:String(Ru?.surfaceId??"")})}return $u}}const CreateSurfaceMessageSchema$1=objectType({version:enumType(["v0.9","v0.9.1"]),createSurface:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be rendered."),catalogId:stringType().describe("A string that uniquely identifies this catalog. It is recommended to prefix this with an internet domain that you own, to avoid conflicts e.g. mycompany.com:somecatalog'."),theme:anyType().optional(),sendDataModel:booleanType().describe("If true, the client will send the full data model of this surface in the metadata of every A2A message sent to the server that created the surface. Defaults to false.").optional()}).strict().describe("Signals the client to create a new surface and begin rendering it. It is an error to send 'createSurface' for a surfaceId that already exists without first deleting it. When this message is sent, the client will expect 'updateComponents' and/or 'updateDataModel' messages for the same surfaceId that define the component tree.")}).strict(),UpdateComponentsMessageSchema$1=objectType({version:enumType(["v0.9","v0.9.1"]),updateComponents:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be updated."),components:arrayType(recordType(stringType(),anyType())).min(1).describe("A list containing all UI components for the surface.")}).strict().describe("Updates a surface with a new set of components. This message can be sent multiple times to update the component tree of an existing surface. One of the components in one of the components lists MUST have an 'id' of 'root' to serve as the root of the component tree. A createSurface message MUST have been previously sent for the 'surfaceId' in this message; the surface's catalog is the one specified by that createSurface.")}).strict(),UpdateDataModelMessageSchema$1=objectType({version:enumType(["v0.9","v0.9.1"]),updateDataModel:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface this data model update applies to."),path:stringType().describe("An optional path to a location within the data model (e.g., '/user/name'). If omitted, or set to '/', refers to the entire data model.").optional(),value:anyType().describe("The data to be updated in the data model. If present, the value at 'path' is replaced (or created). If omitted, the key at 'path' is removed.").optional()}).strict().describe("Updates the data model for an existing surface. This message can be sent multiple times to update the data model. A createSurface message MUST have been previously sent for the 'surfaceId' in this message; the surface's catalog is the one specified by that createSurface.")}).strict(),DeleteSurfaceMessageSchema$1=objectType({version:enumType(["v0.9","v0.9.1"]),deleteSurface:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be deleted.")}).strict().describe("Signals the client to delete the surface identified by 'surfaceId'. A createSurface message MUST have been previously sent for the 'surfaceId' in this message; the surface's catalog is the one specified by that createSurface.")}).strict(),A2uiMessageSchema=unionType([CreateSurfaceMessageSchema$1,UpdateComponentsMessageSchema$1,UpdateDataModelMessageSchema$1,DeleteSurfaceMessageSchema$1]),A2uiMessageListSchema=arrayType(A2uiMessageSchema).describe("A list of messages.");objectType({messages:A2uiMessageListSchema}).strict().describe("An object wrapping a list of messages.");class V0Point9Adapter extends BaseVersionAdapter{constructor(){super(...arguments),this.version="v0.9",this.schema=A2uiMessageSchema}get compatibleCatalogVersions(){return new Set(["0.9","0.9.1"])}getNativeActionKeys(){return["createSurface","updateComponents","updateDataModel","deleteSurface"]}extractOperationsFromObject(lo){const $u=[];if("createSurface"in lo){const Ru=lo.createSurface;$u.push({type:"createSurface",surfaceId:String(Ru?.surfaceId||""),catalogId:typeof Ru?.catalogId=="string"?Ru.catalogId:void 0,theme:Ru?.theme,sendDataModel:!!Ru?.sendDataModel,components:Array.isArray(Ru?.components)?Ru.components:void 0,dataModel:Ru?.dataModel&&typeof Ru.dataModel=="object"&&!Array.isArray(Ru.dataModel)?Ru.dataModel:void 0,version:typeof lo.version=="string"?lo.version:this.version})}if("updateComponents"in lo){const Ru=lo.updateComponents;$u.push({type:"updateComponents",surfaceId:String(Ru?.surfaceId||""),components:Array.isArray(Ru?.components)?Ru.components:[]})}if("updateDataModel"in lo){const Ru=lo.updateDataModel;$u.push({type:"updateDataModel",surfaceId:String(Ru?.surfaceId||""),path:typeof Ru?.path=="string"?Ru.path:void 0,value:Ru?.value})}if("deleteSurface"in lo){const Ru=lo.deleteSurface;$u.push({type:"deleteSurface",surfaceId:String(Ru?.surfaceId||"")})}return $u}}const INTERNAL_OPERATION_TYPES=["createSurface","updateComponents","updateDataModel","deleteSurface","callRendererFunction","agentFunctionResponse"];function isInternalOperation(Au){return typeof Au=="object"&&Au!==null&&"type"in Au&&typeof Au.type=="string"&&INTERNAL_OPERATION_TYPES.includes(Au.type)}objectType({componentId:lazyType(()=>ComponentIdSchema$1),path:stringType().describe("The path to the list of component property objects in the data model.")}).strict().describe("REF:#/$defs/TemplateChildList|A template for generating a dynamic list of children from a data model list. The `componentId` is the component to use as a template.");const AnyComponentSchema=lazyType(()=>ComponentCommonSchema.extend({component:stringType()}).passthrough().refine(Au=>Au.component!=="Surface",{message:'Component type cannot be "Surface". "Surface" is a top-level protocol container defined in createSurface, not a child component.'})),ComponentsListSchema=arrayType(AnyComponentSchema).min(1);recordType(stringType(),anyType());const ComponentIdSchema$1=markChildRef(stringType().describe("REF:#/$defs/ComponentId|The unique identifier for a component, used for both definitions and references within the same surface."),"component-id"),CallIdSchema=stringType().describe("REF:#/$defs/CallId|The unique identifier for a function call."),DataBindingSchema$1=objectType({path:stringType().describe("A JSON Pointer path to a value in the data model.")}).strict().describe("REF:#/$defs/DataBinding"),FunctionCommonSchema=objectType({call:stringType().describe("The name of the function to call."),catalogId:stringType().describe("The catalog ID for this function, overriding any surface-level default catalogId.").optional()}).describe("REF:#/$defs/FunctionCommon|Baseline envelope properties common to all function calls. Function-specific argument schemas ('args') are defined individually by each function in the active catalog."),FunctionCallSchema$1=recordType(stringType(),anyType()).and(intersectionType(FunctionCommonSchema,anyType())).describe("REF:#/$defs/FunctionCall|Invokes a named function, combining common function properties with the catalog function definition."),DynamicStringSchema$1=unionType([stringType(),DataBindingSchema$1,FunctionCallSchema$1]).describe("REF:#/$defs/DynamicString|Represents a string"),DynamicBooleanSchema$1=unionType([booleanType(),DataBindingSchema$1,FunctionCallSchema$1]).describe("REF:#/$defs/DynamicBoolean|A boolean value that can be a literal, a path, or a function call returning a boolean."),AccessibilityAttributesSchema$1=objectType({label:DynamicStringSchema$1.optional(),description:DynamicStringSchema$1.optional(),live:enumType(["off","polite","assertive"]).describe("Controls screen reader announcements for dynamic updates (WAI-ARIA aria-live). 'polite' waits for user pause; 'assertive' interrupts immediately for alerts.").default("off"),hidden:DynamicBooleanSchema$1.optional()}).strict().describe("REF:#/$defs/AccessibilityAttributes|Attributes to enhance accessibility when using assistive technologies like screen readers or model understanding."),ExtensionsSchema=recordType(stringType(),unknownType()).superRefine((Au,lo)=>{for(const $u in Au)$u.match(/^[\p{XID_Start}_][\p{XID_Continue}:-]*$/u)||lo.addIssue({path:[$u],code:ZodIssueCode.custom,message:`Invalid extension key "${$u}": Keys MUST be Unicode identifiers (UAX #31).`})}).describe("REF:#/$defs/Extensions|Optional extension metadata. Keys MUST be Unicode identifiers (UAX #31). Keys starting with 'a2ui_' are reserved for official extensions."),ComponentCommonSchema=objectType({id:ComponentIdSchema$1,catalogId:stringType().describe("The catalog ID for this component, overriding any surface-level default catalogId.").optional(),accessibility:AccessibilityAttributesSchema$1.optional(),metadata:objectType({extensions:ExtensionsSchema.optional()}).strict().describe("Optional component-level metadata for vendor extensions.").optional()}).describe("REF:#/$defs/ComponentCommon");markChildRef(unionType([arrayType(ComponentIdSchema$1).describe("A static list of child component IDs."),objectType({componentId:ComponentIdSchema$1,path:stringType().describe("The path to the list of component property objects in the data model.")}).strict().describe("A template for generating a dynamic list of children from a data model list. The `componentId` is the component to use as a template.")]).describe("REF:#/$defs/ChildList"),"child-list");const DynamicValueSchema$1=unionType([stringType(),numberType(),booleanType(),arrayType(anyType()),recordType(stringType(),unknownType()).refine(Au=>!Au||!("path"in Au)&&!("call"in Au)),DataBindingSchema$1,FunctionCallSchema$1]).describe("REF:#/$defs/DynamicValue|A value that can be a literal, a path, or a function call returning any type."),DynamicNumberSchema$1=unionType([numberType(),DataBindingSchema$1,FunctionCallSchema$1]).describe("REF:#/$defs/DynamicNumber|Represents a value that can be either a literal number, a path to a number in the data model, or a function call returning a number.");unionType([arrayType(stringType()),DataBindingSchema$1,FunctionCallSchema$1]).describe("REF:#/$defs/DynamicStringList|Represents a value that can be either a literal array of strings, a path to a string array in the data model, or a function call returning a string array.");objectType({call:literalType("@index"),args:objectType({offset:DynamicNumberSchema$1.optional()}).optional()}).describe("REF:#/$defs/IndexSystemFunction|Returns the 0-based index of the current item when rendering a dynamic list from a template. This function MUST ONLY be available when evaluating template items within a list context.");const CheckRuleSchema$1=objectType({condition:unionType([DataBindingSchema$1,FunctionCallSchema$1]).describe("Path or function call evaluating to a structured validation result object."),message:stringType().describe("Optional fallback error message.").optional()}).strict().describe("REF:#/$defs/CheckRule|A single validation check rule applied to an input component. The condition function or path evaluates to a structured validation result object.");objectType({checks:arrayType(CheckRuleSchema$1).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional()}).describe("REF:#/$defs/Checkable|Properties for components that support renderer-side checks.");unionType([objectType({event:objectType({name:stringType().describe("The name of the action to be dispatched to the agent."),userMessage:DynamicStringSchema$1.optional(),context:recordType(stringType(),DynamicValueSchema$1).describe("A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.").optional()}).strict().describe("The event to dispatch to the agent.")}).strict().describe("Triggers an agent-side event."),objectType({functionCall:FunctionCallSchema$1}).strict().describe("Executes a renderer or agent-side function.")]).describe("REF:#/$defs/Action|Defines an interaction handler that can either trigger an agent-side event or execute a local renderer-side function.");objectType({component:literalType("Surface").optional(),child:literalType("root").optional()}).strict().describe("REF:#/$defs/Surface|The reserved canonical container component representing an A2UI surface. The Surface component is immutable and always has 'child': 'root'.");const FunctionResponseSchema=objectType({functionCallId:CallIdSchema,value:anyType().describe("The return value of the function.").optional(),error:objectType({code:stringType(),message:stringType()}).strict().describe("An error object indicating failure of the function execution.").optional()}).strict().superRefine((Au,lo)=>{const $u="value"in Au,Ru="error"in Au;($u&&Ru||!$u&&!Ru)&&lo.addIssue({code:ZodIssueCode.custom,message:'FunctionResponse must have either "value" or "error", but not both or neither.'})}).describe("REF:#/$defs/FunctionResponse|The return response matching a callAgentFunction or callRendererFunction invocation."),CreateSurfaceMessageSchema=objectType({version:literalType("v1.0"),createSurface:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be rendered. It must be globally unique for the renderer's lifetime."),catalogId:stringType().describe("A string that uniquely identifies the default catalog for this surface. It is recommended to prefix this with an internet domain that you own, to avoid conflicts e.g. 'mycompany.com:somecatalog'. Components and function calls that do not explicitly specify a catalogId will use this surface-level default catalogId.").optional(),sendDataModel:booleanType().describe("If true, the renderer will send the full data model of this surface in the metadata of every A2A message sent to the agent that created the surface. Defaults to false.").optional(),components:ComponentsListSchema.optional(),dataModel:recordType(stringType(),anyType()).describe("The initial root data model object for the surface.").optional(),metadata:objectType({extensions:ExtensionsSchema.optional()}).strict().describe("Optional surface-level metadata.").optional()}).strict().describe("Signals the renderer to create a new surface and begin rendering it. Creating a surface implicitly instantiates the canonical 'Surface' container component ('common_types.json#/$defs/Surface') with 'child': 'root'. It is an error to try to create a surface with an existing ID without first deleting it; surfaceId MUST be globally unique for the renderer's lifetime. When this message is sent, the renderer expects 'updateComponents' and/or 'updateDataModel' messages for the same surfaceId to define the component tree.")}).strict(),UpdateComponentsMessageSchema=objectType({version:literalType("v1.0"),updateComponents:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be updated. It must be globally unique for the renderer's lifetime."),components:ComponentsListSchema}).strict().describe("Updates a surface with a new set of components. This message can be sent multiple times to update the component tree of an existing surface. One of the components in one of the components lists MUST have an 'id' of 'root' to serve as the root of the component tree. The createSurface message MUST have been previously sent for this surfaceId.")}).strict(),UpdateDataModelMessageSchema=objectType({version:literalType("v1.0"),updateDataModel:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface this data model update applies to. It must be globally unique for the renderer's lifetime."),path:stringType().describe("An optional path to a location within the data model (e.g., '/user/name'). If omitted, or set to '/', refers to the entire data model.").optional(),value:anyType().describe("The data to be updated in the data model. To delete the key/value at 'path', set 'value' explicitly to null.")}).strict().describe("Updates the data model for an existing surface. This message can be sent multiple times to update the data model. The createSurface message MUST have been previously sent for this surfaceId.")}).strict(),DeleteSurfaceMessageSchema=objectType({version:literalType("v1.0"),deleteSurface:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be deleted. It must be globally unique for the renderer's lifetime.")}).strict().describe("Signals the renderer to delete the surface identified by 'surfaceId'. The createSurface message MUST have been previously sent for this surfaceId.")}).strict(),CallRendererFunctionMessageSchema=objectType({version:literalType("v1.0"),callRendererFunction:objectType({functionCallId:CallIdSchema,callFunction:intersectionType(FunctionCallSchema$1,anyType())}).strict().describe("Signals the renderer to execute a function locally on behalf of the agent.")}).strict(),AgentFunctionResponseMessageSchema=objectType({version:literalType("v1.0"),agentFunctionResponse:FunctionResponseSchema}).strict(),AgentToRendererMessageSchema=unionType([CreateSurfaceMessageSchema,UpdateComponentsMessageSchema,UpdateDataModelMessageSchema,DeleteSurfaceMessageSchema,CallRendererFunctionMessageSchema,AgentFunctionResponseMessageSchema]);class V1Point0Adapter extends BaseVersionAdapter{constructor(){super(...arguments),this.version="v1.0",this.schema=AgentToRendererMessageSchema}getNativeActionKeys(){return[...INTERNAL_OPERATION_TYPES]}extractOperationsFromObject(lo){const $u=[];if("createSurface"in lo){const Ru=lo.createSurface;$u.push({type:"createSurface",surfaceId:String(Ru?.surfaceId||""),catalogId:typeof Ru?.catalogId=="string"?Ru.catalogId:void 0,sendDataModel:!!Ru?.sendDataModel,components:Array.isArray(Ru?.components)?Ru.components:void 0,dataModel:Ru?.dataModel&&typeof Ru.dataModel=="object"&&!Array.isArray(Ru.dataModel)?Ru.dataModel:void 0,version:typeof lo.version=="string"?lo.version:this.version})}if("updateComponents"in lo){const Ru=lo.updateComponents;$u.push({type:"updateComponents",surfaceId:String(Ru?.surfaceId||""),components:Array.isArray(Ru?.components)?Ru.components:[]})}if("updateDataModel"in lo){const Ru=lo.updateDataModel;$u.push({type:"updateDataModel",surfaceId:String(Ru?.surfaceId||""),path:typeof Ru?.path=="string"?Ru.path:void 0,value:Ru?.value})}if("deleteSurface"in lo){const Ru=lo.deleteSurface;$u.push({type:"deleteSurface",surfaceId:String(Ru?.surfaceId||"")})}if("callRendererFunction"in lo){const Ru=lo.callRendererFunction,Iu=Ru?.callFunction||{};$u.push({type:"callRendererFunction",functionCallId:String(Ru?.functionCallId||""),call:String(Iu?.call||""),version:this.version,catalogId:typeof Iu?.catalogId=="string"?Iu.catalogId:void 0,args:Iu?.args&&typeof Iu.args=="object"&&!Array.isArray(Iu.args)?Iu.args:{}})}if("agentFunctionResponse"in lo){const Ru=lo.agentFunctionResponse;$u.push({type:"agentFunctionResponse",functionCallId:String(Ru?.functionCallId||""),version:this.version,value:Ru?.value,error:Ru?.error&&typeof Ru.error=="object"?Ru.error:void 0})}return $u}}class VersionAdapterFactory{constructor(){this.adapters=new Map([["0.8",new V0Point8Adapter],["0.9",new V0Point9Adapter],["0.9.1",new V0Point9Adapter],["1.0",new V1Point0Adapter]])}getAllKnownActions(){const lo=new Set;for(const $u of this.adapters.values())if($u.validActions)for(const Ru of $u.validActions)lo.add(Ru);return lo}registerAdapter(lo){const $u=toCanonicalVersion(lo.version)??normalizeVersionString(lo.version);this.adapters.set($u,lo)}getAdapter(lo){const $u=toCanonicalVersion(lo)??normalizeVersionString(lo),Ru=this.adapters.get($u);if(!Ru){const Iu=Array.from(new Set(Array.from(this.adapters.keys()).map(Ou=>Ou.startsWith("v")?Ou:`v${Ou}`))).sort().join(", ");throw new A2uiValidationError(`[VersionAdapterFactory] Unsupported protocol version '${lo}'. Supported versions: ${Iu}.`)}return Ru}resolveFromPayload(lo){const $u=Array.isArray(lo)?lo[0]:lo;if(typeof $u=="object"&&$u!==null){if("messages"in $u&&Array.isArray($u.messages))return this.resolveFromPayload($u.messages);if("version"in $u){const Ru=$u.version;if(typeof Ru!="string")throw new A2uiValidationError(`[VersionAdapterFactory] Message payload is missing a valid 'version' string: 'version' property must be a string, got ${typeof Ru}.`);return this.getAdapter(Ru)}if("beginRendering"in $u||"surfaceUpdate"in $u||"dataModelUpdate"in $u||"deleteSurface"in $u)return this.getAdapter("v0.8")}throw new A2uiValidationError("[VersionAdapterFactory] Message payload is missing a valid 'version' string.")}static registerAdapter(lo){defaultVersionAdapterFactory.registerAdapter(lo)}static getAdapter(lo){return defaultVersionAdapterFactory.getAdapter(lo)}static resolveFromPayload(lo){return defaultVersionAdapterFactory.resolveFromPayload(lo)}static getAllKnownActions(){return defaultVersionAdapterFactory.getAllKnownActions()}}const defaultVersionAdapterFactory=new VersionAdapterFactory;registerKnownActionsProvider(()=>defaultVersionAdapterFactory.getAllKnownActions());const schemaKeysCache=new WeakMap;function getKnownSchemaKeys(Au){if(schemaKeysCache.has(Au))return schemaKeysCache.get(Au);const lo=(()=>{let $u=Au;for(;$u;){if($u instanceof ZodObject||$u._def?.typeName==="ZodObject"){if($u._def?.unknownKeys==="passthrough")return null;const Ru=typeof $u.shape=="function"?$u.shape():$u.shape;return Ru&&typeof Ru=="object"?new Set(Object.keys(Ru)):null}if($u instanceof ZodEffects||$u._def?.typeName==="ZodEffects"){$u=$u._def.schema;continue}if($u instanceof ZodOptional||$u instanceof ZodNullable||$u._def?.typeName==="ZodOptional"||$u._def?.typeName==="ZodNullable"){$u=$u._def.innerType;continue}if($u instanceof ZodDefault||$u._def?.typeName==="ZodDefault"){$u=$u._def.innerType;continue}if($u instanceof ZodCatch||$u._def?.typeName==="ZodCatch"){$u=$u._def.innerType;continue}if($u instanceof ZodIntersection||$u._def?.typeName==="ZodIntersection"){const Ru=getKnownSchemaKeys($u._def.left),Iu=getKnownSchemaKeys($u._def.right);return!Ru||!Iu?null:new Set([...Ru,...Iu])}if($u instanceof ZodUnion||$u._def?.typeName==="ZodUnion"){const Ru=$u._def.options,Iu=new Set;for(const Ou of Ru){const Pu=getKnownSchemaKeys(Ou);if(!Pu)return null;for(const Du of Pu)Iu.add(Du)}return Iu}return null}return null})();return schemaKeysCache.set(Au,lo),lo}function validateFunctionArgs(Au,lo,$u){if(!lo||typeof lo!="object"||Array.isArray(lo))return;const Ru=Object.keys(lo);if(Ru.length>MAX_FUNCTION_CALL_ARGS)throw new A2uiExpressionError(`Function call '${Au}' exceeds maximum allowed arguments count (${MAX_FUNCTION_CALL_ARGS})`,Au);const Iu=$u?.functions?.get?.(Au);if(!Iu?.schema)return;const Ou=getKnownSchemaKeys(Iu.schema);if(Ou){for(const Pu of Ru)if(!Ou.has(Pu))throw new A2uiExpressionError(`Unknown argument '${Pu}' passed to function '${Au}'`,Au);if(Ru.length>Ou.size)throw new A2uiExpressionError(`Too many arguments for function '${Au}': expected at most ${Ou.size}, received ${Ru.length}`,Au)}}function resolveContextIndex(Au){let lo=Au;for(;lo;){if(lo.explicitIndex!==void 0&&Number.isFinite(lo.explicitIndex))return lo.explicitIndex;if(!(lo instanceof DataContext)&&typeof lo.getIndex=="function"){const $u=lo.getIndex();if($u!==void 0&&Number.isFinite($u))return $u}if(!(lo instanceof DataContext)&&typeof lo.index=="number"&&Number.isFinite(lo.index))return lo.index;if(typeof lo.path=="string"){const $u=lo.path.split("/").filter(Boolean);if($u.length>0&&/^\d+$/.test($u[$u.length-1]))return parseInt($u[$u.length-1],10)}lo=lo.parent}}const MAX_DYNAMIC_VALUE_DEPTH=1e3;class DataContext{constructor(lo,$u,Ru,Iu){this.surface=lo,this.path=$u,this.dataModel=lo.dataModel,this.functionInvoker=lo.defaultCatalog.invoker,this.explicitIndex=Ru,this.parent=Iu,this.warnedPaths=Iu?Iu.warnedPaths:new Set}getIndex(){return resolveContextIndex(this)}get index(){return this.getIndex()}set(lo,$u){const Ru=this.resolvePath(lo);this.dataModel.set(Ru,$u)}static isDataBindingObject(lo){return"path"in lo&&typeof lo.path=="string"&&!("componentId"in lo)}static isFunctionCallObject(lo){return"call"in lo&&typeof lo.call=="string"}static containsDynamicValue(lo){if(lo===null||typeof lo!="object")return!1;if(Array.isArray(lo))return lo.some(Ru=>DataContext.containsDynamicValue(Ru));const $u=lo;return DataContext.isDataBindingObject($u)||DataContext.isFunctionCallObject($u)?!0:Object.values($u).some(Ru=>DataContext.containsDynamicValue(Ru))}emitMissingDataBindingWarning(lo){typeof this.dataModel?.hasPath=="function"&&!this.dataModel.hasPath(lo)&&!this.warnedPaths.has(lo)&&(this.warnedPaths.add(lo),this.surface?.dispatchWarning?.({code:"MISSING_DATA_BINDING",path:lo,message:`Preflight DataBinding Warning: The bound JSON Pointer '${lo}' does not physically exist in the active DataModel. Evaluating to None.`}))}resolveDynamicValue(lo,$u=0){if($u>MAX_DYNAMIC_VALUE_DEPTH){const Iu=new A2uiExpressionError(`Maximum dynamic value nesting depth exceeded (${MAX_DYNAMIC_VALUE_DEPTH})`);this.dispatchExpressionError(Iu,"DynamicValue");return}if(lo===null||typeof lo!="object")return lo;if(Array.isArray(lo))return DataContext.containsDynamicValue(lo)?lo.map(Iu=>this.resolveDynamicValue(Iu,$u+1)):lo;const Ru=lo;if(DataContext.isDataBindingObject(Ru)){const Iu=this.resolvePath(lo.path),Ou=this.dataModel.get(Iu);return Ou===void 0&&this.emitMissingDataBindingWarning(Iu),Ou}return DataContext.isFunctionCallObject(Ru)?this.resolveFunctionCallValue(lo,$u):this.resolvePlainObjectValue(Ru,$u)}resolveFunctionCallValue(lo,$u=0){let Ru;try{Ru=this.resolveFunctionCatalog(lo.catalogId),validateFunctionArgs(lo.call,lo.args,Ru)}catch(Du){this.dispatchExpressionError(Du,lo.call);return}const Iu={};for(const[Du,Lu]of Object.entries(lo.args??{}))Iu[Du]=this.resolveDynamicValue(Lu,$u+1);const Ou=new AbortController,Pu=this.evaluateFunctionReactive(lo.call,Iu,Ou.signal,lo.catalogId,Ru.invoker);if(Pu!==void 0)return isSignal(Pu)?peekValue(Pu):Pu}resolvePlainObjectValue(lo,$u=0){if(!DataContext.containsDynamicValue(lo))return lo;const Ru={};for(const[Iu,Ou]of Object.entries(lo))Ru[Iu]=this.resolveDynamicValue(Ou,$u+1);return Ru}subscribeDynamicValue(lo,$u){const Ru=this.resolveSignal(lo);let Iu=!0,Ou=peekValue(Ru);const Pu=effect(()=>{const Du=getValue(Ru);Ou=Du,Iu||$u(Du)});return Iu=!1,{get value(){return Ou},unsubscribe:()=>{Pu(),Ru.unsubscribe?.()}}}resolveSignal(lo,$u=0){if($u>MAX_DYNAMIC_VALUE_DEPTH){const Du=new A2uiExpressionError(`Maximum dynamic value nesting depth exceeded (${MAX_DYNAMIC_VALUE_DEPTH})`);return this.dispatchExpressionError(Du,typeof lo=="object"&&lo&&"call"in lo?lo.call:"DynamicValue"),signal(void 0)}if(typeof lo!="object"||lo===null)return signal(lo);if(Array.isArray(lo)){if(!DataContext.containsDynamicValue(lo))return signal(lo);const Du=lo.map(ju=>this.resolveSignal(ju,$u+1)),Lu=computed(()=>Du.map(ju=>getValue(ju)));return Lu.unsubscribe=()=>{for(const ju of Du)ju.unsubscribe?.()},Lu}const Ru=lo;if(DataContext.isDataBindingObject(Ru)){const Du=this.resolvePath(lo.path);return this.emitMissingDataBindingWarning(Du),this.dataModel.getSignal(Du)}if(DataContext.isFunctionCallObject(Ru)){const Du=lo;let Lu;try{Lu=this.resolveFunctionCatalog(Du.catalogId),validateFunctionArgs(Du.call,Du.args,Lu)}catch(Vu){return this.dispatchExpressionError(Vu,Du.call),signal(void 0)}const ju={};for(const[Vu,Gu]of Object.entries(Du.args??{}))ju[Vu]=this.resolveSignal(Gu,$u+1);if(Object.keys(ju).length===0){const Vu=new AbortController,Gu=this.evaluateFunctionReactive(Du.call,{},Vu.signal,Du.catalogId,Lu.invoker),Ku=isSignal(Gu)?Gu:signal(Gu);return Ku.unsubscribe=()=>Vu.abort(),Ku}const Bu=Object.keys(ju),Fu=signal(void 0);let zu,qu;const Uu=computed(()=>{const Vu={};for(let Gu=0;Gu<Bu.length;Gu++)Vu[Bu[Gu]]=getValue(ju[Bu[Gu]]);return Vu}),Hu=effect(()=>{try{const Vu=getValue(Uu);zu&&zu.abort(),qu&&(qu(),qu=void 0),zu=new AbortController;const Gu=this.evaluateFunctionReactive(Du.call,Vu,zu.signal,Du.catalogId,Lu.invoker);isSignal(Gu)?qu=effect(()=>{setValue(Fu,getValue(Gu))}):setValue(Fu,Gu)}catch(Vu){this.dispatchExpressionError(Vu,Du.call),setValue(Fu,void 0)}});return Fu.unsubscribe=()=>{Hu(),qu&&qu(),zu&&zu.abort();for(let Vu=0;Vu<Bu.length;Vu++)ju[Bu[Vu]].unsubscribe?.()},Fu}if(!DataContext.containsDynamicValue(Ru))return signal(lo);const Iu=Object.entries(Ru).map(([Du,Lu])=>[Du,this.resolveSignal(Lu)]),Ou=computed(()=>{const Du={};for(const[Lu,ju]of Iu)Du[Lu]=getValue(ju);return Du}),Pu=Ou.unsubscribe?.bind(Ou);return Ou.unsubscribe=()=>{Pu?.();for(const[,Du]of Iu)Du.unsubscribe?.()},Ou}resolveAction(lo){if("event"in lo){const $u={};if(lo.event.context)for(const[Ru,Iu]of Object.entries(lo.event.context))$u[Ru]=this.resolveDynamicValue(Iu);return{event:{...lo.event,context:$u}}}return"functionCall"in lo?this.resolveDynamicValue(lo.functionCall):lo}resolveFunctionCatalog(lo){if(lo===void 0)return this.surface.defaultCatalog;const $u=this.surface.availableCatalogs?.get(lo);if(!$u)throw new A2uiCatalogError(`Catalog not found: ${lo}`);return $u}evaluateFunctionReactive(lo,$u,Ru,Iu,Ou){const Pu=Ou??(Iu===void 0?this.functionInvoker:this.resolveFunctionCatalog(Iu).invoker);try{return Pu(lo,$u,this,Ru)}catch(Du){this.dispatchExpressionError(Du,lo);return}}dispatchExpressionError(lo,$u){if(lo instanceof ZodError||typeof lo=="object"&&lo!==null&&lo.name==="ZodError"){const Ru=lo,Iu=new A2uiExpressionError(`Validation failed for function '${$u}': ${Ru.message}`,$u,Ru.errors??Ru.issues);this.surface.dispatchError({code:"EXPRESSION_ERROR",message:Iu.message,expression:$u,details:Iu.details})}else if(lo instanceof A2uiExpressionError)this.surface.dispatchError({code:"EXPRESSION_ERROR",message:lo.message,expression:lo.expression,details:lo.details});else{const Ru=typeof lo=="object"&&lo!==null?lo:{};this.surface.dispatchError({code:"EXPRESSION_ERROR",message:Ru.message??`An unexpected error occurred in function ${$u}.`,expression:$u})}}nested(lo,$u){const Ru=this.resolvePath(lo);return new DataContext(this.surface,Ru,$u,this)}resolvePath(lo){if(lo.startsWith("/"))return lo;if(lo===""||lo===".")return this.path;let $u=this.path;return $u.endsWith("/")&&$u.length>1&&($u=$u.slice(0,-1)),$u==="/"&&($u=""),`${$u}/${lo}`}}const IndexApi={name:"@index",returnType:"number",allowedCallers:"rendererOnly",schema:objectType({offset:coerce.number().optional()})};createFunctionImplementation(IndexApi,(Au,lo)=>{const $u=typeof Au.offset=="number"&&Number.isFinite(Au.offset)?Au.offset:0,Ru=resolveContextIndex(lo);if(Ru===void 0||!Number.isFinite(Ru))throw new A2uiValidationError("@index function can only be evaluated inside a collection template iteration scope.");return Ru+$u});const COMPONENT_ENVELOPE_KEYS=["id","component","catalogId","catalogID"];class PayloadValidator{constructor(lo,$u){this.catalog=lo,this.config=$u,this.enforceIdentifiers=isAtLeastVersion(lo.protocolVersion,"1.0")}get allowUnknown(){return this.config?this.config.allowUnknownElements??!1:!0}validateComponent(lo,$u){const Ru=lo.id;if(typeof Ru!="string"||!Ru)throw new A2uiValidationError(`Component '${lo.component}' is missing an 'id'; entries require a valid string 'id'.`);this.assertIdentifier(Ru,`Component id '${Ru}' must be a valid UAX #31 identifier`);const Iu=lo.component,Ou=typeof Iu=="string"?Iu:$u;if(!Ou)throw new A2uiValidationError(`Cannot create component ${Ru} without a type.`);const Pu=this.catalog.components.get(Ou);if(!Pu){if(!this.allowUnknown)throw new A2uiValidationError(`Unknown component type '${Ou}' not found in catalog '${this.catalog.id}'.`);return}const Du=stripEnvelopeKeys(lo),Lu=Pu.schema.safeParse(Du);if(!Lu.success){const ju=Lu.error.errors.map(formatZodIssue).join(", ");throw new A2uiValidationError(`Validation failed for component '${Ou}' (${Ru}): ${ju}`,Lu.error.issues)}this.validateNestedFunctions(Du)}assertFunctionIdentifiers(lo,$u){if(this.assertIdentifier(lo,`Function name '${lo}' must be a valid UAX #31 identifier`),$u&&typeof $u=="object"&&!Array.isArray($u)){const Ru=Object.keys($u);if(Ru.length>MAX_FUNCTION_CALL_ARGS)throw new A2uiValidationError(`Function call '${lo}' exceeds maximum allowed arguments count (${MAX_FUNCTION_CALL_ARGS})`);for(const Iu of Ru)this.assertIdentifier(Iu,`Function argument '${Iu}' in function '${lo}' must be a valid UAX #31 identifier`)}}validateNestedFunctions(lo){if(Array.isArray(lo)){for(const Iu of lo)this.validateNestedFunctions(Iu);return}if(typeof lo!="object"||lo===null)return;const $u=lo,Ru=$u.call??$u.function;if(typeof Ru=="string"&&Ru.length>0){const Iu=$u.args,Ou=Iu!==void 0?Iu:{},Pu=typeof $u.catalogId=="string"&&$u.catalogId.length>0?$u.catalogId:void 0;Pu&&Pu!==this.catalog.id?this.assertFunctionIdentifiers(Ru,Ou):this.validateFunction(Ru,Ou)}for(const[Iu,Ou]of Object.entries($u))Iu!=="id"&&Iu!=="component"&&this.validateNestedFunctions(Ou)}validateFunction(lo,$u){this.assertFunctionIdentifiers(lo,$u);const Ru=this.catalog.functions.get(lo)??(this.enforceIdentifiers&&lo==="@index"?IndexApi:void 0);if(!Ru){if(!this.allowUnknown)throw new A2uiValidationError(`Unrecognized function '${lo}'`);return $u??{}}if(!Ru.schema){if($u!==void 0&&(typeof $u!="object"||$u===null||Array.isArray($u)))throw new A2uiValidationError(`Validation failed for function '${lo}': Expected object, received ${Array.isArray($u)?"array":typeof $u}`);return $u??{}}const Iu=Ru.schema.safeParse($u??{});if(!Iu.success){const Ou=Iu.error.errors.map(formatZodIssue).join(", ");throw new A2uiValidationError(`Validation failed for function '${lo}': ${Ou}`,Iu.error.issues)}return Iu.data}validateTheme(lo){const $u=this.catalog.themeSchema;if(!$u)return lo;const Ru=$u.safeParse(lo);if(!Ru.success){const Iu=Ru.error.errors.map(formatZodIssue).join(", ");throw new A2uiValidationError(`Validation failed for theme: ${Iu}`,Ru.error.issues)}return Ru.data}assertIdentifier(lo,$u){if(this.enforceIdentifiers&&!isValidUax31Identifier(lo))throw new A2uiValidationError($u)}}function stripEnvelopeKeys(Au){const lo={};for(const[$u,Ru]of Object.entries(Au))COMPONENT_ENVELOPE_KEYS.includes($u)||(lo[$u]=Ru);return lo}class RpcHandler{constructor(lo,$u){if(this.pendingAgentCalls=new Map,this.isDisposed=!1,Array.isArray(lo))this.catalogs=lo,this.outboundListener=$u,this.defaultTimeoutMs=3e4;else{const Ru=lo??{};this.catalogs=Ru.catalogs??[],this.outboundListener=Ru.outboundListener,this.defaultTimeoutMs=Ru.defaultTimeoutMs??3e4}}get disposed(){return this.isDisposed}async handleCallRendererFunction(lo,$u,Ru=!1){const Iu=this.validateInboundMessage(lo);if(Iu)return await this.emitOutboundResponse(Iu),Iu;const{version:Ou,callRendererFunction:Pu}=lo,{functionCallId:Du,callFunction:Lu}=Pu,{call:ju,catalogId:Bu,args:Fu}=Lu,zu=this.resolveFunctionImplementation(Bu,ju,$u,Ou);if("error"in zu){const Vu=this.createResponseError(Du,RpcErrorCode.INVALID_FUNCTION_CALL,zu.error,Ou);return await this.emitOutboundResponse(Vu),Vu}const qu=this.checkExecutionPermissions(zu.funcImpl,ju,Ru);if(qu){const Vu=this.createResponseError(Du,RpcErrorCode.INVALID_FUNCTION_CALL,qu,Ou);return await this.emitOutboundResponse(Vu),Vu}const Uu=this.parseArguments(zu.catalog,zu.funcImpl,Fu,ju);if("error"in Uu){const Vu=this.createResponseError(Du,RpcErrorCode.INVALID_FUNCTION_CALL,Uu.error,Ou);return await this.emitOutboundResponse(Vu),Vu}const Hu=await this.executeFunctionSafely(zu.funcImpl,Uu.args,$u,Du,Ou);return await this.emitOutboundResponse(Hu),Hu}handleAgentFunctionResponse(lo){if(!lo||!lo.agentFunctionResponse)return;const{functionCallId:$u,value:Ru,error:Iu}=lo.agentFunctionResponse,Ou=this.pendingAgentCalls.get($u);if(Ou)if(this.pendingAgentCalls.delete($u),Iu){const Pu=Iu.code??RpcErrorCode.UNKNOWN_ERROR,Du=Iu.message??"Agent function execution failed";Ou.reject(new A2uiRpcError(Du,Pu,$u,Iu))}else Ou.resolve(Ru)}callAgentFunction(lo,$u,Ru){if(this.isDisposed)return Promise.reject(new A2uiRpcError("RpcHandler has been disposed.",RpcErrorCode.DISPOSED));if(!this.outboundListener)return Promise.reject(new A2uiRpcError("Cannot call agent function without outboundListener configured.",RpcErrorCode.NO_LISTENER));if(!$u||!$u.call)return Promise.reject(new A2uiRpcError("Missing or invalid function call name.",RpcErrorCode.INVALID_FUNCTION_CALL));const Iu=Ru??{},Ou=Iu.functionCallId??this.generateFunctionCallId(),Pu=Iu.timeoutMs??this.defaultTimeoutMs;if(this.pendingAgentCalls.has(Ou))return Promise.reject(new A2uiRpcError(`A call with functionCallId '${Ou}' is already pending.`,RpcErrorCode.DUPLICATE,Ou));const Du={functionCallId:Ou,call:$u,effectiveTimeoutMs:Pu,version:Iu.version};return this.dispatchAgentCall(lo,Du)}dispose(){if(!this.isDisposed){this.isDisposed=!0;for(const[lo,$u]of this.pendingAgentCalls.entries())$u.reject(new A2uiRpcError(`RpcHandler disposed while call '${lo}' was pending.`,RpcErrorCode.CANCELLED,lo));this.pendingAgentCalls.clear()}}async emitOutboundResponse(lo){if(this.outboundListener)try{const $u=this.outboundListener(lo);$u&&typeof $u.catch=="function"&&await $u}catch{}}validateInboundMessage(lo){if(!lo)return this.createResponseError("unknown",RpcErrorCode.INVALID_FUNCTION_CALL,"Inbound message is null or undefined.","unknown");const $u=lo.version;return this.isDisposed?this.createResponseError(lo.callRendererFunction?.functionCallId??"unknown",RpcErrorCode.DISPOSED,"RpcHandler has been disposed.",$u):lo.callRendererFunction?.callFunction?null:this.createResponseError(lo.callRendererFunction?.functionCallId??"unknown",RpcErrorCode.INVALID_FUNCTION_CALL,"Malformed message: missing callRendererFunction or callFunction.",$u)}resolveFunctionImplementation(lo,$u,Ru,Iu){let Ou;if(lo){if(Ou=this.catalogs.find(Du=>Du.id===lo),!Ou)return{error:`Catalog not found: ${lo}`}}else Ru?.surface?.defaultCatalog&&(Ou=Ru.surface.defaultCatalog);if(!Ou)return{error:"No catalog available for function resolution."};if(Ou.protocolVersion&&Iu&&!isCatalogVersionCompatible(Ou.protocolVersion,Iu))return{error:`Catalog '${Ou.id}' specification version (${Ou.protocolVersion}) does not match message protocol version (${Iu}).`};const Pu=Ou.functions?.get($u);return Pu?{funcImpl:Pu,catalog:Ou}:{error:`Function not found: ${$u}`}}checkExecutionPermissions(lo,$u,Ru){const Iu=lo.allowedCallers??"rendererOnly";return Iu==="rendererOrAgent"||Iu==="agentOnly"?lo.requiresUserActivation&&!Ru?`Function '${$u}' requires user activation context to execute.`:null:`Function '${$u}' cannot be called by agent (allowedCallers is ${Iu}).`}parseArguments(lo,$u,Ru,Iu){try{return{args:new PayloadValidator(lo,{allowUnknownElements:!1}).validateFunction(Iu,Ru)}}catch(Ou){const Pu=this.extractErrorMessage(Ou);return{error:`Invalid function arguments for '${Iu}': ${Pu}`}}}async executeFunctionSafely(lo,$u,Ru,Iu,Ou){const Pu=Ou||"v1.0";try{const Du=await Promise.resolve(lo.execute($u,Ru)),Lu=isSignal(Du)?getValue(Du):Du;return{version:Pu,rendererFunctionResponse:{functionCallId:Iu,value:Lu!==void 0?Lu:null}}}catch(Du){const Lu=this.extractErrorMessage(Du);return{version:Pu,rendererFunctionResponse:{functionCallId:Iu,error:{code:RpcErrorCode.EXECUTION_ERROR,message:Lu||"An error occurred during function execution."}}}}}generateFunctionCallId(){if(typeof globalThis.crypto?.randomUUID=="function")return globalThis.crypto.randomUUID();const lo=Math.random().toString(36).substring(2,15).padEnd(13,"0");return`call-${Date.now()}-${lo}`}dispatchAgentCall(lo,$u){const{functionCallId:Ru,call:Iu,effectiveTimeoutMs:Ou,version:Pu}=$u;return new Promise((Du,Lu)=>{let ju;const Bu=()=>{ju&&(clearTimeout(ju),ju=void 0),this.pendingAgentCalls.delete(Ru)};ju=this.createTimeoutTimer(Ru,Iu.call,Ou,Bu,Lu),this.pendingAgentCalls.set(Ru,{resolve:Fu=>{Bu(),Du(Fu)},reject:Fu=>{Bu(),Lu(Fu)}}),this.sendOutboundMessage(lo,Ru,Iu,Pu,Bu,Lu)})}createTimeoutTimer(lo,$u,Ru,Iu,Ou){if(!(Ru<=0))return setTimeout(()=>{this.pendingAgentCalls.delete(lo)&&(Iu(),Ou(new A2uiRpcError(`Agent function call '${$u}' timed out after ${Ru}ms.`,RpcErrorCode.TIMEOUT,lo)))},Ru)}sendOutboundMessage(lo,$u,Ru,Iu,Ou,Pu){const Du={version:Iu||"v1.0",callAgentFunction:{surfaceId:lo,functionCallId:$u,callFunction:Ru}};try{const Lu=this.outboundListener(Du);Lu&&typeof Lu.catch=="function"&&Lu.catch(ju=>{Ou(),Pu(ju)})}catch(Lu){Ou(),Pu(Lu)}}extractErrorMessage(lo){return lo instanceof Error?lo.message:String(lo)}createResponseError(lo,$u,Ru,Iu){return{version:Iu||"v1.0",rendererFunctionResponse:{functionCallId:lo,error:{code:$u,message:Ru}}}}}class MessageProcessor{constructor(lo,$u,Ru){this.catalogs=lo,this.actionHandler=$u,this.model=new SurfaceGroupModel,this.adapterRegistry=Ru?.adapterRegistry??defaultVersionAdapterFactory,this.rpc=new RpcHandler({catalogs:this.catalogs,outboundListener:Ru?.outboundListener,defaultTimeoutMs:Ru?.defaultTimeoutMs}),Ru?.validationConfig?this.validationConfig={allowOrphanComponents:!1,allowDanglingReferences:!1,allowMissingRoot:!1,allowUnknownElements:!1,...Ru.validationConfig}:this.validationConfig=void 0,this.actionHandler&&this.model.onAction.subscribe(this.actionHandler)}callAgentFunction(lo,$u,Ru){return this.rpc.callAgentFunction(lo,$u,Ru)}dispose(){this.rpc.dispose()}getRendererCapabilities(lo){if(!lo?.versions||lo.versions.length===0)throw new A2uiValidationError("At least one protocol version must be provided in CapabilitiesOptions to generate renderer capabilities.");const $u=lo.versions,Ru={};for(const Iu of $u){const Ou={supportedCatalogIds:this.catalogs.map(Du=>Du.id)},Pu=lo?.includeInlineCatalogs?this.catalogs.map(Du=>compareSemVer(Iu,"1.0")>=0?generateCatalogSchema(Du,{componentEnvelopeRef:lo?.componentEnvelopeRef,protocolVersion:Iu}):this.generateLegacyInlineCatalog(Du,lo?.componentEnvelopeRef??"common_types.json#/$defs/ComponentCommon")):void 0;Pu&&(Ou.inlineCatalogs=Pu),Ru[Iu]=Ou}return Ru}getClientCapabilities(lo){return this.getRendererCapabilities(lo)}generateLegacyInlineCatalog(lo,$u="common_types.json#/$defs/ComponentCommon"){const Ru=generateCatalogSchema(lo,{componentEnvelopeRef:$u}),Iu=Ru.components||{},Ou=Ru.functions,Pu=[];for(const ju of lo.functions.values()){const Bu=Ou?.[ju.name];Pu.push({name:ju.name,description:ju.description,returnType:ju.returnType,parameters:Bu?.properties?.args??{type:"object",properties:{}}})}const Lu=Ru.$defs?.theme?.properties;return{catalogId:lo.id,components:Iu,...Pu.length>0?{functions:Pu}:{},...Lu?{theme:Lu}:{}}}getRendererDataModel(lo){const $u=Array.from(this.model.surfacesMap.values()).filter(Pu=>Pu.sendDataModel);if($u.length===0)return;if(lo!==void 0){const Pu={};for(const Du of $u){const Lu=Du.defaultCatalog?.protocolVersion;(!Lu||isCatalogVersionCompatible(Lu,lo))&&(Pu[Du.id]=Du.dataModel.get("/"))}return Object.keys(Pu).length===0?void 0:{version:lo,surfaces:Pu}}const Ru=new Set;for(const Pu of $u)if(Pu.defaultCatalog?.protocolVersion){const Du=toCanonicalVersion(Pu.defaultCatalog.protocolVersion),Lu=Du?`v${Du}`:Pu.defaultCatalog.protocolVersion;Ru.add(Lu)}if(Ru.size>1)throw new A2uiValidationError(`Multiple protocol versions detected among active surfaces: ${Array.from(Ru).sort().join(", ")}. Specify a target protocol version in getRendererDataModel(version).`);const Iu=Ru.size===1?Ru.values().next().value:"v1.0",Ou={};for(const Pu of $u)Ou[Pu.id]=Pu.dataModel.get("/");return{version:Iu,surfaces:Ou}}getClientDataModel(lo){return this.getRendererDataModel(lo)}resolvePath(lo,$u){return DataModel.resolvePath(lo,$u)}getSurfaces(){return this.model.surfacesMap}getSurface(lo){return this.model.getSurface(lo)}onSurfaceCreated(lo){return this.model.onSurfaceCreated.subscribe(lo)}onSurfaceDeleted(lo){return this.model.onSurfaceDeleted.subscribe(lo)}processMessages(lo,$u){const Ru=this.prepareOperations(lo);for(const Iu of Ru)this.processOperation(Iu,$u)}async processMessagesAsync(lo,$u){const Ru=this.prepareOperations(lo),Iu=[];for(const Ou of Ru){const Pu=await this.processOperationAsync(Ou,$u);Pu&&Iu.push(Pu)}return Iu}prepareOperations(lo){return!lo||Array.isArray(lo)&&lo.length===0?[]:(this.validationConfig&&validateRecursionAndPaths(lo),this.validationConfig?.targetVersion&&this.validateTargetVersion(lo),isInternalOperation(lo)?[lo]:this.adapterRegistry.resolveFromPayload(lo).extractOperations(lo))}validateTargetVersion(lo){const $u=this.validationConfig?.targetVersion;if(!$u)return;const Ru=Iu=>{if(typeof Iu=="object"&&Iu!==null&&"version"in Iu){const Ou=Iu.version;if(Ou){const Pu=toCanonicalVersion(Ou)??Ou,Du=toCanonicalVersion($u)??$u;if(Pu!==Du)throw new A2uiValidationError(`Message version '${Ou}' does not match expected target version '${$u}'`)}}};if(Array.isArray(lo))for(const Iu of lo)Ru(Iu);else Ru(lo)}applyStateOperation(lo){if(this.validationConfig?.allowedMessages&&!this.validationConfig.allowedMessages.includes(lo.type))throw new A2uiValidationError(`Operation '${lo.type}' is not permitted by ValidationConfig.allowedMessages`);switch(lo.type){case"createSurface":this.processCreateSurfaceOp(lo);break;case"deleteSurface":this.processDeleteSurfaceOp(lo);break;case"updateComponents":this.processUpdateComponentsOp(lo);break;case"updateDataModel":this.processUpdateDataModelOp(lo);break;case"agentFunctionResponse":this.rpc.handleAgentFunctionResponse({version:lo.version??"v1.0",agentFunctionResponse:{functionCallId:lo.functionCallId,value:lo.value,error:lo.error}});break}}resolveRpcDataContext(lo){const $u=(lo.catalogId?this.catalogs.find(Pu=>Pu.id===lo.catalogId):void 0)??this.catalogs[0],Ru=(lo.catalogId?Array.from(this.model.surfacesMap.values()).find(Pu=>Pu.defaultCatalog?.id===lo.catalogId||Pu.availableCatalogs?.has(lo.catalogId)):void 0)??this.model.surfacesMap.values().next().value;if(Ru)return new DataContext(Ru,"/");const Iu=`_rpc_fallback_${lo.functionCallId||"default"}`,Ou=new Map;for(const Pu of this.catalogs)$u?.protocolVersion&&Pu.protocolVersion&&isCatalogVersionCompatible($u.protocolVersion,Pu.protocolVersion)&&Ou.set(Pu.id,Pu);return $u&&Ou.set($u.id,$u),new DataContext(new SurfaceModel(Iu,$u,Ou),"/")}processOperation(lo,$u){if(lo.type==="callRendererFunction"){const Ru=this.resolveRpcDataContext(lo),Iu=$u?.isUserActivated??lo.isUserActivated??!1,Ou={version:lo.version??"v1.0",callRendererFunction:{functionCallId:lo.functionCallId,callFunction:{call:lo.call,catalogId:lo.catalogId,args:lo.args}}};this.rpc.handleCallRendererFunction(Ou,Ru,Iu).catch(Pu=>{console.error(`Unhandled error in callRendererFunction (${lo.call}):`,Pu)});return}this.applyStateOperation(lo)}async processOperationAsync(lo,$u){if(lo.type==="callRendererFunction"){const Ru=this.resolveRpcDataContext(lo),Iu=$u?.isUserActivated??lo.isUserActivated??!1,Ou={version:lo.version??"v1.0",callRendererFunction:{functionCallId:lo.functionCallId,callFunction:{call:lo.call,catalogId:lo.catalogId,args:lo.args}}};return await this.rpc.handleCallRendererFunction(Ou,Ru,Iu)}return this.applyStateOperation(lo),null}processCreateSurfaceOp(lo){const{surfaceId:$u,catalogId:Ru,theme:Iu,sendDataModel:Ou,components:Pu,dataModel:Du}=lo,Lu=Ru!==void 0?this.catalogs.find(qu=>qu.id===Ru):this.catalogs[0];if(!Lu)throw new A2uiStateError(`Catalog not found: ${Ru}`);const ju=lo.version;if(Lu.protocolVersion&&ju&&!isCatalogVersionCompatible(Lu.protocolVersion,ju))throw new A2uiValidationError(`Surface '${$u}' catalog '${Ru??Lu.id}' specification version (${Lu.protocolVersion}) does not match message protocol version (${ju}).`);if(this.model.getSurface($u))throw new A2uiStateError(`Surface ${$u} already exists.`);let Bu=Iu;if(Iu&&Lu.themeSchema)try{Bu=new PayloadValidator(Lu,this.validationConfig).validateTheme(Iu)}catch(qu){throw qu instanceof A2uiValidationError?new A2uiValidationError(qu.message.replace(/^Validation failed for theme:/,`Validation failed for theme on surface '${$u}':`),qu.details):qu}const Fu=new Map(this.catalogs.filter(qu=>isCatalogVersionCompatible(qu.protocolVersion,Lu.protocolVersion)).map(qu=>[qu.id,qu])),zu=new SurfaceModel($u,Lu,Fu,Bu,Ou??!1,void 0,lo.rootId??"root");this.model.addSurface(zu),Du&&zu.dataModel.set("/",Du),Pu&&Pu.length>0&&this.processUpdateComponentsOp({type:"updateComponents",surfaceId:$u,components:Pu})}processDeleteSurfaceOp(lo){lo.surfaceId&&this.model.deleteSurface(lo.surfaceId)}validateComponentProperties(lo,$u){const{id:Ru,component:Iu}=lo,Ou=lo.catalogId??lo.catalogID;if(typeof Ru!="string"||!Ru)throw new A2uiValidationError(`Component '${Iu}' is missing an 'id'; entries require a valid string 'id'.`);let Pu=$u.defaultCatalog;if(typeof Ou=="string"&&Ou){const Lu=$u.availableCatalogs.get(Ou);if(!Lu){const ju=this.catalogs.find(Bu=>Bu.id===Ou);throw ju?new A2uiValidationError(`Component '${Ru}' catalog '${Ou}' specification version (${ju.protocolVersion}) does not match surface default catalog version (${$u.defaultCatalog.protocolVersion}).`):new A2uiValidationError(`Unknown catalog ID '${Ou}' for component '${Ru}'. Available catalogs: ${this.catalogs.map(Bu=>Bu.id).join(", ")}`)}Pu=Lu}const Du=$u.componentsModel.get(Ru);new PayloadValidator(Pu,this.validationConfig).validateComponent(lo,Du?.type)}applyComponentUpdate(lo,$u){const{id:Ru,component:Iu,...Ou}=lo;if(typeof Ru!="string")return;const Pu=lo.catalogId??lo.catalogID,Du=$u.componentsModel.get(Ru);let Lu=$u.defaultCatalog;if(typeof Pu=="string"&&Pu){const ju=$u.availableCatalogs.get(Pu);ju&&(Lu=ju)}if(Du){const ju=typeof Iu=="string"?Iu:Du.type;if(ju!==Du.type||Pu&&Du.catalog?.id!==Lu.id){$u.componentsModel.removeComponent(Ru);const Bu=new ComponentModel(Ru,ju,Ou,Lu);$u.componentsModel.addComponent(Bu)}else Du.properties=Ou}else{if(typeof Iu!="string"||!Iu)throw new A2uiValidationError(`Cannot create component ${Ru} without a type.`);const ju=new ComponentModel(Ru,Iu,Ou,Lu);$u.componentsModel.addComponent(ju)}}processUpdateComponentsOp(lo){if(!lo.surfaceId)return;const $u=this.model.getSurface(lo.surfaceId);if(!$u)throw new A2uiStateError(`Surface not found for message: ${lo.surfaceId}`);for(const Ru of lo.components)this.validateComponentProperties(Ru,$u);this.validateCompositionConstraints($u,lo.components),this.validateCandidateTopology($u,lo.components);for(const Ru of lo.components)this.applyComponentUpdate(Ru,$u)}processUpdateDataModelOp(lo){if(!lo.surfaceId)return;const $u=this.model.getSurface(lo.surfaceId);if(!$u)throw new A2uiStateError(`Surface not found for message: ${lo.surfaceId}`);const Ru=lo.path||"/",Iu=lo.value;$u.dataModel.set(Ru,Iu)}validateParentConstraints(lo,$u,Ru,Iu){if(!Iu||Iu.length===0){if((lo==="root"||this.validationConfig&&this.validationConfig.allowOrphanComponents===!1)&&!Ru.includes("Surface"))throw new A2uiValidationError(`Component '${lo}' (${$u}) cannot be placed under parent 'Surface' (Surface). Allowed parents: ${JSON.stringify(Ru)}.`,void 0,"UNALLOWED_PARENT");return}for(const Ou of Iu)if(!Ru.includes(Ou.parentType))throw new A2uiValidationError(`Component '${lo}' (${$u}) cannot be placed under parent '${Ou.parentId}' (${Ou.parentType||"unknown"}). Allowed parents: ${JSON.stringify(Ru)}.`,void 0,"UNALLOWED_PARENT")}validateChildConstraints(lo,$u,Ru,Iu,Ou){for(const Pu of Iu){const Du=Ou.get(Pu);if(Du&&!Ru.includes(Du))throw new A2uiValidationError(`Container '${lo}' (${$u}) cannot contain child '${Pu}' (${Du}). Allowed children: ${JSON.stringify(Ru)}.`,void 0,"UNALLOWED_CHILD")}}buildCompositionTopology(lo,$u){const Ru=new Map,Iu=new Map,Ou=new Map;for(const[Du,Lu]of lo.componentsModel.entries){Ru.set(Du,Lu.type),Lu.catalog&&Iu.set(Du,Lu.catalog);const ju=lo.componentsModel.getChildIds(Du);ju.length>0&&Ou.set(Du,ju)}for(const Du of $u){const{id:Lu,component:ju,...Bu}=Du;if(typeof Lu!="string")continue;let Fu=lo.defaultCatalog;const zu=Du.catalogId??Du.catalogID;if(typeof zu=="string"&&zu){const Gu=lo.availableCatalogs.get(zu);Gu&&(Fu=Gu,Iu.set(Lu,Gu))}const qu=lo.componentsModel.get(Lu),Uu=(typeof ju=="string"?ju:qu?.type)??"";Uu&&Ru.set(Lu,Uu);const Hu={id:Lu,component:Uu,...Bu},Vu=Array.from(getComponentReferences(Hu,Fu)).map(([Gu])=>Gu);Vu.length>0?Ou.set(Lu,Vu):Ou.delete(Lu)}const Pu=new Map;for(const[Du,Lu]of Ou.entries()){const ju=Ru.get(Du)||"Unknown";for(const Bu of Lu){const Fu=Pu.get(Bu)??[];Fu.push({parentId:Du,parentType:ju}),Pu.set(Bu,Fu)}}return{typeMap:Ru,compCatalogMap:Iu,childMap:Ou,parentMap:Pu}}validateCompositionConstraints(lo,$u){const{typeMap:Ru,compCatalogMap:Iu,childMap:Ou,parentMap:Pu}=this.buildCompositionTopology(lo,$u);for(const[Du,Lu]of Ru.entries()){const Bu=(Iu.get(Du)??lo.defaultCatalog).components.get(Lu);Bu&&(Bu.allowedParents&&Bu.allowedParents.length>0&&this.validateParentConstraints(Du,Lu,Bu.allowedParents,Pu.get(Du)),Bu.allowedChildren&&Bu.allowedChildren.length>0&&this.validateChildConstraints(Du,Lu,Bu.allowedChildren,Ou.get(Du)||[],Ru))}}validateCandidateTopology(lo,$u){if(!this.validationConfig)return;const Ru=new SurfaceComponentsModel(lo.defaultCatalog);for(const[Iu,Ou]of lo.componentsModel.entries)Ru.addComponent(new ComponentModel(Iu,Ou.type,Ou.properties,Ou.catalog));for(const Iu of $u){const{id:Ou,component:Pu,...Du}=Iu;if(typeof Ou!="string"||!Ou)continue;const Lu=Iu.catalogId??Iu.catalogID;let ju=lo.defaultCatalog;if(typeof Lu=="string"&&Lu){const zu=lo.availableCatalogs.get(Lu);zu&&(ju=zu)}const Bu=Ru.get(Ou),Fu=(typeof Pu=="string"?Pu:Bu?.type)||"";Fu&&(Bu?Fu!==Bu.type||Lu&&Bu.catalog?.id!==ju.id?(Ru.removeComponent(Ou),Ru.addComponent(new ComponentModel(Ou,Fu,Du,ju))):Bu.properties=Du:Ru.addComponent(new ComponentModel(Ou,Fu,Du,ju)))}Ru.validateTopology({...this.validationConfig,rootId:this.validationConfig.rootId??lo.rootId})}}class ComponentContext{constructor(lo,$u,Ru="/",Iu,Ou){const Pu=lo.componentsModel.get($u);if(!Pu)throw new A2uiStateError(`Component not found: ${$u}`);this.componentModel=Pu,this.surfaceComponents=lo.componentsModel,this.theme=lo.theme,this.dataContext=new DataContext(lo,Ru,Ou,Iu),this._actionDispatcher=Du=>lo.dispatchAction(Du,this.componentModel.id)}dispatchAction(lo){return this._actionDispatcher(lo)}}function scrapeSchemaBehavior(Au){return getFieldBehavior(Au)}function unwrapZodSchema(Au){let lo=Au;for(;lo;){const $u=lo._def?.typeName;if($u==="ZodOptional"||$u==="ZodNullable"||$u==="ZodDefault"||$u==="ZodReadonly")lo=lo._def.innerType;else if($u==="ZodEffects")lo=lo._def.schema;else if($u==="ZodBranded")lo=lo._def.type;else if($u==="ZodLazy")lo=lo._def.getter();else break}return lo}function getRefDefName(Au){let lo=Au,$u="";for(;lo&&($u=lo.description??lo._def?.description??"",!$u);){const Iu=lo._def?.typeName;if(Iu==="ZodOptional"||Iu==="ZodNullable"||Iu==="ZodDefault"||Iu==="ZodReadonly")lo=lo._def.innerType;else if(Iu==="ZodEffects")lo=lo._def.schema;else if(Iu==="ZodBranded")lo=lo._def.type;else if(Iu==="ZodLazy")lo=lo._def.getter();else break}if(!$u||!$u.startsWith("REF:"))return"";const Ru=$u.slice(4);return extractRefDefName(Ru.split("|")[0])}function isCheckableField(Au){const lo=getRefDefName(Au);if(lo==="Checkable"||lo==="CheckRule")return!0;const $u=unwrapZodSchema(Au);if($u?._def?.typeName==="ZodArray"){const Ru=$u._def.type;if(getRefDefName(Ru)==="CheckRule")return!0}return!1}function isActionOption(Au){if(getRefDefName(Au)==="Action")return!0;const $u=unwrapZodSchema(Au)._def;return $u?.typeName==="ZodObject"&&!!$u.shape?.().event}function isDynamicOption(Au){const lo=getRefDefName(Au);if(lo==="DataBinding"||lo.startsWith("Dynamic"))return!0;const Ru=unwrapZodSchema(Au)._def;if(Ru?.typeName!=="ZodObject")return!1;const Iu=Ru.shape?.()||{},Ou=Object.values(Iu).some(Pu=>getRefDefName(Pu)==="ComponentId");return!!Iu.path&&!Ou}function isChildListOption(Au){if(childRefKindOf(Au)==="child-list"||getRefDefName(Au)==="ChildList")return!0;const $u=unwrapZodSchema(Au)._def;if($u?.typeName!=="ZodObject")return!1;const Ru=$u.shape?.()||{};return Object.values(Ru).some(Iu=>getRefDefName(Iu)==="ComponentId")}function isDynamicDef(Au,lo){return(Au==="DataBinding"||Au.startsWith("Dynamic"))&&lo!=="ZodObject"&&lo!=="ZodArray"}function matchUnionBehavior(Au){if(Au.some(isActionOption))return{type:"ACTION"};if(Au.some(isDynamicOption))return{type:"DYNAMIC"};if(Au.some(isChildListOption))return{type:"STRUCTURAL"}}function scrapeObjectShape(Au){const lo={};for(const[$u,Ru]of Object.entries(Au))lo[$u]=getFieldBehavior(Ru);return lo}function getFieldBehavior(Au){const lo=getRefDefName(Au);if(isCheckableField(Au))return{type:"CHECKABLE"};if(lo==="Action")return{type:"ACTION"};const $u=unwrapZodSchema(Au);if(childRefKindOf($u)==="child-list"||lo==="ChildList")return{type:"STRUCTURAL"};if(isDynamicDef(lo,$u._def?.typeName))return{type:"DYNAMIC"};if($u._def.typeName==="ZodUnion"){const Ru=matchUnionBehavior($u._def.options);if(Ru)return Ru}return $u._def.typeName==="ZodArray"?{type:"ARRAY",element:getFieldBehavior($u._def.type)}:$u._def.typeName==="ZodObject"?{type:"OBJECT",shape:scrapeObjectShape($u._def.shape())}:{type:"STATIC"}}const MAX_DYNAMIC_CHILD_LIST_SIZE=1e4;function getSafeChildList(Au){return Array.isArray(Au)?Au.length>MAX_DYNAMIC_CHILD_LIST_SIZE?Au.slice(0,MAX_DYNAMIC_CHILD_LIST_SIZE):Au:[]}class GenericBinder{constructor(lo,$u){this.dataListeners=[],this.propsListeners=[],this.currentProps={},this.isConnected=!1,this.actionClosures=new Map,this.context=lo,this.behaviorTree=scrapeSchemaBehavior($u),this.behaviorTree.type!=="OBJECT"&&(this.behaviorTree={type:"OBJECT",shape:{}}),this.resolveInitialProps()}resolveInitialProps(){const lo=this.context.componentModel.properties,$u=this.resolveAndBind(lo,this.behaviorTree,[],!0);this.currentProps={...this.currentProps,...$u||{}}}connect(){if(this.isConnected)return;this.isConnected=!0;const lo=this.context.componentModel.onUpdated.subscribe(()=>{this.rebuildAllBindings()});this.compUnsub=()=>lo.unsubscribe(),this.rebuildAllBindings()}rebuildAllBindings(){this.dataListeners.forEach(Ru=>Ru()),this.dataListeners=[];const lo=this.context.componentModel.properties,$u=this.resolveAndBind(lo,this.behaviorTree,[],!1);this.currentProps={...this.currentProps,...$u||{}},this.notify()}bindDynamicValue(lo,$u,Ru){const Iu=this.context.dataContext.subscribeDynamicValue(lo,Ou=>{this.updateDeepValue($u,Ou),this.notify()});return Ru?Iu.unsubscribe():this.dataListeners.push(()=>Iu.unsubscribe()),Iu.value}resolveDeepSync(lo,$u=0){if(typeof lo!="object"||lo===null)return lo;if($u>MAX_DYNAMIC_VALUE_DEPTH)return;if("path"in lo||"call"in lo)return this.context.dataContext.resolveDynamicValue(lo,$u);if(Array.isArray(lo))return lo.map(Iu=>this.resolveDeepSync(Iu,$u+1));const Ru={};for(const[Iu,Ou]of Object.entries(lo))Ru[Iu]=this.resolveDeepSync(Ou,$u+1);return Ru}resolveEventAction(lo){if(typeof lo!="object"||lo===null)return lo;const $u=lo;if("event"in $u&&typeof $u.event=="object"&&$u.event!==null){const Ru=$u.event,Iu={...Ru,context:Ru.context?this.resolveDeepSync(Ru.context,1):void 0};return Ru.userMessage!==void 0&&(Iu.userMessage=this.resolveDeepSync(Ru.userMessage,1)),{...$u,event:Iu}}if("name"in $u){const Ru={...$u,context:$u.context?this.resolveDeepSync($u.context,1):void 0};return $u.userMessage!==void 0&&(Ru.userMessage=this.resolveDeepSync($u.userMessage,1)),Ru}return this.resolveDeepSync(lo,0)}bindAction(lo,$u){const Ru=$u.join("/"),Iu=this.actionClosures.get(Ru);if(Iu&&jsonEquals(Iu.raw,lo))return Iu.closure;const Ou=()=>{if(lo&&typeof lo=="object"){const Pu=lo,Du=Pu.functionCall&&typeof Pu.functionCall=="object"?Pu.functionCall:Pu;if(typeof Du.call=="string"){this.context.dataContext.resolveDynamicValue(Du);return}}this.context.dispatchAction(this.resolveEventAction(lo))};return this.actionClosures.set(Ru,{raw:lo,closure:Ou}),Ou}mapTemplateChildren(lo,$u,Ru){const Iu=getSafeChildList(lo),Ou=this.context.dataContext.nested(Ru);return Iu.map((Pu,Du)=>({id:$u,basePath:Ou.nested(String(Du)).path}))}bindStructuralTemplate(lo,$u,Ru){if(!lo||typeof lo!="object"||Array.isArray(lo))return lo;const Iu=lo,Ou=typeof Iu.path=="string"?Iu.path:void 0,Pu=typeof Iu.componentId=="string"?Iu.componentId:void 0;if(!Ou||!Pu)return lo;const Du=this.context.dataContext.subscribeDynamicValue({path:Ou},Lu=>{const ju=this.mapTemplateChildren(Lu,Pu,Ou);this.updateDeepValue($u,ju),this.notify()});return Ru?Du.unsubscribe():this.dataListeners.push(()=>Du.unsubscribe()),this.mapTemplateChildren(Du.value,Pu,Ou)}extractValidationResult(lo,$u){if(typeof lo=="object"&&lo!==null&&"valid"in lo){const Ru=lo.message;return{valid:!!lo.valid,message:Ru!=null?String(Ru):$u}}return{valid:!!lo,message:$u}}bindCheckable(lo,$u,Ru){const Iu=Array.isArray(lo)?lo:[],Ou=Iu.map(()=>({valid:!0,message:""})),Pu=$u.slice(0,-1),Du=()=>{const ju=Ou.filter(Bu=>!Bu.valid).map(Bu=>Bu.message);this.updateDeepValue([...Pu,"isValid"],ju.length===0),this.updateDeepValue([...Pu,"validationErrors"],ju),this.notify()};Iu.forEach((ju,Bu)=>{const Fu=typeof ju=="object"&&ju!==null?ju:void 0,zu=Fu&&Fu.condition!==void 0?Fu.condition:ju,qu=typeof Fu?.message=="string"?Fu.message:"Validation failed";Ou[Bu].message=qu;const Uu=this.context.dataContext.subscribeDynamicValue(zu,Hu=>{Ou[Bu]=this.extractValidationResult(Hu,qu),Du()});Ru?Uu.unsubscribe():this.dataListeners.push(()=>Uu.unsubscribe()),Ou[Bu]=this.extractValidationResult(Uu.value,qu)});const Lu=Ou.filter(ju=>!ju.valid).map(ju=>ju.message);return this.updateDeepValue([...Pu,"isValid"],Lu.length===0),this.updateDeepValue([...Pu,"validationErrors"],Lu),lo}bindObject(lo,$u,Ru,Iu){const Ou={};for(const[Pu,Du]of Object.entries(lo)){const Lu=$u[Pu]||{type:"STATIC"};Ou[Pu]=this.resolveAndBind(Du,Lu,[...Ru,Pu],Iu)}for(const[Pu,Du]of Object.entries($u))if(Du.type==="DYNAMIC"){const Lu=`set${Pu.charAt(0).toUpperCase()+Pu.slice(1)}`,ju=lo[Pu];Ou[Lu]=Bu=>{if(ju&&typeof ju=="object"&&"path"in ju){const Fu=ju.path;typeof Fu=="string"&&this.context.dataContext.set(Fu,Bu)}}}return Ou}resolveAndBind(lo,$u,Ru,Iu){if(lo==null)return lo;switch($u.type){case"DYNAMIC":return this.bindDynamicValue(lo,Ru,Iu);case"ACTION":return this.bindAction(lo,Ru);case"STRUCTURAL":return this.bindStructuralTemplate(lo,Ru,Iu);case"CHECKABLE":return this.bindCheckable(lo,Ru,Iu);case"STATIC":return lo;case"ARRAY":return Array.isArray(lo)?lo.map((Ou,Pu)=>this.resolveAndBind(Ou,$u.element,[...Ru,Pu.toString()],Iu)):lo;case"OBJECT":return typeof lo!="object"?lo:this.bindObject(lo,$u.shape,Ru,Iu)}}updateDeepValue(lo,$u){this.currentProps=this.cloneAndUpdate(this.currentProps,lo,$u)}cloneAndUpdate(lo,$u,Ru){if($u.length===0)return Ru;const[Iu,...Ou]=$u;if(Array.isArray(lo)){const Pu=[...lo];return Pu[Number(Iu)]=this.cloneAndUpdate(Pu[Number(Iu)],Ou,Ru),Pu}else{const Pu=typeof lo=="object"&&lo!==null?lo:{};return{...Pu,[Iu]:this.cloneAndUpdate(Pu[Iu],Ou,Ru)}}}dispose(){this.isConnected&&(this.isConnected=!1,this.dataListeners.forEach(lo=>lo()),this.dataListeners=[],this.compUnsub&&(this.compUnsub(),this.compUnsub=void 0))}notify(){this.propsListeners.forEach(lo=>lo(this.currentProps))}subscribe(lo){return this.propsListeners.length===0&&this.connect(),this.propsListeners.push(lo),{unsubscribe:()=>{this.propsListeners=this.propsListeners.filter($u=>$u!==lo),this.propsListeners.length===0&&this.dispose()}}}get snapshot(){return this.currentProps}}function jsonEquals(Au,lo){if(Object.is(Au,lo))return!0;if(typeof Au!="object"||typeof lo!="object"||Au===null||lo===null)return!1;if(Array.isArray(Au)||Array.isArray(lo))return!Array.isArray(Au)||!Array.isArray(lo)||Au.length!==lo.length?!1:Au.every((Iu,Ou)=>jsonEquals(Iu,lo[Ou]));const $u=Object.keys(Au),Ru=Object.keys(lo);return $u.length!==Ru.length?!1:$u.every(Iu=>Object.prototype.hasOwnProperty.call(lo,Iu)&&jsonEquals(Au[Iu],lo[Iu]))}class ResolvedBinding{constructor(lo){this.value=lo}}class WritableBinding extends ResolvedBinding{constructor(lo,$u,Ru){super(lo),this.set=$u,this.path=Ru}}function isWritable(Au){return Au instanceof WritableBinding}function sameBinding(Au,lo){return isWritable(Au)!==isWritable(lo)||isWritable(Au)&&isWritable(lo)&&Au.path!==lo.path?!1:valueEquals(Au.value,lo.value)}function valueEquals(Au,lo){if(Object.is(Au,lo))return!0;if(Array.isArray(Au)&&Array.isArray(lo))return Au.length===lo.length&&Au.every(($u,Ru)=>valueEquals($u,lo[Ru]));if(isPlainObject$2(Au)&&isPlainObject$2(lo)){const $u=Object.keys(Au),Ru=Object.keys(lo);return $u.length===Ru.length&&$u.every(Iu=>Iu in lo&&valueEquals(Au[Iu],lo[Iu]))}return!1}function isPlainObject$2(Au){if(typeof Au!="object"||Au===null)return!1;const lo=Object.getPrototypeOf(Au);return lo===Object.prototype||lo===null}const PLACEHOLDER_TYPE="Placeholder";function isComponentNode(Au){return Au instanceof MutableComponentNode}class MutableComponentNode{constructor(lo,$u,Ru,Iu,Ou,Pu,Du="resolved"){this._onDestroyed=new EventEmitter,this.onDestroyed=this._onDestroyed,this.cleanups=[],this._disposed=!1,this.instanceId=lo,this.componentId=$u,this.type=Ru,this.dataPath=Iu,this.props=signal(Ou),this.impl=Pu,this.state=Du}get disposed(){return this._disposed}get isPlaceholder(){return this.state!=="resolved"}addCleanup(lo){this.cleanups.push(lo)}toJSON(){if(this.isPlaceholder)return{id:this.componentId,type:this.type,state:this.state};const lo={id:this.componentId,type:this.type},$u=peekValue(this.props);for(const[Ru,Iu]of Object.entries($u))lo[Ru]=serializeValue(Iu);return lo}setProps(lo){if(this._disposed)return;const $u=peekValue(this.props);shallowEqual($u,lo)||setValue(this.props,lo)}dispose(){if(!this._disposed){this._disposed=!0;for(const lo of this.cleanups)try{lo()}catch($u){console.error(`ComponentNode cleanup error (${this.instanceId}):`,$u)}this.cleanups=[],this._onDestroyed.emit(),this._onDestroyed.dispose()}}}function serializeValue(Au){if(isComponentNode(Au))return Au.toJSON();if(Au instanceof ResolvedBinding)return serializeValue(Au.value);if(typeof Au=="function")return"<Action>";if(Array.isArray(Au))return Au.map(serializeValue);if(Au&&typeof Au=="object"){const lo={};for(const[$u,Ru]of Object.entries(Au))lo[$u]=serializeValue(Ru);return lo}return Au}function shallowEqual(Au,lo){if(Object.is(Au,lo))return!0;const $u=Object.keys(Au),Ru=Object.keys(lo);if($u.length!==Ru.length)return!1;for(const Iu of $u)if(!Object.is(Au[Iu],lo[Iu]))return!1;return!0}const COMPONENT_ID_REF="REF:common_types.json#/$defs/ComponentId",CHILD_LIST_REF="REF:common_types.json#/$defs/ChildList",EMPTY_REF_FIELDS$1=new Map,refFieldsCache=new WeakMap;function extractRefFields(Au){const lo=refFieldsCache.get(Au);if(lo)return lo;const $u=unwrap(Au);if($u.schema._def.typeName!=="ZodObject")return refFieldsCache.set(Au,EMPTY_REF_FIELDS$1),EMPTY_REF_FIELDS$1;const Ru=new Map,Iu=$u.schema.shape;for(const[Pu,Du]of Object.entries(Iu)){const Lu=unwrap(Du);if(marksChildList(Lu)||isChildListUnion(Lu.schema)){Ru.set(Pu,{kind:"list"});continue}if(marksComponentId(Lu)){Ru.set(Pu,{kind:"single"});continue}if(Lu.schema._def.typeName==="ZodArray"){const ju=unwrap(Lu.schema._def.type);if(marksComponentId(ju)){Ru.set(Pu,{kind:"list"});continue}if(ju.schema._def.typeName==="ZodObject"){const Bu=new Set,Fu=ju.schema.shape;for(const[zu,qu]of Object.entries(Fu))marksComponentId(unwrap(qu))&&Bu.add(zu);Bu.size>0&&Ru.set(Pu,{kind:"nested",keys:Bu})}}}const Ou=Ru;return refFieldsCache.set(Au,Ou),Ou}function unwrap(Au){const lo=[],$u=new Set;let Ru=Au;for(;;){Ru.description&&lo.push(Ru.description);const Iu=childRefKindOf(Ru);Iu&&$u.add(Iu);const Ou=Ru._def.typeName;if(Ou==="ZodOptional"||Ou==="ZodNullable"||Ou==="ZodDefault")Ru=Ru._def.innerType;else if(Ou==="ZodEffects")Ru=Ru._def.schema;else return{schema:Ru,descriptions:lo,refs:$u}}}function marksComponentId(Au){return Au.refs.has("component-id")||hasPointer(Au.descriptions,COMPONENT_ID_REF)}function marksChildList(Au){return Au.refs.has("child-list")||hasPointer(Au.descriptions,CHILD_LIST_REF)}function hasPointer(Au,lo){return Au.some($u=>$u.startsWith(lo))}function isChildListUnion(Au){return Au._def.typeName!=="ZodUnion"?!1:Au._def.options.some($u=>{if($u._def.typeName!=="ZodObject")return!1;const Ru=$u.shape;return Ru.componentId&&Ru.path})}const ROOT_COMPONENT_ID="root",ROOT_DATA_PATH="/",EMPTY_REF_FIELDS=new Map;class NodeResolver{constructor(lo,$u){if(this.records=new Map,this.nodesByEdge=new Map,this.nodesByComponentId=new Map,this.pendingParents=new Map,this.dispatchedErrors=new Map,this.modelSubs=[],this._disposed=!1,$u!==lo.defaultCatalog)throw new A2uiStateError("NodeResolver requires the same catalog instance its surface was constructed with.");this.surface=lo,this.catalog=$u,this.rootId=lo.rootId??ROOT_COMPONENT_ID,this.rootNode=signal(void 0),this.modelSubs.push(lo.componentsModel.onCreated.subscribe(Ru=>this.onComponentCreated(Ru))),this.modelSubs.push(lo.componentsModel.onDeleted.subscribe(Ru=>this.onComponentDeleted(Ru))),lo.componentsModel.get(this.rootId)&&this.buildRoot()}dispatchOnce(lo,$u,Ru,Iu){let Ou=this.dispatchedErrors.get($u);Ou||(Ou=new Map,this.dispatchedErrors.set($u,Ou));let Pu=Ou.get(Ru);Pu||(Pu=new Set,Ou.set(Ru,Pu)),!Pu.has(lo)&&(Pu.add(lo),this.surface.dispatchError({code:lo,message:Iu}))}clearDispatched(lo,$u){const Ru=this.dispatchedErrors.get(lo);Ru?.delete($u)&&Ru.size===0&&this.dispatchedErrors.delete(lo)}get activeNodeCount(){return this.records.size}get disposed(){return this._disposed}dispose(){if(!this._disposed){this._disposed=!0;for(const lo of this.modelSubs)lo.unsubscribe();this.modelSubs.length=0;for(const lo of[...this.records.keys()])this.disposeNode(lo);this.pendingParents.clear(),this.dispatchedErrors.clear(),this.rootRecord=void 0,setValue(this.rootNode,void 0)}}buildRoot(){if(this.rootRecord)return;const lo=`>${escapeIdPart(this.rootId)}>${escapeIdPart(this.rootId)}@/`,$u=this.createNode(this.rootId,ROOT_DATA_PATH,lo,void 0);this.rootRecord=this.records.get($u),setValue(this.rootNode,$u)}onComponentCreated(lo){if(this._disposed)return;if(lo.id===this.rootId){const Ru=this.surface.componentsModel.get(this.rootId);this.rootRecord&&this.rootRecord.componentModel!==Ru&&(this.disposeNode(this.rootRecord.node),this.rootRecord=void 0,Ru||setValue(this.rootNode,void 0)),Ru&&this.buildRoot()}const $u=this.pendingParents.get(lo.id);if($u){this.pendingParents.delete(lo.id);for(const Ru of $u){const Iu=this.records.get(Ru);Iu&&!Ru.disposed&&this.materialize(Iu)}}}onComponentDeleted(lo){if(this._disposed)return;this.dispatchedErrors.delete(lo);const $u=this.surface.componentsModel.get(lo),Ru=this.nodesByComponentId.get(lo);if(!Ru)return;const Iu=new Set;let Ou=!1;for(const Pu of[...Ru]){const Du=this.records.get(Pu);Du&&(Du.parent?Iu.add(Du.parent):Ou=!0)}Ou&&this.rootRecord&&($u?this.rootRecord.componentModel!==$u&&(this.disposeNode(this.rootRecord.node),this.rootRecord=void 0,this.buildRoot()):(this.disposeNode(this.rootRecord.node),this.rootRecord=void 0,setValue(this.rootNode,void 0)));for(const Pu of Iu){const Du=this.records.get(Pu);Du&&!Pu.disposed&&this.materialize(Du)}}createNode(lo,$u,Ru,Iu,Ou=1){const Pu=this.surface.componentsModel.get(lo);if(!Pu){const qu=this.registerNode(new MutableComponentNode(instanceIdFor(lo,$u,Ou),lo,PLACEHOLDER_TYPE,$u,{},void 0,"pending"),{edgeKey:Ru,parent:Iu,occurrence:Ou,refFields:EMPTY_REF_FIELDS});return Iu&&this.registerPendingParent(lo,Iu),qu.node}const Du=(Pu.catalog?.components.size?Pu.catalog:void 0)??this.catalog,Lu=Du.components.get(Pu.type);if(!Lu)return this.dispatchOnce("UNKNOWN_COMPONENT_TYPE",lo,$u,`Component '${lo}' has type '${Pu.type}', which is not in catalog '${Du.id}'.`),this.registerNode(new MutableComponentNode(instanceIdFor(lo,$u,Ou),lo,Pu.type,$u,{},void 0,"unknown-type"),{edgeKey:Ru,parent:Iu,occurrence:Ou,refFields:EMPTY_REF_FIELDS,componentModel:Pu}).node;this.clearDispatched(lo,$u);const ju=Iu?this.records.get(Iu)?.context?.dataContext:void 0,Bu=new ComponentContext(this.surface,lo,$u,ju),Fu=new GenericBinder(Bu,Lu.schema),zu=this.registerNode(new MutableComponentNode(instanceIdFor(lo,$u,Ou),lo,Pu.type,$u,{},Lu),{edgeKey:Ru,parent:Iu,occurrence:Ou,refFields:extractRefFields(Lu.schema),behavior:scrapeSchemaBehavior(Lu.schema),context:Bu,componentModel:Pu,binder:Fu});return zu.binderSub=Fu.subscribe(qu=>{zu.lastBinderProps=qu,this.materialize(zu)}),zu.lastBinderProps=Fu.snapshot,this.materialize(zu),zu.node}registerNode(lo,$u){const Ru={node:lo,edgeKey:$u.edgeKey,parent:$u.parent,occurrence:$u.occurrence,refFields:$u.refFields,behavior:$u.behavior,context:$u.context,componentModel:$u.componentModel,binder:$u.binder,childEdges:new Map};this.records.set(lo,Ru),this.nodesByEdge.set($u.edgeKey,lo);let Iu=this.nodesByComponentId.get(lo.componentId);return Iu||(Iu=new Set,this.nodesByComponentId.set(lo.componentId,Iu)),Iu.add(lo),Ru}childNode(lo,$u,Ru,Iu,Ou=1){const Pu=this.nodesByEdge.get(Ru);if(this.isCyclic(lo,$u,Iu))return Pu&&!Pu.disposed&&Pu.isPlaceholder&&this.records.get(Pu)?.occurrence===Ou?Pu:(Pu&&!Pu.disposed&&this.disposeNode(Pu),this.dispatchOnce("CYCLIC_REFERENCE",lo,$u,`Component '${lo}' at '${$u}' is referenced by one of its own descendants; rendering a placeholder instead.`),this.registerNode(new MutableComponentNode(instanceIdFor(lo,$u,Ou),lo,PLACEHOLDER_TYPE,$u,{},void 0,"cyclic"),{edgeKey:Ru,parent:Iu,occurrence:Ou,refFields:EMPTY_REF_FIELDS}).node);if(Pu&&!Pu.disposed){const Du=this.surface.componentsModel.get(lo),Lu=(Du?.catalog?.components.size?Du.catalog:void 0)??this.catalog,ju=Du?Lu.components.get(Du.type):void 0,Bu=this.records.get(Pu);if(Pu.componentId===lo&&Pu.dataPath===$u&&Bu?.occurrence===Ou&&(Pu.isPlaceholder?Du===void 0&&Pu.state==="pending"||Du!==void 0&&ju===void 0&&Pu.state==="unknown-type"&&Bu?.componentModel===Du:Du!==void 0&&Pu.type===Du.type&&Bu?.componentModel===Du))return Pu.state==="pending"&&this.registerPendingParent(lo,Iu),Pu;this.disposeNode(Pu)}return this.createNode(lo,$u,Ru,Iu,Ou)}registerPendingParent(lo,$u){let Ru=this.pendingParents.get(lo);Ru||(Ru=new Set,this.pendingParents.set(lo,Ru)),Ru.add($u)}isCyclic(lo,$u,Ru){for(let Iu=Ru;Iu;Iu=this.records.get(Iu)?.parent)if(Iu.componentId===lo&&Iu.dataPath===$u)return!0;return!1}materialize(lo){if(lo.node.disposed)return;const Ru={...lo.lastBinderProps??lo.binder?.snapshot??{}},Iu=new Map,Ou=lo.componentModel?.properties;if(Ou)for(const Bu of lo.refFields.keys())Bu in Ru&&!(Bu in Ou)&&delete Ru[Bu];const Pu=new Map,Du=(Bu,Fu,zu)=>{const qu=`${escapeIdPart(Fu)}@${escapeIdPart(zu)}`,Uu=(Pu.get(qu)??0)+1;Pu.set(qu,Uu);const Hu=`${lo.edgeKey}>${Bu}>${qu}`,Vu=this.childNode(Fu,zu,Hu,lo.node,Uu);return Iu.set(Hu,Vu),Vu};for(const[Bu,Fu]of lo.refFields)switch(Fu.kind){case"single":{const zu=Ru[Bu];typeof zu=="string"&&zu&&(Ru[Bu]=Du(escapeIdPart(Bu),zu,lo.node.dataPath));break}case"list":{const zu=Ru[Bu];if(!Array.isArray(zu))break;const qu=getSafeChildList(zu);Ru[Bu]=qu.map((Uu,Hu)=>{if(typeof Uu=="string"&&Uu)return Du(`${escapeIdPart(Bu)}[${Hu}]`,Uu,lo.node.dataPath);if(Uu&&typeof Uu=="object"&&!Array.isArray(Uu)){const Vu=Uu;if(typeof Vu.id=="string"&&typeof Vu.basePath=="string")return Du(`${escapeIdPart(Bu)}[${Hu}]`,Vu.id,Vu.basePath);if(typeof Vu.componentId=="string"&&Vu.componentId)return Du(`${escapeIdPart(Bu)}[${Hu}]`,Vu.componentId,lo.node.dataPath)}return Uu});break}case"nested":{const zu=Ru[Bu];if(!Array.isArray(zu))break;Ru[Bu]=zu.map((qu,Uu)=>{if(!qu||typeof qu!="object"||Array.isArray(qu))return qu;const Hu={...qu};let Vu=!1;for(const Gu of Fu.keys){const Ku=Hu[Gu];typeof Ku=="string"&&Ku&&(Hu[Gu]=Du(`${escapeIdPart(Bu)}[${Uu}].${escapeIdPart(Gu)}`,Ku,lo.node.dataPath),Vu=!0)}return Vu?Hu:qu});break}}for(const[Bu,Fu]of lo.childEdges)if(!Iu.has(Bu)&&(this.disposeNode(Fu),Fu.isPlaceholder&&![...Iu.values()].some(qu=>qu.isPlaceholder&&qu.componentId===Fu.componentId))){const qu=this.pendingParents.get(Fu.componentId);qu&&(qu.delete(lo.node),qu.size===0&&this.pendingParents.delete(Fu.componentId))}lo.childEdges=Iu;const Lu=lo.behavior&&lo.context?wrapDynamicValues(Ru,lo.behavior,Ou??{},lo.context.dataContext):Ru,ju=peekValue(lo.node.props);for(const Bu of Object.keys(Lu))Lu[Bu]=stabilize(ju[Bu],Lu[Bu]);lo.node.setProps(Lu)}disposeNode(lo){if(lo.disposed)return;const $u=this.records.get(lo);if($u){for(const Iu of $u.childEdges.values())this.disposeNode(Iu);$u.childEdges.clear(),$u.binderSub?.unsubscribe(),$u.binderSub=void 0,this.nodesByEdge.get($u.edgeKey)===lo&&this.nodesByEdge.delete($u.edgeKey),this.records.delete(lo)}const Ru=this.nodesByComponentId.get(lo.componentId);Ru&&(Ru.delete(lo),Ru.size===0&&this.nodesByComponentId.delete(lo.componentId));for(const[Iu,Ou]of this.pendingParents)Ou.delete(lo),Ou.size===0&&this.pendingParents.delete(Iu);lo.state==="cyclic"&&this.clearDispatched(lo.componentId,lo.dataPath),lo.dispose()}}const ID_PART_ESCAPES={"~":"~0","#":"~1","[":"~2","]":"~3",">":"~4","@":"~5"};function escapeIdPart(Au){return Au.replace(/[~#[\]>@]/g,lo=>ID_PART_ESCAPES[lo])}function instanceIdFor(Au,lo,$u){const Ru=lo.replace(/\/+$/,"")||ROOT_DATA_PATH,Iu=lo===ROOT_DATA_PATH?escapeIdPart(Au):`${escapeIdPart(Au)}-[${escapeIdPart(Ru)}]`;return $u>1?`${Iu}#${$u}`:Iu}function wrapDynamicValues(Au,lo,$u,Ru){switch(lo.type){case"DYNAMIC":{const Iu=$u&&typeof $u=="object"&&!Array.isArray($u)&&typeof $u.path=="string"?$u.path:void 0;return Iu===void 0?new ResolvedBinding(Au):new WritableBinding(Au,Ou=>Ru.set(Iu,Ou),Iu)}case"ARRAY":{if(!Array.isArray(Au))return Au;const Iu=Array.isArray($u)?$u:[];return Au.map((Ou,Pu)=>wrapDynamicValues(Ou,lo.element,Iu[Pu],Ru))}case"OBJECT":{if(!Au||typeof Au!="object"||Array.isArray(Au))return Au;const Iu=new Set;for(const[Du,Lu]of Object.entries(lo.shape))Lu.type==="DYNAMIC"&&Iu.add(`set${Du.charAt(0).toUpperCase()}${Du.slice(1)}`);const Ou=$u&&typeof $u=="object"&&!Array.isArray($u)?$u:{},Pu={};for(const[Du,Lu]of Object.entries(Au))Iu.has(Du)||(Pu[Du]=wrapDynamicValues(Lu,lo.shape[Du]??{type:"STATIC"},Ou[Du],Ru));for(const[Du,Lu]of Object.entries(lo.shape))Lu.type==="DYNAMIC"&&!(Du in Pu)&&(Pu[Du]=new ResolvedBinding(void 0));return Pu}default:return Au}}function stabilize(Au,lo){if(Object.is(Au,lo))return lo;if(Au instanceof ResolvedBinding&&lo instanceof ResolvedBinding)return sameBinding(Au,lo)?Au:lo;if(isComponentNode(Au)||isComponentNode(lo))return lo;if(Array.isArray(Au)&&Array.isArray(lo)&&Au.length===lo.length){let $u=!0;const Ru=lo.map((Iu,Ou)=>{const Pu=stabilize(Au[Ou],Iu);return Object.is(Pu,Au[Ou])||($u=!1),Pu});return $u?Au:Ru}if(isPlainObject$1(Au)&&isPlainObject$1(lo)){const $u=Object.keys(Au),Ru=Object.keys(lo);if($u.length===Ru.length){let Iu=!0;const Ou={};for(const Pu of Ru){const Du=stabilize(Au[Pu],lo[Pu]);Ou[Pu]=Du,(!(Pu in Au)||!Object.is(Du,Au[Pu]))&&(Iu=!1)}return Iu?Au:Ou}}return lo}function isPlainObject$1(Au){if(!Au||typeof Au!="object"||Array.isArray(Au)||isComponentNode(Au))return!1;const lo=Object.getPrototypeOf(Au);return lo===Object.prototype||lo===null}const ComponentIdSchema=markChildRef(stringType().describe("REF:#/$defs/ComponentId|The unique identifier for a component, used for both definitions and references within the same surface."),"component-id"),DataBindingSchema=objectType({path:stringType().describe("A JSON Pointer path to a value in the data model.")}).strict().describe("REF:#/$defs/DataBinding"),DynamicValueSchema=unionType([stringType(),numberType(),booleanType(),arrayType(anyType()),DataBindingSchema,lazyType(()=>FunctionCallSchema)]).describe("REF:#/$defs/DynamicValue|A value that can be a literal, a path, or a function call returning any type."),FunctionCallSchema=objectType({call:stringType().describe("The name of the function to call."),args:recordType(stringType(),unionType([DynamicValueSchema,recordType(stringType(),anyType()).describe("A literal object argument (e.g. configuration).")])).describe("Arguments passed to the function.").optional(),returnType:enumType(["string","number","boolean","array","object","any","void"]).describe("The expected return type of the function call.").default("boolean")}).describe("REF:#/$defs/FunctionCall|Invokes a named function on the client."),DynamicStringSchema=unionType([stringType(),DataBindingSchema,FunctionCallSchema]).describe("REF:#/$defs/DynamicString|Represents a string"),AccessibilityAttributesSchema=objectType({label:DynamicStringSchema.optional(),description:DynamicStringSchema.optional()}).describe("REF:#/$defs/AccessibilityAttributes|Attributes to enhance accessibility when using assistive technologies like screen readers.");objectType({id:ComponentIdSchema,accessibility:AccessibilityAttributesSchema.optional()}).describe("REF:#/$defs/ComponentCommon");const ChildListSchema=markChildRef(unionType([arrayType(ComponentIdSchema).describe("A static list of child component IDs."),objectType({componentId:ComponentIdSchema,path:stringType().describe("The path to the list of component property objects in the data model.")}).strict().describe("A template for generating a dynamic list of children from a data model list. The `componentId` is the component to use as a template.")]).describe("REF:#/$defs/ChildList"),"child-list"),DynamicNumberSchema=unionType([numberType(),DataBindingSchema,FunctionCallSchema]).describe("REF:#/$defs/DynamicNumber|Represents a value that can be either a literal number, a path to a number in the data model, or a function call returning a number."),DynamicBooleanSchema=unionType([booleanType(),DataBindingSchema,FunctionCallSchema]).describe("REF:#/$defs/DynamicBoolean|A boolean value that can be a literal, a path, or a function call returning a boolean."),DynamicStringListSchema=unionType([arrayType(stringType()),DataBindingSchema,FunctionCallSchema]).describe("REF:#/$defs/DynamicStringList|Represents a value that can be either a literal array of strings, a path to a string array in the data model, or a function call returning a string array."),CheckRuleSchema=objectType({condition:DynamicBooleanSchema,message:stringType().describe("The error message to display if the check fails.")}).strict().describe("REF:#/$defs/CheckRule|A single validation rule applied to an input component.");objectType({checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional()}).describe("REF:#/$defs/Checkable|Properties for components that support client-side checks.");const ActionSchema=unionType([objectType({event:objectType({name:stringType().describe("The name of the action to be dispatched to the server."),context:recordType(stringType(),DynamicValueSchema).describe("A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.").optional()}).strict().describe("The event to dispatch to the server.")}).strict().describe("Triggers a server-side event."),objectType({functionCall:FunctionCallSchema}).strict().describe("Executes a local client-side function.")]).describe("REF:#/$defs/Action|Defines an interaction handler that can either trigger a server-side event or execute a local client-side function."),TextApi={name:"Text",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),text:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The text content to display. While simple Markdown formatting is supported (i.e. without HTML, images, or links), utilizing dedicated UI components is generally preferred for a richer and more structured presentation."),variant:enumType(["h1","h2","h3","h4","h5","caption","body"]).default("body").describe("A hint for the base text style.").optional()}).strict()},ImageApi={name:"Image",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),url:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The URL of the image to display."),description:DynamicStringSchema.describe("REF:#/$defs/DynamicString|Accessibility text for the image.").optional(),fit:enumType(["contain","cover","fill","none","scaleDown"]).default("fill").describe("Specifies how the image should be resized to fit its container. This corresponds to the CSS 'object-fit' property.").optional(),variant:enumType(["icon","avatar","smallFeature","mediumFeature","largeFeature","header"]).default("mediumFeature").describe("A hint for the image size and style.").optional()}).strict()},IconApi={name:"Icon",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),name:unionType([enumType(["accountCircle","add","arrowBack","arrowForward","attachFile","calendarToday","call","camera","check","close","delete","download","edit","event","error","fastForward","favorite","favoriteOff","folder","help","home","info","locationOn","lock","lockOpen","mail","menu","moreVert","moreHoriz","notificationsOff","notifications","pause","payment","person","phone","photo","play","print","refresh","rewind","search","send","settings","share","shoppingCart","skipNext","skipPrevious","star","starHalf","starOff","stop","upload","visibility","visibilityOff","volumeDown","volumeMute","volumeOff","volumeUp","warning"]),objectType({svgPath:stringType()}),DataBindingSchema.describe("REF:#/$defs/DataBinding")]).describe("The name of the icon to display.")}).strict()},VideoApi={name:"Video",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),url:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The URL of the video to display.")}).strict()},AudioPlayerApi={name:"AudioPlayer",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),url:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The URL of the audio to be played."),description:DynamicStringSchema.describe("REF:#/$defs/DynamicString|A description of the audio, such as a title or summary.").optional()}).strict()},RowApi={name:"Row",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),children:ChildListSchema.describe("REF:#/$defs/ChildList|Defines the children. Use an array of strings for a fixed set of children, or a template object to generate children from a data list. Children cannot be defined inline, they must be referred to by ID."),justify:enumType(["center","end","spaceAround","spaceBetween","spaceEvenly","start","stretch"]).default("start").describe("Defines the arrangement of children along the main axis (horizontally). Use 'spaceBetween' to push items to the edges, or 'start'/'end'/'center' to pack them together.").optional(),align:enumType(["start","center","end","stretch"]).default("stretch").describe("Defines the alignment of children along the cross axis (vertically). This is similar to the CSS 'align-items' property, but uses camelCase values (e.g., 'start').").optional()}).strict()},ColumnApi={name:"Column",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),children:ChildListSchema.describe("REF:#/$defs/ChildList|Defines the children. Use an array of strings for a fixed set of children, or a template object to generate children from a data list. Children cannot be defined inline, they must be referred to by ID."),justify:enumType(["start","center","end","spaceBetween","spaceAround","spaceEvenly","stretch"]).default("start").describe("Defines the arrangement of children along the main axis (vertically). Use 'spaceBetween' to push items to the edges (e.g. header at top, footer at bottom), or 'start'/'end'/'center' to pack them together.").optional(),align:enumType(["center","end","start","stretch"]).default("stretch").describe("Defines the alignment of children along the cross axis (horizontally). This is similar to the CSS 'align-items' property.").optional()}).strict()},ListApi={name:"List",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),children:ChildListSchema.describe("REF:#/$defs/ChildList|Defines the children. Use an array of strings for a fixed set of children, or a template object to generate children from a data list."),direction:enumType(["vertical","horizontal"]).default("vertical").describe("The direction in which the list items are laid out.").optional(),align:enumType(["start","center","end","stretch"]).default("stretch").describe("Defines the alignment of children along the cross axis.").optional()}).strict()},CardApi={name:"Card",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),child:ComponentIdSchema.describe("REF:#/$defs/ComponentId|The ID of the single child component to be rendered inside the card. To display multiple elements, you MUST wrap them in a layout component (like Column or Row) and pass that container's ID here. Do NOT pass multiple IDs or a non-existent ID.")}).strict()},TabsApi={name:"Tabs",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),tabs:arrayType(objectType({title:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The tab title."),child:ComponentIdSchema.describe("REF:#/$defs/ComponentId|The ID of the child component.")})).min(1).describe("An array of objects, where each object defines a tab with a title and a child component.")}).strict()},ModalApi={name:"Modal",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),trigger:ComponentIdSchema.describe("REF:#/$defs/ComponentId|The ID of the component that opens the modal when interacted with (e.g., a button)."),content:ComponentIdSchema.describe("REF:#/$defs/ComponentId|The ID of the component to be displayed inside the modal.")}).strict()},DividerApi={name:"Divider",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),axis:enumType(["horizontal","vertical"]).default("horizontal").describe("The orientation of the divider.").optional()}).strict()},ButtonApi={name:"Button",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),child:ComponentIdSchema.describe("REF:#/$defs/ComponentId|The ID of the child component. Use a 'Text' component for a labeled button. Only use an 'Icon' if the requirements explicitly ask for an icon-only button."),variant:enumType(["default","primary","borderless"]).default("default").describe("A hint for the button style. If omitted, a default button style is used. 'primary' indicates this is the main call-to-action button. 'borderless' means the button has no visual border or background, making its child content appear like a clickable link.").optional(),action:ActionSchema.describe("REF:#/$defs/Action")}).strict()},TextFieldApi={name:"TextField",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The text label for the input field."),value:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The value of the text field.").optional(),variant:enumType(["longText","number","shortText","obscured"]).default("shortText").describe("The type of input field to display.").optional(),validationRegexp:stringType().describe("A regular expression used for client-side validation of the input.").optional()}).strict()},CheckBoxApi={name:"CheckBox",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The text to display next to the checkbox."),value:DynamicBooleanSchema.describe("REF:#/$defs/DynamicBoolean|The current state of the checkbox (true for checked, false for unchecked).")}).strict()},ChoicePickerApi={name:"ChoicePicker",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The label for the group of options.").optional(),variant:enumType(["multipleSelection","mutuallyExclusive"]).default("mutuallyExclusive").describe("A hint for how the choice picker should be displayed and behave.").optional(),options:arrayType(objectType({label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The text to display for this option."),value:stringType().describe("The stable value associated with this option.")})).describe("The list of available options to choose from."),value:DynamicStringListSchema.describe("REF:#/$defs/DynamicStringList|The list of currently selected values. This should be bound to a string array in the data model."),displayStyle:enumType(["checkbox","chips"]).default("checkbox").describe("The display style of the component.").optional(),filterable:booleanType().default(!1).describe("If true, displays a search input to filter the options.").optional()}).strict()},SliderApi={name:"Slider",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The label for the slider.").optional(),min:numberType().default(0).describe("The minimum value of the slider.").optional(),max:numberType().describe("The maximum value of the slider."),value:DynamicNumberSchema.describe("REF:#/$defs/DynamicNumber|The current value of the slider.")}).strict()},DateTimeInputApi={name:"DateTimeInput",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),value:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The selected date and/or time value in ISO 8601 format. If not yet set, initialize with an empty string."),enableDate:booleanType().default(!1).describe("If true, allows the user to select a date.").optional(),enableTime:booleanType().default(!1).describe("If true, allows the user to select a time.").optional(),min:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The minimum allowed date/time in ISO 8601 format.").optional(),max:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The maximum allowed date/time in ISO 8601 format.").optional(),label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The text label for the input field.").optional()}).strict()},DEFAULT_CSS=`
3440
+ `).replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/`([^`]*)`/g,"$1").replace(/^\s{0,3}#{1,6}\s+(.*)$/gm,"$1.").replace(/^\s*(?:[-*+]|\d+[.)])\s+/gm,"").replace(/^\s*>\s?/gm,"").replace(/[*_~]+/g,"").replace(/\.\s*\./g,".").replace(/\s+/g," ").trim()}const END=/[.!?…:;](?=["'»)\]]*(\s|$))/g,SHORTEST=12;class SentenceCutter{said=0;feed(lo){const $u=plainWords(lo),Ru=[];END.lastIndex=this.said;let Iu;for(;(Iu=END.exec($u))!==null;){const Ou=Iu.index+Iu[0].length;if(Ou>=$u.length)break;const Pu=$u.slice(this.said,Ou).trim();Pu.length>=SHORTEST&&(Ru.push(Pu),this.said=Ou)}return Ru}end(lo){const $u=plainWords(lo).slice(this.said).trim();return this.said=plainWords(lo).length,$u?[$u]:[]}}function answerText(Au){const lo=Au;if(!(!lo||lo.role!=="assistant"||typeof lo.toolName=="string")){if(typeof lo.content=="string")return lo.content;if(Array.isArray(lo.content))return lo.content.map($u=>$u&&typeof $u=="object"&&$u.type==="text"?String($u.text??""):"").join(" ")}}function useSpokenAnswers(Au,lo,$u,Ru){const Iu=reactExports.useRef(new Set),Ou=reactExports.useRef(void 0),Pu=reactExports.useRef(!1);reactExports.useEffect(()=>{if(!$u||!Ru){Pu.current=!1,Ou.current=void 0;return}const Du=Au.map((Bu,Fu)=>({id:String(Bu?.id??Fu),text:answerText(Bu)})).filter(Bu=>Bu.text!==void 0);if(!Pu.current){Pu.current=!0,Du.forEach(Bu=>Iu.current.add(Bu.id));return}const Lu=Du[Du.length-1];if(!Lu||Iu.current.has(Lu.id)&&Ou.current?.id!==Lu.id)return;Ou.current?.id!==Lu.id&&(Iu.current.add(Lu.id),Ou.current={id:Lu.id,cutter:new SentenceCutter,ended:!1});const ju=Ou.current;if(!ju.ended){for(const Bu of ju.cutter.feed(Lu.text??""))Ru.say(Bu);if(!lo){for(const Bu of ju.cutter.end(Lu.text??""))Ru.say(Bu);ju.ended=!0}}},[Au,lo,$u,Ru])}const CONVERSATION_BALLOON_WIDTH=380,CONVERSATION_BALLOON_MAX_HEIGHT=560,CONVERSATION_BALLOON_VIEWPORT_SHARE=.6,CURRENT_BALLOON_HEIGHT=230;function conversationBalloonHeight(Au){return Math.max(240,Math.min(CONVERSATION_BALLOON_MAX_HEIGHT,Math.round(Au*CONVERSATION_BALLOON_VIEWPORT_SHARE)))}const TAIL=7;function balloonTailAt(Au,lo,$u=CONVERSATION_BALLOON_WIDTH){return Math.min($u-24-TAIL,Math.max(24,Au-lo-TAIL))}function conversationBalloonSx(Au,lo="canvas.default"){return{borderRadius:"var(--theme-radius-bubble, 16px)",overflow:"visible",...Au.edge==="none"?{}:{"&::after":{content:'""',position:"absolute",...Au.edge==="bottom"?{bottom:`-${TAIL}px`}:{top:`-${TAIL}px`},left:`${Au.at}px`,width:`${TAIL*2}px`,height:`${TAIL*2}px`,bg:lo,borderRight:"1px solid",borderBottom:"1px solid",borderColor:"border.default",transform:Au.edge==="bottom"?"rotate(45deg)":"rotate(225deg)",pointerEvents:"none"}}}}function ConversationBalloonClose({name:Au,onClose:lo}){return jsxRuntimeExports.jsx(Box,{"data-conversation-balloon-close":"",position:"absolute",top:"6px",right:"6px",zIndex:30,children:jsxRuntimeExports.jsx(IconButton,{icon:XIcon,size:"small",variant:"invisible","aria-label":Au?`Close the conversation with ${Au}`:"Close the conversation",onClick:lo,sx:{bg:"canvas.default",borderRadius:"50%"}})})}function BalloonApprovalMessage({approval:Au}){const lo=useChatWords(),$u=reactExports.useRef(null);return reactExports.useEffect(()=>{$u.current?.scrollIntoView?.({block:"nearest"})},[Au.id]),jsxRuntimeExports.jsx(Box,{ref:$u,"data-balloon-approval":Au.id,px:3,py:2,display:"flex",children:jsxRuntimeExports.jsxs(Box,{maxWidth:"90%",px:3,py:2,bg:"attention.subtle",border:"1px solid",borderColor:"attention.muted",borderRadius:"var(--theme-radius-bubble, 16px)",fontSize:1,children:[jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:lo.waitingForYou}),jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{m:0,fontWeight:"semibold"},children:Au.asks}),Au.why?jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:Au.why}):null,jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,mt:2,alignItems:"center",children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",disabled:Au.deciding,onClick:Au.onApprove,children:lo.approve}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Au.deciding,onClick:Au.onDeny,children:lo.deny}),Au.others>0?jsxRuntimeExports.jsx(Text$5,{sx:{color:"fg.muted",fontSize:0},children:lo.moreWaiting(Au.others)}):null]})]})})}const PEEK_LIMIT=60;function peekLine(Au,lo=PEEK_LIMIT){const $u=Au.replace(/\s+/g," ").trim();if($u.length<=lo)return{text:$u,more:!1};const Ru=$u.slice(0,lo);return{text:`${Ru.slice(0,Math.max(Ru.lastIndexOf(" "),lo*.6)).trimEnd()}…`,more:!0}}const PRESENCE_LINES={idle:"Ready",thinking:"Thinking…",working:"Working…",waiting:"Waiting for you",paused:"Paused"};function presenceState(Au,lo,$u=!1){return $u?"paused":lo?.open&&lo.pendingApproval?"waiting":Au?lo?.open?"working":"thinking":"idle"}function presenceToolOf(Au){for(let lo=Au.length-1;lo>=0;lo-=1){const $u=Au[lo];if(typeof $u.toolName=="string"&&$u.toolCallId){const Ru=$u.status!=="complete"&&$u.status!=="error",Iu=Ru&&$u.result?.pending_approval===!0;return{open:Ru,pendingApproval:Iu}}}return{open:!1,pendingApproval:!1}}const LIVE=new Set(["running","idle","busy","starting"]);function sandboxIsLive(Au){return Au.status===void 0||LIVE.has(Au.status)}const NO_SANDBOX_YET="No sandbox is running yet: run a cell or ask the agent to execute code.",SANDBOX_KIND_LABELS={browser:"Python in your browser (Pyodide)",local:"Local Jupyter server",jupyter:"Jupyter server",cloud:"Datalayer cloud runtime",runtime:"In the agent runtime"};function isLocalUrl(Au){if(!Au)return!1;try{const lo=new URL(Au).hostname;return lo==="localhost"||lo==="127.0.0.1"||lo==="::1"||lo==="[::1]"||lo.endsWith(".localhost")}catch{return!1}}const SECRET_PARAMS=/^(token|access_token|api_key|apikey|key|auth|password|secret|signature|sig|jwt)$/i;function displayUrl(Au){if(Au)try{const lo=new URL(Au);lo.username="",lo.password="";for(const $u of[...lo.searchParams.keys()])SECRET_PARAMS.test($u)&&lo.searchParams.delete($u);return lo.toString()}catch{return Au.split("?")[0]}}const text$3=Au=>typeof Au=="string"&&Au?Au:void 0;function assistantSandboxOf(Au,lo={}){if(!Au)return;const $u=text$3(Au.variant),Ru=text$3(Au.jupyter_url)??text$3(Au.agent_base_url),Iu=Au.sandbox_running===!0||Au.jupyter_connected===!0;return!$u&&!Iu?void 0:{kind:$u==="datalayer"?"cloud":$u==="jupyter-server"||$u==="jupyter"?isLocalUrl(text$3(Au.jupyter_url))?"local":"jupyter":"runtime",status:lo.state??(Iu?"running":"stopped"),variant:$u,url:Ru,token:text$3(Au.jupyter_token),kernelId:text$3(Au.kernel_id),agentId:lo.agentId,environment:text$3(Au.environment_name),serverUrl:lo.serverUrl}}function sandboxExecuteOverHttp(Au,lo){const $u=Au.replace(/\/+$/,"").replace(/\/api\/v1$/,"");return async Ru=>{const Iu=await fetch(`${$u}/api/v1/sandbox/execute`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:Ru,agent_id:lo})});if(!Iu.ok)return{stdout:"",error:`The sandbox did not run the code (HTTP ${Iu.status}).`};const Ou=await Iu.json();return{stdout:Ou.stdout??"",error:Ou.error??void 0}}}function timeLeft(Au,lo=Date.now()){if(Au===null)return"never";if(Au===void 0||Au==="")return;const $u=typeof Au=="number"?Au<1e12?Au*1e3:Au:Date.parse(Au);if(!Number.isFinite($u))return;const Ru=Math.round(($u-lo)/6e4);if(Ru<=0)return"ended";const Iu=Math.floor(Ru/60);return Iu?`${Iu} h ${Ru%60} min`:`${Ru} min`}function useIsMobile(Au=640){const[lo,$u]=reactExports.useState(!1);return reactExports.useEffect(()=>{const Ru=()=>{$u(window.innerWidth<Au)};return Ru(),window.addEventListener("resize",Ru),()=>window.removeEventListener("resize",Ru)},[Au]),lo}const px=Au=>`${Math.round(Au)}px`,clamp=(Au,lo)=>Math.max(8,Math.min(Au,Math.max(8,lo)));function ChatFloating({endpoint:Au,protocol:lo,useStore:$u=!0,title:Ru="Chat",description:Iu="Start a conversation with the AI agent.",position:Ou="bottom-right",defaultOpen:Pu=!1,width:Du=400,height:Lu=550,showHeader:ju=!0,showButton:Bu=!0,showNewChatButton:Fu=!0,showClearButton:zu=!0,showSettingsButton:qu=!1,enableKeyboardShortcuts:Uu=!0,toggleShortcut:Hu="/",showPoweredBy:Vu=!0,promptVariant:Gu,mentionableAgents:Ku,poweredByProps:Zu,clickOutsideToClose:Qu=!1,escapeToClose:Yu=!0,className:ed,onSettingsClick:Xu,onNewChat:rd,onOpen:nd,onClose:od,onStateUpdate:ad,children:ld,brandIcon:fd,buttonIcon:pd,buttonTooltip:Sd="Chat with AI",brandColor:wd,buttonGlow:bd=!0,offset:Td=20,animationDuration:Pd=200,renderToolResult:ud,frontendTools:md,initialState:_d,suggestions:hd,submitOnSuggestionClick:gd=!0,hideMessagesAfterToolUI:Ed=!1,defaultViewMode:xd="floating",onViewModeChange:Od,sidebarMountPoint:Bd=null,showPanelBackdrop:Gd=!1,availableModels:Ud,showModelSelector:Md=!1,showToolsMenu:zd=!1,showSkillsMenu:Vd=!1,showTokenUsage:kd=!0,showContextRing:Rd=!1,themeVariant:Ld,themeOverrides:Jd,colorMode:Xd,runtimeId:uh,historyEndpoint:xh,authToken:Mh,historyAuthToken:Rh,pendingPrompt:bh,showInformation:_h=!1,onInformationClick:eh,onToolCallStart:Sh,onToolCallComplete:Dd,showToolApprovalBanner:$d,pendingApprovals:jd,onApproveApproval:Fd,onRejectApproval:rh,panelProps:Yd,launching:th=!1,launchingMessage:ah,assistantCharacter:Ah=DEFAULT_ASSISTANT_CHARACTER,balloonDisplay:Dh=DEFAULT_BALLOON_DISPLAY,expandTarget:zh,conversation:mf,decisions:Zd,voice:Ad,inspector:sh,onBalloonDisplayChange:ih,onChangeCharacter:Bh,about:Yh,sandbox:Kh,contextMenu:rf}){const hf=useChatWords(),Rf=reactExports.useRef(null),[Cf,Df]=reactExports.useState(),[sf,qf]=reactExports.useState(!1),[Uf,mh]=reactExports.useState();reactExports.useEffect(()=>mh(void 0),[Dh]);const oh=Uf??Dh,ph=reactExports.useCallback(xf=>{mh(xf),ih?.(xf)},[ih]),Lh=useChatOpen(),kh=useChatMessages(),vf=useChatStore(xf=>xf.setOpen),Jh=useChatStore(xf=>xf.clearMessages),[lf,Yf]=reactExports.useState(Pu),Tf=$u?Lh:lf,Nf=$u?vf:Yf,Qh=kh,kf=reactExports.useRef(null),yf=useIsMobile(),[rp,up]=reactExports.useState(!1),[np,kp]=reactExports.useState(!1),[Bf,zp]=reactExports.useState(xd),[Zp,sm]=reactExports.useState(0),[pp,qp]=reactExports.useState(!1),[Jf,gp]=reactExports.useState(null),dp=Bf==="panel"?"sidebar":Bf,[Cp,Tp]=reactExports.useState(null);reactExports.useLayoutEffect(()=>{Tp(resolveMountPoint(Bd))},[Bd,Tf,Bf]);const hp=disabledChatViewModes({sidebarMountPoint:Cp,viewMode:dp}),Rp=hp.includes("sidebar"),Qf=Bf==="panel"&&!yf&&!!Cp,cm=useViewportDrag(kf),um=cm.reset;reactExports.useEffect(()=>{Bf!=="floating-draggable"&&um()},[Bf,um]);const Mp=88,Np=Bf==="assistant"&&!yf,[Em,nm]=reactExports.useState(!1),[qm,Km]=reactExports.useState({open:!1,pendingApproval:!1}),[Lp,Sf]=reactExports.useState(!1),[hh,jh]=reactExports.useState(),[Ef,wf]=reactExports.useState(0),[gf,$f]=reactExports.useState([]),[vh,Th]=reactExports.useState([]),[gh,Kd]=reactExports.useState({speaking:!1}),dh=reactExports.useMemo(()=>Ad&&Ad.output==="always"&&Ad.speechUrl?new ServerSpeaker({speechUrl:Ad.speechUrl,voice:Ad.voice,language:Ad.language,token:Ad.token,onState:Kd}):void 0,[Ad?.output,Ad?.speechUrl]);reactExports.useEffect(()=>{dh?.update({voice:Ad?.voice,language:Ad?.language,token:Ad?.token})},[dh,Ad?.voice,Ad?.language,Ad?.token]),reactExports.useEffect(()=>()=>dh?.close(),[dh]),reactExports.useEffect(()=>{if(!dh)return;const xf=()=>dh.unlock();return window.addEventListener("pointerdown",xf,{once:!0}),window.addEventListener("keydown",xf,{once:!0}),()=>{window.removeEventListener("pointerdown",xf),window.removeEventListener("keydown",xf)}},[dh]),useSpokenAnswers(vh,Em,!!dh&&!sf,dh);const $h=reactExports.useCallback(()=>dh?.stop(),[dh]),Uh=reactExports.useMemo(()=>dh?()=>dh.level():void 0,[dh]),[cf,Pf]=reactExports.useState(!1),[Ff,Vf]=reactExports.useState(!1),[Ip,ep]=reactExports.useState(keptAway),_p=Np&&Ip==="none",Jp=reactExports.useCallback(()=>{keepAway("none"),ep("none")},[]),[sp,xp]=reactExports.useState(),$p=mf?mf.saying:sp,am=mf?mf.answering:Lp,Cm=mf?mf.tool:hh,Dm=oh==="current",[Lf,Up]=reactExports.useState(),[lm,ym]=reactExports.useState(!1);reactExports.useEffect(()=>{if(!$p||Tf)return;ym(!0);const xf=setTimeout(()=>ym(!1),12e3);return()=>clearTimeout(xf)},[$p?.id,$p?.text,Tf]),reactExports.useEffect(()=>{Tf&&$p&&Up($p.id)},[Tf,$p?.id]);const Zm=reactExports.useRef(null),Bm=useViewportDrag(Zm,{whole:!0});reactExports.useEffect(()=>{if(!_p)return;Pf(!0);const xf=setTimeout(()=>Pf(!1),1800);return()=>clearTimeout(xf)},[_p]);const Um=assistantStateOf(mf?mf.presence:presenceState(Em,qm),{arriving:cf,leaving:Ff,speaking:am,voicing:gh.speaking}),Hp=!!$p&&$p.id!==Lf,[cg,Ym]=reactExports.useState(!1),gm=jd?.[0],Gf=gm&&Fd&&rh?{id:gm.id,asks:gm.toolDescription||gm.toolName,others:(jd?.length??1)-1,deciding:cg,onApprove:()=>{Ym(!0),Promise.resolve(Fd(gm.id)).finally(()=>Ym(!1))},onDeny:()=>{Ym(!0),Promise.resolve(rh(gm.id)).finally(()=>Ym(!1))}}:void 0,Yp=reactExports.useMemo(()=>Zd?.serverUrl?decisionsAskerAt(Zd.serverUrl,Zd.token):void 0,[Zd?.serverUrl,Zd?.token]),cd=Um==="thinking"||Um==="working"||Um==="speaking",yd=Cm&&(Cm.phase==="running"||cd)?Cm:void 0,Id=cd&&!am?hf.thinking:($p?.more?$p.text:$p?.markdown)||void 0,Nd=cd&&!am?void 0:$p?.more?$p.markdown:void 0,Hd=!Dm&&!mf&&gf.length>0?gf:void 0,Wd=xf=>Hd?{...xf,history:Hd}:xf,Qd=Um==="paused"?{text:hf.paused}:gh.sentence?{text:gh.sentence}:gh.refused?{text:gh.refused}:Gf?Wd({text:hf.waitingForYou,approval:Gf}):Um==="waiting"?{text:hf.waitingOpen}:yd?Wd({text:toolLineText(yd,hf),tool:yd,busy:cd}):Dm&&(Hp||cd)?{text:Id??Iu,fullText:Nd,more:$p?.more,speaking:am&&cd,busy:cd,onDismiss:$p?()=>{Up($p.id),ym(!1)}:void 0}:Wd(Hp&&$p?{...peekLine($p.text),onDismiss:()=>{Up($p.id),ym(!1)}}:{text:Iu}),wh=!!gh.sentence||Um==="greeting"||Um==="waiting"||!!Gf||!!yd||Dm&&cd||Hp&&(Um==="speaking"||lm),yh=reactExports.useMemo(()=>mf||!hd?.length?void 0:hd.map(xf=>({label:xf.title,prompt:xf.message})),[mf,hd]),Nh=reactExports.useCallback(xf=>{Rf.current?Rf.current.send(xf.prompt):Df(xf.prompt)},[]),tf=Yd?.onSendReady,df=reactExports.useCallback(xf=>{Rf.current=xf,tf?.(xf)},[tf]),Hh=Yd?.onLoadingChange,Af=Yd?.onDisplayItemsChange,bp=reactExports.useCallback(xf=>{nm(xf),Hh?.(xf)},[Hh]),Mf=reactExports.useCallback(xf=>{const Vp=presenceToolOf(xf);Km(vm=>vm.open===Vp.open&&vm.pendingApproval===Vp.pendingApproval?vm:Vp),Sf(newestIsAnswer(xf));const Lm=newestToolLine(xf);jh(vm=>vm?.id===Lm?.id&&vm?.phase===Lm?.phase?vm:Lm),wf(conversationCount(xf)),$f(xf),Th(xf);const _m=latestSaying(xf);xp(vm=>vm?.id===_m?.id&&vm?.text===_m?.text?vm:_m),Af?.(xf)},[Af]),Pp=reactExports.useCallback(xf=>{if(!(xf==="sidebar"&&Rp))if(xf==="sidebar"){if(Od){Od(xf);return}zp("panel"),sm(Vp=>Vp+1)}else xf==="assistant"&&Jp(),zp(xf),sm(Vp=>Vp+1),Od?.(xf)},[Od,Rp,Jp]);reactExports.useLayoutEffect(()=>{if(Bf!=="panel"||yf){qp(!1);return}if(Cp){qp(!0);return}const xf=kf.current?.parentElement;if(!xf){qp(!1);return}const Vp=window.getComputedStyle(xf),Lm=Vp.display.includes("flex")&&(Vp.flexDirection==="row"||Vp.flexDirection==="row-reverse"),_m=Vp.display.includes("grid");qp(Lm||_m)},[Bf,yf,Tf,Cp]);const Pm=typeof Du=="number"?Du:typeof Du=="string"&&Number.parseInt(Du,10)||420;reactExports.useLayoutEffect(()=>{if(yf||Bf!=="panel"||pp||!Tf){gp(null);return}const xf=kf.current?.parentElement;if(!xf){gp(null);return}const Vp=xf.style.paddingRight,Lm=xf.style.boxSizing,_m=window.getComputedStyle(xf).paddingRight;xf.style.boxSizing="border-box",xf.style.paddingRight=`calc(${_m} + ${Pm}px)`;const vm=()=>{const Ng=xf.getBoundingClientRect();gp(ig=>{const Xm=Ng.height<1?{top:0,height:window.innerHeight,right:0}:{top:Ng.top,height:Ng.height,right:Math.max(0,window.innerWidth-Ng.right)};return ig&&Math.abs(ig.top-Xm.top)<1&&Math.abs(ig.height-Xm.height)<1&&Math.abs(ig.right-Xm.right)<1?ig:Xm})};vm(),window.addEventListener("resize",vm),window.addEventListener("scroll",vm,!0);const yg=new ResizeObserver(vm);return yg.observe(xf),()=>{window.removeEventListener("resize",vm),window.removeEventListener("scroll",vm,!0),yg.disconnect(),xf.style.paddingRight=Vp,xf.style.boxSizing=Lm}},[yf,Bf,pp,Tf,Pm]);const Xp=reactExports.useMemo(()=>{if(lo&&typeof lo=="object")return lo;if(!Au)return;const xf=typeof lo=="string"?lo:void 0,Vp=Au.match(/^(.*?)\/api\/v1\//)?.[1]||Au.match(/^(https?:\/\/[^/]+)/)?.[1]||"",Lm=Au.match(/\/api\/v1\/(ag-ui|vercel-ai|a2a|acp)\//),_m=xf??Lm?.[1]??"vercel-ai",vm=Au.match(/\/api\/v1\/(?:ag-ui|vercel-ai|a2a\/agents|acp\/ws)\/([^/]+)/),yg=vm?vm[1]:void 0;return{type:_m,endpoint:Au,agentId:yg,authToken:Mh,enableConfigQuery:Md||zd||Vd||kd,configEndpoint:Md||zd||Vd||kd?`${Vp}/api/v1/configure`:void 0}},[lo,Au,Mh,Md,zd,Vd,kd]),og=Au?.match(/^(.*?)\/api\/v1\//)?.[1],dm=reactExports.useMemo(()=>Yh||Xp?.agentId?{name:Ru,protocol:Xp?.type,url:Xp?.endpoint,agentId:Xp?.agentId,apiBase:og,...Yh}:void 0,[Yh,Xp,Ru,og]),Hf=useAgentRuntimeCodemodeStatus(),ug=reactExports.useMemo(()=>Kh??assistantSandboxOf(Hf?.sandbox,{agentId:Xp?.agentId,serverUrl:og})??(Xp?.agentId&&og?{kind:"runtime",status:"not running",agentId:Xp.agentId,serverUrl:og}:void 0),[Kh,Hf,Xp?.agentId,og]);reactExports.useEffect(()=>{Jh()},[Au,lo]),reactExports.useEffect(()=>{Nf(Pu)},[]);const yp=reactExports.useCallback(()=>{const xf=!Tf;up(!0),xf?(Nf(xf),nd?.()):setTimeout(()=>{Nf(xf),od?.(),up(!1)},Pd),setTimeout(()=>up(!1),Pd)},[Tf,Nf,nd,od,Pd]),Tm=reactExports.useCallback(xf=>{Tf&&yp(),keepAway(xf),Vf(!0),setTimeout(()=>{Vf(!1),ep(xf)},600)},[Tf,yp]),jg=typeof window>"u"?1280:window.innerWidth,mg=typeof window>"u"?800:window.innerHeight,Hm=conversationBalloonHeight(mg),Rg=Dm&&!mf,vg=Rg?CURRENT_BALLOON_HEIGHT:Hm,Bg=()=>{const xf=CONVERSATION_BALLOON_WIDTH,Vp=vg;if(Bm.position){const{left:ig,top:Xm}=Bm.position,y0=ig+Mp/2<jg/2,jp=Xm-Vp-16,Tg=Xm+Mp+16,km=jp<8&&Tg+Vp>mg-8,Yg=km?y0?ig+Mp+16:ig-xf-16:y0?ig:ig+Mp-xf,_0=km?Xm+Mp-Vp:jp>=8?jp:Tg,x0=clamp(Yg,jg-xf-8);return{place:{left:px(x0),top:px(clamp(_0,mg-Vp-8)),right:"auto",bottom:"auto"},tail:km?{edge:"none"}:{edge:jp>=8?"bottom":"top",at:balloonTailAt(ig+Mp/2,x0)}}}const Lm=Ou.endsWith("right"),_m=Lm?jg-Td-Mp/2:Td+Mp/2,vm=Lm?jg-Td-xf:Td,yg={edge:Ou.startsWith("bottom")?"bottom":"top",at:balloonTailAt(_m,vm)},Ng=Nm();return{place:Ou.startsWith("bottom")?{...Ng,bottom:px(Td+Mp+16)}:{...Ng,top:px(Td+Mp+16)},tail:yg}},Jm=reactExports.useCallback(()=>{$u&&Jh(),rd?.()},[$u,Jh,rd]),Qm=reactExports.useCallback(()=>{window.confirm("Clear all messages?")&&$u&&Jh()},[$u,Jh]);useChatKeyboardShortcuts({onToggle:Uu?yp:void 0,onNewChat:Uu?Jm:void 0,onClear:Uu&&Qh.length>0?Qm:void 0,enabled:Uu}),reactExports.useEffect(()=>{if(!Yu||!Tf)return;const xf=Vp=>{Vp.key==="Escape"&&yp()};return document.addEventListener("keydown",xf),()=>document.removeEventListener("keydown",xf)},[Yu,Tf,yp]);const Fg=!!mf;reactExports.useEffect(()=>{if(!Fg||!Tf)return;const xf=setTimeout(()=>{kf.current?.querySelector('[data-chat-composer] textarea, [data-chat-composer] [contenteditable="true"], textarea')?.focus()},Pd);return()=>clearTimeout(xf)},[Fg,Tf,Pd,Zp]),reactExports.useEffect(()=>{if(!_p||!Tf)return;const xf=setTimeout(()=>{const Vp=kf.current?.querySelector("[data-chat-history]");Vp?.scrollTo?.({top:Vp.scrollHeight})},Pd);return()=>clearTimeout(xf)},[_p,Tf,Pd]),reactExports.useEffect(()=>{if(!Qu||!Tf)return;const xf=Lm=>{kf.current&&!kf.current.contains(Lm.target)&&yp()},Vp=setTimeout(()=>{document.addEventListener("mousedown",xf)},100);return()=>{clearTimeout(Vp),document.removeEventListener("mousedown",xf)}},[Qu,Tf,yp]),reactExports.useEffect(()=>{if(yf&&Tf)return document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.width="100%",document.body.style.touchAction="none",()=>{document.body.style.overflow="",document.body.style.position="",document.body.style.width="",document.body.style.touchAction=""}},[yf,Tf]);const Nm=()=>{const xf={position:"fixed",zIndex:1e3};switch(Ou){case"bottom-right":xf.bottom=Td,xf.right=Td;break;case"bottom-left":xf.bottom=Td,xf.left=Td;break;case"top-right":xf.top=Td,xf.right=Td;break;case"top-left":xf.top=Td,xf.left=Td;break}return xf},Vm=xf=>{if(xf)return"scale(1) translateY(0)";switch(Ou){case"bottom-right":case"bottom-left":return"scale(0.95) translateY(20px)";case"top-right":case"top-left":return"scale(0.95) translateY(-20px)";default:return"scale(0.95)"}},F0=Uu?getShortcutDisplay({key:Hu}):void 0,Am=_p?Bg():void 0,zg=yf?"100%":Am?CONVERSATION_BALLOON_WIDTH:Du,Wp=yf?"100%":Am?vg:Lu,qg=yf?{position:"fixed",top:0,left:0,right:0,bottom:0,width:"100%",height:"100%",borderRadius:0}:{},Fm=jsxRuntimeExports.jsx(Tooltip,{text:`Close${Yu?" (Esc)":""}`,direction:"s",children:jsxRuntimeExports.jsx(IconButton,{icon:XIcon,"aria-label":"Close",onClick:yp,variant:"invisible",size:"small"})}),Dg=Am?{showHeader:!1,showPoweredBy:!1,promptVariant:"lexical",showModelSelector:!1,showToolsMenu:!1,showSkillsMenu:!1,showTokenUsage:!1,showContextRing:!1,showInformation:!1,showToolApprovalBanner:!1,showAgentsMenu:!1,showTurnFooter:!1,compact:!0,welcome:Iu,backgroundColor:"canvas.default",borderRadius:"var(--theme-radius-bubble, 16px)",trailingContent:Gf?jsxRuntimeExports.jsx(BalloonApprovalMessage,{approval:Gf}):void 0,footerContent:Yp?jsxRuntimeExports.jsx(Box,{"data-balloon-decisions":"",px:3,pb:1,display:"flex",flexDirection:"column",alignItems:"flex-end",fontSize:0,sx:{"& form":{alignSelf:"stretch"},'& [data-balloon-decision="answered"]':{alignSelf:"stretch"}},children:jsxRuntimeExports.jsx(DecisionAsk,{ask:Yp})}):void 0}:void 0,O0=jsxRuntimeExports.jsxs(Box,{ref:kf,className:ed,sx:{position:Bf==="panel"&&!yf&&(pp||Qf)?"relative":"fixed",...Bf==="floating"&&!yf?{top:0,right:0,bottom:0,left:"auto"}:{},...Bf==="floating-small"&&!yf?Nm():{},...Bf==="floating-draggable"&&!yf?cm.position?{left:px(cm.position.left),top:px(cm.position.top),right:"auto",bottom:"auto"}:Nm():{},...Am?Am.place:Np&&!yf?Nm():{},...Bf==="panel"&&!yf?{...pp||Qf?{top:"auto",right:"auto",bottom:"auto",left:"auto",marginLeft:"auto",alignSelf:"stretch"}:{top:Jf?`${Jf.top}px`:0,right:Jf?`${Jf.right}px`:0,bottom:Jf?"auto":0,left:"auto"}}:{},width:Bf==="panel"&&!yf?Tf||rp?`${Pm}px`:"0px":Bf==="floating"&&!yf?typeof zg=="number"?`${zg}px`:zg:(Bf==="floating-small"||Bf==="floating-draggable"||Bf==="assistant")&&!yf?typeof zg=="number"?`${zg}px`:zg:yf?"100%":typeof zg=="number"?`${zg}px`:zg,height:Bf==="panel"&&!yf?pp||Qf?"100%":Jf?`${Jf.height}px`:"100%":Bf==="floating"&&!yf?"100%":(Bf==="floating-small"||Bf==="floating-draggable"||Bf==="assistant")&&!yf?typeof Wp=="number"?`${Wp}px`:Wp:yf?"100%":typeof Wp=="number"?`${Wp}px`:Wp,display:"flex",flexDirection:"column",bg:"canvas.default",border:"1px solid",borderColor:"border.default",borderRadius:Bf==="panel"||yf?0:Np?"var(--theme-radius-bubble, 16px)":"12px",boxShadow:Bf==="panel"?"shadow.none":"shadow.extra-large",overflow:"hidden",transform:Bf==="panel"?Tf?"translateX(0)":"translateX(100%)":Vm(Tf),opacity:Bf==="panel"||Tf?1:0,transition:`transform ${Pd}ms ease, opacity ${Pd}ms ease, width ${Pd}ms ease`,zIndex:Bf==="panel"&&!yf&&(pp||Qf)?"auto":1001,visibility:Tf||rp?"visible":"hidden",pointerEvents:Tf?"auto":"none",...qg,...Am?conversationBalloonSx(Am.tail,Am.tail.edge==="bottom"?"canvas.subtle":"canvas.default"):{}},"data-conversation-balloon":Am?"":void 0,"data-balloon-display":Am?oh:void 0,children:[Am?jsxRuntimeExports.jsx(ConversationBalloonClose,{onClose:yp}):null,Am&&!Rg?jsxRuntimeExports.jsx(ConversationBalloonHeader,{count:Ef}):null,Bf==="floating-draggable"&&!yf&&jsxRuntimeExports.jsx(Box,{onPointerDown:cm.onHandlePointerDown,"aria-label":"Move the chat",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,height:18,cursor:"grab",color:"fg.subtle",bg:"canvas.subtle",borderBottom:"1px solid",borderColor:"border.muted",active:{cursor:"grabbing"},touchAction:"none",children:jsxRuntimeExports.jsx(GrabberIcon,{size:16})}),mf?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[ju&&!Am?jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,flexShrink:0,px:3,py:2,borderBottom:"1px solid",borderColor:"border.default",children:[fd||jsxRuntimeExports.jsx(ForwardRef$3,{colored:!0,size:20}),jsxRuntimeExports.jsx(Text$5,{sx:{flex:1,minWidth:0,fontWeight:"semibold",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Ru}),Fm]}):null,jsxRuntimeExports.jsx(Box,{"data-floating-conversation":!0,flex:"1 1 auto",minHeight:0,display:"flex",borderRadius:Am?"bubble":void 0,overflow:Am?"hidden":void 0,children:mf.body})]}):jsxRuntimeExports.jsx(ChatBase,{title:Ru,showHeader:ju,useStore:$u,protocol:Xp,themeVariant:Ld,themeOverrides:Jd,colorMode:Xd,autoFocus:Tf,focusTrigger:Zp,launching:th,launchingMessage:ah,brandIcon:fd||jsxRuntimeExports.jsx(ForwardRef$3,{colored:!0,size:20}),headerButtons:{showNewChat:Fu,showClear:zu&&Qh.length>0,showSettings:qu&&!!Xu,onNewChat:Jm,onClear:Qm,onSettings:Xu},headerActions:jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Fm}),chatViewMode:dp,onChatViewModeChange:Pp,disabledViewModes:hp,showPoweredBy:Vu,promptVariant:Gu,mentionableAgents:Ku,poweredByProps:{brandName:"Datalayer",brandUrl:"https://datalayer.ai",...Zu},renderToolResult:ud,description:Iu,onStateUpdate:ad,onNewChat:rd,suggestions:hd,submitOnSuggestionClick:gd,hideMessagesAfterToolUI:Ed,avatarConfig:{showAvatars:!0},placeholder:"Type a message...",backgroundColor:"canvas.subtle",frontendTools:md,showModelSelector:Md,availableModels:Ud,showToolsMenu:zd,showSkillsMenu:Vd,showTokenUsage:kd,showContextRing:Rd,runtimeId:uh,historyEndpoint:xh,historyAuthToken:Rh,pendingPrompt:bh??Cf,inspector:sh,showInformation:_h,onInformationClick:eh,onToolCallStart:Sh,onToolCallComplete:Dd,showToolApprovalBanner:$d,pendingApprovals:jd,onApproveApproval:Fd,onRejectApproval:rh,voice:Ad,voiceSpeaking:gh.speaking,onStopSpeaking:dh?$h:void 0,...Yd,...Dg,onLoadingChange:bp,onDisplayItemsChange:Mf,onSendReady:df,children:Am&&Rg?jsxRuntimeExports.jsx(Box,{px:3,pt:3,pb:2,overflow:"hidden",children:jsxRuntimeExports.jsx(CurrentBalloonBody,{text:yd?void 0:Id??Iu,fullText:yd?void 0:Nd,tool:yd,busy:cd,speaking:am&&cd,waiting:cd&&!am})}):ld})]}),bg=jsxRuntimeExports.jsx(IconButton,{icon:pd||CommentDiscussionIcon,"aria-label":Sd,unsafeDisableTooltip:!!$p,onClick:Np&&Ip==="page"?Jp:yp,size:"large",sx:{width:56,height:56,borderRadius:"50%",bg:wd||"accent.emphasis",color:"fg.onEmphasis",boxShadow:"shadow.large",transition:"transform 0.2s ease, box-shadow 0.2s ease",transform:np?"scale(1.1)":"scale(1)",...Hp?{animation:"chatFloatingBlink 1.1s ease-in-out infinite","@keyframes chatFloatingBlink":{"0%, 100%":{filter:"brightness(1)",boxShadow:"0 0 0 0 rgba(0,0,0,0)"},"50%":{filter:"brightness(1.25)",boxShadow:"0 0 0 6px var(--bgColor-accent-muted, rgba(84,174,255,0.4))"}},"@media (prefers-reduced-motion: reduce)":{animation:"none"}}:{},"&:hover":{bg:wd||"accent.emphasis",boxShadow:"shadow.extra-large"}}});return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[_p&&jsxRuntimeExports.jsx(AssistantStage,{character:Ah,state:Um,size:Mp,place:Bm.position?{left:px(Bm.position.left),top:px(Bm.position.top)}:Nm(),stageRef:Zm,onDragStart:Bm.onHandlePointerDown,open:Tf,onToggle:yp,balloon:Qd,balloonDisplay:oh,expandTarget:zh,insist:wh,onDismiss:Tm,ownRef:kf,mouthLevel:Uh,suggestions:yh,onSuggestion:Nh,inspector:sh,onBalloonDisplayChange:ph,onStop:Em&&Rf.current?()=>Rf.current?.stop():void 0,onNewChat:!mf&&Fu?Jm:void 0,onClear:!mf&&$u?Qm:void 0,onChangeCharacter:Bh,speech:dh?{muted:sf,onToggle:()=>{sf||dh.stop(),qf(!sf)}}:void 0,onResetPosition:Bm.position?Bm.reset:void 0,about:dm,sandbox:ug,contextMenu:rf}),Bu&&!Tf&&!_p&&jsxRuntimeExports.jsx(Box,{sx:{...Nm()},children:jsxRuntimeExports.jsxs(Box,{position:"relative",display:"inline-flex",isolation:"isolate",onMouseEnter:()=>kp(!0),onMouseLeave:()=>kp(!1),children:[bd&&jsxRuntimeExports.jsx(ButtonGlow,{color:wd}),np&&$p?jsxRuntimeExports.jsx(SpeechBalloon,{text:$p.text,more:$p.more,onOpen:yp,above:64,side:Ou.startsWith("bottom")?"above":"below",align:Ou.includes("right")?"right":"left",tailAt:28}):null,$p?bg:jsxRuntimeExports.jsx(Tooltip,{text:`${Sd}${F0?` (${F0})`:""}`,direction:Ou.includes("right")?"w":"e",children:bg}),Qh.length>0&&jsxRuntimeExports.jsx(Box,{position:"absolute",top:0,right:0,minWidth:18,height:18,px:1,display:"flex",alignItems:"center",justifyContent:"center",bg:"danger.emphasis",color:"fg.onEmphasis",borderRadius:"50%",fontSize:0,fontWeight:"bold",pointerEvents:"none",children:jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0},children:Qh.length>99?"99+":Qh.length})}),Hp&&jsxRuntimeExports.jsx(Box,{position:"absolute",top:0,left:0,right:0,bottom:0,borderRadius:"50%",border:"2px solid",borderColor:wd||"accent.emphasis",animation:"pulse 2s infinite",pointerEvents:"none",reducedMotion:{animation:"none",transform:"scale(1.15)",opacity:.6},sx:{"@keyframes pulse":{"0%":{transform:"scale(1)",opacity:1},"100%":{transform:"scale(1.5)",opacity:0}}}})]})}),yf&&Tf&&jsxRuntimeExports.jsx(Box,{position:"fixed",top:0,left:0,right:0,bottom:0,bg:"neutral.muted",opacity:.5,zIndex:999,onClick:yp}),Gd&&Bf==="panel"&&Tf&&!yf&&jsxRuntimeExports.jsx(Box,{position:"fixed",top:0,left:0,right:0,bottom:0,bg:"neutral.muted",opacity:.3,zIndex:1e3,onClick:yp}),Qf&&Cp?reactDomExports.createPortal(O0,Cp):O0]})}const LoopCanvasBlock=defineContributionPoint("loop.canvas.block"),LoopA2uiComponent=defineContributionPoint("loop.a2ui.component"),LoopAppFiles=defineContributionPoint("loop.app.files"),listeners$2=new Set;function requestSurface(Au){if(listeners$2.size===0)return!1;for(const lo of[...listeners$2])lo(Au);return!0}function onSurfaceRequest(Au){return listeners$2.add(Au),()=>{listeners$2.delete(Au)}}const listeners$1=new Set;function focusPrompt(){if(listeners$1.size===0)return!1;for(const Au of[...listeners$1])Au();return!0}function onPromptFocusRequest(Au){return listeners$1.add(Au),()=>{listeners$1.delete(Au)}}function agentServerOf(Au,lo){return Au.target==="datalayer"?Au.agentBaseUrl||void 0:Au.agentBaseUrl||lo}function noRuntimeSaid(Au,lo){return Au.state==="error"?lo.noRuntime(Au.errorReason??""):lo.runtimeStarting}const IDLE_SANDBOX_SNAPSHOT=Object.freeze({state:"idle"}),IDLE_SANDBOX_SNAPSHOT_SIGNAL={value:IDLE_SANDBOX_SNAPSHOT,peek:()=>IDLE_SANDBOX_SNAPSHOT},IDLE_SANDBOX_TARGET_SIGNAL={value:void 0,peek:()=>{}};function loopSurfaceId(Au){return`loop-${Au||"default"}`}function createPromptChannel(){const Au=new Set,lo=[];return{submit($u){if(Au.size===0)return lo.push($u),!0;for(const Ru of[...Au])Ru($u);return!0},subscribe($u){if(Au.add($u),lo.length>0){const Ru=lo.splice(0,lo.length);queueMicrotask(()=>{for(const Iu of Ru)$u(Iu)})}return()=>{Au.delete($u)}}}}const LoopViewType=defineContributionPoint("loop.viewType"),LoopEditorView=defineContributionPoint("loop.chat.surface"),LoopChatSurface=LoopEditorView,LoopFrontendTool=defineContributionPoint("loop.frontendTool"),LoopChatComposer=defineContributionPoint("loop.chat.composer"),LoopChatHeader=defineContributionPoint("loop.chat.header"),LoopAgentBlueprint=defineContributionPoint("loop.agent.blueprint"),LoopChatSuggestion=defineContributionPoint("loop.chat.suggestion"),LoopAssistantCharacter=defineContributionPoint("loop.assistant.character");defineContributionPoint("loop.assistant.menu");const LoopChatExtras=defineContributionPoint("loop.chat.extras"),LoopOpeningNotebook=defineContributionPoint("loop.notebook.opening"),LoopOpeningDocument=defineContributionPoint("loop.document.opening"),LoopAgentGate=defineGate("loop.agent.available"),LoopNotebookToolbar=defineContributionPoint("loop.notebook.toolbar"),LoopNotebookToolbarItem=defineContributionPoint("loop.notebook.toolbar.item"),LoopDocumentToolbar=defineContributionPoint("loop.document.toolbar"),LoopDocumentToolbarItem=defineContributionPoint("loop.document.toolbar.item"),LoopCommand=defineContributionPoint("loop.command"),LoopRunProps=defineContributionPoint("loop.runProps");function runForwardedProps(Au,lo){let $u;for(const Ru of[...Au.map(Iu=>Iu.props()),lo]){if(!Ru)continue;const Iu={...$u?.loop??{},...Ru.loop??{}};$u={...$u,...Ru},Object.keys(Iu).length>0&&($u.loop=Iu)}return $u}defineContributionPoint("loop.mention");const LoopSlots={header:"loop.header",chatHeader:"loop.chatHeader",promptAction:"loop.promptAction",inpromptMenu:"loop.inpromptMenu",footer:"loop.footer",status:"loop.status",root:"root",sidebar:"loop.sidebar"};function sandboxIndicatorState(Au,lo,$u){return Au==="error"?"connected-dead":Au==="starting"?"connected-starting":Au==="stopping"?"disconnecting":Au!=="running"?"disconnected":lo==="busy"||$u?"connected-busy":"connected-idle"}function canOpenView(Au,lo){return Au.canOpen?Au.canOpen(lo):!0}function parseCommand(Au){const lo=Au.trimStart();if(!lo.startsWith("/"))return;const[$u,...Ru]=lo.slice(1).split(/\s+/);if($u)return{name:$u.toLowerCase(),argv:Ru.join(" ").trim()}}const LoopChatLayout=defineContributionPoint("loop.chat.layout"),LoopPromptPanel=defineContributionPoint("loop.prompt.panel"),LoopChatTurn=defineContributionPoint("loop.chat.turn");function defineAgentCapacityPlugin(Au){const{key:lo,displayName:$u,description:Ru,specId:Iu,octicon:Ou,emoji:Pu,codemode:Du,createPayload:Lu,suggestions:ju,instructions:Bu,model:Fu,modeEffect:zu,name:qu,requiredBackendPlugins:Uu}=Au;return{name:qu??`@datalayer/loop-plugin-agent-${lo}`,...Uu?{requiredBackendPlugins:Uu}:{},displayName:$u,description:Ru,octicon:Ou??"dependabot",emoji:Pu,contributes:[contribution(LoopAgentBlueprint,{id:lo,specId:Iu,createPayload:{description:Ru,agent_library:"pydantic-ai",enable_codemode:Du??!1,...Lu},...Bu?{instructions:Bu}:{},...Fu?{model:Fu}:{},...zu?{modeEffect:zu}:{}},{id:lo}),...ju&&ju.length>0?[contribution(LoopChatSuggestion,{id:lo,suggestions:ju},{id:lo})]:[]]}}var util;(function(Au){Au.assertEqual=Iu=>{};function lo(Iu){}Au.assertIs=lo;function $u(Iu){throw new Error}Au.assertNever=$u,Au.arrayToEnum=Iu=>{const Ou={};for(const Pu of Iu)Ou[Pu]=Pu;return Ou},Au.getValidEnumValues=Iu=>{const Ou=Au.objectKeys(Iu).filter(Du=>typeof Iu[Iu[Du]]!="number"),Pu={};for(const Du of Ou)Pu[Du]=Iu[Du];return Au.objectValues(Pu)},Au.objectValues=Iu=>Au.objectKeys(Iu).map(function(Ou){return Iu[Ou]}),Au.objectKeys=typeof Object.keys=="function"?Iu=>Object.keys(Iu):Iu=>{const Ou=[];for(const Pu in Iu)Object.prototype.hasOwnProperty.call(Iu,Pu)&&Ou.push(Pu);return Ou},Au.find=(Iu,Ou)=>{for(const Pu of Iu)if(Ou(Pu))return Pu},Au.isInteger=typeof Number.isInteger=="function"?Iu=>Number.isInteger(Iu):Iu=>typeof Iu=="number"&&Number.isFinite(Iu)&&Math.floor(Iu)===Iu;function Ru(Iu,Ou=" | "){return Iu.map(Pu=>typeof Pu=="string"?`'${Pu}'`:Pu).join(Ou)}Au.joinValues=Ru,Au.jsonStringifyReplacer=(Iu,Ou)=>typeof Ou=="bigint"?Ou.toString():Ou})(util||(util={}));var objectUtil;(function(Au){Au.mergeShapes=(lo,$u)=>({...lo,...$u})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=Au=>{switch(typeof Au){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(Au)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(Au)?ZodParsedType.array:Au===null?ZodParsedType.null:Au.then&&typeof Au.then=="function"&&Au.catch&&typeof Au.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&Au instanceof Map?ZodParsedType.map:typeof Set<"u"&&Au instanceof Set?ZodParsedType.set:typeof Date<"u"&&Au instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ZodError extends Error{get errors(){return this.issues}constructor(lo){super(),this.issues=[],this.addIssue=Ru=>{this.issues=[...this.issues,Ru]},this.addIssues=(Ru=[])=>{this.issues=[...this.issues,...Ru]};const $u=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,$u):this.__proto__=$u,this.name="ZodError",this.issues=lo}format(lo){const $u=lo||function(Ou){return Ou.message},Ru={_errors:[]},Iu=Ou=>{for(const Pu of Ou.issues)if(Pu.code==="invalid_union")Pu.unionErrors.map(Iu);else if(Pu.code==="invalid_return_type")Iu(Pu.returnTypeError);else if(Pu.code==="invalid_arguments")Iu(Pu.argumentsError);else if(Pu.path.length===0)Ru._errors.push($u(Pu));else{let Du=Ru,Lu=0;for(;Lu<Pu.path.length;){const ju=Pu.path[Lu];Lu===Pu.path.length-1?(Du[ju]=Du[ju]||{_errors:[]},Du[ju]._errors.push($u(Pu))):Du[ju]=Du[ju]||{_errors:[]},Du=Du[ju],Lu++}}};return Iu(this),Ru}static assert(lo){if(!(lo instanceof ZodError))throw new Error(`Not a ZodError: ${lo}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(lo=$u=>$u.message){const $u={},Ru=[];for(const Iu of this.issues)if(Iu.path.length>0){const Ou=Iu.path[0];$u[Ou]=$u[Ou]||[],$u[Ou].push(lo(Iu))}else Ru.push(lo(Iu));return{formErrors:Ru,fieldErrors:$u}}get formErrors(){return this.flatten()}}ZodError.create=Au=>new ZodError(Au);const errorMap=(Au,lo)=>{let $u;switch(Au.code){case ZodIssueCode.invalid_type:Au.received===ZodParsedType.undefined?$u="Required":$u=`Expected ${Au.expected}, received ${Au.received}`;break;case ZodIssueCode.invalid_literal:$u=`Invalid literal value, expected ${JSON.stringify(Au.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:$u=`Unrecognized key(s) in object: ${util.joinValues(Au.keys,", ")}`;break;case ZodIssueCode.invalid_union:$u="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:$u=`Invalid discriminator value. Expected ${util.joinValues(Au.options)}`;break;case ZodIssueCode.invalid_enum_value:$u=`Invalid enum value. Expected ${util.joinValues(Au.options)}, received '${Au.received}'`;break;case ZodIssueCode.invalid_arguments:$u="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:$u="Invalid function return type";break;case ZodIssueCode.invalid_date:$u="Invalid date";break;case ZodIssueCode.invalid_string:typeof Au.validation=="object"?"includes"in Au.validation?($u=`Invalid input: must include "${Au.validation.includes}"`,typeof Au.validation.position=="number"&&($u=`${$u} at one or more positions greater than or equal to ${Au.validation.position}`)):"startsWith"in Au.validation?$u=`Invalid input: must start with "${Au.validation.startsWith}"`:"endsWith"in Au.validation?$u=`Invalid input: must end with "${Au.validation.endsWith}"`:util.assertNever(Au.validation):Au.validation!=="regex"?$u=`Invalid ${Au.validation}`:$u="Invalid";break;case ZodIssueCode.too_small:Au.type==="array"?$u=`Array must contain ${Au.exact?"exactly":Au.inclusive?"at least":"more than"} ${Au.minimum} element(s)`:Au.type==="string"?$u=`String must contain ${Au.exact?"exactly":Au.inclusive?"at least":"over"} ${Au.minimum} character(s)`:Au.type==="number"?$u=`Number must be ${Au.exact?"exactly equal to ":Au.inclusive?"greater than or equal to ":"greater than "}${Au.minimum}`:Au.type==="bigint"?$u=`Number must be ${Au.exact?"exactly equal to ":Au.inclusive?"greater than or equal to ":"greater than "}${Au.minimum}`:Au.type==="date"?$u=`Date must be ${Au.exact?"exactly equal to ":Au.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(Au.minimum))}`:$u="Invalid input";break;case ZodIssueCode.too_big:Au.type==="array"?$u=`Array must contain ${Au.exact?"exactly":Au.inclusive?"at most":"less than"} ${Au.maximum} element(s)`:Au.type==="string"?$u=`String must contain ${Au.exact?"exactly":Au.inclusive?"at most":"under"} ${Au.maximum} character(s)`:Au.type==="number"?$u=`Number must be ${Au.exact?"exactly":Au.inclusive?"less than or equal to":"less than"} ${Au.maximum}`:Au.type==="bigint"?$u=`BigInt must be ${Au.exact?"exactly":Au.inclusive?"less than or equal to":"less than"} ${Au.maximum}`:Au.type==="date"?$u=`Date must be ${Au.exact?"exactly":Au.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(Au.maximum))}`:$u="Invalid input";break;case ZodIssueCode.custom:$u="Invalid input";break;case ZodIssueCode.invalid_intersection_types:$u="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:$u=`Number must be a multiple of ${Au.multipleOf}`;break;case ZodIssueCode.not_finite:$u="Number must be finite";break;default:$u=lo.defaultError,util.assertNever(Au)}return{message:$u}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=Au=>{const{data:lo,path:$u,errorMaps:Ru,issueData:Iu}=Au,Ou=[...$u,...Iu.path||[]],Pu={...Iu,path:Ou};if(Iu.message!==void 0)return{...Iu,path:Ou,message:Iu.message};let Du="";const Lu=Ru.filter(ju=>!!ju).slice().reverse();for(const ju of Lu)Du=ju(Pu,{data:lo,defaultError:Du}).message;return{...Iu,path:Ou,message:Du}};function addIssueToContext(Au,lo){const $u=getErrorMap(),Ru=makeIssue({issueData:lo,data:Au.data,path:Au.path,errorMaps:[Au.common.contextualErrorMap,Au.schemaErrorMap,$u,$u===errorMap?void 0:errorMap].filter(Iu=>!!Iu)});Au.common.issues.push(Ru)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(lo,$u){const Ru=[];for(const Iu of $u){if(Iu.status==="aborted")return INVALID;Iu.status==="dirty"&&lo.dirty(),Ru.push(Iu.value)}return{status:lo.value,value:Ru}}static async mergeObjectAsync(lo,$u){const Ru=[];for(const Iu of $u){const Ou=await Iu.key,Pu=await Iu.value;Ru.push({key:Ou,value:Pu})}return ParseStatus.mergeObjectSync(lo,Ru)}static mergeObjectSync(lo,$u){const Ru={};for(const Iu of $u){const{key:Ou,value:Pu}=Iu;if(Ou.status==="aborted"||Pu.status==="aborted")return INVALID;Ou.status==="dirty"&&lo.dirty(),Pu.status==="dirty"&&lo.dirty(),Ou.value!=="__proto__"&&(typeof Pu.value<"u"||Iu.alwaysSet)&&(Ru[Ou.value]=Pu.value)}return{status:lo.value,value:Ru}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=Au=>({status:"dirty",value:Au}),OK=Au=>({status:"valid",value:Au}),isAborted=Au=>Au.status==="aborted",isDirty=Au=>Au.status==="dirty",isValid=Au=>Au.status==="valid",isAsync=Au=>typeof Promise<"u"&&Au instanceof Promise;var errorUtil;(function(Au){Au.errToObj=lo=>typeof lo=="string"?{message:lo}:lo||{},Au.toString=lo=>typeof lo=="string"?lo:lo?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(lo,$u,Ru,Iu){this._cachedPath=[],this.parent=lo,this.data=$u,this._path=Ru,this._key=Iu}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(Au,lo)=>{if(isValid(lo))return{success:!0,data:lo.value};if(!Au.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const $u=new ZodError(Au.common.issues);return this._error=$u,this._error}}};function processCreateParams(Au){if(!Au)return{};const{errorMap:lo,invalid_type_error:$u,required_error:Ru,description:Iu}=Au;if(lo&&($u||Ru))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return lo?{errorMap:lo,description:Iu}:{errorMap:(Pu,Du)=>{const{message:Lu}=Au;return Pu.code==="invalid_enum_value"?{message:Lu??Du.defaultError}:typeof Du.data>"u"?{message:Lu??Ru??Du.defaultError}:Pu.code!=="invalid_type"?{message:Du.defaultError}:{message:Lu??$u??Du.defaultError}},description:Iu}}class ZodType{get description(){return this._def.description}_getType(lo){return getParsedType(lo.data)}_getOrReturnCtx(lo,$u){return $u||{common:lo.parent.common,data:lo.data,parsedType:getParsedType(lo.data),schemaErrorMap:this._def.errorMap,path:lo.path,parent:lo.parent}}_processInputParams(lo){return{status:new ParseStatus,ctx:{common:lo.parent.common,data:lo.data,parsedType:getParsedType(lo.data),schemaErrorMap:this._def.errorMap,path:lo.path,parent:lo.parent}}}_parseSync(lo){const $u=this._parse(lo);if(isAsync($u))throw new Error("Synchronous parse encountered promise.");return $u}_parseAsync(lo){const $u=this._parse(lo);return Promise.resolve($u)}parse(lo,$u){const Ru=this.safeParse(lo,$u);if(Ru.success)return Ru.data;throw Ru.error}safeParse(lo,$u){const Ru={common:{issues:[],async:$u?.async??!1,contextualErrorMap:$u?.errorMap},path:$u?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:lo,parsedType:getParsedType(lo)},Iu=this._parseSync({data:lo,path:Ru.path,parent:Ru});return handleResult(Ru,Iu)}"~validate"(lo){const $u={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:lo,parsedType:getParsedType(lo)};if(!this["~standard"].async)try{const Ru=this._parseSync({data:lo,path:[],parent:$u});return isValid(Ru)?{value:Ru.value}:{issues:$u.common.issues}}catch(Ru){Ru?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),$u.common={issues:[],async:!0}}return this._parseAsync({data:lo,path:[],parent:$u}).then(Ru=>isValid(Ru)?{value:Ru.value}:{issues:$u.common.issues})}async parseAsync(lo,$u){const Ru=await this.safeParseAsync(lo,$u);if(Ru.success)return Ru.data;throw Ru.error}async safeParseAsync(lo,$u){const Ru={common:{issues:[],contextualErrorMap:$u?.errorMap,async:!0},path:$u?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:lo,parsedType:getParsedType(lo)},Iu=this._parse({data:lo,path:Ru.path,parent:Ru}),Ou=await(isAsync(Iu)?Iu:Promise.resolve(Iu));return handleResult(Ru,Ou)}refine(lo,$u){const Ru=Iu=>typeof $u=="string"||typeof $u>"u"?{message:$u}:typeof $u=="function"?$u(Iu):$u;return this._refinement((Iu,Ou)=>{const Pu=lo(Iu),Du=()=>Ou.addIssue({code:ZodIssueCode.custom,...Ru(Iu)});return typeof Promise<"u"&&Pu instanceof Promise?Pu.then(Lu=>Lu?!0:(Du(),!1)):Pu?!0:(Du(),!1)})}refinement(lo,$u){return this._refinement((Ru,Iu)=>lo(Ru)?!0:(Iu.addIssue(typeof $u=="function"?$u(Ru,Iu):$u),!1))}_refinement(lo){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:lo}})}superRefine(lo){return this._refinement(lo)}constructor(lo){this.spa=this.safeParseAsync,this._def=lo,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:$u=>this["~validate"]($u)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(lo){return ZodUnion.create([this,lo],this._def)}and(lo){return ZodIntersection.create(this,lo,this._def)}transform(lo){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:lo}})}default(lo){const $u=typeof lo=="function"?lo:()=>lo;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:$u,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(lo){const $u=typeof lo=="function"?lo:()=>lo;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:$u,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(lo){const $u=this.constructor;return new $u({...this._def,description:lo})}pipe(lo){return ZodPipeline.create(this,lo)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(Au){let lo="[0-5]\\d";Au.precision?lo=`${lo}\\.\\d{${Au.precision}}`:Au.precision==null&&(lo=`${lo}(\\.\\d+)?`);const $u=Au.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${lo})${$u}`}function timeRegex(Au){return new RegExp(`^${timeRegexSource(Au)}$`)}function datetimeRegex(Au){let lo=`${dateRegexSource}T${timeRegexSource(Au)}`;const $u=[];return $u.push(Au.local?"Z?":"Z"),Au.offset&&$u.push("([+-]\\d{2}:?\\d{2})"),lo=`${lo}(${$u.join("|")})`,new RegExp(`^${lo}$`)}function isValidIP(Au,lo){return!!((lo==="v4"||!lo)&&ipv4Regex.test(Au)||(lo==="v6"||!lo)&&ipv6Regex.test(Au))}function isValidJWT(Au,lo){if(!jwtRegex.test(Au))return!1;try{const[$u]=Au.split(".");if(!$u)return!1;const Ru=$u.replace(/-/g,"+").replace(/_/g,"/").padEnd($u.length+(4-$u.length%4)%4,"="),Iu=JSON.parse(atob(Ru));return!(typeof Iu!="object"||Iu===null||"typ"in Iu&&Iu?.typ!=="JWT"||!Iu.alg||lo&&Iu.alg!==lo)}catch{return!1}}function isValidCidr(Au,lo){return!!((lo==="v4"||!lo)&&ipv4CidrRegex.test(Au)||(lo==="v6"||!lo)&&ipv6CidrRegex.test(Au))}class ZodString extends ZodType{_parse(lo){if(this._def.coerce&&(lo.data=String(lo.data)),this._getType(lo)!==ZodParsedType.string){const Ou=this._getOrReturnCtx(lo);return addIssueToContext(Ou,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:Ou.parsedType}),INVALID}const Ru=new ParseStatus;let Iu;for(const Ou of this._def.checks)if(Ou.kind==="min")lo.data.length<Ou.value&&(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.too_small,minimum:Ou.value,type:"string",inclusive:!0,exact:!1,message:Ou.message}),Ru.dirty());else if(Ou.kind==="max")lo.data.length>Ou.value&&(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.too_big,maximum:Ou.value,type:"string",inclusive:!0,exact:!1,message:Ou.message}),Ru.dirty());else if(Ou.kind==="length"){const Pu=lo.data.length>Ou.value,Du=lo.data.length<Ou.value;(Pu||Du)&&(Iu=this._getOrReturnCtx(lo,Iu),Pu?addIssueToContext(Iu,{code:ZodIssueCode.too_big,maximum:Ou.value,type:"string",inclusive:!0,exact:!0,message:Ou.message}):Du&&addIssueToContext(Iu,{code:ZodIssueCode.too_small,minimum:Ou.value,type:"string",inclusive:!0,exact:!0,message:Ou.message}),Ru.dirty())}else if(Ou.kind==="email")emailRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"email",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty());else if(Ou.kind==="emoji")emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"emoji",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty());else if(Ou.kind==="uuid")uuidRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"uuid",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty());else if(Ou.kind==="nanoid")nanoidRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty());else if(Ou.kind==="cuid")cuidRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"cuid",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty());else if(Ou.kind==="cuid2")cuid2Regex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty());else if(Ou.kind==="ulid")ulidRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"ulid",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty());else if(Ou.kind==="url")try{new URL(lo.data)}catch{Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"url",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty()}else Ou.kind==="regex"?(Ou.regex.lastIndex=0,Ou.regex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"regex",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty())):Ou.kind==="trim"?lo.data=lo.data.trim():Ou.kind==="includes"?lo.data.includes(Ou.value,Ou.position)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:{includes:Ou.value,position:Ou.position},message:Ou.message}),Ru.dirty()):Ou.kind==="toLowerCase"?lo.data=lo.data.toLowerCase():Ou.kind==="toUpperCase"?lo.data=lo.data.toUpperCase():Ou.kind==="startsWith"?lo.data.startsWith(Ou.value)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:{startsWith:Ou.value},message:Ou.message}),Ru.dirty()):Ou.kind==="endsWith"?lo.data.endsWith(Ou.value)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:{endsWith:Ou.value},message:Ou.message}),Ru.dirty()):Ou.kind==="datetime"?datetimeRegex(Ou).test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:"datetime",message:Ou.message}),Ru.dirty()):Ou.kind==="date"?dateRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:"date",message:Ou.message}),Ru.dirty()):Ou.kind==="time"?timeRegex(Ou).test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.invalid_string,validation:"time",message:Ou.message}),Ru.dirty()):Ou.kind==="duration"?durationRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"duration",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty()):Ou.kind==="ip"?isValidIP(lo.data,Ou.version)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"ip",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty()):Ou.kind==="jwt"?isValidJWT(lo.data,Ou.alg)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"jwt",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty()):Ou.kind==="cidr"?isValidCidr(lo.data,Ou.version)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"cidr",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty()):Ou.kind==="base64"?base64Regex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"base64",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty()):Ou.kind==="base64url"?base64urlRegex.test(lo.data)||(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{validation:"base64url",code:ZodIssueCode.invalid_string,message:Ou.message}),Ru.dirty()):util.assertNever(Ou);return{status:Ru.value,value:lo.data}}_regex(lo,$u,Ru){return this.refinement(Iu=>lo.test(Iu),{validation:$u,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(Ru)})}_addCheck(lo){return new ZodString({...this._def,checks:[...this._def.checks,lo]})}email(lo){return this._addCheck({kind:"email",...errorUtil.errToObj(lo)})}url(lo){return this._addCheck({kind:"url",...errorUtil.errToObj(lo)})}emoji(lo){return this._addCheck({kind:"emoji",...errorUtil.errToObj(lo)})}uuid(lo){return this._addCheck({kind:"uuid",...errorUtil.errToObj(lo)})}nanoid(lo){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(lo)})}cuid(lo){return this._addCheck({kind:"cuid",...errorUtil.errToObj(lo)})}cuid2(lo){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(lo)})}ulid(lo){return this._addCheck({kind:"ulid",...errorUtil.errToObj(lo)})}base64(lo){return this._addCheck({kind:"base64",...errorUtil.errToObj(lo)})}base64url(lo){return this._addCheck({kind:"base64url",...errorUtil.errToObj(lo)})}jwt(lo){return this._addCheck({kind:"jwt",...errorUtil.errToObj(lo)})}ip(lo){return this._addCheck({kind:"ip",...errorUtil.errToObj(lo)})}cidr(lo){return this._addCheck({kind:"cidr",...errorUtil.errToObj(lo)})}datetime(lo){return typeof lo=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:lo}):this._addCheck({kind:"datetime",precision:typeof lo?.precision>"u"?null:lo?.precision,offset:lo?.offset??!1,local:lo?.local??!1,...errorUtil.errToObj(lo?.message)})}date(lo){return this._addCheck({kind:"date",message:lo})}time(lo){return typeof lo=="string"?this._addCheck({kind:"time",precision:null,message:lo}):this._addCheck({kind:"time",precision:typeof lo?.precision>"u"?null:lo?.precision,...errorUtil.errToObj(lo?.message)})}duration(lo){return this._addCheck({kind:"duration",...errorUtil.errToObj(lo)})}regex(lo,$u){return this._addCheck({kind:"regex",regex:lo,...errorUtil.errToObj($u)})}includes(lo,$u){return this._addCheck({kind:"includes",value:lo,position:$u?.position,...errorUtil.errToObj($u?.message)})}startsWith(lo,$u){return this._addCheck({kind:"startsWith",value:lo,...errorUtil.errToObj($u)})}endsWith(lo,$u){return this._addCheck({kind:"endsWith",value:lo,...errorUtil.errToObj($u)})}min(lo,$u){return this._addCheck({kind:"min",value:lo,...errorUtil.errToObj($u)})}max(lo,$u){return this._addCheck({kind:"max",value:lo,...errorUtil.errToObj($u)})}length(lo,$u){return this._addCheck({kind:"length",value:lo,...errorUtil.errToObj($u)})}nonempty(lo){return this.min(1,errorUtil.errToObj(lo))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(lo=>lo.kind==="datetime")}get isDate(){return!!this._def.checks.find(lo=>lo.kind==="date")}get isTime(){return!!this._def.checks.find(lo=>lo.kind==="time")}get isDuration(){return!!this._def.checks.find(lo=>lo.kind==="duration")}get isEmail(){return!!this._def.checks.find(lo=>lo.kind==="email")}get isURL(){return!!this._def.checks.find(lo=>lo.kind==="url")}get isEmoji(){return!!this._def.checks.find(lo=>lo.kind==="emoji")}get isUUID(){return!!this._def.checks.find(lo=>lo.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(lo=>lo.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(lo=>lo.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(lo=>lo.kind==="cuid2")}get isULID(){return!!this._def.checks.find(lo=>lo.kind==="ulid")}get isIP(){return!!this._def.checks.find(lo=>lo.kind==="ip")}get isCIDR(){return!!this._def.checks.find(lo=>lo.kind==="cidr")}get isBase64(){return!!this._def.checks.find(lo=>lo.kind==="base64")}get isBase64url(){return!!this._def.checks.find(lo=>lo.kind==="base64url")}get minLength(){let lo=null;for(const $u of this._def.checks)$u.kind==="min"&&(lo===null||$u.value>lo)&&(lo=$u.value);return lo}get maxLength(){let lo=null;for(const $u of this._def.checks)$u.kind==="max"&&(lo===null||$u.value<lo)&&(lo=$u.value);return lo}}ZodString.create=Au=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:Au?.coerce??!1,...processCreateParams(Au)});function floatSafeRemainder(Au,lo){const $u=(Au.toString().split(".")[1]||"").length,Ru=(lo.toString().split(".")[1]||"").length,Iu=$u>Ru?$u:Ru,Ou=Number.parseInt(Au.toFixed(Iu).replace(".","")),Pu=Number.parseInt(lo.toFixed(Iu).replace(".",""));return Ou%Pu/10**Iu}class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(lo){if(this._def.coerce&&(lo.data=Number(lo.data)),this._getType(lo)!==ZodParsedType.number){const Ou=this._getOrReturnCtx(lo);return addIssueToContext(Ou,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:Ou.parsedType}),INVALID}let Ru;const Iu=new ParseStatus;for(const Ou of this._def.checks)Ou.kind==="int"?util.isInteger(lo.data)||(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:Ou.message}),Iu.dirty()):Ou.kind==="min"?(Ou.inclusive?lo.data<Ou.value:lo.data<=Ou.value)&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.too_small,minimum:Ou.value,type:"number",inclusive:Ou.inclusive,exact:!1,message:Ou.message}),Iu.dirty()):Ou.kind==="max"?(Ou.inclusive?lo.data>Ou.value:lo.data>=Ou.value)&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.too_big,maximum:Ou.value,type:"number",inclusive:Ou.inclusive,exact:!1,message:Ou.message}),Iu.dirty()):Ou.kind==="multipleOf"?floatSafeRemainder(lo.data,Ou.value)!==0&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.not_multiple_of,multipleOf:Ou.value,message:Ou.message}),Iu.dirty()):Ou.kind==="finite"?Number.isFinite(lo.data)||(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.not_finite,message:Ou.message}),Iu.dirty()):util.assertNever(Ou);return{status:Iu.value,value:lo.data}}gte(lo,$u){return this.setLimit("min",lo,!0,errorUtil.toString($u))}gt(lo,$u){return this.setLimit("min",lo,!1,errorUtil.toString($u))}lte(lo,$u){return this.setLimit("max",lo,!0,errorUtil.toString($u))}lt(lo,$u){return this.setLimit("max",lo,!1,errorUtil.toString($u))}setLimit(lo,$u,Ru,Iu){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:lo,value:$u,inclusive:Ru,message:errorUtil.toString(Iu)}]})}_addCheck(lo){return new ZodNumber({...this._def,checks:[...this._def.checks,lo]})}int(lo){return this._addCheck({kind:"int",message:errorUtil.toString(lo)})}positive(lo){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(lo)})}negative(lo){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(lo)})}nonpositive(lo){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(lo)})}nonnegative(lo){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(lo)})}multipleOf(lo,$u){return this._addCheck({kind:"multipleOf",value:lo,message:errorUtil.toString($u)})}finite(lo){return this._addCheck({kind:"finite",message:errorUtil.toString(lo)})}safe(lo){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(lo)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(lo)})}get minValue(){let lo=null;for(const $u of this._def.checks)$u.kind==="min"&&(lo===null||$u.value>lo)&&(lo=$u.value);return lo}get maxValue(){let lo=null;for(const $u of this._def.checks)$u.kind==="max"&&(lo===null||$u.value<lo)&&(lo=$u.value);return lo}get isInt(){return!!this._def.checks.find(lo=>lo.kind==="int"||lo.kind==="multipleOf"&&util.isInteger(lo.value))}get isFinite(){let lo=null,$u=null;for(const Ru of this._def.checks){if(Ru.kind==="finite"||Ru.kind==="int"||Ru.kind==="multipleOf")return!0;Ru.kind==="min"?($u===null||Ru.value>$u)&&($u=Ru.value):Ru.kind==="max"&&(lo===null||Ru.value<lo)&&(lo=Ru.value)}return Number.isFinite($u)&&Number.isFinite(lo)}}ZodNumber.create=Au=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:Au?.coerce||!1,...processCreateParams(Au)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(lo){if(this._def.coerce)try{lo.data=BigInt(lo.data)}catch{return this._getInvalidInput(lo)}if(this._getType(lo)!==ZodParsedType.bigint)return this._getInvalidInput(lo);let Ru;const Iu=new ParseStatus;for(const Ou of this._def.checks)Ou.kind==="min"?(Ou.inclusive?lo.data<Ou.value:lo.data<=Ou.value)&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.too_small,type:"bigint",minimum:Ou.value,inclusive:Ou.inclusive,message:Ou.message}),Iu.dirty()):Ou.kind==="max"?(Ou.inclusive?lo.data>Ou.value:lo.data>=Ou.value)&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.too_big,type:"bigint",maximum:Ou.value,inclusive:Ou.inclusive,message:Ou.message}),Iu.dirty()):Ou.kind==="multipleOf"?lo.data%Ou.value!==BigInt(0)&&(Ru=this._getOrReturnCtx(lo,Ru),addIssueToContext(Ru,{code:ZodIssueCode.not_multiple_of,multipleOf:Ou.value,message:Ou.message}),Iu.dirty()):util.assertNever(Ou);return{status:Iu.value,value:lo.data}}_getInvalidInput(lo){const $u=this._getOrReturnCtx(lo);return addIssueToContext($u,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:$u.parsedType}),INVALID}gte(lo,$u){return this.setLimit("min",lo,!0,errorUtil.toString($u))}gt(lo,$u){return this.setLimit("min",lo,!1,errorUtil.toString($u))}lte(lo,$u){return this.setLimit("max",lo,!0,errorUtil.toString($u))}lt(lo,$u){return this.setLimit("max",lo,!1,errorUtil.toString($u))}setLimit(lo,$u,Ru,Iu){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:lo,value:$u,inclusive:Ru,message:errorUtil.toString(Iu)}]})}_addCheck(lo){return new ZodBigInt({...this._def,checks:[...this._def.checks,lo]})}positive(lo){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(lo)})}negative(lo){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(lo)})}nonpositive(lo){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(lo)})}nonnegative(lo){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(lo)})}multipleOf(lo,$u){return this._addCheck({kind:"multipleOf",value:lo,message:errorUtil.toString($u)})}get minValue(){let lo=null;for(const $u of this._def.checks)$u.kind==="min"&&(lo===null||$u.value>lo)&&(lo=$u.value);return lo}get maxValue(){let lo=null;for(const $u of this._def.checks)$u.kind==="max"&&(lo===null||$u.value<lo)&&(lo=$u.value);return lo}}ZodBigInt.create=Au=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:Au?.coerce??!1,...processCreateParams(Au)});class ZodBoolean extends ZodType{_parse(lo){if(this._def.coerce&&(lo.data=!!lo.data),this._getType(lo)!==ZodParsedType.boolean){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:Ru.parsedType}),INVALID}return OK(lo.data)}}ZodBoolean.create=Au=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:Au?.coerce||!1,...processCreateParams(Au)});class ZodDate extends ZodType{_parse(lo){if(this._def.coerce&&(lo.data=new Date(lo.data)),this._getType(lo)!==ZodParsedType.date){const Ou=this._getOrReturnCtx(lo);return addIssueToContext(Ou,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:Ou.parsedType}),INVALID}if(Number.isNaN(lo.data.getTime())){const Ou=this._getOrReturnCtx(lo);return addIssueToContext(Ou,{code:ZodIssueCode.invalid_date}),INVALID}const Ru=new ParseStatus;let Iu;for(const Ou of this._def.checks)Ou.kind==="min"?lo.data.getTime()<Ou.value&&(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.too_small,message:Ou.message,inclusive:!0,exact:!1,minimum:Ou.value,type:"date"}),Ru.dirty()):Ou.kind==="max"?lo.data.getTime()>Ou.value&&(Iu=this._getOrReturnCtx(lo,Iu),addIssueToContext(Iu,{code:ZodIssueCode.too_big,message:Ou.message,inclusive:!0,exact:!1,maximum:Ou.value,type:"date"}),Ru.dirty()):util.assertNever(Ou);return{status:Ru.value,value:new Date(lo.data.getTime())}}_addCheck(lo){return new ZodDate({...this._def,checks:[...this._def.checks,lo]})}min(lo,$u){return this._addCheck({kind:"min",value:lo.getTime(),message:errorUtil.toString($u)})}max(lo,$u){return this._addCheck({kind:"max",value:lo.getTime(),message:errorUtil.toString($u)})}get minDate(){let lo=null;for(const $u of this._def.checks)$u.kind==="min"&&(lo===null||$u.value>lo)&&(lo=$u.value);return lo!=null?new Date(lo):null}get maxDate(){let lo=null;for(const $u of this._def.checks)$u.kind==="max"&&(lo===null||$u.value<lo)&&(lo=$u.value);return lo!=null?new Date(lo):null}}ZodDate.create=Au=>new ZodDate({checks:[],coerce:Au?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(Au)});class ZodSymbol extends ZodType{_parse(lo){if(this._getType(lo)!==ZodParsedType.symbol){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:Ru.parsedType}),INVALID}return OK(lo.data)}}ZodSymbol.create=Au=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(Au)});class ZodUndefined extends ZodType{_parse(lo){if(this._getType(lo)!==ZodParsedType.undefined){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:Ru.parsedType}),INVALID}return OK(lo.data)}}ZodUndefined.create=Au=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(Au)});class ZodNull extends ZodType{_parse(lo){if(this._getType(lo)!==ZodParsedType.null){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:Ru.parsedType}),INVALID}return OK(lo.data)}}ZodNull.create=Au=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(Au)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(lo){return OK(lo.data)}}ZodAny.create=Au=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(Au)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(lo){return OK(lo.data)}}ZodUnknown.create=Au=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(Au)});class ZodNever extends ZodType{_parse(lo){const $u=this._getOrReturnCtx(lo);return addIssueToContext($u,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:$u.parsedType}),INVALID}}ZodNever.create=Au=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(Au)});class ZodVoid extends ZodType{_parse(lo){if(this._getType(lo)!==ZodParsedType.undefined){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:Ru.parsedType}),INVALID}return OK(lo.data)}}ZodVoid.create=Au=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(Au)});class ZodArray extends ZodType{_parse(lo){const{ctx:$u,status:Ru}=this._processInputParams(lo),Iu=this._def;if($u.parsedType!==ZodParsedType.array)return addIssueToContext($u,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:$u.parsedType}),INVALID;if(Iu.exactLength!==null){const Pu=$u.data.length>Iu.exactLength.value,Du=$u.data.length<Iu.exactLength.value;(Pu||Du)&&(addIssueToContext($u,{code:Pu?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:Du?Iu.exactLength.value:void 0,maximum:Pu?Iu.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:Iu.exactLength.message}),Ru.dirty())}if(Iu.minLength!==null&&$u.data.length<Iu.minLength.value&&(addIssueToContext($u,{code:ZodIssueCode.too_small,minimum:Iu.minLength.value,type:"array",inclusive:!0,exact:!1,message:Iu.minLength.message}),Ru.dirty()),Iu.maxLength!==null&&$u.data.length>Iu.maxLength.value&&(addIssueToContext($u,{code:ZodIssueCode.too_big,maximum:Iu.maxLength.value,type:"array",inclusive:!0,exact:!1,message:Iu.maxLength.message}),Ru.dirty()),$u.common.async)return Promise.all([...$u.data].map((Pu,Du)=>Iu.type._parseAsync(new ParseInputLazyPath($u,Pu,$u.path,Du)))).then(Pu=>ParseStatus.mergeArray(Ru,Pu));const Ou=[...$u.data].map((Pu,Du)=>Iu.type._parseSync(new ParseInputLazyPath($u,Pu,$u.path,Du)));return ParseStatus.mergeArray(Ru,Ou)}get element(){return this._def.type}min(lo,$u){return new ZodArray({...this._def,minLength:{value:lo,message:errorUtil.toString($u)}})}max(lo,$u){return new ZodArray({...this._def,maxLength:{value:lo,message:errorUtil.toString($u)}})}length(lo,$u){return new ZodArray({...this._def,exactLength:{value:lo,message:errorUtil.toString($u)}})}nonempty(lo){return this.min(1,lo)}}ZodArray.create=(Au,lo)=>new ZodArray({type:Au,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(lo)});function deepPartialify(Au){if(Au instanceof ZodObject){const lo={};for(const $u in Au.shape){const Ru=Au.shape[$u];lo[$u]=ZodOptional.create(deepPartialify(Ru))}return new ZodObject({...Au._def,shape:()=>lo})}else return Au instanceof ZodArray?new ZodArray({...Au._def,type:deepPartialify(Au.element)}):Au instanceof ZodOptional?ZodOptional.create(deepPartialify(Au.unwrap())):Au instanceof ZodNullable?ZodNullable.create(deepPartialify(Au.unwrap())):Au instanceof ZodTuple?ZodTuple.create(Au.items.map(lo=>deepPartialify(lo))):Au}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const lo=this._def.shape(),$u=util.objectKeys(lo);return this._cached={shape:lo,keys:$u},this._cached}_parse(lo){if(this._getType(lo)!==ZodParsedType.object){const ju=this._getOrReturnCtx(lo);return addIssueToContext(ju,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ju.parsedType}),INVALID}const{status:Ru,ctx:Iu}=this._processInputParams(lo),{shape:Ou,keys:Pu}=this._getCached(),Du=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const ju in Iu.data)Pu.includes(ju)||Du.push(ju);const Lu=[];for(const ju of Pu){const Bu=Ou[ju],Fu=Iu.data[ju];Lu.push({key:{status:"valid",value:ju},value:Bu._parse(new ParseInputLazyPath(Iu,Fu,Iu.path,ju)),alwaysSet:ju in Iu.data})}if(this._def.catchall instanceof ZodNever){const ju=this._def.unknownKeys;if(ju==="passthrough")for(const Bu of Du)Lu.push({key:{status:"valid",value:Bu},value:{status:"valid",value:Iu.data[Bu]}});else if(ju==="strict")Du.length>0&&(addIssueToContext(Iu,{code:ZodIssueCode.unrecognized_keys,keys:Du}),Ru.dirty());else if(ju!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const ju=this._def.catchall;for(const Bu of Du){const Fu=Iu.data[Bu];Lu.push({key:{status:"valid",value:Bu},value:ju._parse(new ParseInputLazyPath(Iu,Fu,Iu.path,Bu)),alwaysSet:Bu in Iu.data})}}return Iu.common.async?Promise.resolve().then(async()=>{const ju=[];for(const Bu of Lu){const Fu=await Bu.key,zu=await Bu.value;ju.push({key:Fu,value:zu,alwaysSet:Bu.alwaysSet})}return ju}).then(ju=>ParseStatus.mergeObjectSync(Ru,ju)):ParseStatus.mergeObjectSync(Ru,Lu)}get shape(){return this._def.shape()}strict(lo){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...lo!==void 0?{errorMap:($u,Ru)=>{const Iu=this._def.errorMap?.($u,Ru).message??Ru.defaultError;return $u.code==="unrecognized_keys"?{message:errorUtil.errToObj(lo).message??Iu}:{message:Iu}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(lo){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...lo})})}merge(lo){return new ZodObject({unknownKeys:lo._def.unknownKeys,catchall:lo._def.catchall,shape:()=>({...this._def.shape(),...lo._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(lo,$u){return this.augment({[lo]:$u})}catchall(lo){return new ZodObject({...this._def,catchall:lo})}pick(lo){const $u={};for(const Ru of util.objectKeys(lo))lo[Ru]&&this.shape[Ru]&&($u[Ru]=this.shape[Ru]);return new ZodObject({...this._def,shape:()=>$u})}omit(lo){const $u={};for(const Ru of util.objectKeys(this.shape))lo[Ru]||($u[Ru]=this.shape[Ru]);return new ZodObject({...this._def,shape:()=>$u})}deepPartial(){return deepPartialify(this)}partial(lo){const $u={};for(const Ru of util.objectKeys(this.shape)){const Iu=this.shape[Ru];lo&&!lo[Ru]?$u[Ru]=Iu:$u[Ru]=Iu.optional()}return new ZodObject({...this._def,shape:()=>$u})}required(lo){const $u={};for(const Ru of util.objectKeys(this.shape))if(lo&&!lo[Ru])$u[Ru]=this.shape[Ru];else{let Ou=this.shape[Ru];for(;Ou instanceof ZodOptional;)Ou=Ou._def.innerType;$u[Ru]=Ou}return new ZodObject({...this._def,shape:()=>$u})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(Au,lo)=>new ZodObject({shape:()=>Au,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(lo)});ZodObject.strictCreate=(Au,lo)=>new ZodObject({shape:()=>Au,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(lo)});ZodObject.lazycreate=(Au,lo)=>new ZodObject({shape:Au,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(lo)});class ZodUnion extends ZodType{_parse(lo){const{ctx:$u}=this._processInputParams(lo),Ru=this._def.options;function Iu(Ou){for(const Du of Ou)if(Du.result.status==="valid")return Du.result;for(const Du of Ou)if(Du.result.status==="dirty")return $u.common.issues.push(...Du.ctx.common.issues),Du.result;const Pu=Ou.map(Du=>new ZodError(Du.ctx.common.issues));return addIssueToContext($u,{code:ZodIssueCode.invalid_union,unionErrors:Pu}),INVALID}if($u.common.async)return Promise.all(Ru.map(async Ou=>{const Pu={...$u,common:{...$u.common,issues:[]},parent:null};return{result:await Ou._parseAsync({data:$u.data,path:$u.path,parent:Pu}),ctx:Pu}})).then(Iu);{let Ou;const Pu=[];for(const Lu of Ru){const ju={...$u,common:{...$u.common,issues:[]},parent:null},Bu=Lu._parseSync({data:$u.data,path:$u.path,parent:ju});if(Bu.status==="valid")return Bu;Bu.status==="dirty"&&!Ou&&(Ou={result:Bu,ctx:ju}),ju.common.issues.length&&Pu.push(ju.common.issues)}if(Ou)return $u.common.issues.push(...Ou.ctx.common.issues),Ou.result;const Du=Pu.map(Lu=>new ZodError(Lu));return addIssueToContext($u,{code:ZodIssueCode.invalid_union,unionErrors:Du}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(Au,lo)=>new ZodUnion({options:Au,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(lo)});function mergeValues(Au,lo){const $u=getParsedType(Au),Ru=getParsedType(lo);if(Au===lo)return{valid:!0,data:Au};if($u===ZodParsedType.object&&Ru===ZodParsedType.object){const Iu=util.objectKeys(lo),Ou=util.objectKeys(Au).filter(Du=>Iu.indexOf(Du)!==-1),Pu={...Au,...lo};for(const Du of Ou){const Lu=mergeValues(Au[Du],lo[Du]);if(!Lu.valid)return{valid:!1};Pu[Du]=Lu.data}return{valid:!0,data:Pu}}else if($u===ZodParsedType.array&&Ru===ZodParsedType.array){if(Au.length!==lo.length)return{valid:!1};const Iu=[];for(let Ou=0;Ou<Au.length;Ou++){const Pu=Au[Ou],Du=lo[Ou],Lu=mergeValues(Pu,Du);if(!Lu.valid)return{valid:!1};Iu.push(Lu.data)}return{valid:!0,data:Iu}}else return $u===ZodParsedType.date&&Ru===ZodParsedType.date&&+Au==+lo?{valid:!0,data:Au}:{valid:!1}}class ZodIntersection extends ZodType{_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo),Iu=(Ou,Pu)=>{if(isAborted(Ou)||isAborted(Pu))return INVALID;const Du=mergeValues(Ou.value,Pu.value);return Du.valid?((isDirty(Ou)||isDirty(Pu))&&$u.dirty(),{status:$u.value,value:Du.data}):(addIssueToContext(Ru,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return Ru.common.async?Promise.all([this._def.left._parseAsync({data:Ru.data,path:Ru.path,parent:Ru}),this._def.right._parseAsync({data:Ru.data,path:Ru.path,parent:Ru})]).then(([Ou,Pu])=>Iu(Ou,Pu)):Iu(this._def.left._parseSync({data:Ru.data,path:Ru.path,parent:Ru}),this._def.right._parseSync({data:Ru.data,path:Ru.path,parent:Ru}))}}ZodIntersection.create=(Au,lo,$u)=>new ZodIntersection({left:Au,right:lo,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams($u)});class ZodTuple extends ZodType{_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo);if(Ru.parsedType!==ZodParsedType.array)return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:Ru.parsedType}),INVALID;if(Ru.data.length<this._def.items.length)return addIssueToContext(Ru,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&Ru.data.length>this._def.items.length&&(addIssueToContext(Ru,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),$u.dirty());const Ou=[...Ru.data].map((Pu,Du)=>{const Lu=this._def.items[Du]||this._def.rest;return Lu?Lu._parse(new ParseInputLazyPath(Ru,Pu,Ru.path,Du)):null}).filter(Pu=>!!Pu);return Ru.common.async?Promise.all(Ou).then(Pu=>ParseStatus.mergeArray($u,Pu)):ParseStatus.mergeArray($u,Ou)}get items(){return this._def.items}rest(lo){return new ZodTuple({...this._def,rest:lo})}}ZodTuple.create=(Au,lo)=>{if(!Array.isArray(Au))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:Au,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(lo)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo);if(Ru.parsedType!==ZodParsedType.object)return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:Ru.parsedType}),INVALID;const Iu=[],Ou=this._def.keyType,Pu=this._def.valueType;for(const Du in Ru.data)Iu.push({key:Ou._parse(new ParseInputLazyPath(Ru,Du,Ru.path,Du)),value:Pu._parse(new ParseInputLazyPath(Ru,Ru.data[Du],Ru.path,Du)),alwaysSet:Du in Ru.data});return Ru.common.async?ParseStatus.mergeObjectAsync($u,Iu):ParseStatus.mergeObjectSync($u,Iu)}get element(){return this._def.valueType}static create(lo,$u,Ru){return $u instanceof ZodType?new ZodRecord({keyType:lo,valueType:$u,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(Ru)}):new ZodRecord({keyType:ZodString.create(),valueType:lo,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams($u)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo);if(Ru.parsedType!==ZodParsedType.map)return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:Ru.parsedType}),INVALID;const Iu=this._def.keyType,Ou=this._def.valueType,Pu=[...Ru.data.entries()].map(([Du,Lu],ju)=>({key:Iu._parse(new ParseInputLazyPath(Ru,Du,Ru.path,[ju,"key"])),value:Ou._parse(new ParseInputLazyPath(Ru,Lu,Ru.path,[ju,"value"]))}));if(Ru.common.async){const Du=new Map;return Promise.resolve().then(async()=>{for(const Lu of Pu){const ju=await Lu.key,Bu=await Lu.value;if(ju.status==="aborted"||Bu.status==="aborted")return INVALID;(ju.status==="dirty"||Bu.status==="dirty")&&$u.dirty(),Du.set(ju.value,Bu.value)}return{status:$u.value,value:Du}})}else{const Du=new Map;for(const Lu of Pu){const ju=Lu.key,Bu=Lu.value;if(ju.status==="aborted"||Bu.status==="aborted")return INVALID;(ju.status==="dirty"||Bu.status==="dirty")&&$u.dirty(),Du.set(ju.value,Bu.value)}return{status:$u.value,value:Du}}}}ZodMap.create=(Au,lo,$u)=>new ZodMap({valueType:lo,keyType:Au,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams($u)});class ZodSet extends ZodType{_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo);if(Ru.parsedType!==ZodParsedType.set)return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:Ru.parsedType}),INVALID;const Iu=this._def;Iu.minSize!==null&&Ru.data.size<Iu.minSize.value&&(addIssueToContext(Ru,{code:ZodIssueCode.too_small,minimum:Iu.minSize.value,type:"set",inclusive:!0,exact:!1,message:Iu.minSize.message}),$u.dirty()),Iu.maxSize!==null&&Ru.data.size>Iu.maxSize.value&&(addIssueToContext(Ru,{code:ZodIssueCode.too_big,maximum:Iu.maxSize.value,type:"set",inclusive:!0,exact:!1,message:Iu.maxSize.message}),$u.dirty());const Ou=this._def.valueType;function Pu(Lu){const ju=new Set;for(const Bu of Lu){if(Bu.status==="aborted")return INVALID;Bu.status==="dirty"&&$u.dirty(),ju.add(Bu.value)}return{status:$u.value,value:ju}}const Du=[...Ru.data.values()].map((Lu,ju)=>Ou._parse(new ParseInputLazyPath(Ru,Lu,Ru.path,ju)));return Ru.common.async?Promise.all(Du).then(Lu=>Pu(Lu)):Pu(Du)}min(lo,$u){return new ZodSet({...this._def,minSize:{value:lo,message:errorUtil.toString($u)}})}max(lo,$u){return new ZodSet({...this._def,maxSize:{value:lo,message:errorUtil.toString($u)}})}size(lo,$u){return this.min(lo,$u).max(lo,$u)}nonempty(lo){return this.min(1,lo)}}ZodSet.create=(Au,lo)=>new ZodSet({valueType:Au,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(lo)});class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(lo){const{ctx:$u}=this._processInputParams(lo);return this._def.getter()._parse({data:$u.data,path:$u.path,parent:$u})}}ZodLazy.create=(Au,lo)=>new ZodLazy({getter:Au,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(lo)});class ZodLiteral extends ZodType{_parse(lo){if(lo.data!==this._def.value){const $u=this._getOrReturnCtx(lo);return addIssueToContext($u,{received:$u.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:lo.data}}get value(){return this._def.value}}ZodLiteral.create=(Au,lo)=>new ZodLiteral({value:Au,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(lo)});function createZodEnum(Au,lo){return new ZodEnum({values:Au,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(lo)})}class ZodEnum extends ZodType{_parse(lo){if(typeof lo.data!="string"){const $u=this._getOrReturnCtx(lo),Ru=this._def.values;return addIssueToContext($u,{expected:util.joinValues(Ru),received:$u.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(lo.data)){const $u=this._getOrReturnCtx(lo),Ru=this._def.values;return addIssueToContext($u,{received:$u.data,code:ZodIssueCode.invalid_enum_value,options:Ru}),INVALID}return OK(lo.data)}get options(){return this._def.values}get enum(){const lo={};for(const $u of this._def.values)lo[$u]=$u;return lo}get Values(){const lo={};for(const $u of this._def.values)lo[$u]=$u;return lo}get Enum(){const lo={};for(const $u of this._def.values)lo[$u]=$u;return lo}extract(lo,$u=this._def){return ZodEnum.create(lo,{...this._def,...$u})}exclude(lo,$u=this._def){return ZodEnum.create(this.options.filter(Ru=>!lo.includes(Ru)),{...this._def,...$u})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(lo){const $u=util.getValidEnumValues(this._def.values),Ru=this._getOrReturnCtx(lo);if(Ru.parsedType!==ZodParsedType.string&&Ru.parsedType!==ZodParsedType.number){const Iu=util.objectValues($u);return addIssueToContext(Ru,{expected:util.joinValues(Iu),received:Ru.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(lo.data)){const Iu=util.objectValues($u);return addIssueToContext(Ru,{received:Ru.data,code:ZodIssueCode.invalid_enum_value,options:Iu}),INVALID}return OK(lo.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(Au,lo)=>new ZodNativeEnum({values:Au,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(lo)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(lo){const{ctx:$u}=this._processInputParams(lo);if($u.parsedType!==ZodParsedType.promise&&$u.common.async===!1)return addIssueToContext($u,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:$u.parsedType}),INVALID;const Ru=$u.parsedType===ZodParsedType.promise?$u.data:Promise.resolve($u.data);return OK(Ru.then(Iu=>this._def.type.parseAsync(Iu,{path:$u.path,errorMap:$u.common.contextualErrorMap})))}}ZodPromise.create=(Au,lo)=>new ZodPromise({type:Au,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(lo)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo),Iu=this._def.effect||null,Ou={addIssue:Pu=>{addIssueToContext(Ru,Pu),Pu.fatal?$u.abort():$u.dirty()},get path(){return Ru.path}};if(Ou.addIssue=Ou.addIssue.bind(Ou),Iu.type==="preprocess"){const Pu=Iu.transform(Ru.data,Ou);if(Ru.common.async)return Promise.resolve(Pu).then(async Du=>{if($u.value==="aborted")return INVALID;const Lu=await this._def.schema._parseAsync({data:Du,path:Ru.path,parent:Ru});return Lu.status==="aborted"?INVALID:Lu.status==="dirty"||$u.value==="dirty"?DIRTY(Lu.value):Lu});{if($u.value==="aborted")return INVALID;const Du=this._def.schema._parseSync({data:Pu,path:Ru.path,parent:Ru});return Du.status==="aborted"?INVALID:Du.status==="dirty"||$u.value==="dirty"?DIRTY(Du.value):Du}}if(Iu.type==="refinement"){const Pu=Du=>{const Lu=Iu.refinement(Du,Ou);if(Ru.common.async)return Promise.resolve(Lu);if(Lu instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return Du};if(Ru.common.async===!1){const Du=this._def.schema._parseSync({data:Ru.data,path:Ru.path,parent:Ru});return Du.status==="aborted"?INVALID:(Du.status==="dirty"&&$u.dirty(),Pu(Du.value),{status:$u.value,value:Du.value})}else return this._def.schema._parseAsync({data:Ru.data,path:Ru.path,parent:Ru}).then(Du=>Du.status==="aborted"?INVALID:(Du.status==="dirty"&&$u.dirty(),Pu(Du.value).then(()=>({status:$u.value,value:Du.value}))))}if(Iu.type==="transform")if(Ru.common.async===!1){const Pu=this._def.schema._parseSync({data:Ru.data,path:Ru.path,parent:Ru});if(!isValid(Pu))return INVALID;const Du=Iu.transform(Pu.value,Ou);if(Du instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:$u.value,value:Du}}else return this._def.schema._parseAsync({data:Ru.data,path:Ru.path,parent:Ru}).then(Pu=>isValid(Pu)?Promise.resolve(Iu.transform(Pu.value,Ou)).then(Du=>({status:$u.value,value:Du})):INVALID);util.assertNever(Iu)}}ZodEffects.create=(Au,lo,$u)=>new ZodEffects({schema:Au,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:lo,...processCreateParams($u)});ZodEffects.createWithPreprocess=(Au,lo,$u)=>new ZodEffects({schema:lo,effect:{type:"preprocess",transform:Au},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams($u)});class ZodOptional extends ZodType{_parse(lo){return this._getType(lo)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(lo)}unwrap(){return this._def.innerType}}ZodOptional.create=(Au,lo)=>new ZodOptional({innerType:Au,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(lo)});class ZodNullable extends ZodType{_parse(lo){return this._getType(lo)===ZodParsedType.null?OK(null):this._def.innerType._parse(lo)}unwrap(){return this._def.innerType}}ZodNullable.create=(Au,lo)=>new ZodNullable({innerType:Au,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(lo)});class ZodDefault extends ZodType{_parse(lo){const{ctx:$u}=this._processInputParams(lo);let Ru=$u.data;return $u.parsedType===ZodParsedType.undefined&&(Ru=this._def.defaultValue()),this._def.innerType._parse({data:Ru,path:$u.path,parent:$u})}removeDefault(){return this._def.innerType}}ZodDefault.create=(Au,lo)=>new ZodDefault({innerType:Au,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof lo.default=="function"?lo.default:()=>lo.default,...processCreateParams(lo)});class ZodCatch extends ZodType{_parse(lo){const{ctx:$u}=this._processInputParams(lo),Ru={...$u,common:{...$u.common,issues:[]}},Iu=this._def.innerType._parse({data:Ru.data,path:Ru.path,parent:{...Ru}});return isAsync(Iu)?Iu.then(Ou=>({status:"valid",value:Ou.status==="valid"?Ou.value:this._def.catchValue({get error(){return new ZodError(Ru.common.issues)},input:Ru.data})})):{status:"valid",value:Iu.status==="valid"?Iu.value:this._def.catchValue({get error(){return new ZodError(Ru.common.issues)},input:Ru.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(Au,lo)=>new ZodCatch({innerType:Au,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof lo.catch=="function"?lo.catch:()=>lo.catch,...processCreateParams(lo)});class ZodNaN extends ZodType{_parse(lo){if(this._getType(lo)!==ZodParsedType.nan){const Ru=this._getOrReturnCtx(lo);return addIssueToContext(Ru,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:Ru.parsedType}),INVALID}return{status:"valid",value:lo.data}}}ZodNaN.create=Au=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(Au)});class ZodBranded extends ZodType{_parse(lo){const{ctx:$u}=this._processInputParams(lo),Ru=$u.data;return this._def.type._parse({data:Ru,path:$u.path,parent:$u})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(lo){const{status:$u,ctx:Ru}=this._processInputParams(lo);if(Ru.common.async)return(async()=>{const Ou=await this._def.in._parseAsync({data:Ru.data,path:Ru.path,parent:Ru});return Ou.status==="aborted"?INVALID:Ou.status==="dirty"?($u.dirty(),DIRTY(Ou.value)):this._def.out._parseAsync({data:Ou.value,path:Ru.path,parent:Ru})})();{const Iu=this._def.in._parseSync({data:Ru.data,path:Ru.path,parent:Ru});return Iu.status==="aborted"?INVALID:Iu.status==="dirty"?($u.dirty(),{status:"dirty",value:Iu.value}):this._def.out._parseSync({data:Iu.value,path:Ru.path,parent:Ru})}}static create(lo,$u){return new ZodPipeline({in:lo,out:$u,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(lo){const $u=this._def.innerType._parse(lo),Ru=Iu=>(isValid(Iu)&&(Iu.value=Object.freeze(Iu.value)),Iu);return isAsync($u)?$u.then(Iu=>Ru(Iu)):Ru($u)}unwrap(){return this._def.innerType}}ZodReadonly.create=(Au,lo)=>new ZodReadonly({innerType:Au,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(lo)});var ZodFirstPartyTypeKind;(function(Au){Au.ZodString="ZodString",Au.ZodNumber="ZodNumber",Au.ZodNaN="ZodNaN",Au.ZodBigInt="ZodBigInt",Au.ZodBoolean="ZodBoolean",Au.ZodDate="ZodDate",Au.ZodSymbol="ZodSymbol",Au.ZodUndefined="ZodUndefined",Au.ZodNull="ZodNull",Au.ZodAny="ZodAny",Au.ZodUnknown="ZodUnknown",Au.ZodNever="ZodNever",Au.ZodVoid="ZodVoid",Au.ZodArray="ZodArray",Au.ZodObject="ZodObject",Au.ZodUnion="ZodUnion",Au.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Au.ZodIntersection="ZodIntersection",Au.ZodTuple="ZodTuple",Au.ZodRecord="ZodRecord",Au.ZodMap="ZodMap",Au.ZodSet="ZodSet",Au.ZodFunction="ZodFunction",Au.ZodLazy="ZodLazy",Au.ZodLiteral="ZodLiteral",Au.ZodEnum="ZodEnum",Au.ZodEffects="ZodEffects",Au.ZodNativeEnum="ZodNativeEnum",Au.ZodOptional="ZodOptional",Au.ZodNullable="ZodNullable",Au.ZodDefault="ZodDefault",Au.ZodCatch="ZodCatch",Au.ZodPromise="ZodPromise",Au.ZodBranded="ZodBranded",Au.ZodPipeline="ZodPipeline",Au.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,numberType=ZodNumber.create;ZodBigInt.create;const booleanType=ZodBoolean.create;ZodDate.create;const anyType=ZodAny.create,unknownType=ZodUnknown.create;ZodNever.create;const arrayType=ZodArray.create,objectType=ZodObject.create,unionType=ZodUnion.create,intersectionType=ZodIntersection.create;ZodTuple.create;const recordType=ZodRecord.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create;ZodPromise.create;ZodOptional.create;ZodNullable.create;const coerce={string:(Au=>ZodString.create({...Au,coerce:!0})),number:(Au=>ZodNumber.create({...Au,coerce:!0})),boolean:(Au=>ZodBoolean.create({...Au,coerce:!0})),bigint:(Au=>ZodBigInt.create({...Au,coerce:!0})),date:(Au=>ZodDate.create({...Au,coerce:!0}))};class A2uiError extends Error{constructor(lo,$u="UNKNOWN_ERROR"){super(lo),this.name=this.constructor.name,this.code=$u,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}class A2uiValidationError extends A2uiError{constructor(lo,$u,Ru="VALIDATION_ERROR"){super(lo,Ru),this.details=$u}}class A2uiDataError extends A2uiError{constructor(lo,$u){super(lo,"DATA_ERROR"),this.path=$u}}class A2uiExpressionError extends A2uiError{constructor(lo,$u,Ru){super(lo,"EXPRESSION_ERROR"),this.expression=$u,this.details=Ru}}class A2uiStateError extends A2uiError{constructor(lo){super(lo,"STATE_ERROR")}}class A2uiCatalogError extends A2uiError{constructor(lo,$u="CATALOG_ERROR"){super(lo,$u)}}class A2uiIntegrityError extends A2uiValidationError{constructor(lo,$u,Ru="INTEGRITY_ERROR"){super(lo,$u,Ru),this.name="A2uiIntegrityError"}}class A2uiRecursionError extends A2uiValidationError{constructor(lo,$u,Ru="RECURSION_ERROR"){super(lo,$u,Ru),this.name="A2uiRecursionError"}}var RpcErrorCode;(function(Au){Au.INVALID_FUNCTION_CALL="INVALID_FUNCTION_CALL",Au.EXECUTION_ERROR="EXECUTION_ERROR",Au.UNKNOWN_FUNCTION="UNKNOWN_FUNCTION",Au.UNKNOWN_ERROR="UNKNOWN_ERROR",Au.TIMEOUT="TIMEOUT",Au.CANCELLED="CANCELLED",Au.DISPOSED="DISPOSED",Au.DUPLICATE="DUPLICATE",Au.NO_LISTENER="NO_LISTENER"})(RpcErrorCode||(RpcErrorCode={}));class A2uiRpcError extends A2uiError{constructor(lo,$u=RpcErrorCode.UNKNOWN_ERROR,Ru,Iu){const Ou=$u||RpcErrorCode.UNKNOWN_ERROR;super(`[${Ou}] ${lo}`,Ou),this.functionCallId=Ru,this.details=Iu,this.name="A2uiRpcError"}}function markChildRef(Au,lo){return Au._def.a2uiChildRef=lo,Au}function childRefKindOf(Au){return Au?._def?.a2uiChildRef}const MAX_FUNCTION_CALL_ARGS=1e3;objectType({component:stringType().describe("The type name of the component."),id:lazyType(()=>ComponentIdSchema$2).optional(),weight:numberType().optional()}).passthrough().describe("A generic A2UI component definition.");const ComponentIdSchema$2=markChildRef(stringType().describe("REF:common_types.json#/$defs/ComponentId|The unique identifier for a component, used for both definitions and references within the same surface."),"component-id"),DataBindingSchema$2=objectType({path:stringType().describe("A JSON Pointer path to a value in the data model.")}).describe("REF:common_types.json#/$defs/DataBinding"),FunctionCallSchema$2=objectType({call:stringType().describe("The name of the function to call."),args:recordType(stringType(),unknownType()).describe("Arguments passed to the function.").optional(),returnType:enumType(["string","number","boolean","array","object","any","void"]).describe("The expected return type of the function call.").optional(),catalogId:stringType().describe("The catalog ID for this function, overriding any surface-level default catalogId.").optional()}).describe("REF:common_types.json#/$defs/FunctionCall|Invokes a named function, combining common function properties with the catalog function definition."),DynamicStringSchema$2=unionType([stringType(),DataBindingSchema$2,FunctionCallSchema$2]).describe("REF:common_types.json#/$defs/DynamicString|Represents a string"),DynamicBooleanSchema$2=unionType([booleanType(),DataBindingSchema$2,FunctionCallSchema$2]).describe("REF:common_types.json#/$defs/DynamicBoolean|A boolean value that can be a literal, a path, or a function call returning a boolean."),AccessibilityAttributesSchema$2=objectType({label:DynamicStringSchema$2.optional(),description:DynamicStringSchema$2.optional(),live:enumType(["off","polite","assertive"]).default("off").describe("Controls screen reader announcements for dynamic updates (WAI-ARIA aria-live). 'polite' waits for user pause; 'assertive' interrupts immediately for alerts.").optional(),hidden:DynamicBooleanSchema$2.optional()}).describe("REF:common_types.json#/$defs/AccessibilityAttributes|Attributes to enhance accessibility when using assistive technologies like screen readers or model understanding."),ExtensionsSchema$1=recordType(stringType(),unknownType()).superRefine((Au,lo)=>{for(const $u in Au)$u.match(/^[\p{XID_Start}_][\p{XID_Continue}]*$/u)||lo.addIssue({path:[$u],code:ZodIssueCode.custom,message:`Invalid extension key "${$u}": Keys MUST be Unicode identifiers (UAX #31).`})}).describe("REF:#/$defs/Extensions|Optional extension metadata. Keys MUST be Unicode identifiers (UAX #31). Keys starting with 'a2ui_' are reserved for official extensions.");objectType({id:ComponentIdSchema$2,accessibility:AccessibilityAttributesSchema$2.optional(),catalogId:stringType().describe("The catalog ID for this component, overriding any surface-level default catalogId.").optional(),metadata:objectType({extensions:ExtensionsSchema$1.optional()}).strict().describe("Optional component-level metadata for vendor extensions.").optional()}).describe("REF:common_types.json#/$defs/ComponentCommon");const ChildListSchema$1=markChildRef(unionType([arrayType(ComponentIdSchema$2).describe("A static list of child component IDs."),objectType({componentId:ComponentIdSchema$2,path:stringType().describe("The path to the list of component property objects in the data model.")}).describe("A template for generating a dynamic list of children.")]).describe("REF:common_types.json#/$defs/ChildList"),"child-list"),DynamicValueSchema$2=unionType([stringType(),numberType(),booleanType(),arrayType(unknownType()),DataBindingSchema$2,FunctionCallSchema$2,recordType(stringType(),unknownType()).refine(Au=>!Au||!("path"in Au)&&!("call"in Au))]).describe("REF:common_types.json#/$defs/DynamicValue|A value that can be a literal, a path, or a function call returning any type."),DynamicNumberSchema$2=unionType([numberType(),DataBindingSchema$2,FunctionCallSchema$2]).describe("REF:common_types.json#/$defs/DynamicNumber|Represents a value that can be either a literal number, a path to a number in the data model, or a function call returning a number."),DynamicStringListSchema$1=unionType([arrayType(stringType()),DataBindingSchema$2,FunctionCallSchema$2]).describe("REF:common_types.json#/$defs/DynamicStringList|Represents a value that can be either a literal array of strings, a path to a string array in the data model, or a function call returning a string array."),CheckRuleSchema$2=objectType({condition:unionType([DynamicBooleanSchema$2,DataBindingSchema$2,FunctionCallSchema$2]).describe("Path or function call evaluating to a structured validation result object."),message:stringType().describe("Optional fallback error message.").optional()}).describe("REF:common_types.json#/$defs/CheckRule|A single validation check rule applied to an input component. The condition function or path evaluates to a structured validation result object."),CheckableSchema=objectType({checks:arrayType(CheckRuleSchema$2).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional()}).describe("REF:common_types.json#/$defs/Checkable|Properties for components that support renderer-side checks."),ActionSchema$2=unionType([objectType({event:objectType({name:stringType().describe("The name of the action to be dispatched to the server."),context:recordType(stringType(),unknownType()).describe("A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.").optional()}).strict().describe("The event to dispatch to the server.")}).strict().describe("Triggers a server-side event."),objectType({functionCall:FunctionCallSchema$2}).strict().describe("Executes a local client-side function."),objectType({event:objectType({name:stringType().describe("The name of the action to be dispatched to the agent."),userMessage:DynamicStringSchema$2.optional(),context:recordType(stringType(),unknownType()).describe("A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.").optional()}).strict().describe("The event to dispatch to the agent.")}).strict().describe("Triggers an agent-side event."),objectType({functionCall:FunctionCallSchema$2}).strict().describe("Executes a renderer or agent-side function.")]).describe("REF:common_types.json#/$defs/Action|Defines an interaction handler that can either trigger an agent-side event or execute a local renderer-side function."),CallIdSchema$1=stringType().describe("REF:common_types.json#/$defs/CallId|The unique identifier for a function call.");objectType({call:stringType().describe("The name of the function to call."),catalogId:stringType().describe("The catalog ID for this function, overriding any surface-level default catalogId.").optional()}).describe("REF:common_types.json#/$defs/FunctionCommon|Baseline envelope properties common to all function calls. Function-specific argument schemas (\\'args\\') are defined individually by each function in the active catalog.");objectType({call:literalType("@index"),args:objectType({offset:DynamicNumberSchema$2.optional()}).strict().optional()}).strict().describe("REF:common_types.json#/$defs/IndexSystemFunction|Returns the 0-based index of the current item when rendering a dynamic list from a template. This function MUST ONLY be available when evaluating template items within a list context.");objectType({component:literalType("Surface").optional(),child:literalType("root").optional()}).strict().describe("REF:common_types.json#/$defs/Surface|The reserved canonical container component representing an A2UI surface. The Surface component is immutable and always has \\'child\\': \\'root\\'.");objectType({functionCallId:CallIdSchema$1,value:unknownType().describe("The return value of the function.").optional(),error:objectType({code:stringType(),message:stringType()}).strict().describe("An error object indicating failure of the function execution.").optional()}).strict().describe("REF:common_types.json#/$defs/FunctionResponse|The return response matching a callAgentFunction or callRendererFunction invocation.");const SEMVER_REGEX=/^[vV]?(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*))?(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;function normalizeVersionString(Au){if(!Au||typeof Au!="string")return"";const lo=Au.trim().replace(/^[vV]/,""),$u=lo.indexOf("-"),Ru=lo.indexOf("+");let Iu=lo.length;return $u!==-1&&Ru!==-1?Iu=Math.min($u,Ru):$u!==-1?Iu=$u:Ru!==-1&&(Iu=Ru),`${lo.slice(0,Iu).replace(/_/g,".")}${lo.slice(Iu)}`}function parseSemVer(Au){if(!Au||typeof Au!="string")return null;const lo=Au.trim().match(SEMVER_REGEX);return lo?{major:parseInt(lo[1],10),minor:parseInt(lo[2],10),patch:lo[3]!==void 0?parseInt(lo[3],10):0,prerelease:lo[4]?lo[4].split("."):[],build:lo[5]?lo[5].split("."):[]}:null}function toSemVer(Au){if(!Au)return null;if(typeof Au=="object"){const lo=Au;return typeof lo.major!="number"||!Number.isInteger(lo.major)||lo.major<0||typeof lo.minor=="number"&&(!Number.isInteger(lo.minor)||lo.minor<0)||typeof lo.patch=="number"&&(!Number.isInteger(lo.patch)||lo.patch<0)?null:{major:lo.major,minor:typeof lo.minor=="number"?lo.minor:0,patch:typeof lo.patch=="number"?lo.patch:0,prerelease:Array.isArray(lo.prerelease)?lo.prerelease:[],build:Array.isArray(lo.build)?lo.build:[]}}return parseSemVer(normalizeVersionString(Au))}function toCanonicalVersion(Au){if(!Au)return null;const lo=toSemVer(Au);if(!lo)return null;if(lo.patch===0&&lo.prerelease.length===0&&lo.build.length===0)return`${lo.major}.${lo.minor}`;const $u=lo.prerelease.length>0?`-${lo.prerelease.join(".")}`:"",Ru=lo.build.length>0?`+${lo.build.join(".")}`:"";return`${lo.major}.${lo.minor}.${lo.patch}${$u}${Ru}`}function comparePrereleaseId(Au,lo){const $u=/^\d+$/.test(Au),Ru=/^\d+$/.test(lo);return $u&&Ru?Au.length!==lo.length?Au.length-lo.length:Au<lo?-1:Au>lo?1:0:$u?-1:Ru?1:Au<lo?-1:Au>lo?1:0}function comparePrereleaseLists(Au,lo){if(Au.length===0&&lo.length===0)return 0;if(Au.length===0)return 1;if(lo.length===0)return-1;const $u=Math.min(Au.length,lo.length);for(let Ru=0;Ru<$u;Ru++){const Iu=comparePrereleaseId(Au[Ru],lo[Ru]);if(Iu!==0)return Iu}return Au.length-lo.length}function compareSemVer(Au,lo){const $u=toSemVer(Au),Ru=toSemVer(lo);return!$u&&!Ru?0:$u?Ru?$u.major!==Ru.major?$u.major-Ru.major:$u.minor!==Ru.minor?$u.minor-Ru.minor:$u.patch!==Ru.patch?$u.patch-Ru.patch:comparePrereleaseLists($u.prerelease,Ru.prerelease):1:-1}function isAtLeastVersion(Au,lo){if(!Au)return!1;const $u=toSemVer(Au),Ru=toSemVer(lo);return!$u||!Ru?!1:compareSemVer($u,Ru)>=0}const UAX31_IDENTIFIER=/^[\p{XID_Start}_][\p{XID_Continue}]*$/u;function isValidUax31Identifier(Au){if(!Au)return!1;const lo=Au.startsWith("@")?Au.slice(1):Au;return UAX31_IDENTIFIER.test(lo)}function assertUax31Identifier(Au,lo){if(!isValidUax31Identifier(Au))throw new A2uiCatalogError(`Invalid UAX #31 ${lo}`)}const DEFAULT_PROTOCOL_VERSION="0.9",COMMON_TYPE_SCHEMAS={DynamicString:DynamicStringSchema$2,DynamicNumber:DynamicNumberSchema$2,DynamicBoolean:DynamicBooleanSchema$2,DynamicStringList:DynamicStringListSchema$1,DynamicValue:DynamicValueSchema$2,ComponentId:ComponentIdSchema$2,ChildList:ChildListSchema$1,Action:ActionSchema$2,CheckRule:CheckRuleSchema$2,Checkable:CheckableSchema,AccessibilityAttributes:AccessibilityAttributesSchema$2,DataBinding:DataBindingSchema$2,FunctionCall:FunctionCallSchema$2};function resolveJsonPointer(Au,lo){if(!lo.startsWith("#/"))return;const $u=lo.slice(2).split("/").map(Iu=>Iu.replace(/~1/g,"/").replace(/~0/g,"~"));let Ru=Au;for(const Iu of $u)if(Ru&&typeof Ru=="object"&&Iu in Ru)Ru=Ru[Iu];else return;return typeof Ru=="object"&&Ru!==null?Ru:void 0}function resolveProtocolRef(Au){const lo=Au.split(/#\/(?:\$defs|definitions)\//)[1];return lo?COMMON_TYPE_SCHEMAS[lo]:void 0}function convertEnumToZod(Au){return Au.length===0?unknownType():Au.every(lo=>typeof lo=="string")?enumType(Au):Au.length===1?literalType(Au[0]):unionType(Au.map(lo=>literalType(lo)))}function canonicalJsonStringify(Au){return Au===null||typeof Au!="object"?JSON.stringify(Au):Array.isArray(Au)?`[${Au.map(canonicalJsonStringify).join(",")}]`:`{${Object.keys(Au).sort().map(Ru=>`${JSON.stringify(Ru)}:${canonicalJsonStringify(Au[Ru])}`).join(",")}}`}function finalizePropertyZod(Au,lo,$u,Ru,Iu){let Ou=Au;if(lo.not&&typeof lo.not=="object"){const Pu=convertPropertyToZod(lo.not,$u,new Set(Ru),Iu);Ou=Ou.refine(Du=>!Pu.safeParse(Du).success,{message:'Value matched prohibited "not" schema'})}return lo.default!==void 0&&(Ou=Ou.default(lo.default)),typeof lo.description=="string"&&(Ou=Ou.describe(lo.description)),Ou}function convertRefToZod(Au,lo,$u,Ru,Iu){const Ou=resolveProtocolRef(Au);if(Ou){const Pu=Au.split(/#\/(?:\$defs|definitions)\//)[1],Du=typeof lo.description=="string"?`REF:common_types.json#/$defs/${Pu}|${lo.description}`:Ou.description;return Du?Ou.describe(Du):Ou}if($u&&Au.startsWith("#/")){const Pu=resolveJsonPointer($u,Au);if(!Pu)return unknownType().superRefine((Lu,ju)=>{ju.addIssue({code:ZodIssueCode.custom,message:`Unresolvable schema reference: '${Au}'`})});if(Ru.has(Au)){let Lu=Iu.get(Au);return lazyType(()=>(Lu||(Lu=Iu.get(Au)??convertPropertyToZod(Pu,$u,new Set([Au]),Iu),Iu.set(Au,Lu)),Lu))}let Du=Iu.get(Au);if(!Du){const Lu=new Set(Ru);Lu.add(Au),Du=convertPropertyToZod(Pu,$u,Lu,Iu),Iu.set(Au,Du)}return typeof lo.description=="string"&&(Du=Du.describe(lo.description)),Du}}function convertUnionToZod(Au,lo,$u,Ru){const Iu=Array.isArray(Au.oneOf),Pu=(Au.oneOf||Au.anyOf).filter(zu=>typeof zu=="object"&&zu!==null);if(Pu.length===0)return;const Du=Pu.find(zu=>Array.isArray(zu.enum)),Lu=Pu.some(zu=>typeof zu.$ref=="string"&&zu.$ref.includes("DataBinding")),ju=Pu.map(zu=>convertPropertyToZod(zu,lo,new Set($u),Ru));let Bu;if(ju.length===1)Bu=ju[0];else{const zu=unionType([ju[0],ju[1],...ju.slice(2)]);Bu=Iu?anyType().superRefine((qu,Uu)=>{let Hu=0;for(const Vu of ju)if(Vu.safeParse(qu).success&&++Hu>1){Uu.addIssue({code:ZodIssueCode.custom,message:"Value matched more than one schema in oneOf"});return}}).pipe(zu):zu}Au.default!==void 0&&(Bu=Bu.default(Au.default));const Fu=(typeof Au.description=="string"?Au.description:void 0)||(Du&&Lu?"REF:common_types.json#/$defs/DynamicString":void 0);return Fu?Bu.describe(Fu):Bu}function convertPropertyToZod(Au,lo,$u=new Set,Ru=new Map){if(!Au||typeof Au!="object")return unknownType();if(Au.$ref&&typeof Au.$ref=="string"){const Iu=convertRefToZod(Au.$ref,Au,lo,$u,Ru);if(Iu)return Iu}if(Array.isArray(Au.oneOf)||Array.isArray(Au.anyOf)){const Iu=convertUnionToZod(Au,lo,$u,Ru);if(Iu)return Iu}if(Au.const!==void 0){const Iu=literalType(Au.const);return finalizePropertyZod(Iu,Au,lo,$u,Ru)}if(Array.isArray(Au.enum)&&Au.enum.length>0){const Iu=convertEnumToZod(Au.enum);return finalizePropertyZod(Iu,Au,lo,$u,Ru)}if(Au.type==="array"){const Iu=Au.items&&typeof Au.items=="object"?convertPropertyToZod(Au.items,lo,new Set($u),Ru):unknownType();let Ou=arrayType(Iu);return typeof Au.minItems=="number"&&(Ou=Ou.min(Au.minItems)),typeof Au.maxItems=="number"&&(Ou=Ou.max(Au.maxItems)),Au.uniqueItems===!0&&(Ou=Ou.refine(Pu=>new Set(Pu.map(canonicalJsonStringify)).size===Pu.length,{message:"Array items must be unique"})),finalizePropertyZod(Ou,Au,lo,$u,Ru)}switch(Au.type){case"string":{let Iu=stringType();if(typeof Au.minLength=="number"&&(Iu=Iu.min(Au.minLength)),typeof Au.maxLength=="number"&&(Iu=Iu.max(Au.maxLength)),typeof Au.pattern=="string")try{Iu=Iu.regex(new RegExp(Au.pattern,"u"))}catch{}return finalizePropertyZod(Iu,Au,lo,$u,Ru)}case"integer":case"number":{let Iu=Au.type==="integer"?numberType().int():numberType();return typeof Au.minimum=="number"&&(Iu=Iu.min(Au.minimum)),typeof Au.maximum=="number"&&(Iu=Iu.max(Au.maximum)),typeof Au.exclusiveMinimum=="number"&&(Iu=Iu.gt(Au.exclusiveMinimum)),typeof Au.exclusiveMaximum=="number"&&(Iu=Iu.lt(Au.exclusiveMaximum)),typeof Au.multipleOf=="number"&&(Iu=Iu.multipleOf(Au.multipleOf)),finalizePropertyZod(Iu,Au,lo,$u,Ru)}case"boolean":return finalizePropertyZod(booleanType(),Au,lo,$u,Ru);case"object":{const Iu=Au.properties;let Ou;if(typeof Iu=="object"&&Iu!==null){const Pu=Array.isArray(Au.required)?new Set(Au.required.filter(ju=>typeof ju=="string")):new Set,Du=objectType(convertPropertiesToShape(Iu,Pu,!1,lo,$u,Ru));Ou=Au.additionalProperties===!1||Au.unevaluatedProperties===!1?Du.strict():Du.passthrough()}else Ou=recordType(unknownType());return finalizePropertyZod(Ou,Au,lo,$u,Ru)}default:return finalizePropertyZod(unknownType(),Au,lo,$u,Ru)}}function convertPropertiesToShape(Au,lo,$u=!1,Ru,Iu,Ou=new Map){const Pu={};for(const[Du,Lu]of Object.entries(Au)){if($u&&(Du==="component"||Du==="id"))continue;const ju=convertPropertyToZod(typeof Lu=="object"&&Lu!==null?Lu:{},Ru,Iu?new Set(Iu):new Set,Ou);Pu[Du]=lo.has(Du)?ju:ju.optional()}return Pu}function collectComponentSubSchemas(Au,lo,$u=new Set){const Ru=[];if(!Au||typeof Au!="object")return Ru;if(Array.isArray(Au.allOf)){for(const Iu of Au.allOf)if(!(!Iu||typeof Iu!="object"))if(typeof Iu.$ref=="string"){const Ou=Iu.$ref;if(Ou.includes("common_types.json")&&Ou.includes("ComponentCommon"))Ru.push({properties:{accessibility:AccessibilityAttributesSchema$2.optional()}});else if(Ou.startsWith("#/")&&!$u.has(Ou)){$u.add(Ou);const Pu=resolveJsonPointer(lo,Ou);Pu&&Ru.push(...collectComponentSubSchemas(Pu,lo,$u))}}else Ru.push(...collectComponentSubSchemas(Iu,lo,$u))}return Au.properties&&Ru.push(Au),Ru}function convertComponentJsonSchemaToZod(Au,lo,$u=!0,Ru=new Map){const Iu={},Ou=collectComponentSubSchemas(Au,lo),Pu=new Set;for(const ju of Ou)Array.isArray(ju.required)&&ju.required.forEach(Bu=>{typeof Bu=="string"&&Pu.add(Bu)});for(const ju of Ou){const Bu=convertPropertiesToShape(ju.properties||{},Pu,$u,lo,void 0,Ru);Object.assign(Iu,Bu)}const Du=objectType(Iu);return Au.unevaluatedProperties===!0||typeof Au.unevaluatedProperties=="object"&&Au.unevaluatedProperties!==null||Au.additionalProperties===!0||typeof Au.additionalProperties=="object"&&Au.additionalProperties!==null?Du.passthrough():Du.strict()}function convertFunctionArgsJsonSchemaToZod(Au,lo,$u=new Map){const Ru=new Set(Array.isArray(Au.required)?Au.required.filter(Du=>typeof Du=="string"):[]),Iu=convertPropertiesToShape(Au.properties||{},Ru,!1,lo,void 0,$u),Ou=objectType(Iu);return Au.unevaluatedProperties===!0||typeof Au.unevaluatedProperties=="object"&&Au.unevaluatedProperties!==null||Au.additionalProperties===!0||typeof Au.additionalProperties=="object"&&Au.additionalProperties!==null?Ou.passthrough():Ou.strict()}function parseFunctionDefinitions(Au,lo,$u,Ru=!1){const Iu=[];if(!Au)return Iu;const Ou=new Map,Pu=(Du,Lu)=>{if(Ru&&(assertUax31Identifier(Du,`function identifier: '${Du}'`),Lu&&typeof Lu=="object"))for(const ju of Object.keys(Lu))assertUax31Identifier(ju,`argument identifier: '${ju}' in function '${Du}'`)};if(Array.isArray(Au)){for(const Du of Au)if(Du&&typeof Du=="object"&&typeof Du.name=="string"){if(Pu(Du.name,Du.parameters),$u&&!$u.has(Du.name))continue;const Lu=Du.parameters&&typeof Du.parameters=="object"?convertFunctionArgsJsonSchemaToZod(Du.parameters,lo,Ou):recordType(unknownType());Iu.push({name:Du.name,description:typeof Du.description=="string"?Du.description:void 0,returnType:typeof Du.returnType=="string"?Du.returnType:"any",allowedCallers:Du.allowedCallers,requiresUserActivation:Du.requiresUserActivation,schema:Lu})}return Iu}if(typeof Au=="object"&&Au!==null)for(const[Du,Lu]of Object.entries(Au)){const ju=Lu&&typeof Lu=="object"?Lu:{};if(Pu(Du,ju.properties&&typeof ju.properties=="object"?ju.properties:ju.parameters),$u&&!$u.has(Du)||!Lu||typeof Lu!="object")continue;const Bu=Lu,Fu=Bu.properties;let zu=Fu?.args??Bu.args??Bu.parameters;!zu&&Fu&&!("call"in Fu)&&!("function"in Fu)?zu=Bu:zu&&typeof zu=="object"&&!("properties"in zu)&&!("type"in zu)&&(zu={type:"object",properties:zu,required:Bu.required,additionalProperties:Bu.additionalProperties});const qu=zu&&typeof zu=="object"?convertFunctionArgsJsonSchemaToZod(zu,lo,Ou):recordType(unknownType()),Uu=(typeof Bu.returnType=="string"?Bu.returnType:void 0)??(typeof Fu?.returnType?.const=="string"?(Fu?.returnType).const:"any"),Hu=Bu.allowedCallers??Fu?.allowedCallers?.const,Vu=Bu.requiresUserActivation??Fu?.requiresUserActivation?.const;Iu.push({name:Du,description:typeof Bu.description=="string"?Bu.description:void 0,returnType:Uu,allowedCallers:Hu,requiresUserActivation:Vu,schema:qu})}return Iu}function extractPermittedNames(Au,lo){if(!Array.isArray(Au))return;const $u=new Set;for(const Ru of Au)if(typeof Ru?.$ref=="string"&&Ru.$ref.startsWith(lo)){const Ou=Ru.$ref.slice(lo.length).replace(/~([01])/g,(Pu,Du)=>Du==="1"?"/":"~");$u.add(Ou)}return $u}function parseCatalogComponents(Au,lo,$u,Ru){const Iu=[],Ou=new Map;for(const[Pu,Du]of Object.entries(Au)){const Lu=Du||{};if($u){assertUax31Identifier(Pu,`component identifier: '${Pu}'`);const Bu=Lu.properties;if(Bu&&typeof Bu=="object")for(const Fu of Object.keys(Bu))assertUax31Identifier(Fu,`property identifier: '${Fu}' in component '${Pu}'`)}if(Ru&&!Ru.has(Pu))continue;const ju=convertComponentJsonSchemaToZod(Lu,lo,!0,Ou);Iu.push({name:Pu,schema:ju,allowedParents:Array.isArray(Lu.allowedParents)?Lu.allowedParents.filter(Bu=>typeof Bu=="string"):void 0,allowedChildren:Array.isArray(Lu.allowedChildren)?Lu.allowedChildren.filter(Bu=>typeof Bu=="string"):void 0})}return Iu}function parseThemeSchema(Au,lo){const $u=Au.theme??Au.themeSchema??Au.styles??lo?.theme;if($u&&typeof $u=="object")return convertComponentJsonSchemaToZod($u,Au,!1)}function loadCatalogFromSchema(Au,lo){const $u=Au.catalogId??Au.$id??Au.id;if(!$u||typeof $u!="string")throw new Error("Catalog ID must be specified via catalog metadata ('catalogId' or '$id').");const Ru=Au.$defs,Iu=Ru?.anyComponent,Ou=extractPermittedNames(Iu?.oneOf,"#/components/"),Pu=lo??Au.protocolVersion??DEFAULT_PROTOCOL_VERSION,Du=isAtLeastVersion(Pu,"1.0"),Lu=Au.components??{},ju=parseCatalogComponents(Lu,Au,Du,Ou),Bu=Ru?.anyFunction,Fu=extractPermittedNames(Bu?.oneOf,"#/functions/"),zu=parseFunctionDefinitions(Au.functions,Au,Fu,Du),qu=parseThemeSchema(Au,Ru),Uu=typeof Au.instructions=="string"?Au.instructions:void 0;return new Catalog($u,Pu,ju,zu,qu,Uu)}const V08_STANDARD_DEFS={ComponentId:{description:"The unique identifier for a component, used for both definitions and references within the same surface.",type:"string"},TextItem:{additionalProperties:!1,description:"The value of the text field. This can be a literal string or a reference to a value in the data model ('path', e.g. '/user/name').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},UrlItem:{additionalProperties:!1,description:"The URL of the audio to be played. This can be a literal string ('literal') or a reference to a value in the data model ('path', e.g. '/song/url').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},AltTextItem:{additionalProperties:!1,description:"The alt text for the image. This can be a literal string ('literal') or a reference to a value in the data model ('path', e.g. '/thumbnail/altText').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},NameItem:{additionalProperties:!1,description:"The name of the icon to display. This can be a literal string or a reference to a value in the data model ('path', e.g. '/form/submit').",properties:{literalString:{enum:["accountCircle","add","arrowBack","arrowForward","attachFile","calendarToday","call","camera","check","close","delete","download","edit","event","error","favorite","favoriteOff","folder","help","home","info","locationOn","lock","lockOpen","mail","menu","moreVert","moreHoriz","notificationsOff","notifications","payment","person","phone","photo","print","refresh","search","send","settings","share","shoppingCart","star","starHalf","starOff","upload","visibility","visibilityOff","warning"],type:"string"},path:{type:"string"}},type:"object"},DescriptionItem:{additionalProperties:!1,description:"A description of the audio, such as a title or summary. This can be a literal string or a reference to a value in the data model ('path', e.g. '/song/title').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},ChildrenItem:{additionalProperties:!1,description:"Defines the children. Use 'explicitList' for a fixed set of children, or 'template' to generate children from a data list.",properties:{explicitList:{items:{type:"string"},type:"array"},template:{$ref:"#/$defs/TemplateItem",description:"A template for generating a dynamic list of children from a data model list. `componentId` is the component to use as a template, and `dataBinding` is the path to the map of components in the data model. Values in the map will define the list of children."}},type:"object"},TemplateItem:{additionalProperties:!1,description:"A template for generating a dynamic list of children from a data model list. `componentId` is the component to use as a template, and `dataBinding` is the path to the map of components in the data model. Values in the map will define the list of children.",properties:{componentId:{type:"string"},dataBinding:{type:"string"}},required:["componentId","dataBinding"],type:"object"},TabItemItem:{additionalProperties:!1,properties:{child:{type:"string"},title:{$ref:"#/$defs/TitleItem"}},required:["title","child"],type:"object"},TitleItem:{additionalProperties:!1,description:"The tab title. Defines the value as either a literal value or a path to data model value (e.g. '/options/title').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},ActionItem:{additionalProperties:!1,description:"The client-side action to be dispatched when the button is clicked. It includes the action's name and an optional context payload.",properties:{context:{items:{$ref:"#/$defs/ContextItem"},type:"array"},name:{type:"string"}},required:["name"],type:"object"},ContextItem:{additionalProperties:!1,properties:{key:{type:"string"},value:{$ref:"#/$defs/ValueItem",description:"Defines the value to be included in the context as either a literal value or a path to a data model value (e.g. '/user/name')."}},required:["key","value"],type:"object"},ValueItem:{additionalProperties:!1,description:"The current value of the slider. This can be a literal number ('literalNumber') or a reference to a value in the data model ('path', e.g. '/restaurant/cost').",properties:{literalNumber:{type:"number"},path:{type:"string"}},type:"object"},LabelItem:{additionalProperties:!1,description:"The label for the slider. This can be a literal string or a reference to a value in the data model ('path').",properties:{literalString:{type:"string"},path:{type:"string"}},type:"object"},OptionItem:{additionalProperties:!1,properties:{label:{$ref:"#/$defs/LabelItem",description:"The text to display for this option. This can be a literal string or a reference to a value in the data model (e.g. '/option/label')."},value:{description:"The value to be associated with this option when selected.",type:"string"}},required:["label","value"],type:"object"},SelectionItem:{additionalProperties:!1,description:"The currently selected values for the component. This can be a literal array of strings or a path to an array in the data model('path', e.g. '/hotel/options').",properties:{literalArray:{items:{type:"string"},type:"array"},path:{type:"string"}},type:"object"}},V09_CHILD_REF_OPTIONS={childRefNames:new Set(["ComponentId","Child","ChildComponentId"]),childListRefNames:new Set(["ChildList","TemplateChildList","ChildrenItem","TemplateItem"])},V09_STANDARD_DEFS={ComponentId:{type:"string",description:"The unique identifier for a component, used for both definitions and references within the same surface."},AccessibilityAttributes:{type:"object",description:"Attributes to enhance accessibility when using assistive technologies like screen readers.",properties:{label:{$ref:"#/$defs/DynamicString",description:"A short string, typically 1 to 3 words, used by assistive technologies to convey the purpose or intent of an element. For example, an input field might have an accessible label of 'User ID' or a button might be labeled 'Submit'."},description:{$ref:"#/$defs/DynamicString",description:"Additional information provided by assistive technologies about an element such as instructions, format requirements, or result of an action. For example, a mute button might have a label of 'Mute' and a description of 'Silences notifications about this conversation'."}}},ComponentCommon:{type:"object",properties:{id:{$ref:"#/$defs/ComponentId"},accessibility:{$ref:"#/$defs/AccessibilityAttributes"}},required:["id"]},ChildList:{oneOf:[{type:"array",items:{$ref:"#/$defs/ComponentId"},description:"A static list of child component IDs."},{type:"object",description:"A template for generating a dynamic list of children from a data model list. The `componentId` is the component to use as a template.",properties:{componentId:{$ref:"#/$defs/ComponentId"},path:{type:"string",description:"The path to the list of component property objects in the data model."}},required:["componentId","path"],additionalProperties:!1}]},DataBinding:{type:"object",properties:{path:{type:"string",description:"A JSON Pointer path to a value in the data model."}},required:["path"],additionalProperties:!1},DynamicValue:{description:"A value that can be a literal, a path, or a function call returning any type.",oneOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"array"},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},DynamicString:{description:"Represents a string",oneOf:[{type:"string"},{$ref:"#/$defs/DataBinding"},{allOf:[{$ref:"#/$defs/FunctionCall"},{properties:{returnType:{const:"string"}}}]}]},DynamicNumber:{description:"Represents a value that can be either a literal number, a path to a number in the data model, or a function call returning a number.",oneOf:[{type:"number"},{$ref:"#/$defs/DataBinding"},{allOf:[{$ref:"#/$defs/FunctionCall"},{properties:{returnType:{const:"number"}}}]}]},DynamicBoolean:{description:"A boolean value that can be a literal, a path, or a function call returning a boolean.",oneOf:[{type:"boolean"},{$ref:"#/$defs/DataBinding"},{allOf:[{$ref:"#/$defs/FunctionCall"},{properties:{returnType:{const:"boolean"}}}]}]},DynamicStringList:{description:"Represents a value that can be either a literal array of strings, a path to a string array in the data model, or a function call returning a string array.",oneOf:[{type:"array",items:{type:"string"}},{$ref:"#/$defs/DataBinding"},{allOf:[{$ref:"#/$defs/FunctionCall"},{properties:{returnType:{const:"array"}}}]}]},FunctionCall:{type:"object",description:"Invokes a named function on the client.",properties:{call:{type:"string",description:"The name of the function to call."},args:{type:"object",description:"Arguments passed to the function.",additionalProperties:{anyOf:[{$ref:"#/$defs/DynamicValue"},{type:"object",description:"A literal object argument (e.g. configuration)."}]}},returnType:{type:"string",description:"The expected return type of the function call.",enum:["string","number","boolean","array","object","any","void"],default:"boolean"}},required:["call"],oneOf:[{$ref:"catalog.json#/$defs/anyFunction"}]},CheckRule:{type:"object",description:"A single validation rule applied to an input component.",properties:{condition:{$ref:"#/$defs/DynamicBoolean"},message:{type:"string",description:"The error message to display if the check fails."}},required:["condition","message"],additionalProperties:!1},Checkable:{description:"Properties for components that support client-side checks.",type:"object",properties:{checks:{type:"array",description:"A list of checks to perform. These are function calls that must return a boolean indicating validity.",items:{$ref:"#/$defs/CheckRule"}}}},Action:{description:"Defines an interaction handler that can either trigger a server-side event or execute a local client-side function.",oneOf:[{type:"object",description:"Triggers a server-side event.",properties:{event:{type:"object",description:"The event to dispatch to the server.",properties:{name:{type:"string",description:"The name of the action to be dispatched to the server."},context:{type:"object",description:"A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.",additionalProperties:{$ref:"#/$defs/DynamicValue"}}},required:["name"],additionalProperties:!1}},required:["event"],additionalProperties:!1},{type:"object",description:"Executes a local client-side function.",properties:{functionCall:{$ref:"#/$defs/FunctionCall"}},required:["functionCall"],additionalProperties:!1}]}},V10_STANDARD_DEFS={ComponentId:{type:"string",description:"The unique identifier for a component, used for both definitions and references within the same surface."},CallId:{type:"string",description:"The unique identifier for a function call."},AccessibilityAttributes:{type:"object",description:"Attributes to enhance accessibility when using assistive technologies like screen readers or model understanding.",properties:{label:{$ref:"#/$defs/DynamicString",description:"A short string, typically 1 to 3 words, used by assistive technologies to convey the purpose or intent of an element. For example, an input field might have an accessible label of 'User ID' or a button might be labeled 'Submit'."},description:{$ref:"#/$defs/DynamicString",description:"Additional information provided by assistive technologies about an element such as instructions, format requirements, or result of an action. For example, a mute button might have a label of 'Mute' and a description of 'Silences notifications about this conversation'."},live:{type:"string",enum:["off","polite","assertive"],default:"off",description:"Controls screen reader announcements for dynamic updates (WAI-ARIA aria-live). 'polite' waits for user pause; 'assertive' interrupts immediately for alerts."},hidden:{$ref:"#/$defs/DynamicBoolean",description:"Hides the element and its children from assistive technologies when true. Default is false."}},additionalProperties:!1},Extensions:{type:"object",description:"Optional extension metadata. Keys MUST be Unicode identifiers (UAX #31). Keys starting with 'a2ui_' are reserved for official extensions.",patternProperties:{"^[\\p{XID_Start}_][\\p{XID_Continue}]*$":{}},additionalProperties:!1},ComponentCommon:{type:"object",properties:{id:{$ref:"#/$defs/ComponentId"},catalogId:{type:"string",description:"The catalog ID for this component, overriding any surface-level default catalogId."},accessibility:{$ref:"#/$defs/AccessibilityAttributes"},metadata:{type:"object",description:"Optional component-level metadata for vendor extensions.",properties:{extensions:{$ref:"#/$defs/Extensions"}},additionalProperties:!1}},required:["id"]},Child:{$ref:"#/$defs/ComponentId",description:"A reference to a single child component ID."},ChildList:{oneOf:[{type:"array",items:{$ref:"#/$defs/ComponentId"},description:"A static list of child component IDs."},{type:"object",description:"A template for generating a dynamic list of children from a data model list. The `componentId` is the component to use as a template.",properties:{componentId:{$ref:"#/$defs/ComponentId"},path:{type:"string",description:"The path to the list of component property objects in the data model."}},required:["componentId","path"],additionalProperties:!1}]},DataBinding:{type:"object",properties:{path:{type:"string",description:"A JSON Pointer path to a value in the data model."}},required:["path"],additionalProperties:!1},DynamicValue:{description:"A value that can be a literal, a path, or a function call returning any type.",oneOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"array"},{type:"object",not:{anyOf:[{required:["path"]},{required:["call"]}]}},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},DynamicString:{description:"Represents a string",oneOf:[{type:"string"},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},DynamicNumber:{description:"Represents a value that can be either a literal number, a path to a number in the data model, or a function call returning a number.",oneOf:[{type:"number"},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},DynamicBoolean:{description:"A boolean value that can be a literal, a path, or a function call returning a boolean.",oneOf:[{type:"boolean"},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},DynamicStringList:{description:"Represents a value that can be either a literal array of strings, a path to a string array in the data model, or a function call returning a string array.",oneOf:[{type:"array",items:{type:"string"}},{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}]},FunctionCommon:{type:"object",description:"Baseline envelope properties common to all function calls. Function-specific argument schemas ('args') are defined individually by each function in the active catalog.",properties:{call:{type:"string",description:"The name of the function to call."},catalogId:{type:"string",description:"The catalog ID for this function, overriding any surface-level default catalogId."}},required:["call"]},IndexSystemFunction:{type:"object",description:"Returns the 0-based index of the current item when rendering a dynamic list from a template. This function MUST ONLY be available when evaluating template items within a list context.",returnType:"number",properties:{call:{const:"@index"},args:{type:"object",properties:{offset:{$ref:"#/$defs/DynamicNumber",description:"Optional. An offset to add to the 0-based index (e.g., 1 for 1-based indexing). Defaults to 0.",default:0}},unevaluatedProperties:!1}},required:["call"],unevaluatedProperties:!1},FunctionCall:{type:"object",description:"Invokes a named function, combining common function properties with the catalog function definition.",allOf:[{$ref:"#/$defs/FunctionCommon"},{oneOf:[{$ref:"catalog.json#/$defs/anyFunction"},{$ref:"#/$defs/IndexSystemFunction"}]}],unevaluatedProperties:!1},CheckRule:{type:"object",description:"A single validation check rule applied to an input component. The condition function or path evaluates to a structured validation result object.",properties:{condition:{oneOf:[{$ref:"#/$defs/DataBinding"},{$ref:"#/$defs/FunctionCall"}],description:"Path or function call evaluating to a structured validation result object."},message:{type:"string",description:"Optional fallback error message."}},required:["condition"],additionalProperties:!1},Checkable:{description:"Properties for components that support renderer-side checks.",type:"object",properties:{checks:{type:"array",description:"A list of checks to perform. These are function calls that must return a boolean indicating validity.",items:{$ref:"#/$defs/CheckRule"}}}},Action:{description:"Defines an interaction handler that can either trigger an agent-side event or execute a local renderer-side function.",oneOf:[{type:"object",description:"Triggers an agent-side event.",properties:{event:{type:"object",description:"The event to dispatch to the agent.",properties:{name:{type:"string",description:"The name of the action to be dispatched to the agent."},userMessage:{$ref:"#/$defs/DynamicString",description:"An optional human-readable message describing the action performed by the user, to present in conversation history or user feedback."},context:{type:"object",description:"A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.",additionalProperties:{$ref:"#/$defs/DynamicValue"}}},required:["name"],additionalProperties:!1}},required:["event"],additionalProperties:!1},{type:"object",description:"Executes a renderer or agent-side function.",properties:{functionCall:{$ref:"#/$defs/FunctionCall"}},required:["functionCall"],additionalProperties:!1}]},Surface:{title:"Surface Container Component",description:"The reserved canonical container component representing an A2UI surface. The Surface component is immutable and always has 'child': 'root'.",type:"object",allowedParents:[],properties:{component:{const:"Surface"},child:{const:"root"}},additionalProperties:!1},FunctionResponse:{type:"object",description:"The return response matching a callAgentFunction or callRendererFunction invocation.",properties:{functionCallId:{$ref:"#/$defs/CallId",description:"The unique ID matching the initiating function call."},value:{description:"The return value of the function."},error:{type:"object",description:"An error object indicating failure of the function execution.",properties:{code:{type:"string"},message:{type:"string"}},required:["code","message"],additionalProperties:!1}},required:["functionCallId"],oneOf:[{required:["value"]},{required:["error"]}],additionalProperties:!1}};const STANDARD_DEFS_BY_VERSION={"0.8":V08_STANDARD_DEFS,"0.9":V09_STANDARD_DEFS,"0.9.1":V09_STANDARD_DEFS,"1.0":V10_STANDARD_DEFS};function getStandardDefsForCatalog(Au,lo){if(lo?.standardDefs)return lo.standardDefs;if(lo?.protocolVersion){const $u=toCanonicalVersion(lo.protocolVersion)??normalizeVersionString(lo.protocolVersion);if($u in STANDARD_DEFS_BY_VERSION)return STANDARD_DEFS_BY_VERSION[$u]}return V09_STANDARD_DEFS}function transformRefDescriptionNode(Au){if(typeof Au.description!="string"||!Au.description.startsWith("REF:"))return!1;const lo=Au.description.substring(4),$u=lo.indexOf("|"),Ru=$u===-1?lo:lo.substring(0,$u),Iu=$u===-1?"":lo.substring($u+1),Ou=Au.default;for(const Pu of Object.keys(Au))delete Au[Pu];return Au.$ref=Ru.startsWith("#")?Ru:`#/$defs/${Ru.split("/").pop()}`,Ou!==void 0&&(Au.default=Ou),Iu&&(Au.description=Iu),!0}function cleanSchemaProperties(Au){Array.isArray(Au.anyOf)&&(Au.oneOf=Au.anyOf,delete Au.anyOf),Au.additionalProperties&&typeof Au.additionalProperties=="object"&&Object.keys(Au.additionalProperties).length===0&&(Au.additionalProperties=!0),Au.unevaluatedProperties&&typeof Au.unevaluatedProperties=="object"&&Object.keys(Au.unevaluatedProperties).length===0&&(Au.unevaluatedProperties=!0),"$schema"in Au&&delete Au.$schema}function cleanSchemaNode(Au,lo=new Set){if(typeof Au!="object"||Au===null||lo.has(Au))return;if(lo.add(Au),Array.isArray(Au)){for(const Ru of Au)cleanSchemaNode(Ru,lo);return}const $u=Au;if(!transformRefDescriptionNode($u)){cleanSchemaProperties($u);for(const Ru of Object.keys($u))cleanSchemaNode($u[Ru],lo)}}function processTheme(Au,lo){if(!Au.themeSchema)return;const $u=zodToJsonSchema(Au.themeSchema,{target:"jsonSchema2019-09",$refStrategy:"none"});cleanSchemaNode($u),$u.definitions&&typeof $u.definitions=="object"?(Object.assign(lo,$u.definitions),delete $u.definitions):$u.$defs&&typeof $u.$defs=="object"&&(Object.assign(lo,$u.$defs),delete $u.$defs);const Ru=Au.id.includes("v0_8")||Au.id.includes("v0.8"),Iu={type:"object",properties:$u.properties||{},...Array.isArray($u.required)&&$u.required.length>0?{required:$u.required}:{},...Ru?{}:{additionalProperties:$u.additionalProperties!==void 0?$u.additionalProperties:!0}};lo.theme=Iu}function extractZodComponentSchema(Au,lo){if(!Au.schema||typeof Au.schema!="object"||!("safeParse"in Au.schema))return{props:{},reqList:[],additionalProps:void 0};const $u=zodToJsonSchema(Au.schema,{target:"jsonSchema2019-09",$refStrategy:"none"});cleanSchemaNode($u),$u.definitions&&typeof $u.definitions=="object"?Object.assign(lo,$u.definitions):$u.$defs&&typeof $u.$defs=="object"&&Object.assign(lo,$u.$defs);const Ru=$u.properties||{},Iu=Array.isArray($u.required)?$u.required.filter(Du=>Du!=="component"&&Du!=="id"):[],Ou=$u.unevaluatedProperties??$u.additionalProperties;return{props:Ru,reqList:Iu,additionalProps:typeof Ou=="boolean"||typeof Ou=="object"&&Ou!==null?Ou:void 0}}function processSingleComponent(Au,lo,$u,Ru,Iu){const{props:Ou,reqList:Pu,additionalProps:Du}=extractZodComponentSchema(lo,$u),{component:Lu,id:ju,...Bu}=Ou,Fu={id:{$ref:"#/$defs/ComponentId"},...Bu,component:{const:Au}},zu=["id",...Pu,"component"];let qu;return Iu?.componentEnvelopeRef?qu={allOf:[{$ref:Iu.componentEnvelopeRef},{type:"object",properties:Fu,required:zu}],unevaluatedProperties:Du!==void 0?Du:!1}:qu={type:"object",properties:Fu,required:zu,unevaluatedProperties:Du!==void 0?Du:!1},lo.allowedParents&&lo.allowedParents.length>0&&(qu.allowedParents=lo.allowedParents),lo.allowedChildren&&lo.allowedChildren.length>0&&(qu.allowedChildren=lo.allowedChildren),qu}function processComponents(Au,lo,$u,Ru){if(Au.components.size===0){lo.components={};return}const Iu={};for(const[Ou,Pu]of Au.components.entries())Iu[Ou]=processSingleComponent(Ou,Pu,$u,Au,Ru);lo.components=Iu,$u.anyComponent={oneOf:Array.from(Au.components.keys()).map(Ou=>({$ref:`#/components/${Ou}`})),discriminator:{propertyName:"component"}}}function processSingleFunction(Au,lo,$u){let Ru;if(lo.schema&&typeof lo.schema=="object"&&"safeParse"in lo.schema){const Iu=zodToJsonSchema(lo.schema,{target:"jsonSchema2019-09",$refStrategy:"none"});cleanSchemaNode(Iu),Iu.definitions&&typeof Iu.definitions=="object"?(Object.assign($u,Iu.definitions),delete Iu.definitions):Iu.$defs&&typeof Iu.$defs=="object"&&(Object.assign($u,Iu.$defs),delete Iu.$defs),Ru=Iu}else Ru={type:"object",properties:{}};if(lo.description&&Ru.description===void 0&&(Ru.description=lo.description),Ru.type==="object"){const Iu=Ru.unevaluatedProperties??Ru.additionalProperties,Ou=typeof Iu=="boolean"||typeof Iu=="object"&&Iu!==null?Iu:void 0;Ru.additionalProperties!==void 0&&delete Ru.additionalProperties,Ru.unevaluatedProperties=Ou!==void 0?Ou:!1}return Ru}function processFunctions(Au,lo,$u){if(Au.functions.size===0)return;const Ru={};for(const[Iu,Ou]of Au.functions.entries())Ru[Iu]=processSingleFunction(Iu,Ou,$u);lo.functions=Ru,$u.anyFunction={oneOf:Array.from(Au.functions.keys()).map(Iu=>({$ref:`#/functions/${Iu}`}))}}function collectReferencedDefs(Au,lo,$u=new Set){if(!(typeof Au!="object"||Au===null)&&!$u.has(Au)){if($u.add(Au),typeof Au.$ref=="string"){const Ru=Au.$ref;Ru.startsWith("#/$defs/")&&lo.add(Ru.substring(8))}if(Array.isArray(Au))for(const Ru of Au)collectReferencedDefs(Ru,lo,$u);else for(const Ru of Object.values(Au))collectReferencedDefs(Ru,lo,$u)}}function generateCatalogSchema(Au,lo){const $u={$schema:"https://json-schema.org/draft/2020-12/schema",catalogId:Au.id};Au.instructions&&($u.instructions=Au.instructions);const Ru={};processTheme(Au,Ru),processComponents(Au,$u,Ru,lo),processFunctions(Au,$u,Ru);const Iu=getStandardDefsForCatalog(Au,lo);let Ou;do{Ou=Object.keys(Ru).length;const Pu=new Set;collectReferencedDefs($u,Pu),collectReferencedDefs(Ru,Pu),(Pu.has("DynamicString")||Pu.has("DynamicNumber")||Pu.has("DynamicBoolean")||Pu.has("DynamicValue"))&&(Pu.add("DataBinding"),Pu.add("FunctionCall"));for(const Du of Pu)Du in Iu&&!(Du in Ru)&&(Ru[Du]=Iu[Du])}while(Object.keys(Ru).length>Ou);return Object.keys(Ru).length>0&&($u.$defs=Ru),$u}function extractRefDefName(Au){if(!Au)return"";const lo=Au.lastIndexOf("#");return(lo!==-1?Au.slice(lo+1):Au).split("/").filter(Boolean).pop()??""}function unwrapNextZodLayer(Au,lo){if(!Au?._def)return null;if(lo){if(lo.has(Au))return null;lo.add(Au)}switch(Au._def.typeName){case"ZodOptional":case"ZodNullable":case"ZodDefault":case"ZodReadonly":return Au._def.innerType;case"ZodBranded":return Au._def.type;case"ZodEffects":return Au._def.schema;case"ZodLazy":return Au._def.getter();default:return null}}function getDescriptions(Au){const lo=[],$u=new Set;let Ru=Au;for(;Ru;){Ru.description&&lo.push(Ru.description),Ru._def?.description&&lo.push(Ru._def.description);const Iu=unwrapNextZodLayer(Ru,$u);if(!Iu)break;Ru=Iu}return lo}function unwrapZodType(Au){const lo=new Set;let $u=Au;for(;$u;){const Ru=unwrapNextZodLayer($u,lo);if(!Ru)break;$u=Ru}return $u}function checkDirectJsonRef(Au,lo){if(!Au)return null;const $u=extractRefDefName(Au),Ru=lo.childListRefNames,Iu=lo.childRefNames;return Ru.has($u)?{isChild:!1,isChildList:!0}:Iu.has($u)?{isChild:!0,isChildList:!1}:null}function checkCombinerList(Au,lo){let $u=!1;for(const Ru of Au){if(typeof Ru!="object"||Ru===null)continue;const Iu=checkJsonSchemaRef(Ru,lo);if(Iu.isChildList)return{isChild:!1,isChildList:!0};Iu.isChild&&($u=!0)}return $u?{isChild:!0,isChildList:!1}:null}function checkCombinerRefs(Au,lo){let $u=!1;for(const Ru of["oneOf","anyOf","allOf"]){const Iu=Au[Ru];if(!Array.isArray(Iu))continue;const Ou=checkCombinerList(Iu,lo);if(Ou?.isChildList)return Ou;Ou?.isChild&&($u=!0)}return $u?{isChild:!0,isChildList:!1}:null}function checkJsonSchemaRef(Au,lo){const $u=typeof Au.$ref=="string"?Au.$ref:"",Ru=checkDirectJsonRef($u,lo);if(Ru)return Ru;if(Au.type==="array"&&Au.items){const Ou=checkJsonSchemaRef(Au.items,lo);if(Ou.isChild||Ou.isChildList)return{isChild:!1,isChildList:!0}}const Iu=checkCombinerRefs(Au,lo);return Iu||(Au.type==="object"&&Au.properties&&("componentId"in Au.properties&&("path"in Au.properties||"dataBinding"in Au.properties)||"explicitList"in Au.properties||"template"in Au.properties)?{isChild:!1,isChildList:!0}:{isChild:!1,isChildList:!1})}function isTemplateShape(Au){if(Au?._def?.typeName==="ZodObject"&&typeof Au._def.shape=="function"){const lo=Au._def.shape();return!!(lo.componentId&&(lo.path||lo.dataBinding)||lo.explicitList||lo.template)}return!1}function isArrayOfChild(Au,lo){if(Au?._def?.typeName==="ZodArray"){const $u=unwrapZodType(Au._def.type);return analyzeChildRefSchema($u,lo).isChild}return!1}function analyzeUnionOptions(Au,lo){let $u=!1,Ru=!1,Iu=!1;for(const Ou of Au){const Pu=unwrapZodType(Ou);isTemplateShape(Pu)&&($u=!0),isArrayOfChild(Pu,lo)&&(Ru=!0);const Du=analyzeChildRefSchema(Pu,lo);if(Du.isChildList)return{isChild:!1,isChildList:!0};Du.isChild&&(Iu=!0)}return $u||Ru?{isChild:!1,isChildList:!0}:Iu?{isChild:!0,isChildList:!1}:{isChild:!1,isChildList:!1}}function isChildListDescription(Au,lo){if(!Au)return!1;if(Au.startsWith("REF:")){const Iu=extractRefDefName(Au.substring(4).split("|")[0]);if(lo.has(Iu))return!0}const $u=extractRefDefName(Au.split("|")[0]);if($u&&lo.has($u))return!0;const Ru=Au.trim();return!!lo.has(Ru)}function isChildDescription(Au,lo){if(!Au)return!1;if(Au.startsWith("REF:")){const Iu=extractRefDefName(Au.substring(4).split("|")[0]);if(lo.has(Iu))return!0}const $u=extractRefDefName(Au.split("|")[0]);if($u&&lo.has($u))return!0;const Ru=Au.trim();return!!lo.has(Ru)}function checkDescriptionChildRef(Au,lo){const $u=lo.childListRefNames,Ru=lo.childRefNames;for(const Iu of Au){if(isChildListDescription(Iu,$u))return{isChild:!1,isChildList:!0};if(isChildDescription(Iu,Ru))return{isChild:!0,isChildList:!1}}return null}function analyzeZodArray(Au,lo){const $u=analyzeChildRefSchema(Au,lo);return $u.isChild||$u.isChildList?{isChild:!1,isChildList:!0}:{isChild:!1,isChildList:!1}}function analyzeChildRefSchema(Au,lo){if(!Au||typeof Au!="object")return{isChild:!1,isChildList:!1};const $u=childRefKindOf(Au);if($u==="component-id")return{isChild:!0,isChildList:!1};if($u==="child-list")return{isChild:!1,isChildList:!0};const Ru=checkDescriptionChildRef(getDescriptions(Au),lo);if(Ru)return Ru;const Iu=unwrapZodType(Au);if(!Iu?._def)return checkJsonSchemaRef(Au,lo);const Ou=childRefKindOf(Iu);if(Ou==="component-id")return{isChild:!0,isChildList:!1};if(Ou==="child-list")return{isChild:!1,isChildList:!0};const Pu=Iu._def.typeName;if(Pu==="ZodArray"){const Du=unwrapZodType(Iu._def.type);return analyzeZodArray(Du,lo)}if(Pu==="ZodUnion"){const Du=Iu._def.options??[];return analyzeUnionOptions(Du,lo)}if(Pu==="ZodObject"&&typeof Iu._def.shape=="function"){const Du=Iu._def.shape();if(Du.componentId&&(Du.path||Du.dataBinding)||Du.explicitList||Du.template)return{isChild:!1,isChildList:!0}}return{isChild:!1,isChildList:!1}}function addNestedRef(Au,lo,$u){const Ru=Au.nestedRefs[lo];if(Ru){Ru.add($u);return}Au.nestedRefs[lo]=new Set([$u])}function inspectShapeField(Au,lo,$u,Ru){const Iu=analyzeChildRefSchema(lo,Ru);if(Iu.isChildList){$u.listRefs.add(Au);return}if(Iu.isChild){$u.singleRefs.add(Au);return}const Ou=unwrapZodType(lo);if(Ou?._def?.typeName!=="ZodArray")return;const Pu=unwrapZodType(Ou._def.type);if(Pu?._def?.typeName!=="ZodObject"||typeof Pu._def.shape!="function")return;const Du=Pu._def.shape();for(const[Lu,ju]of Object.entries(Du)){const Bu=analyzeChildRefSchema(ju,Ru);(Bu.isChild||Bu.isChildList)&&($u.listRefs.add(Au),addNestedRef($u,Au,Lu))}}function rawArrayItemProperties(Au){if(typeof Au!="object"||Au===null)return null;const lo=Au;if(lo.type!=="array"&&!("items"in lo))return null;const $u=lo.items;if(typeof $u!="object"||$u===null)return null;const Ru=$u.properties;return typeof Ru!="object"||Ru===null?null:Ru}function inspectRawProperties(Au,lo,$u){for(const[Ru,Iu]of Object.entries(Au)){const Ou=analyzeChildRefSchema(Iu,$u);if(Ou.isChildList){lo.listRefs.add(Ru);continue}if(Ou.isChild){lo.singleRefs.add(Ru);continue}const Pu=rawArrayItemProperties(Iu);if(Pu)for(const[Du,Lu]of Object.entries(Pu)){const ju=analyzeChildRefSchema(Lu,$u);(ju.isChild||ju.isChildList)&&(lo.listRefs.add(Ru),addNestedRef(lo,Ru,Du))}}}function inspectComponentSchema(Au,lo,$u){if(!Au)return;const Ru=unwrapZodType(Au);if(Ru?._def?.typeName==="ZodObject"&&typeof Ru._def.shape=="function"){const Iu=Ru._def.shape();for(const[Ou,Pu]of Object.entries(Iu))inspectShapeField(Ou,Pu,lo,$u);return}if(typeof Au=="object"&&Au!==null&&"properties"in Au){const Iu=Au.properties;typeof Iu=="object"&&Iu!==null&&inspectRawProperties(Iu,lo,$u)}}function buildComponentRefMap(Au,lo){const $u={},Ru=typeof Au?.components?.values=="function"?Array.from(Au.components.values()):Array.isArray(Au)?Au:Array.from(Au.values());for(const Iu of Ru){const Ou={singleRefs:new Set,listRefs:new Set,nestedRefs:{}};inspectComponentSchema(Iu.schema,Ou,lo),$u[Iu.name]={singleRefs:Ou.singleRefs,listRefs:Ou.listRefs,nestedRefs:Ou.nestedRefs}}return $u}function createFunctionImplementation(Au,lo){return{name:Au.name,returnType:Au.returnType,schema:Au.schema,allowedCallers:Au.allowedCallers,requiresUserActivation:Au.requiresUserActivation,description:Au.description,execute:lo}}class Catalog{get catalogSchema(){return this.cachedCatalogSchema||(this.cachedCatalogSchema=generateCatalogSchema(this)),this.cachedCatalogSchema}get componentRefMap(){return this._componentRefMap||(this._componentRefMap=buildComponentRefMap(this,V09_CHILD_REF_OPTIONS)),this._componentRefMap}constructor(lo,$u,Ru=[],Iu=[],Ou,Pu){if(!$u)throw new A2uiCatalogError("protocolVersion must be provided.");this.id=lo,this.protocolVersion=$u;const Du=new Map;for(const ju of Ru)Du.set(ju.name,ju);this.components=Du;const Lu=new Map;for(const ju of Iu)Lu.set(ju.name,ju);this.functions=Lu,this.themeSchema=Ou,this.instructions=Pu,this.invoker=(ju,Bu,Fu,zu)=>{const qu=this.functions.get(ju);if(!qu)throw new A2uiExpressionError(`Function not found in catalog '${this.id}': ${ju}`,ju);const Uu=qu.execute;if(typeof Uu!="function")throw new A2uiExpressionError(`Function '${ju}' in catalog '${this.id}' is schema-only and has no implementation.`,ju);try{const Hu=qu.schema.parse(Bu);return Uu.call(qu,Hu,Fu,zu)}catch(Hu){throw Hu?.name==="ZodError"||Hu instanceof ZodError?new A2uiExpressionError(`Validation failed for function '${ju}': ${Hu.message}`,ju,Hu.errors??Hu.issues):Hu}}}static fromSchema(lo,$u){return loadCatalogFromSchema(lo,$u)}}class EventEmitter{constructor(){this.listeners=new Set}subscribe(lo){return this.listeners.add(lo),{unsubscribe:()=>this.listeners.delete(lo)}}async emit(lo){for(const $u of this.listeners)try{await $u(lo)}catch(Ru){console.error("EventEmitter error:",Ru)}}dispose(){this.listeners.clear()}}var i=Symbol.for("preact-signals");function t(){if(v>1)v--;else{var Au,lo=!1;for((function(){var Iu=c;for(c=void 0;Iu!==void 0;){var Ou=Iu.S;if(Ou.v===Iu.v)for(var Pu=Ou.t;Pu!==void 0;Pu=Pu.x)Pu.i===Iu.i&&(Pu.i=Ou.i);Iu=Iu.o}})();h!==void 0;){var $u=h;for(h=void 0,s++;$u!==void 0;){var Ru=$u.u;if($u.u=void 0,$u.f&=-3,!(8&$u.f)&&w($u))try{$u.c()}catch(Iu){lo||(Au=Iu,lo=!0)}$u=Ru}}if(s=0,v--,lo)throw Au}}function n(Au){if(v>0)return Au();e=++u,v++;try{return Au()}finally{t()}}var r,o=void 0;function f(Au){var lo=o,$u=r;o=void 0,r=void 0;try{return Au()}finally{o=lo,r=$u}}var h=void 0,v=0,s=0,u=0,e=0,c=void 0,d=0;function a(Au){if(o!==void 0){var lo=Au.n;if(lo===void 0||lo.t!==o)return lo={i:0,S:Au,p:o.s,n:void 0,t:o,e:void 0,x:void 0,r:lo},o.s!==void 0&&(o.s.n=lo),o.s=lo,Au.n=lo,32&o.f&&Au.S(lo),lo;if(lo.i===-1)return lo.i=0,lo.n!==void 0&&(lo.n.p=lo.p,lo.p!==void 0&&(lo.p.n=lo.n),lo.p=o.s,lo.n=void 0,o.s.n=lo,o.s=lo),lo}}function l(Au,lo){this.v=Au,this.i=0,this.n=void 0,this.t=void 0,this.l=0,this.W=lo?.watched,this.Z=lo?.unwatched,this.name=lo?.name}l.prototype.brand=i;l.prototype.h=function(){return!0};l.prototype.S=function(Au){var lo=this,$u=this.t;$u!==Au&&Au.e===void 0&&(Au.x=$u,this.t=Au,$u!==void 0?$u.e=Au:f(function(){var Ru;(Ru=lo.W)==null||Ru.call(lo)}))};l.prototype.U=function(Au){var lo=this;if(this.t!==void 0){var $u=Au.e,Ru=Au.x;$u!==void 0&&($u.x=Ru,Au.e=void 0),Ru!==void 0&&(Ru.e=$u,Au.x=void 0),Au===this.t&&(this.t=Ru,Ru===void 0&&f(function(){var Iu;(Iu=lo.Z)==null||Iu.call(lo)}))}};l.prototype.subscribe=function(Au){var lo=this;return j(function(){var $u=lo.value;f(function(){return Au($u)})},{name:"sub"})};l.prototype.valueOf=function(){return this.value};l.prototype.toString=function(){return this.value+""};l.prototype.toJSON=function(){return this.value};l.prototype.peek=function(){var Au=this;return f(function(){return Au.value})};Object.defineProperty(l.prototype,"value",{get:function(){var Au=a(this);return Au!==void 0&&(Au.i=this.i),this.v},set:function(Au){if(Au!==this.v){if(s>100)throw new Error("Cycle detected");(function($u){v!==0&&s===0&&$u.l!==e&&($u.l=e,c={S:$u,v:$u.v,i:$u.i,o:c})})(this),this.v=Au,this.i++,d++,v++;try{for(var lo=this.t;lo!==void 0;lo=lo.x)lo.t.N()}finally{t()}}}});function y(Au,lo){return new l(Au,lo)}function w(Au){for(var lo=Au.s;lo!==void 0;lo=lo.n)if(lo.S.i!==lo.i||!lo.S.h()||lo.S.i!==lo.i)return!0;return!1}function _(Au){for(var lo=Au.s;lo!==void 0;lo=lo.n){var $u=lo.S.n;if($u!==void 0&&(lo.r=$u),lo.S.n=lo,lo.i=-1,lo.n===void 0){Au.s=lo;break}}}function b(Au){for(var lo=Au.s,$u=void 0;lo!==void 0;){var Ru=lo.p;lo.i===-1?(lo.S.U(lo),Ru!==void 0&&(Ru.n=lo.n),lo.n!==void 0&&(lo.n.p=Ru)):$u=lo,lo.S.n=lo.r,lo.r!==void 0&&(lo.r=void 0),lo=Ru}Au.s=$u}function p(Au,lo){l.call(this,void 0,lo),this.x=Au,this.s=void 0,this.g=d-1,this.f=4}p.prototype=new l;p.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===d))return!0;if(this.g=d,this.f|=1,this.i>0&&!w(this))return this.f&=-2,!0;var Au=o;try{_(this),o=this;var lo=this.x();(16&this.f||this.v!==lo||this.i===0)&&(this.v=lo,this.f&=-17,this.i++)}catch($u){this.v=$u,this.f|=16,this.i++}return o=Au,b(this),this.f&=-2,!0};p.prototype.S=function(Au){if(this.t===void 0){this.f|=36;for(var lo=this.s;lo!==void 0;lo=lo.n)lo.S.S(lo)}l.prototype.S.call(this,Au)};p.prototype.U=function(Au){if(this.t!==void 0&&(l.prototype.U.call(this,Au),this.t===void 0)){this.f&=-33;for(var lo=this.s;lo!==void 0;lo=lo.n)lo.S.U(lo)}};p.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var Au=this.t;Au!==void 0;Au=Au.x)Au.t.N()}};Object.defineProperty(p.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var Au=a(this);if(this.h(),Au!==void 0&&(Au.i=this.i),16&this.f)throw this.v;return this.v}});function g(Au,lo){return new p(Au,lo)}function S(Au){var lo=Au.m;if(Au.m=void 0,typeof lo=="function"){v++;var $u=o;o=void 0;try{lo()}catch(Ru){throw Au.f&=-2,Au.f|=8,m(Au),Ru}finally{o=$u,t()}}}function m(Au){for(var lo=Au.s;lo!==void 0;lo=lo.n)lo.S.U(lo);Au.x=void 0,Au.s=void 0,S(Au)}function x(Au){if(o!==this)throw new Error("Out-of-order effect");b(this),o=Au,this.f&=-2,8&this.f&&m(this),t()}function E(Au,lo){this.x=Au,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=lo?.name,r&&r.push(this)}E.prototype.c=function(){var Au=this.S();try{if(8&this.f||this.x===void 0)return;var lo=this.x();typeof lo=="function"&&(this.m=lo)}finally{Au()}};E.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,S(this),_(this),v++;var Au=o;return o=this,x.bind(this,Au)};E.prototype.N=function(){2&this.f||(this.f|=2,this.u=h,h=this)};E.prototype.d=function(){this.f|=8,1&this.f||m(this)};E.prototype.dispose=function(){this.d()};function j(Au,lo){var $u=new E(Au,lo);try{$u.c()}catch(Iu){throw $u.d(),Iu}var Ru=$u.d.bind($u);return Ru[Symbol.dispose]=Ru,Ru}let signalImpl,computedImpl,effectImpl,batchWriteImpl,isSignalImpl,getValueImpl,setValueImpl,peekValueImpl;const _PRIVATE_DEFAULT_SIGNAL_IMPLEMENTATION={signal:y,computed:g,effect:j,batchWrite:n,isSignal:Au=>!!Au&&typeof Au=="object"&&"value"in Au&&"peek"in Au,getValue:Au=>Au.value,setValue:(Au,lo)=>{Au instanceof p||(Au.value=lo)},peekValue:Au=>Au.peek()};setSignalImplementation(_PRIVATE_DEFAULT_SIGNAL_IMPLEMENTATION);function setSignalImplementation(Au){signalImpl=Au.signal,computedImpl=Au.computed,effectImpl=Au.effect,batchWriteImpl=Au.batchWrite,isSignalImpl=Au.isSignal,getValueImpl=Au.getValue,setValueImpl=Au.setValue,peekValueImpl=Au.peekValue}function signal(Au){return signalImpl(Au)}function computed(Au){return computedImpl(Au)}function effect(Au){return effectImpl(Au)}function batchWrite(Au){return batchWriteImpl(Au)}function isSignal(Au){return isSignalImpl(Au)}function getValue(Au){return getValueImpl(Au)}function setValue(Au,lo){setValueImpl(Au,lo)}function peekValue(Au){return peekValueImpl(Au)}function isNumeric(Au){return/^(0|[1-9]\d*)$/.test(Au)}const MAX_ARRAY_INDEX=1e4,FORBIDDEN_KEYS=new Set(["__proto__","constructor","prototype"]);class DataModel{constructor(lo={}){this.data={},this.signals=new Map,this.subscriptions=new Set,this.data=lo}getSignal(lo){const $u=this.normalizePath(lo);return this.signals.has($u)||this.signals.set($u,signal(this.get($u))),this.signals.get($u)}set(lo,$u){if(lo==null)throw new A2uiDataError("Path cannot be null or undefined.");if(lo==="/"||lo==="")return this.data=$u??{},this.notifyAllSignals(),this;const Ru=this.parsePath(lo),Iu=Ru.pop();if($u==null&&this.get(lo)===void 0)return this;if(this.data===void 0||this.data===null)this.data={};else if(typeof this.data!="object")throw new A2uiDataError(`Cannot set path '${lo}': the data model root is a primitive value.`,lo);let Ou=this.data;for(let Pu=0;Pu<Ru.length;Pu++){const Du=Ru[Pu];if(Array.isArray(Ou)){if(!isNumeric(Du))throw new A2uiDataError(`Cannot use non-numeric segment '${Du}' on an array in path '${lo}'.`,lo);const Lu=parseInt(Du,10);if(Lu>MAX_ARRAY_INDEX)throw new A2uiDataError(`Cannot set path '${lo}': array index '${Du}' exceeds maximum supported index (${MAX_ARRAY_INDEX}).`,lo);const ju=Ou[Lu];if(ju!=null&&typeof ju!="object")throw new A2uiDataError(`Cannot set path '${lo}': segment '${Du}' is a primitive value.`,lo);if(ju==null){const Bu=Pu<Ru.length-1?Ru[Pu+1]:Iu;if(isNumeric(Bu)){if(parseInt(Bu,10)>MAX_ARRAY_INDEX)throw new A2uiDataError(`Cannot set path '${lo}': array index '${Bu}' exceeds maximum supported index (${MAX_ARRAY_INDEX}).`,lo);Ou[Lu]=[]}else Ou[Lu]={}}}else{const Lu=Object.prototype.hasOwnProperty.call(Ou,Du);if(Lu){const ju=Ou[Du];if(ju!=null&&typeof ju!="object")throw new A2uiDataError(`Cannot set path '${lo}': segment '${Du}' is a primitive value.`,lo)}if(!Lu||Ou[Du]===void 0||Ou[Du]===null){const ju=Pu<Ru.length-1?Ru[Pu+1]:Iu;if(isNumeric(ju)){if(parseInt(ju,10)>MAX_ARRAY_INDEX)throw new A2uiDataError(`Cannot set path '${lo}': array index '${ju}' exceeds maximum supported index (${MAX_ARRAY_INDEX}).`,lo);Ou[Du]=[]}else Ou[Du]={}}}Ou=Ou[Du]}if(Array.isArray(Ou)){if(!isNumeric(Iu))throw new A2uiDataError(`Cannot use non-numeric segment '${Iu}' on an array in path '${lo}'.`,lo);if(parseInt(Iu,10)>MAX_ARRAY_INDEX)throw new A2uiDataError(`Cannot set path '${lo}': array index '${Iu}' exceeds maximum supported index (${MAX_ARRAY_INDEX}).`,lo)}if($u==null)if(Array.isArray(Ou)){const Pu=parseInt(Iu,10);Pu<Ou.length&&(Ou[Pu]=void 0)}else delete Ou[Iu];else Ou[Iu]=$u;return this.notifySignals(lo),this}delete(lo){return this.set(lo,void 0)}static resolvePath(lo,$u){return lo.startsWith("/")?lo:$u?`${$u.endsWith("/")?$u:`${$u}/`}${lo}`:`/${lo}`}get(lo){if(lo==null)throw new A2uiDataError("Path cannot be null or undefined.");if(lo==="/"||lo==="")return this.data;const $u=this.parsePath(lo);let Ru=this.data;for(const Iu of $u){if(Ru==null||typeof Ru!="object")return;if(Array.isArray(Ru)){if(!isNumeric(Iu))return;const Ou=parseInt(Iu,10);if(Ou<0||Ou>=Ru.length)return;Ru=Ru[Ou]}else{if(!Object.prototype.hasOwnProperty.call(Ru,Iu))return;Ru=Ru[Iu]}}return Ru}hasPath(lo){return lo==null?!1:this.get(lo)!==void 0}subscribe(lo,$u){const Ru=this.getSignal(lo);let Iu=!0,Ou=peekValue(Ru);const Pu=effect(()=>{const Du=getValue(Ru);Ou=Du,Iu||$u(Du)});return Iu=!1,this.subscriptions.add(Pu),{get value(){return Ou},unsubscribe:()=>{Pu(),this.subscriptions.delete(Pu)}}}dispose(){for(const lo of this.subscriptions)lo();this.subscriptions.clear(),this.signals.clear()}normalizePath(lo){return lo.length>1&&lo.endsWith("/")?lo.slice(0,-1):lo||"/"}parsePath(lo){return lo.split("/").filter($u=>$u.length>0).map($u=>{const Ru=$u.replace(/~([01])/g,(Iu,Ou)=>Ou==="1"?"/":"~");if(FORBIDDEN_KEYS.has(Ru))throw new A2uiDataError(`Forbidden path segment '${Ru}' in path '${lo}'.`,lo);return Ru})}notifySignals(lo){const $u=this.normalizePath(lo);batchWrite(()=>{this.updateSignal($u);let Ru=$u;for(;Ru!=="/"&&Ru!=="";)Ru=Ru.substring(0,Ru.lastIndexOf("/"))||"/",this.updateSignal(Ru);for(const Iu of this.signals.keys())this.isDescendant(Iu,$u)&&this.updateSignal(Iu)})}updateSignal(lo){const $u=this.signals.get(lo);if($u){const Ru=this.get(lo);Array.isArray(Ru)?setValue($u,Ru.slice()):typeof Ru=="object"&&Ru!==null?setValue($u,{...Ru}):setValue($u,Ru)}}notifyAllSignals(){batchWrite(()=>{for(const lo of this.signals.keys())this.updateSignal(lo)})}isDescendant(lo,$u){return $u==="/"||$u===""?lo!=="/":lo.startsWith($u+"/")}}const MAX_GLOBAL_DEPTH=50,MAX_FUNC_CALL_DEPTH=5,RELAXED_PATH_PATTERN=/^(?:(?:\/(?:[^~/]|~[01])*)*|(?:[^~/]|~[01])+(?:\/(?:[^~/]|~[01])*)*)$/;function*extractPointers(Au,lo,$u){if(typeof Au=="string")yield[Au,lo];else if(Array.isArray(Au))for(let Ru=0;Ru<Au.length;Ru++){const Iu=Au[Ru],Ou=`${lo}[${Ru}]`;yield*extractPointers(Iu,Ou,$u)}else if(typeof Au=="object"&&Au!==null){const Ru=Au;if("componentId"in Ru&&typeof Ru.componentId=="string"&&("path"in Ru||"dataBinding"in Ru))yield[Ru.componentId,`${lo}.componentId`];else if($u?.size)for(const Iu of $u)Iu in Ru&&(yield*extractPointers(Ru[Iu],`${lo}.${Iu}`));else for(const[Iu,Ou]of Object.entries(Ru))yield*extractPointers(Ou,`${lo}.${Iu}`)}}function getOrCreateRefMap(Au){return Au.componentRefMap}function*getComponentReferences(Au,lo){if(!Au||typeof Au!="object")return;const $u=lo instanceof Catalog?getOrCreateRefMap(lo):lo,Ru=Au.component;let Iu="",Ou=Au;if(typeof Ru=="string")Iu=Ru;else if(typeof Ru=="object"&&Ru!==null){const Bu=Ru;Iu=Object.keys(Bu)[0]??"",Ou=Bu[Iu]??{}}if(!Iu||typeof Ou!="object"||Ou===null)return;const Pu=$u[Iu],Du=Pu?Pu.singleRefs:new Set,Lu=Pu?Pu.listRefs:new Set,ju=Pu?.nestedRefs;for(const[Bu,Fu]of Object.entries(Ou))(Du.has(Bu)||Lu.has(Bu))&&(yield*extractPointers(Fu,Bu,ju?.[Bu]))}function traverseRecursionAndPaths(Au,lo,$u){if(lo>MAX_GLOBAL_DEPTH)throw new A2uiRecursionError(`Global recursion limit exceeded: Depth > ${MAX_GLOBAL_DEPTH}`);if(Array.isArray(Au)){for(const Ru of Au)traverseRecursionAndPaths(Ru,lo+1,$u);return}if(typeof Au=="object"&&Au!==null){const Ru=Au;if("path"in Ru&&typeof Ru.path=="string"){const Pu=Ru.path;if(!RELAXED_PATH_PATTERN.test(Pu))throw new A2uiValidationError(`Invalid path syntax: '${Pu}'`)}const Iu="functionCall"in Ru&&typeof Ru.functionCall=="object"&&Ru.functionCall!==null,Ou="call"in Ru&&"args"in Ru;if(Iu){if($u>=MAX_FUNC_CALL_DEPTH)throw new A2uiRecursionError(`Recursion limit exceeded: functionCall depth > ${MAX_FUNC_CALL_DEPTH}`);for(const[Pu,Du]of Object.entries(Ru))Pu==="functionCall"?traverseRecursionAndPaths(Du,lo+1,$u+1):traverseRecursionAndPaths(Du,lo+1,$u)}else if(Ou){if($u>=MAX_FUNC_CALL_DEPTH)throw new A2uiRecursionError(`Recursion limit exceeded: functionCall depth > ${MAX_FUNC_CALL_DEPTH}`);for(const[Pu,Du]of Object.entries(Ru))Pu==="args"?traverseRecursionAndPaths(Du,lo+1,$u+1):traverseRecursionAndPaths(Du,lo+1,$u)}else for(const Pu of Object.values(Ru))traverseRecursionAndPaths(Pu,lo+1,$u)}}function validateRecursionAndPaths(Au){traverseRecursionAndPaths(Au,0,0)}class SurfaceComponentsModel{constructor(lo){this.components=new Map,this._onCreated=new EventEmitter,this._onDeleted=new EventEmitter,this.onCreated=this._onCreated,this.onDeleted=this._onDeleted,lo&&this.setCatalog(lo)}setCatalog(lo){this.refMap=lo instanceof Catalog?lo.componentRefMap:lo}get(lo){return this.components.get(lo)}getAll(){return new Map(this.components)}has(lo){return this.components.has(lo)}get entries(){return this.components.entries()}get keys(){return this.components.keys()}get values(){return this.components.values()}get size(){return this.components.size}get componentsMap(){return this.components}addComponent(lo){if(this.components.has(lo.id))throw new A2uiStateError(`Component with id '${lo.id}' already exists.`);this.components.set(lo.id,lo),this._onCreated.emit(lo)}removeComponent(lo){const $u=this.components.get(lo);$u&&(this.components.delete(lo),$u.dispose(),this._onDeleted.emit(lo))}getChildReferences(lo){const $u=this.components.get(lo);if(!$u)return[];const Ru=$u.catalog?.components.size?$u.catalog.componentRefMap:this.refMap??$u.catalog?.componentRefMap??{};return Array.from(getComponentReferences({id:$u.id,component:$u.type,...$u.properties},Ru))}getChildIds(lo){return this.getChildReferences(lo).map(([$u])=>$u)}detectCycles(lo={}){const $u=lo.rootId??"root",Ru=lo.maxDepth??MAX_GLOBAL_DEPTH,Iu=lo.allowMissingRoot??!1;for(const Lu of this.components.values())for(const[ju,Bu]of this.getChildReferences(Lu.id))if(ju===Lu.id)throw new A2uiRecursionError(`Circular reference detected: Component '${Lu.id}' references itself in field '${Bu}' (Self-reference detected)`);const Ou=new Set,Pu=new Set,Du=(Lu,ju)=>{if(ju>Ru)throw new A2uiRecursionError(`Global recursion limit exceeded: logical depth > ${Ru}`);Ou.add(Lu),Pu.add(Lu);const Bu=this.getChildIds(Lu);for(const Fu of Bu)if(this.components.has(Fu)){if(!Ou.has(Fu))Du(Fu,ju+1);else if(Pu.has(Fu))throw new A2uiRecursionError(`Circular reference detected involving component '${Fu}'`)}Pu.delete(Lu)};if(Iu){const Lu=Array.from(this.components.keys()).sort();for(const ju of Lu)Ou.has(ju)||Du(ju,0)}else this.components.has($u)&&Du($u,0);return Ou}validateTopology(lo={}){if(this.components.size===0)return;const $u=lo.rootId??"root",Ru=lo.allowMissingRoot??!1,Iu=lo.allowDanglingReferences??!1,Ou=lo.allowOrphanComponents??!1;if(!Ru&&!this.components.has($u))throw new A2uiIntegrityError(`Missing root component: No component has id='${$u}'`);if(!Iu){for(const Du of this.components.values())for(const[Lu,ju]of this.getChildReferences(Du.id))if(!this.components.has(Lu))throw new A2uiIntegrityError(`Component '${Du.id}' references non-existent component '${Lu}' in field '${ju}' (Dangling reference '${Lu}' in component '${Du.id}')`)}const Pu=this.detectCycles({rootId:$u,allowMissingRoot:Ru,maxDepth:lo.maxDepth});if(!Ou&&!Ru&&Pu.size<this.components.size){const Du=Array.from(this.components.keys()).filter(Lu=>!Pu.has(Lu)).sort();if(Du.length>0)throw new A2uiIntegrityError(`Component '${Du[0]}' is not reachable from '${$u}' (Orphaned component '${Du[0]}' is not reachable from root)`)}}validateReferences(lo={}){const $u=[];try{this.validateTopology(lo)}catch(Ru){Ru instanceof A2uiValidationError?$u.push(Ru):Ru instanceof Error&&$u.push(new A2uiValidationError(Ru.message))}return $u}dispose(){for(const lo of this.components.values())lo.dispose();this.components.clear(),this._onCreated.dispose(),this._onDeleted.dispose()}}class SurfaceModel{constructor(lo,$u,Ru=new Map,Iu={},Ou=!1,Pu,Du="root"){if(this.id=lo,this.defaultCatalog=$u,this.theme=Iu,this.sendDataModel=Ou,this.rootId=Du,this._onAction=new EventEmitter,this._onError=new EventEmitter,this._onWarning=new EventEmitter,this.onAction=this._onAction,this.onError=this._onError,this.onWarning=this._onWarning,Ru!=null&&!(Ru instanceof Map))throw new TypeError("availableCatalogs must be a Map, or undefined/null. Note that availableCatalogs is now the 3rd argument to SurfaceModel and theme is the 4th argument.");const Lu=new Map(Ru??[]);$u?.id&&!Lu.has($u.id)&&Lu.set($u.id,$u),this.availableCatalogs=Lu,this.dataModel=Pu??new DataModel({}),this.componentsModel=new SurfaceComponentsModel($u)}get catalog(){return this.defaultCatalog}async dispatchAction(lo,$u){if(!lo||typeof lo!="object")return;const Ru=extractActionTarget(lo);if(!Ru)return;const Iu=Ru.name;if(!Iu||typeof Iu!="string")return;const Ou=Ru.context,Pu=Ou&&typeof Ou=="object"&&!Array.isArray(Ou)?Ou:{},Du={name:Iu,surfaceId:this.id,sourceComponentId:$u,timestamp:new Date().toISOString(),context:Pu},Lu=Ru.catalogId??lo.catalogId;typeof Lu=="string"&&Lu&&(Du.catalogId=Lu),typeof Ru.userMessage=="string"&&Ru.userMessage.length>0&&(Du.userMessage=Ru.userMessage),await this._onAction.emit(Du)}async dispatchError(lo){await this._onError.emit({...lo,surfaceId:this.id})}async dispatchWarning(lo){await this._onWarning.emit({...lo,surfaceId:this.id})}dispose(){this.dataModel.dispose(),this.componentsModel.dispose(),this._onAction.dispose(),this._onError.dispose(),this._onWarning.dispose()}}function extractActionTarget(Au){return"event"in Au&&Au.event&&typeof Au.event=="object"?Au.event:"name"in Au&&typeof Au.name=="string"?Au:null}class SurfaceGroupModel{constructor(){this.surfaces=new Map,this.surfaceUnsubscribers=new Map,this._onSurfaceCreated=new EventEmitter,this._onSurfaceDeleted=new EventEmitter,this._onAction=new EventEmitter,this.onSurfaceCreated=this._onSurfaceCreated,this.onSurfaceDeleted=this._onSurfaceDeleted,this.onAction=this._onAction}addSurface(lo){if(this.surfaces.has(lo.id)){console.warn(`Surface ${lo.id} already exists. Ignoring.`);return}this.surfaces.set(lo.id,lo);const $u=lo.onAction.subscribe(Ru=>this._onAction.emit(Ru));this.surfaceUnsubscribers.set(lo.id,$u),this._onSurfaceCreated.emit(lo)}deleteSurface(lo){const $u=this.surfaces.get(lo);if($u){const Ru=this.surfaceUnsubscribers.get(lo);Ru&&(Ru.unsubscribe(),this.surfaceUnsubscribers.delete(lo)),this.surfaces.delete(lo),$u.dispose(),this._onSurfaceDeleted.emit(lo)}}getSurface(lo){return this.surfaces.get(lo)}get surfacesMap(){return this.surfaces}dispose(){for(const lo of Array.from(this.surfaces.keys()))this.deleteSurface(lo);this._onSurfaceCreated.dispose(),this._onSurfaceDeleted.dispose(),this._onAction.dispose()}}class ComponentModel{constructor(lo,$u,Ru,Iu){this.id=lo,this.type=$u,this.catalog=Iu,this._onUpdated=new EventEmitter,this.onUpdated=this._onUpdated,this._properties=Ru}get properties(){return this._properties}set properties(lo){this._properties=lo,this._onUpdated.emit(this)}dispose(){this._onUpdated.dispose()}get componentTree(){return{id:this.id,type:this.type,...this._properties}}}function formatZodIssue(Au){const lo=Au.path.join(".")||"root";switch(Au.code){case ZodIssueCode.invalid_union:{const $u=Au.unionErrors?.flatMap(Ru=>Ru.issues);return $u&&$u.length>0?$u.map(formatZodIssue).join("; "):`${lo}: Invalid union`}case ZodIssueCode.unrecognized_keys:{const $u=Au.keys.map(Ru=>`'${Ru}'`).join(", ");return`${lo}: Unrecognized key(s) in object: ${$u}`}case ZodIssueCode.invalid_enum_value:{const $u=Au,Ru=$u.options.map(Iu=>String(Iu)).join(" | ");return`${lo}: Invalid enum value. Expected ${Ru}, received '${String($u.received)}'`}case ZodIssueCode.invalid_type:{const $u=Au;return`${lo}: Expected ${$u.expected}, received ${$u.received}`}case ZodIssueCode.custom:return`${lo}: ${Au.message}`;default:return Au.message?`${lo}: ${Au.message}`:`${lo}: Validation error (${Au.code})`}}const DEFAULT_CATALOG_COMPATIBILITY={"0.8":new Set(["0.8"]),"0.9":new Set(["0.9","0.9.1"]),"0.9.1":new Set(["0.9.1","0.9"]),"1.0":new Set(["1.0"])};function isCatalogVersionCompatible(Au,lo,$u=DEFAULT_CATALOG_COMPATIBILITY){if(!Au||!lo)return!1;const Ru=toCanonicalVersion(Au),Iu=toCanonicalVersion(lo);if(Ru&&Iu){if(Ru===Iu)return!0;const Du=$u[Iu];if(Du&&Du.has(Ru))return!0;const Lu=toSemVer(Au),ju=toSemVer(lo);return!!(Lu&&ju&&Lu.major>=1&&Lu.major===ju.major)}if(typeof Au!="string"||typeof lo!="string")return!1;const Ou=normalizeVersionString(Au),Pu=normalizeVersionString(lo);return Ou.length>0&&Ou===Pu}let globalKnownActionsProvider;function registerKnownActionsProvider(Au){globalKnownActionsProvider=Au}function validateActionSurfaceIds(Au,lo){for(const $u of lo){const Ru=Au[$u];if(Ru&&typeof Ru=="object"){const Iu=Ru;if("surfaceId"in Iu&&Iu.surfaceId!==void 0&&typeof Iu.surfaceId!="string")throw new A2uiValidationError("surfaceId must be a string")}}}class BaseVersionAdapter{get compatibleCatalogVersions(){const lo=toCanonicalVersion(this.version);return lo?new Set([lo]):new Set}get validActions(){return new Set(this.getNativeActionKeys())}isCatalogCompatible(lo){return lo?isCatalogVersionCompatible(lo,this.version):!1}extractOperations(lo){if(!lo||typeof lo!="object")return[];if(Array.isArray(lo))return lo.flatMap(Du=>this.extractOperations(Du));const $u=lo;if(Array.isArray($u.messages))return this.extractOperations($u.messages);const Ru=this.getNativeActionKeys();validateActionSurfaceIds($u,Ru);const Iu=Ru.filter(Du=>Du in $u).sort();if(Iu.length>1)throw new A2uiValidationError(`Message contains multiple conflicting update actions: ${Iu.join(", ")}.`);if(Iu.length===0){const Du=globalKnownActionsProvider?globalKnownActionsProvider():new Set(Ru),Lu=Object.keys($u).find(Bu=>Du.has(Bu)&&!Ru.includes(Bu)),ju=Ru.slice().sort().join(", ");throw Lu?new A2uiValidationError(`Invalid ${this.version} message: action '${Lu}' is not supported in protocol version ${this.version}. Allowed actions: ${ju}.`):new A2uiValidationError(`Invalid ${this.version} message: message must contain exactly one update action: ${ju}.`)}const Ou=this.preparePayloadForValidation($u),Pu=this.schema.safeParse(Ou);if(!Pu.success){const Du=Pu.error.errors.map(formatZodIssue).join("; ");throw new A2uiValidationError(`Invalid ${this.version} message: ${Du}`,Pu.error)}return this.extractOperationsFromObject($u)}preparePayloadForValidation(lo){return"version"in lo?lo:{version:this.version,...lo}}}const exactlyOneKey=(Au,lo)=>{const $u=Object.keys(Au).filter(Ru=>Au[Ru]!==void 0);$u.length!==1&&lo.addIssue({code:ZodIssueCode.custom,message:`Must define exactly one property, found ${$u.length} (${$u.join(", ")}).`})},StringValueSchema=objectType({path:stringType().optional(),literalString:stringType().optional(),literal:stringType().optional()}).strict().superRefine(exactlyOneKey),DataValueMapItemSchema=lazyType(()=>objectType({key:stringType(),valueString:stringType().optional(),valueNumber:numberType().optional(),valueBoolean:booleanType().optional(),valueMap:arrayType(DataValueMapItemSchema).optional()}).strict().superRefine((Au,lo)=>{let $u=0;Au.valueString!==void 0&&$u++,Au.valueNumber!==void 0&&$u++,Au.valueBoolean!==void 0&&$u++,Au.valueMap!==void 0&&$u++,$u!==1&&lo.addIssue({code:ZodIssueCode.custom,message:`Value map item must have exactly one value property (valueString, valueNumber, valueBoolean, valueMap), found ${$u}.`})}));function createDataValueSchema(Au={}){const lo=Au.maxDepth??5;return DataValueMapItemSchema.superRefine(($u,Ru)=>{const Iu=(Ou,Pu)=>{if(Pu>lo){Ru.addIssue({code:ZodIssueCode.custom,message:`valueMap recursion exceeded maximum depth of ${lo}.`});return}if(Ou.valueMap&&Array.isArray(Ou.valueMap))for(const Du of Ou.valueMap)Iu(Du,Pu+1)};Iu($u,1)})}const DataValueSchema=createDataValueSchema();objectType({path:stringType().optional(),literalNumber:numberType().optional(),literal:numberType().optional()}).strict().superRefine(exactlyOneKey);objectType({path:stringType().optional(),literalBoolean:booleanType().optional(),literal:booleanType().optional()}).strict().superRefine(exactlyOneKey);const ActionSchema$1=objectType({name:stringType().describe("A unique name identifying the action (e.g., 'submitForm')."),context:arrayType(objectType({key:stringType(),value:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalString:stringType().describe("A fixed, hardcoded string value.").optional(),literalNumber:numberType().optional(),literalBoolean:booleanType().optional()}).describe("The dynamic value. Define EXACTLY ONE of the nested properties.").strict().superRefine(exactlyOneKey)})).describe("A key-value map of data bindings to be resolved when the action is triggered.").optional()});objectType({text:StringValueSchema,usageHint:enumType(["h1","h2","h3","h4","h5","caption","body"]).optional()});objectType({url:StringValueSchema,usageHint:enumType(["icon","avatar","smallFeature","mediumFeature","largeFeature","header"]).optional(),fit:enumType(["contain","cover","fill","none","scale-down"]).optional(),altText:StringValueSchema.optional()});objectType({name:StringValueSchema});objectType({url:StringValueSchema});objectType({url:StringValueSchema,description:StringValueSchema.optional().describe("A label, title, or placeholder text.")});objectType({tabItems:arrayType(objectType({title:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalString:stringType().describe("A fixed, hardcoded string value.").optional()}),child:stringType().describe("A reference to a component instance by its unique ID.")}).strict().superRefine((Au,lo)=>{Au.title||lo.addIssue({code:ZodIssueCode.custom,message:"Tab item is missing 'title'."}),Au.child||lo.addIssue({code:ZodIssueCode.custom,message:"Tab item is missing 'child'."}),Au.title&&exactlyOneKey(Au.title,lo)})).describe("A list of tabs, each with a title and a child component ID.")});objectType({axis:enumType(["horizontal","vertical"]).optional().describe("The orientation."),color:stringType().optional().describe("The color of the divider (e.g., hex code or semantic name)."),thickness:numberType().optional().describe("The thickness of the divider.")});objectType({entryPointChild:stringType().describe("The ID of the component (e.g., a button) that triggers the modal."),contentChild:stringType().describe("The ID of the component to display as the modal's content.")});objectType({child:stringType().describe("The ID of the component to display as the button's content."),action:ActionSchema$1.describe("Represents a user-initiated action."),primary:booleanType().optional().describe("Indicates if this button should be styled as the primary action.")});objectType({label:StringValueSchema,value:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalBoolean:booleanType().optional()}).strict().superRefine(exactlyOneKey)});objectType({text:StringValueSchema.optional(),label:StringValueSchema.describe("A label, title, or placeholder text."),textFieldType:enumType(["shortText","number","date","longText","obscured"]).optional(),validationRegexp:stringType().optional().describe("A regex string to validate the input.")});objectType({value:StringValueSchema,enableDate:booleanType().optional(),enableTime:booleanType().optional(),outputFormat:stringType().optional().describe("The string format for the output (e.g., 'YYYY-MM-DD').")});objectType({selections:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalArray:arrayType(stringType()).optional()}).strict().superRefine(exactlyOneKey),options:arrayType(objectType({label:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalString:stringType().describe("A fixed, hardcoded string value.").optional()}).strict().superRefine(exactlyOneKey),value:stringType()})).optional(),maxAllowedSelections:numberType().optional(),type:enumType(["checkbox","chips"]).optional(),filterable:booleanType().optional()});objectType({value:objectType({path:stringType().describe("A data binding reference to a location in the data model (e.g., '/user/name').").optional(),literalNumber:numberType().optional()}).strict().superRefine(exactlyOneKey),minValue:numberType().optional(),maxValue:numberType().optional(),label:StringValueSchema.optional()});const ComponentArrayTemplateSchema=objectType({componentId:stringType(),dataBinding:stringType()}),ComponentArrayReferenceSchema=objectType({explicitList:arrayType(stringType()).optional(),template:ComponentArrayTemplateSchema.describe("A template for generating a dynamic list of children from a data model list. `componentId` is the component to use as a template, and `dataBinding` is the path to the map of components in the data model. Values in the map will define the list of children.").optional()}).strict().superRefine(exactlyOneKey);objectType({children:ComponentArrayReferenceSchema,distribution:enumType(["start","center","end","spaceBetween","spaceAround","spaceEvenly"]).optional(),alignment:enumType(["start","center","end","stretch"]).optional()});objectType({children:ComponentArrayReferenceSchema,distribution:enumType(["start","center","end","spaceBetween","spaceAround","spaceEvenly"]).optional(),alignment:enumType(["start","center","end","stretch"]).optional()});objectType({children:ComponentArrayReferenceSchema,direction:enumType(["vertical","horizontal"]).optional(),alignment:enumType(["start","center","end","stretch"]).optional()});objectType({child:stringType().describe("The ID of the component to be rendered inside the card.")});const ValueMapSchema=DataValueSchema.describe("A single data entry. Exactly one 'value*' property should be provided alongside the key."),ComponentPropertiesSchema=recordType(anyType()).refine(Au=>Object.keys(Au).length===1,"A wrapper object that MUST contain exactly one key, which is the name of the component type (e.g., 'Heading')."),ComponentInstanceSchema=objectType({id:stringType().describe("The unique identifier for this component."),weight:numberType().optional().describe("The relative weight of this component within a Row or Column. This corresponds to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column."),component:ComponentPropertiesSchema.describe("A wrapper object that MUST contain exactly one key, which is the name of the component type (e.g., 'Heading'). The value is an object containing the properties for that specific component.")}).strict().describe("Represents a *single* component in a UI widget tree. This component could be one of many supported types."),BeginRenderingMessageSchema=objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be rendered."),catalogId:stringType().optional().describe("The identifier of the component catalog to use for this surface. If omitted, the client MUST default to the standard catalog for this A2UI version (https://a2ui.org/specification/v0_8/standard_catalog_definition.json)."),root:stringType().describe("The ID of the root component to render."),styles:objectType({font:stringType().optional().describe("The primary font for the UI."),primaryColor:stringType().regex(/^#[0-9a-fA-F]{6}$/).optional().describe("The primary UI color as a hexadecimal code (e.g., '#00BFFF').")}).strict().optional().describe("Styling information for the UI.")}).strict().describe("Signals the client to begin rendering a surface with a root component and specific styles."),SurfaceUpdateMessageSchema=objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be updated. If you are adding a new surface this *must* be a new, unique identified that has never been used for any existing surfaces shown."),components:arrayType(ComponentInstanceSchema).min(1).describe("A list containing all UI components for the surface.")}).strict().superRefine((Au,lo)=>{const $u=new Set;for(const Iu of Au.components)Iu.id&&($u.has(Iu.id)&&lo.addIssue({code:ZodIssueCode.custom,message:`Duplicate component ID found: ${Iu.id}`,path:["components"]}),$u.add(Iu.id));const Ru=(Iu,Ou)=>{for(const Pu of Iu)Pu&&!$u.has(Pu)&&lo.addIssue({code:ZodIssueCode.custom,message:`Component '${Ou}' references non-existent component ID '${Pu}'.`,path:["components"]})};for(const Iu of Au.components){if(!Iu.id||!Iu.component)continue;const Ou=Object.keys(Iu.component);if(Ou.length!==1)continue;const Pu=Ou[0],Du=Iu.component[Pu];switch(Pu){case"Row":case"Column":case"List":if(Du.children&&!Array.isArray(Du.children)){const Lu=!!Du.children.explicitList,ju=!!Du.children.template;(Lu&&ju||!Lu&&!ju)&&lo.addIssue({code:ZodIssueCode.custom,message:`Component '${Iu.id}' must have either 'explicitList' or 'template' in children, but not both or neither.`}),Lu&&Ru(Du.children.explicitList,Iu.id),ju&&Ru([Du.children.template?.componentId],Iu.id)}break;case"Card":Du.child&&Ru([Du.child],Iu.id);break;case"Tabs":Du.tabItems&&Array.isArray(Du.tabItems)&&Du.tabItems.forEach(Lu=>{Lu.child&&Ru([Lu.child],Iu.id)});break;case"Modal":Ru([Du.entryPointChild,Du.contentChild],Iu.id);break;case"Button":Du.child&&Ru([Du.child],Iu.id);break}}}).describe("Updates a surface with a new set of components."),DataModelUpdateMessageSchema=objectType({surfaceId:stringType().describe("The unique identifier for the UI surface this data model update applies to."),path:stringType().optional().describe("An optional path to a location within the data model (e.g., '/user/name'). If omitted, or set to '/', the entire data model will be replaced."),contents:arrayType(ValueMapSchema).describe("An array of data entries. Each entry must contain a 'key' and exactly one corresponding typed 'value*' property.")}).strict().describe("Updates the data model for a surface."),DeleteSurfaceMessageSchema$2=objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be deleted.")}).strict().describe("Signals the client to delete the surface identified by 'surfaceId'."),A2uiMessageSchema$1=objectType({beginRendering:BeginRenderingMessageSchema.optional(),surfaceUpdate:SurfaceUpdateMessageSchema.optional(),dataModelUpdate:DataModelUpdateMessageSchema.optional(),deleteSurface:DeleteSurfaceMessageSchema$2.optional()}).strict().superRefine((Au,lo)=>{Object.keys(Au).filter(Ru=>["beginRendering","surfaceUpdate","dataModelUpdate","deleteSurface"].includes(Ru)).length!==1&&lo.addIssue({code:ZodIssueCode.custom,message:"A2UI Protocol message must have exactly one of: surfaceUpdate, dataModelUpdate, beginRendering, deleteSurface."})}).describe("Describes a JSON payload for an A2UI (Agent to UI) message, which is used to dynamically construct and update user interfaces. A message MUST contain exactly ONE of the action properties: 'beginRendering', 'surfaceUpdate', 'dataModelUpdate', or 'deleteSurface'.");function normalizeV08Component(Au){if(!Au||typeof Au!="object")return{id:"",component:""};const lo=Au;let $u=typeof lo.component=="string"?lo.component:"";const Ru={};for(const[Iu,Ou]of Object.entries(lo))Iu!=="component"&&Iu!=="id"&&(Ru[Iu]=Ou);if(lo.component&&typeof lo.component=="object"){const Iu=lo.component,Ou=Object.keys(Iu);if(Ou.length>0){$u=Ou[0];const Pu=Iu[Ou[0]];Pu&&typeof Pu=="object"&&Pu!==null&&!Array.isArray(Pu)&&Object.assign(Ru,Pu)}}return{...Ru,id:String(lo.id??""),component:$u}}class V0Point8Adapter extends BaseVersionAdapter{constructor(){super(...arguments),this.version="v0.8",this.schema=A2uiMessageSchema$1}getNativeActionKeys(){return["beginRendering","surfaceUpdate","dataModelUpdate","deleteSurface"]}preparePayloadForValidation(lo){const $u={...lo};return delete $u.version,$u}extractOperationsFromObject(lo){const $u=[];if("beginRendering"in lo){const Ru=lo.beginRendering;$u.push({type:"createSurface",surfaceId:String(Ru?.surfaceId??""),catalogId:typeof Ru?.catalogId=="string"?Ru.catalogId:void 0,theme:Ru?.theme??Ru?.styles,sendDataModel:!!Ru?.sendDataModel,components:Array.isArray(Ru?.components)?Ru.components.map(normalizeV08Component):void 0,dataModel:Ru?.dataModel&&typeof Ru.dataModel=="object"&&!Array.isArray(Ru.dataModel)?Ru.dataModel:void 0,version:typeof lo.version=="string"?lo.version:this.version,rootId:typeof Ru?.root=="string"&&Ru.root?Ru.root:void 0})}if("surfaceUpdate"in lo){const Ru=lo.surfaceUpdate;$u.push({type:"updateComponents",surfaceId:String(Ru?.surfaceId??""),components:Array.isArray(Ru?.components)?Ru.components.map(normalizeV08Component):[]})}if("dataModelUpdate"in lo){const Ru=lo.dataModelUpdate,Iu=String(Ru?.surfaceId??"");if(Array.isArray(Ru?.contents)){for(const Ou of Ru.contents)if(Ou&&typeof Ou=="object"&&typeof Ou.key=="string"){const Pu="valueNumber"in Ou?Ou.valueNumber:"valueString"in Ou?Ou.valueString:"valueBoolean"in Ou?Ou.valueBoolean:"valueObject"in Ou?Ou.valueObject:"valueArray"in Ou?Ou.valueArray:Ou.value;$u.push({type:"updateDataModel",surfaceId:Iu,path:Ou.key,value:Pu})}}else $u.push({type:"updateDataModel",surfaceId:Iu,path:typeof Ru?.path=="string"?Ru.path:void 0,value:Ru?.value})}if("deleteSurface"in lo){const Ru=lo.deleteSurface;$u.push({type:"deleteSurface",surfaceId:String(Ru?.surfaceId??"")})}return $u}}const CreateSurfaceMessageSchema$1=objectType({version:enumType(["v0.9","v0.9.1"]),createSurface:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be rendered."),catalogId:stringType().describe("A string that uniquely identifies this catalog. It is recommended to prefix this with an internet domain that you own, to avoid conflicts e.g. mycompany.com:somecatalog'."),theme:anyType().optional(),sendDataModel:booleanType().describe("If true, the client will send the full data model of this surface in the metadata of every A2A message sent to the server that created the surface. Defaults to false.").optional()}).strict().describe("Signals the client to create a new surface and begin rendering it. It is an error to send 'createSurface' for a surfaceId that already exists without first deleting it. When this message is sent, the client will expect 'updateComponents' and/or 'updateDataModel' messages for the same surfaceId that define the component tree.")}).strict(),UpdateComponentsMessageSchema$1=objectType({version:enumType(["v0.9","v0.9.1"]),updateComponents:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be updated."),components:arrayType(recordType(stringType(),anyType())).min(1).describe("A list containing all UI components for the surface.")}).strict().describe("Updates a surface with a new set of components. This message can be sent multiple times to update the component tree of an existing surface. One of the components in one of the components lists MUST have an 'id' of 'root' to serve as the root of the component tree. A createSurface message MUST have been previously sent for the 'surfaceId' in this message; the surface's catalog is the one specified by that createSurface.")}).strict(),UpdateDataModelMessageSchema$1=objectType({version:enumType(["v0.9","v0.9.1"]),updateDataModel:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface this data model update applies to."),path:stringType().describe("An optional path to a location within the data model (e.g., '/user/name'). If omitted, or set to '/', refers to the entire data model.").optional(),value:anyType().describe("The data to be updated in the data model. If present, the value at 'path' is replaced (or created). If omitted, the key at 'path' is removed.").optional()}).strict().describe("Updates the data model for an existing surface. This message can be sent multiple times to update the data model. A createSurface message MUST have been previously sent for the 'surfaceId' in this message; the surface's catalog is the one specified by that createSurface.")}).strict(),DeleteSurfaceMessageSchema$1=objectType({version:enumType(["v0.9","v0.9.1"]),deleteSurface:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be deleted.")}).strict().describe("Signals the client to delete the surface identified by 'surfaceId'. A createSurface message MUST have been previously sent for the 'surfaceId' in this message; the surface's catalog is the one specified by that createSurface.")}).strict(),A2uiMessageSchema=unionType([CreateSurfaceMessageSchema$1,UpdateComponentsMessageSchema$1,UpdateDataModelMessageSchema$1,DeleteSurfaceMessageSchema$1]),A2uiMessageListSchema=arrayType(A2uiMessageSchema).describe("A list of messages.");objectType({messages:A2uiMessageListSchema}).strict().describe("An object wrapping a list of messages.");class V0Point9Adapter extends BaseVersionAdapter{constructor(){super(...arguments),this.version="v0.9",this.schema=A2uiMessageSchema}get compatibleCatalogVersions(){return new Set(["0.9","0.9.1"])}getNativeActionKeys(){return["createSurface","updateComponents","updateDataModel","deleteSurface"]}extractOperationsFromObject(lo){const $u=[];if("createSurface"in lo){const Ru=lo.createSurface;$u.push({type:"createSurface",surfaceId:String(Ru?.surfaceId||""),catalogId:typeof Ru?.catalogId=="string"?Ru.catalogId:void 0,theme:Ru?.theme,sendDataModel:!!Ru?.sendDataModel,components:Array.isArray(Ru?.components)?Ru.components:void 0,dataModel:Ru?.dataModel&&typeof Ru.dataModel=="object"&&!Array.isArray(Ru.dataModel)?Ru.dataModel:void 0,version:typeof lo.version=="string"?lo.version:this.version})}if("updateComponents"in lo){const Ru=lo.updateComponents;$u.push({type:"updateComponents",surfaceId:String(Ru?.surfaceId||""),components:Array.isArray(Ru?.components)?Ru.components:[]})}if("updateDataModel"in lo){const Ru=lo.updateDataModel;$u.push({type:"updateDataModel",surfaceId:String(Ru?.surfaceId||""),path:typeof Ru?.path=="string"?Ru.path:void 0,value:Ru?.value})}if("deleteSurface"in lo){const Ru=lo.deleteSurface;$u.push({type:"deleteSurface",surfaceId:String(Ru?.surfaceId||"")})}return $u}}const INTERNAL_OPERATION_TYPES=["createSurface","updateComponents","updateDataModel","deleteSurface","callRendererFunction","agentFunctionResponse"];function isInternalOperation(Au){return typeof Au=="object"&&Au!==null&&"type"in Au&&typeof Au.type=="string"&&INTERNAL_OPERATION_TYPES.includes(Au.type)}objectType({componentId:lazyType(()=>ComponentIdSchema$1),path:stringType().describe("The path to the list of component property objects in the data model.")}).strict().describe("REF:#/$defs/TemplateChildList|A template for generating a dynamic list of children from a data model list. The `componentId` is the component to use as a template.");const AnyComponentSchema=lazyType(()=>ComponentCommonSchema.extend({component:stringType()}).passthrough().refine(Au=>Au.component!=="Surface",{message:'Component type cannot be "Surface". "Surface" is a top-level protocol container defined in createSurface, not a child component.'})),ComponentsListSchema=arrayType(AnyComponentSchema).min(1);recordType(stringType(),anyType());const ComponentIdSchema$1=markChildRef(stringType().describe("REF:#/$defs/ComponentId|The unique identifier for a component, used for both definitions and references within the same surface."),"component-id"),CallIdSchema=stringType().describe("REF:#/$defs/CallId|The unique identifier for a function call."),DataBindingSchema$1=objectType({path:stringType().describe("A JSON Pointer path to a value in the data model.")}).strict().describe("REF:#/$defs/DataBinding"),FunctionCommonSchema=objectType({call:stringType().describe("The name of the function to call."),catalogId:stringType().describe("The catalog ID for this function, overriding any surface-level default catalogId.").optional()}).describe("REF:#/$defs/FunctionCommon|Baseline envelope properties common to all function calls. Function-specific argument schemas ('args') are defined individually by each function in the active catalog."),FunctionCallSchema$1=recordType(stringType(),anyType()).and(intersectionType(FunctionCommonSchema,anyType())).describe("REF:#/$defs/FunctionCall|Invokes a named function, combining common function properties with the catalog function definition."),DynamicStringSchema$1=unionType([stringType(),DataBindingSchema$1,FunctionCallSchema$1]).describe("REF:#/$defs/DynamicString|Represents a string"),DynamicBooleanSchema$1=unionType([booleanType(),DataBindingSchema$1,FunctionCallSchema$1]).describe("REF:#/$defs/DynamicBoolean|A boolean value that can be a literal, a path, or a function call returning a boolean."),AccessibilityAttributesSchema$1=objectType({label:DynamicStringSchema$1.optional(),description:DynamicStringSchema$1.optional(),live:enumType(["off","polite","assertive"]).describe("Controls screen reader announcements for dynamic updates (WAI-ARIA aria-live). 'polite' waits for user pause; 'assertive' interrupts immediately for alerts.").default("off"),hidden:DynamicBooleanSchema$1.optional()}).strict().describe("REF:#/$defs/AccessibilityAttributes|Attributes to enhance accessibility when using assistive technologies like screen readers or model understanding."),ExtensionsSchema=recordType(stringType(),unknownType()).superRefine((Au,lo)=>{for(const $u in Au)$u.match(/^[\p{XID_Start}_][\p{XID_Continue}:-]*$/u)||lo.addIssue({path:[$u],code:ZodIssueCode.custom,message:`Invalid extension key "${$u}": Keys MUST be Unicode identifiers (UAX #31).`})}).describe("REF:#/$defs/Extensions|Optional extension metadata. Keys MUST be Unicode identifiers (UAX #31). Keys starting with 'a2ui_' are reserved for official extensions."),ComponentCommonSchema=objectType({id:ComponentIdSchema$1,catalogId:stringType().describe("The catalog ID for this component, overriding any surface-level default catalogId.").optional(),accessibility:AccessibilityAttributesSchema$1.optional(),metadata:objectType({extensions:ExtensionsSchema.optional()}).strict().describe("Optional component-level metadata for vendor extensions.").optional()}).describe("REF:#/$defs/ComponentCommon");markChildRef(unionType([arrayType(ComponentIdSchema$1).describe("A static list of child component IDs."),objectType({componentId:ComponentIdSchema$1,path:stringType().describe("The path to the list of component property objects in the data model.")}).strict().describe("A template for generating a dynamic list of children from a data model list. The `componentId` is the component to use as a template.")]).describe("REF:#/$defs/ChildList"),"child-list");const DynamicValueSchema$1=unionType([stringType(),numberType(),booleanType(),arrayType(anyType()),recordType(stringType(),unknownType()).refine(Au=>!Au||!("path"in Au)&&!("call"in Au)),DataBindingSchema$1,FunctionCallSchema$1]).describe("REF:#/$defs/DynamicValue|A value that can be a literal, a path, or a function call returning any type."),DynamicNumberSchema$1=unionType([numberType(),DataBindingSchema$1,FunctionCallSchema$1]).describe("REF:#/$defs/DynamicNumber|Represents a value that can be either a literal number, a path to a number in the data model, or a function call returning a number.");unionType([arrayType(stringType()),DataBindingSchema$1,FunctionCallSchema$1]).describe("REF:#/$defs/DynamicStringList|Represents a value that can be either a literal array of strings, a path to a string array in the data model, or a function call returning a string array.");objectType({call:literalType("@index"),args:objectType({offset:DynamicNumberSchema$1.optional()}).optional()}).describe("REF:#/$defs/IndexSystemFunction|Returns the 0-based index of the current item when rendering a dynamic list from a template. This function MUST ONLY be available when evaluating template items within a list context.");const CheckRuleSchema$1=objectType({condition:unionType([DataBindingSchema$1,FunctionCallSchema$1]).describe("Path or function call evaluating to a structured validation result object."),message:stringType().describe("Optional fallback error message.").optional()}).strict().describe("REF:#/$defs/CheckRule|A single validation check rule applied to an input component. The condition function or path evaluates to a structured validation result object.");objectType({checks:arrayType(CheckRuleSchema$1).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional()}).describe("REF:#/$defs/Checkable|Properties for components that support renderer-side checks.");unionType([objectType({event:objectType({name:stringType().describe("The name of the action to be dispatched to the agent."),userMessage:DynamicStringSchema$1.optional(),context:recordType(stringType(),DynamicValueSchema$1).describe("A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.").optional()}).strict().describe("The event to dispatch to the agent.")}).strict().describe("Triggers an agent-side event."),objectType({functionCall:FunctionCallSchema$1}).strict().describe("Executes a renderer or agent-side function.")]).describe("REF:#/$defs/Action|Defines an interaction handler that can either trigger an agent-side event or execute a local renderer-side function.");objectType({component:literalType("Surface").optional(),child:literalType("root").optional()}).strict().describe("REF:#/$defs/Surface|The reserved canonical container component representing an A2UI surface. The Surface component is immutable and always has 'child': 'root'.");const FunctionResponseSchema=objectType({functionCallId:CallIdSchema,value:anyType().describe("The return value of the function.").optional(),error:objectType({code:stringType(),message:stringType()}).strict().describe("An error object indicating failure of the function execution.").optional()}).strict().superRefine((Au,lo)=>{const $u="value"in Au,Ru="error"in Au;($u&&Ru||!$u&&!Ru)&&lo.addIssue({code:ZodIssueCode.custom,message:'FunctionResponse must have either "value" or "error", but not both or neither.'})}).describe("REF:#/$defs/FunctionResponse|The return response matching a callAgentFunction or callRendererFunction invocation."),CreateSurfaceMessageSchema=objectType({version:literalType("v1.0"),createSurface:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be rendered. It must be globally unique for the renderer's lifetime."),catalogId:stringType().describe("A string that uniquely identifies the default catalog for this surface. It is recommended to prefix this with an internet domain that you own, to avoid conflicts e.g. 'mycompany.com:somecatalog'. Components and function calls that do not explicitly specify a catalogId will use this surface-level default catalogId.").optional(),sendDataModel:booleanType().describe("If true, the renderer will send the full data model of this surface in the metadata of every A2A message sent to the agent that created the surface. Defaults to false.").optional(),components:ComponentsListSchema.optional(),dataModel:recordType(stringType(),anyType()).describe("The initial root data model object for the surface.").optional(),metadata:objectType({extensions:ExtensionsSchema.optional()}).strict().describe("Optional surface-level metadata.").optional()}).strict().describe("Signals the renderer to create a new surface and begin rendering it. Creating a surface implicitly instantiates the canonical 'Surface' container component ('common_types.json#/$defs/Surface') with 'child': 'root'. It is an error to try to create a surface with an existing ID without first deleting it; surfaceId MUST be globally unique for the renderer's lifetime. When this message is sent, the renderer expects 'updateComponents' and/or 'updateDataModel' messages for the same surfaceId to define the component tree.")}).strict(),UpdateComponentsMessageSchema=objectType({version:literalType("v1.0"),updateComponents:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be updated. It must be globally unique for the renderer's lifetime."),components:ComponentsListSchema}).strict().describe("Updates a surface with a new set of components. This message can be sent multiple times to update the component tree of an existing surface. One of the components in one of the components lists MUST have an 'id' of 'root' to serve as the root of the component tree. The createSurface message MUST have been previously sent for this surfaceId.")}).strict(),UpdateDataModelMessageSchema=objectType({version:literalType("v1.0"),updateDataModel:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface this data model update applies to. It must be globally unique for the renderer's lifetime."),path:stringType().describe("An optional path to a location within the data model (e.g., '/user/name'). If omitted, or set to '/', refers to the entire data model.").optional(),value:anyType().describe("The data to be updated in the data model. To delete the key/value at 'path', set 'value' explicitly to null.")}).strict().describe("Updates the data model for an existing surface. This message can be sent multiple times to update the data model. The createSurface message MUST have been previously sent for this surfaceId.")}).strict(),DeleteSurfaceMessageSchema=objectType({version:literalType("v1.0"),deleteSurface:objectType({surfaceId:stringType().describe("The unique identifier for the UI surface to be deleted. It must be globally unique for the renderer's lifetime.")}).strict().describe("Signals the renderer to delete the surface identified by 'surfaceId'. The createSurface message MUST have been previously sent for this surfaceId.")}).strict(),CallRendererFunctionMessageSchema=objectType({version:literalType("v1.0"),callRendererFunction:objectType({functionCallId:CallIdSchema,callFunction:intersectionType(FunctionCallSchema$1,anyType())}).strict().describe("Signals the renderer to execute a function locally on behalf of the agent.")}).strict(),AgentFunctionResponseMessageSchema=objectType({version:literalType("v1.0"),agentFunctionResponse:FunctionResponseSchema}).strict(),AgentToRendererMessageSchema=unionType([CreateSurfaceMessageSchema,UpdateComponentsMessageSchema,UpdateDataModelMessageSchema,DeleteSurfaceMessageSchema,CallRendererFunctionMessageSchema,AgentFunctionResponseMessageSchema]);class V1Point0Adapter extends BaseVersionAdapter{constructor(){super(...arguments),this.version="v1.0",this.schema=AgentToRendererMessageSchema}getNativeActionKeys(){return[...INTERNAL_OPERATION_TYPES]}extractOperationsFromObject(lo){const $u=[];if("createSurface"in lo){const Ru=lo.createSurface;$u.push({type:"createSurface",surfaceId:String(Ru?.surfaceId||""),catalogId:typeof Ru?.catalogId=="string"?Ru.catalogId:void 0,sendDataModel:!!Ru?.sendDataModel,components:Array.isArray(Ru?.components)?Ru.components:void 0,dataModel:Ru?.dataModel&&typeof Ru.dataModel=="object"&&!Array.isArray(Ru.dataModel)?Ru.dataModel:void 0,version:typeof lo.version=="string"?lo.version:this.version})}if("updateComponents"in lo){const Ru=lo.updateComponents;$u.push({type:"updateComponents",surfaceId:String(Ru?.surfaceId||""),components:Array.isArray(Ru?.components)?Ru.components:[]})}if("updateDataModel"in lo){const Ru=lo.updateDataModel;$u.push({type:"updateDataModel",surfaceId:String(Ru?.surfaceId||""),path:typeof Ru?.path=="string"?Ru.path:void 0,value:Ru?.value})}if("deleteSurface"in lo){const Ru=lo.deleteSurface;$u.push({type:"deleteSurface",surfaceId:String(Ru?.surfaceId||"")})}if("callRendererFunction"in lo){const Ru=lo.callRendererFunction,Iu=Ru?.callFunction||{};$u.push({type:"callRendererFunction",functionCallId:String(Ru?.functionCallId||""),call:String(Iu?.call||""),version:this.version,catalogId:typeof Iu?.catalogId=="string"?Iu.catalogId:void 0,args:Iu?.args&&typeof Iu.args=="object"&&!Array.isArray(Iu.args)?Iu.args:{}})}if("agentFunctionResponse"in lo){const Ru=lo.agentFunctionResponse;$u.push({type:"agentFunctionResponse",functionCallId:String(Ru?.functionCallId||""),version:this.version,value:Ru?.value,error:Ru?.error&&typeof Ru.error=="object"?Ru.error:void 0})}return $u}}class VersionAdapterFactory{constructor(){this.adapters=new Map([["0.8",new V0Point8Adapter],["0.9",new V0Point9Adapter],["0.9.1",new V0Point9Adapter],["1.0",new V1Point0Adapter]])}getAllKnownActions(){const lo=new Set;for(const $u of this.adapters.values())if($u.validActions)for(const Ru of $u.validActions)lo.add(Ru);return lo}registerAdapter(lo){const $u=toCanonicalVersion(lo.version)??normalizeVersionString(lo.version);this.adapters.set($u,lo)}getAdapter(lo){const $u=toCanonicalVersion(lo)??normalizeVersionString(lo),Ru=this.adapters.get($u);if(!Ru){const Iu=Array.from(new Set(Array.from(this.adapters.keys()).map(Ou=>Ou.startsWith("v")?Ou:`v${Ou}`))).sort().join(", ");throw new A2uiValidationError(`[VersionAdapterFactory] Unsupported protocol version '${lo}'. Supported versions: ${Iu}.`)}return Ru}resolveFromPayload(lo){const $u=Array.isArray(lo)?lo[0]:lo;if(typeof $u=="object"&&$u!==null){if("messages"in $u&&Array.isArray($u.messages))return this.resolveFromPayload($u.messages);if("version"in $u){const Ru=$u.version;if(typeof Ru!="string")throw new A2uiValidationError(`[VersionAdapterFactory] Message payload is missing a valid 'version' string: 'version' property must be a string, got ${typeof Ru}.`);return this.getAdapter(Ru)}if("beginRendering"in $u||"surfaceUpdate"in $u||"dataModelUpdate"in $u||"deleteSurface"in $u)return this.getAdapter("v0.8")}throw new A2uiValidationError("[VersionAdapterFactory] Message payload is missing a valid 'version' string.")}static registerAdapter(lo){defaultVersionAdapterFactory.registerAdapter(lo)}static getAdapter(lo){return defaultVersionAdapterFactory.getAdapter(lo)}static resolveFromPayload(lo){return defaultVersionAdapterFactory.resolveFromPayload(lo)}static getAllKnownActions(){return defaultVersionAdapterFactory.getAllKnownActions()}}const defaultVersionAdapterFactory=new VersionAdapterFactory;registerKnownActionsProvider(()=>defaultVersionAdapterFactory.getAllKnownActions());const schemaKeysCache=new WeakMap;function getKnownSchemaKeys(Au){if(schemaKeysCache.has(Au))return schemaKeysCache.get(Au);const lo=(()=>{let $u=Au;for(;$u;){if($u instanceof ZodObject||$u._def?.typeName==="ZodObject"){if($u._def?.unknownKeys==="passthrough")return null;const Ru=typeof $u.shape=="function"?$u.shape():$u.shape;return Ru&&typeof Ru=="object"?new Set(Object.keys(Ru)):null}if($u instanceof ZodEffects||$u._def?.typeName==="ZodEffects"){$u=$u._def.schema;continue}if($u instanceof ZodOptional||$u instanceof ZodNullable||$u._def?.typeName==="ZodOptional"||$u._def?.typeName==="ZodNullable"){$u=$u._def.innerType;continue}if($u instanceof ZodDefault||$u._def?.typeName==="ZodDefault"){$u=$u._def.innerType;continue}if($u instanceof ZodCatch||$u._def?.typeName==="ZodCatch"){$u=$u._def.innerType;continue}if($u instanceof ZodIntersection||$u._def?.typeName==="ZodIntersection"){const Ru=getKnownSchemaKeys($u._def.left),Iu=getKnownSchemaKeys($u._def.right);return!Ru||!Iu?null:new Set([...Ru,...Iu])}if($u instanceof ZodUnion||$u._def?.typeName==="ZodUnion"){const Ru=$u._def.options,Iu=new Set;for(const Ou of Ru){const Pu=getKnownSchemaKeys(Ou);if(!Pu)return null;for(const Du of Pu)Iu.add(Du)}return Iu}return null}return null})();return schemaKeysCache.set(Au,lo),lo}function validateFunctionArgs(Au,lo,$u){if(!lo||typeof lo!="object"||Array.isArray(lo))return;const Ru=Object.keys(lo);if(Ru.length>MAX_FUNCTION_CALL_ARGS)throw new A2uiExpressionError(`Function call '${Au}' exceeds maximum allowed arguments count (${MAX_FUNCTION_CALL_ARGS})`,Au);const Iu=$u?.functions?.get?.(Au);if(!Iu?.schema)return;const Ou=getKnownSchemaKeys(Iu.schema);if(Ou){for(const Pu of Ru)if(!Ou.has(Pu))throw new A2uiExpressionError(`Unknown argument '${Pu}' passed to function '${Au}'`,Au);if(Ru.length>Ou.size)throw new A2uiExpressionError(`Too many arguments for function '${Au}': expected at most ${Ou.size}, received ${Ru.length}`,Au)}}function resolveContextIndex(Au){let lo=Au;for(;lo;){if(lo.explicitIndex!==void 0&&Number.isFinite(lo.explicitIndex))return lo.explicitIndex;if(!(lo instanceof DataContext)&&typeof lo.getIndex=="function"){const $u=lo.getIndex();if($u!==void 0&&Number.isFinite($u))return $u}if(!(lo instanceof DataContext)&&typeof lo.index=="number"&&Number.isFinite(lo.index))return lo.index;if(typeof lo.path=="string"){const $u=lo.path.split("/").filter(Boolean);if($u.length>0&&/^\d+$/.test($u[$u.length-1]))return parseInt($u[$u.length-1],10)}lo=lo.parent}}const MAX_DYNAMIC_VALUE_DEPTH=1e3;class DataContext{constructor(lo,$u,Ru,Iu){this.surface=lo,this.path=$u,this.dataModel=lo.dataModel,this.functionInvoker=lo.defaultCatalog.invoker,this.explicitIndex=Ru,this.parent=Iu,this.warnedPaths=Iu?Iu.warnedPaths:new Set}getIndex(){return resolveContextIndex(this)}get index(){return this.getIndex()}set(lo,$u){const Ru=this.resolvePath(lo);this.dataModel.set(Ru,$u)}static isDataBindingObject(lo){return"path"in lo&&typeof lo.path=="string"&&!("componentId"in lo)}static isFunctionCallObject(lo){return"call"in lo&&typeof lo.call=="string"}static containsDynamicValue(lo){if(lo===null||typeof lo!="object")return!1;if(Array.isArray(lo))return lo.some(Ru=>DataContext.containsDynamicValue(Ru));const $u=lo;return DataContext.isDataBindingObject($u)||DataContext.isFunctionCallObject($u)?!0:Object.values($u).some(Ru=>DataContext.containsDynamicValue(Ru))}emitMissingDataBindingWarning(lo){typeof this.dataModel?.hasPath=="function"&&!this.dataModel.hasPath(lo)&&!this.warnedPaths.has(lo)&&(this.warnedPaths.add(lo),this.surface?.dispatchWarning?.({code:"MISSING_DATA_BINDING",path:lo,message:`Preflight DataBinding Warning: The bound JSON Pointer '${lo}' does not physically exist in the active DataModel. Evaluating to None.`}))}resolveDynamicValue(lo,$u=0){if($u>MAX_DYNAMIC_VALUE_DEPTH){const Iu=new A2uiExpressionError(`Maximum dynamic value nesting depth exceeded (${MAX_DYNAMIC_VALUE_DEPTH})`);this.dispatchExpressionError(Iu,"DynamicValue");return}if(lo===null||typeof lo!="object")return lo;if(Array.isArray(lo))return DataContext.containsDynamicValue(lo)?lo.map(Iu=>this.resolveDynamicValue(Iu,$u+1)):lo;const Ru=lo;if(DataContext.isDataBindingObject(Ru)){const Iu=this.resolvePath(lo.path),Ou=this.dataModel.get(Iu);return Ou===void 0&&this.emitMissingDataBindingWarning(Iu),Ou}return DataContext.isFunctionCallObject(Ru)?this.resolveFunctionCallValue(lo,$u):this.resolvePlainObjectValue(Ru,$u)}resolveFunctionCallValue(lo,$u=0){let Ru;try{Ru=this.resolveFunctionCatalog(lo.catalogId),validateFunctionArgs(lo.call,lo.args,Ru)}catch(Du){this.dispatchExpressionError(Du,lo.call);return}const Iu={};for(const[Du,Lu]of Object.entries(lo.args??{}))Iu[Du]=this.resolveDynamicValue(Lu,$u+1);const Ou=new AbortController,Pu=this.evaluateFunctionReactive(lo.call,Iu,Ou.signal,lo.catalogId,Ru.invoker);if(Pu!==void 0)return isSignal(Pu)?peekValue(Pu):Pu}resolvePlainObjectValue(lo,$u=0){if(!DataContext.containsDynamicValue(lo))return lo;const Ru={};for(const[Iu,Ou]of Object.entries(lo))Ru[Iu]=this.resolveDynamicValue(Ou,$u+1);return Ru}subscribeDynamicValue(lo,$u){const Ru=this.resolveSignal(lo);let Iu=!0,Ou=peekValue(Ru);const Pu=effect(()=>{const Du=getValue(Ru);Ou=Du,Iu||$u(Du)});return Iu=!1,{get value(){return Ou},unsubscribe:()=>{Pu(),Ru.unsubscribe?.()}}}resolveSignal(lo,$u=0){if($u>MAX_DYNAMIC_VALUE_DEPTH){const Du=new A2uiExpressionError(`Maximum dynamic value nesting depth exceeded (${MAX_DYNAMIC_VALUE_DEPTH})`);return this.dispatchExpressionError(Du,typeof lo=="object"&&lo&&"call"in lo?lo.call:"DynamicValue"),signal(void 0)}if(typeof lo!="object"||lo===null)return signal(lo);if(Array.isArray(lo)){if(!DataContext.containsDynamicValue(lo))return signal(lo);const Du=lo.map(ju=>this.resolveSignal(ju,$u+1)),Lu=computed(()=>Du.map(ju=>getValue(ju)));return Lu.unsubscribe=()=>{for(const ju of Du)ju.unsubscribe?.()},Lu}const Ru=lo;if(DataContext.isDataBindingObject(Ru)){const Du=this.resolvePath(lo.path);return this.emitMissingDataBindingWarning(Du),this.dataModel.getSignal(Du)}if(DataContext.isFunctionCallObject(Ru)){const Du=lo;let Lu;try{Lu=this.resolveFunctionCatalog(Du.catalogId),validateFunctionArgs(Du.call,Du.args,Lu)}catch(Vu){return this.dispatchExpressionError(Vu,Du.call),signal(void 0)}const ju={};for(const[Vu,Gu]of Object.entries(Du.args??{}))ju[Vu]=this.resolveSignal(Gu,$u+1);if(Object.keys(ju).length===0){const Vu=new AbortController,Gu=this.evaluateFunctionReactive(Du.call,{},Vu.signal,Du.catalogId,Lu.invoker),Ku=isSignal(Gu)?Gu:signal(Gu);return Ku.unsubscribe=()=>Vu.abort(),Ku}const Bu=Object.keys(ju),Fu=signal(void 0);let zu,qu;const Uu=computed(()=>{const Vu={};for(let Gu=0;Gu<Bu.length;Gu++)Vu[Bu[Gu]]=getValue(ju[Bu[Gu]]);return Vu}),Hu=effect(()=>{try{const Vu=getValue(Uu);zu&&zu.abort(),qu&&(qu(),qu=void 0),zu=new AbortController;const Gu=this.evaluateFunctionReactive(Du.call,Vu,zu.signal,Du.catalogId,Lu.invoker);isSignal(Gu)?qu=effect(()=>{setValue(Fu,getValue(Gu))}):setValue(Fu,Gu)}catch(Vu){this.dispatchExpressionError(Vu,Du.call),setValue(Fu,void 0)}});return Fu.unsubscribe=()=>{Hu(),qu&&qu(),zu&&zu.abort();for(let Vu=0;Vu<Bu.length;Vu++)ju[Bu[Vu]].unsubscribe?.()},Fu}if(!DataContext.containsDynamicValue(Ru))return signal(lo);const Iu=Object.entries(Ru).map(([Du,Lu])=>[Du,this.resolveSignal(Lu)]),Ou=computed(()=>{const Du={};for(const[Lu,ju]of Iu)Du[Lu]=getValue(ju);return Du}),Pu=Ou.unsubscribe?.bind(Ou);return Ou.unsubscribe=()=>{Pu?.();for(const[,Du]of Iu)Du.unsubscribe?.()},Ou}resolveAction(lo){if("event"in lo){const $u={};if(lo.event.context)for(const[Ru,Iu]of Object.entries(lo.event.context))$u[Ru]=this.resolveDynamicValue(Iu);return{event:{...lo.event,context:$u}}}return"functionCall"in lo?this.resolveDynamicValue(lo.functionCall):lo}resolveFunctionCatalog(lo){if(lo===void 0)return this.surface.defaultCatalog;const $u=this.surface.availableCatalogs?.get(lo);if(!$u)throw new A2uiCatalogError(`Catalog not found: ${lo}`);return $u}evaluateFunctionReactive(lo,$u,Ru,Iu,Ou){const Pu=Ou??(Iu===void 0?this.functionInvoker:this.resolveFunctionCatalog(Iu).invoker);try{return Pu(lo,$u,this,Ru)}catch(Du){this.dispatchExpressionError(Du,lo);return}}dispatchExpressionError(lo,$u){if(lo instanceof ZodError||typeof lo=="object"&&lo!==null&&lo.name==="ZodError"){const Ru=lo,Iu=new A2uiExpressionError(`Validation failed for function '${$u}': ${Ru.message}`,$u,Ru.errors??Ru.issues);this.surface.dispatchError({code:"EXPRESSION_ERROR",message:Iu.message,expression:$u,details:Iu.details})}else if(lo instanceof A2uiExpressionError)this.surface.dispatchError({code:"EXPRESSION_ERROR",message:lo.message,expression:lo.expression,details:lo.details});else{const Ru=typeof lo=="object"&&lo!==null?lo:{};this.surface.dispatchError({code:"EXPRESSION_ERROR",message:Ru.message??`An unexpected error occurred in function ${$u}.`,expression:$u})}}nested(lo,$u){const Ru=this.resolvePath(lo);return new DataContext(this.surface,Ru,$u,this)}resolvePath(lo){if(lo.startsWith("/"))return lo;if(lo===""||lo===".")return this.path;let $u=this.path;return $u.endsWith("/")&&$u.length>1&&($u=$u.slice(0,-1)),$u==="/"&&($u=""),`${$u}/${lo}`}}const IndexApi={name:"@index",returnType:"number",allowedCallers:"rendererOnly",schema:objectType({offset:coerce.number().optional()})};createFunctionImplementation(IndexApi,(Au,lo)=>{const $u=typeof Au.offset=="number"&&Number.isFinite(Au.offset)?Au.offset:0,Ru=resolveContextIndex(lo);if(Ru===void 0||!Number.isFinite(Ru))throw new A2uiValidationError("@index function can only be evaluated inside a collection template iteration scope.");return Ru+$u});const COMPONENT_ENVELOPE_KEYS=["id","component","catalogId","catalogID"];class PayloadValidator{constructor(lo,$u){this.catalog=lo,this.config=$u,this.enforceIdentifiers=isAtLeastVersion(lo.protocolVersion,"1.0")}get allowUnknown(){return this.config?this.config.allowUnknownElements??!1:!0}validateComponent(lo,$u){const Ru=lo.id;if(typeof Ru!="string"||!Ru)throw new A2uiValidationError(`Component '${lo.component}' is missing an 'id'; entries require a valid string 'id'.`);this.assertIdentifier(Ru,`Component id '${Ru}' must be a valid UAX #31 identifier`);const Iu=lo.component,Ou=typeof Iu=="string"?Iu:$u;if(!Ou)throw new A2uiValidationError(`Cannot create component ${Ru} without a type.`);const Pu=this.catalog.components.get(Ou);if(!Pu){if(!this.allowUnknown)throw new A2uiValidationError(`Unknown component type '${Ou}' not found in catalog '${this.catalog.id}'.`);return}const Du=stripEnvelopeKeys(lo),Lu=Pu.schema.safeParse(Du);if(!Lu.success){const ju=Lu.error.errors.map(formatZodIssue).join(", ");throw new A2uiValidationError(`Validation failed for component '${Ou}' (${Ru}): ${ju}`,Lu.error.issues)}this.validateNestedFunctions(Du)}assertFunctionIdentifiers(lo,$u){if(this.assertIdentifier(lo,`Function name '${lo}' must be a valid UAX #31 identifier`),$u&&typeof $u=="object"&&!Array.isArray($u)){const Ru=Object.keys($u);if(Ru.length>MAX_FUNCTION_CALL_ARGS)throw new A2uiValidationError(`Function call '${lo}' exceeds maximum allowed arguments count (${MAX_FUNCTION_CALL_ARGS})`);for(const Iu of Ru)this.assertIdentifier(Iu,`Function argument '${Iu}' in function '${lo}' must be a valid UAX #31 identifier`)}}validateNestedFunctions(lo){if(Array.isArray(lo)){for(const Iu of lo)this.validateNestedFunctions(Iu);return}if(typeof lo!="object"||lo===null)return;const $u=lo,Ru=$u.call??$u.function;if(typeof Ru=="string"&&Ru.length>0){const Iu=$u.args,Ou=Iu!==void 0?Iu:{},Pu=typeof $u.catalogId=="string"&&$u.catalogId.length>0?$u.catalogId:void 0;Pu&&Pu!==this.catalog.id?this.assertFunctionIdentifiers(Ru,Ou):this.validateFunction(Ru,Ou)}for(const[Iu,Ou]of Object.entries($u))Iu!=="id"&&Iu!=="component"&&this.validateNestedFunctions(Ou)}validateFunction(lo,$u){this.assertFunctionIdentifiers(lo,$u);const Ru=this.catalog.functions.get(lo)??(this.enforceIdentifiers&&lo==="@index"?IndexApi:void 0);if(!Ru){if(!this.allowUnknown)throw new A2uiValidationError(`Unrecognized function '${lo}'`);return $u??{}}if(!Ru.schema){if($u!==void 0&&(typeof $u!="object"||$u===null||Array.isArray($u)))throw new A2uiValidationError(`Validation failed for function '${lo}': Expected object, received ${Array.isArray($u)?"array":typeof $u}`);return $u??{}}const Iu=Ru.schema.safeParse($u??{});if(!Iu.success){const Ou=Iu.error.errors.map(formatZodIssue).join(", ");throw new A2uiValidationError(`Validation failed for function '${lo}': ${Ou}`,Iu.error.issues)}return Iu.data}validateTheme(lo){const $u=this.catalog.themeSchema;if(!$u)return lo;const Ru=$u.safeParse(lo);if(!Ru.success){const Iu=Ru.error.errors.map(formatZodIssue).join(", ");throw new A2uiValidationError(`Validation failed for theme: ${Iu}`,Ru.error.issues)}return Ru.data}assertIdentifier(lo,$u){if(this.enforceIdentifiers&&!isValidUax31Identifier(lo))throw new A2uiValidationError($u)}}function stripEnvelopeKeys(Au){const lo={};for(const[$u,Ru]of Object.entries(Au))COMPONENT_ENVELOPE_KEYS.includes($u)||(lo[$u]=Ru);return lo}class RpcHandler{constructor(lo,$u){if(this.pendingAgentCalls=new Map,this.isDisposed=!1,Array.isArray(lo))this.catalogs=lo,this.outboundListener=$u,this.defaultTimeoutMs=3e4;else{const Ru=lo??{};this.catalogs=Ru.catalogs??[],this.outboundListener=Ru.outboundListener,this.defaultTimeoutMs=Ru.defaultTimeoutMs??3e4}}get disposed(){return this.isDisposed}async handleCallRendererFunction(lo,$u,Ru=!1){const Iu=this.validateInboundMessage(lo);if(Iu)return await this.emitOutboundResponse(Iu),Iu;const{version:Ou,callRendererFunction:Pu}=lo,{functionCallId:Du,callFunction:Lu}=Pu,{call:ju,catalogId:Bu,args:Fu}=Lu,zu=this.resolveFunctionImplementation(Bu,ju,$u,Ou);if("error"in zu){const Vu=this.createResponseError(Du,RpcErrorCode.INVALID_FUNCTION_CALL,zu.error,Ou);return await this.emitOutboundResponse(Vu),Vu}const qu=this.checkExecutionPermissions(zu.funcImpl,ju,Ru);if(qu){const Vu=this.createResponseError(Du,RpcErrorCode.INVALID_FUNCTION_CALL,qu,Ou);return await this.emitOutboundResponse(Vu),Vu}const Uu=this.parseArguments(zu.catalog,zu.funcImpl,Fu,ju);if("error"in Uu){const Vu=this.createResponseError(Du,RpcErrorCode.INVALID_FUNCTION_CALL,Uu.error,Ou);return await this.emitOutboundResponse(Vu),Vu}const Hu=await this.executeFunctionSafely(zu.funcImpl,Uu.args,$u,Du,Ou);return await this.emitOutboundResponse(Hu),Hu}handleAgentFunctionResponse(lo){if(!lo||!lo.agentFunctionResponse)return;const{functionCallId:$u,value:Ru,error:Iu}=lo.agentFunctionResponse,Ou=this.pendingAgentCalls.get($u);if(Ou)if(this.pendingAgentCalls.delete($u),Iu){const Pu=Iu.code??RpcErrorCode.UNKNOWN_ERROR,Du=Iu.message??"Agent function execution failed";Ou.reject(new A2uiRpcError(Du,Pu,$u,Iu))}else Ou.resolve(Ru)}callAgentFunction(lo,$u,Ru){if(this.isDisposed)return Promise.reject(new A2uiRpcError("RpcHandler has been disposed.",RpcErrorCode.DISPOSED));if(!this.outboundListener)return Promise.reject(new A2uiRpcError("Cannot call agent function without outboundListener configured.",RpcErrorCode.NO_LISTENER));if(!$u||!$u.call)return Promise.reject(new A2uiRpcError("Missing or invalid function call name.",RpcErrorCode.INVALID_FUNCTION_CALL));const Iu=Ru??{},Ou=Iu.functionCallId??this.generateFunctionCallId(),Pu=Iu.timeoutMs??this.defaultTimeoutMs;if(this.pendingAgentCalls.has(Ou))return Promise.reject(new A2uiRpcError(`A call with functionCallId '${Ou}' is already pending.`,RpcErrorCode.DUPLICATE,Ou));const Du={functionCallId:Ou,call:$u,effectiveTimeoutMs:Pu,version:Iu.version};return this.dispatchAgentCall(lo,Du)}dispose(){if(!this.isDisposed){this.isDisposed=!0;for(const[lo,$u]of this.pendingAgentCalls.entries())$u.reject(new A2uiRpcError(`RpcHandler disposed while call '${lo}' was pending.`,RpcErrorCode.CANCELLED,lo));this.pendingAgentCalls.clear()}}async emitOutboundResponse(lo){if(this.outboundListener)try{const $u=this.outboundListener(lo);$u&&typeof $u.catch=="function"&&await $u}catch{}}validateInboundMessage(lo){if(!lo)return this.createResponseError("unknown",RpcErrorCode.INVALID_FUNCTION_CALL,"Inbound message is null or undefined.","unknown");const $u=lo.version;return this.isDisposed?this.createResponseError(lo.callRendererFunction?.functionCallId??"unknown",RpcErrorCode.DISPOSED,"RpcHandler has been disposed.",$u):lo.callRendererFunction?.callFunction?null:this.createResponseError(lo.callRendererFunction?.functionCallId??"unknown",RpcErrorCode.INVALID_FUNCTION_CALL,"Malformed message: missing callRendererFunction or callFunction.",$u)}resolveFunctionImplementation(lo,$u,Ru,Iu){let Ou;if(lo){if(Ou=this.catalogs.find(Du=>Du.id===lo),!Ou)return{error:`Catalog not found: ${lo}`}}else Ru?.surface?.defaultCatalog&&(Ou=Ru.surface.defaultCatalog);if(!Ou)return{error:"No catalog available for function resolution."};if(Ou.protocolVersion&&Iu&&!isCatalogVersionCompatible(Ou.protocolVersion,Iu))return{error:`Catalog '${Ou.id}' specification version (${Ou.protocolVersion}) does not match message protocol version (${Iu}).`};const Pu=Ou.functions?.get($u);return Pu?{funcImpl:Pu,catalog:Ou}:{error:`Function not found: ${$u}`}}checkExecutionPermissions(lo,$u,Ru){const Iu=lo.allowedCallers??"rendererOnly";return Iu==="rendererOrAgent"||Iu==="agentOnly"?lo.requiresUserActivation&&!Ru?`Function '${$u}' requires user activation context to execute.`:null:`Function '${$u}' cannot be called by agent (allowedCallers is ${Iu}).`}parseArguments(lo,$u,Ru,Iu){try{return{args:new PayloadValidator(lo,{allowUnknownElements:!1}).validateFunction(Iu,Ru)}}catch(Ou){const Pu=this.extractErrorMessage(Ou);return{error:`Invalid function arguments for '${Iu}': ${Pu}`}}}async executeFunctionSafely(lo,$u,Ru,Iu,Ou){const Pu=Ou||"v1.0";try{const Du=await Promise.resolve(lo.execute($u,Ru)),Lu=isSignal(Du)?getValue(Du):Du;return{version:Pu,rendererFunctionResponse:{functionCallId:Iu,value:Lu!==void 0?Lu:null}}}catch(Du){const Lu=this.extractErrorMessage(Du);return{version:Pu,rendererFunctionResponse:{functionCallId:Iu,error:{code:RpcErrorCode.EXECUTION_ERROR,message:Lu||"An error occurred during function execution."}}}}}generateFunctionCallId(){if(typeof globalThis.crypto?.randomUUID=="function")return globalThis.crypto.randomUUID();const lo=Math.random().toString(36).substring(2,15).padEnd(13,"0");return`call-${Date.now()}-${lo}`}dispatchAgentCall(lo,$u){const{functionCallId:Ru,call:Iu,effectiveTimeoutMs:Ou,version:Pu}=$u;return new Promise((Du,Lu)=>{let ju;const Bu=()=>{ju&&(clearTimeout(ju),ju=void 0),this.pendingAgentCalls.delete(Ru)};ju=this.createTimeoutTimer(Ru,Iu.call,Ou,Bu,Lu),this.pendingAgentCalls.set(Ru,{resolve:Fu=>{Bu(),Du(Fu)},reject:Fu=>{Bu(),Lu(Fu)}}),this.sendOutboundMessage(lo,Ru,Iu,Pu,Bu,Lu)})}createTimeoutTimer(lo,$u,Ru,Iu,Ou){if(!(Ru<=0))return setTimeout(()=>{this.pendingAgentCalls.delete(lo)&&(Iu(),Ou(new A2uiRpcError(`Agent function call '${$u}' timed out after ${Ru}ms.`,RpcErrorCode.TIMEOUT,lo)))},Ru)}sendOutboundMessage(lo,$u,Ru,Iu,Ou,Pu){const Du={version:Iu||"v1.0",callAgentFunction:{surfaceId:lo,functionCallId:$u,callFunction:Ru}};try{const Lu=this.outboundListener(Du);Lu&&typeof Lu.catch=="function"&&Lu.catch(ju=>{Ou(),Pu(ju)})}catch(Lu){Ou(),Pu(Lu)}}extractErrorMessage(lo){return lo instanceof Error?lo.message:String(lo)}createResponseError(lo,$u,Ru,Iu){return{version:Iu||"v1.0",rendererFunctionResponse:{functionCallId:lo,error:{code:$u,message:Ru}}}}}class MessageProcessor{constructor(lo,$u,Ru){this.catalogs=lo,this.actionHandler=$u,this.model=new SurfaceGroupModel,this.adapterRegistry=Ru?.adapterRegistry??defaultVersionAdapterFactory,this.rpc=new RpcHandler({catalogs:this.catalogs,outboundListener:Ru?.outboundListener,defaultTimeoutMs:Ru?.defaultTimeoutMs}),Ru?.validationConfig?this.validationConfig={allowOrphanComponents:!1,allowDanglingReferences:!1,allowMissingRoot:!1,allowUnknownElements:!1,...Ru.validationConfig}:this.validationConfig=void 0,this.actionHandler&&this.model.onAction.subscribe(this.actionHandler)}callAgentFunction(lo,$u,Ru){return this.rpc.callAgentFunction(lo,$u,Ru)}dispose(){this.rpc.dispose()}getRendererCapabilities(lo){if(!lo?.versions||lo.versions.length===0)throw new A2uiValidationError("At least one protocol version must be provided in CapabilitiesOptions to generate renderer capabilities.");const $u=lo.versions,Ru={};for(const Iu of $u){const Ou={supportedCatalogIds:this.catalogs.map(Du=>Du.id)},Pu=lo?.includeInlineCatalogs?this.catalogs.map(Du=>compareSemVer(Iu,"1.0")>=0?generateCatalogSchema(Du,{componentEnvelopeRef:lo?.componentEnvelopeRef,protocolVersion:Iu}):this.generateLegacyInlineCatalog(Du,lo?.componentEnvelopeRef??"common_types.json#/$defs/ComponentCommon")):void 0;Pu&&(Ou.inlineCatalogs=Pu),Ru[Iu]=Ou}return Ru}getClientCapabilities(lo){return this.getRendererCapabilities(lo)}generateLegacyInlineCatalog(lo,$u="common_types.json#/$defs/ComponentCommon"){const Ru=generateCatalogSchema(lo,{componentEnvelopeRef:$u}),Iu=Ru.components||{},Ou=Ru.functions,Pu=[];for(const ju of lo.functions.values()){const Bu=Ou?.[ju.name];Pu.push({name:ju.name,description:ju.description,returnType:ju.returnType,parameters:Bu?.properties?.args??{type:"object",properties:{}}})}const Lu=Ru.$defs?.theme?.properties;return{catalogId:lo.id,components:Iu,...Pu.length>0?{functions:Pu}:{},...Lu?{theme:Lu}:{}}}getRendererDataModel(lo){const $u=Array.from(this.model.surfacesMap.values()).filter(Pu=>Pu.sendDataModel);if($u.length===0)return;if(lo!==void 0){const Pu={};for(const Du of $u){const Lu=Du.defaultCatalog?.protocolVersion;(!Lu||isCatalogVersionCompatible(Lu,lo))&&(Pu[Du.id]=Du.dataModel.get("/"))}return Object.keys(Pu).length===0?void 0:{version:lo,surfaces:Pu}}const Ru=new Set;for(const Pu of $u)if(Pu.defaultCatalog?.protocolVersion){const Du=toCanonicalVersion(Pu.defaultCatalog.protocolVersion),Lu=Du?`v${Du}`:Pu.defaultCatalog.protocolVersion;Ru.add(Lu)}if(Ru.size>1)throw new A2uiValidationError(`Multiple protocol versions detected among active surfaces: ${Array.from(Ru).sort().join(", ")}. Specify a target protocol version in getRendererDataModel(version).`);const Iu=Ru.size===1?Ru.values().next().value:"v1.0",Ou={};for(const Pu of $u)Ou[Pu.id]=Pu.dataModel.get("/");return{version:Iu,surfaces:Ou}}getClientDataModel(lo){return this.getRendererDataModel(lo)}resolvePath(lo,$u){return DataModel.resolvePath(lo,$u)}getSurfaces(){return this.model.surfacesMap}getSurface(lo){return this.model.getSurface(lo)}onSurfaceCreated(lo){return this.model.onSurfaceCreated.subscribe(lo)}onSurfaceDeleted(lo){return this.model.onSurfaceDeleted.subscribe(lo)}processMessages(lo,$u){const Ru=this.prepareOperations(lo);for(const Iu of Ru)this.processOperation(Iu,$u)}async processMessagesAsync(lo,$u){const Ru=this.prepareOperations(lo),Iu=[];for(const Ou of Ru){const Pu=await this.processOperationAsync(Ou,$u);Pu&&Iu.push(Pu)}return Iu}prepareOperations(lo){return!lo||Array.isArray(lo)&&lo.length===0?[]:(this.validationConfig&&validateRecursionAndPaths(lo),this.validationConfig?.targetVersion&&this.validateTargetVersion(lo),isInternalOperation(lo)?[lo]:this.adapterRegistry.resolveFromPayload(lo).extractOperations(lo))}validateTargetVersion(lo){const $u=this.validationConfig?.targetVersion;if(!$u)return;const Ru=Iu=>{if(typeof Iu=="object"&&Iu!==null&&"version"in Iu){const Ou=Iu.version;if(Ou){const Pu=toCanonicalVersion(Ou)??Ou,Du=toCanonicalVersion($u)??$u;if(Pu!==Du)throw new A2uiValidationError(`Message version '${Ou}' does not match expected target version '${$u}'`)}}};if(Array.isArray(lo))for(const Iu of lo)Ru(Iu);else Ru(lo)}applyStateOperation(lo){if(this.validationConfig?.allowedMessages&&!this.validationConfig.allowedMessages.includes(lo.type))throw new A2uiValidationError(`Operation '${lo.type}' is not permitted by ValidationConfig.allowedMessages`);switch(lo.type){case"createSurface":this.processCreateSurfaceOp(lo);break;case"deleteSurface":this.processDeleteSurfaceOp(lo);break;case"updateComponents":this.processUpdateComponentsOp(lo);break;case"updateDataModel":this.processUpdateDataModelOp(lo);break;case"agentFunctionResponse":this.rpc.handleAgentFunctionResponse({version:lo.version??"v1.0",agentFunctionResponse:{functionCallId:lo.functionCallId,value:lo.value,error:lo.error}});break}}resolveRpcDataContext(lo){const $u=(lo.catalogId?this.catalogs.find(Pu=>Pu.id===lo.catalogId):void 0)??this.catalogs[0],Ru=(lo.catalogId?Array.from(this.model.surfacesMap.values()).find(Pu=>Pu.defaultCatalog?.id===lo.catalogId||Pu.availableCatalogs?.has(lo.catalogId)):void 0)??this.model.surfacesMap.values().next().value;if(Ru)return new DataContext(Ru,"/");const Iu=`_rpc_fallback_${lo.functionCallId||"default"}`,Ou=new Map;for(const Pu of this.catalogs)$u?.protocolVersion&&Pu.protocolVersion&&isCatalogVersionCompatible($u.protocolVersion,Pu.protocolVersion)&&Ou.set(Pu.id,Pu);return $u&&Ou.set($u.id,$u),new DataContext(new SurfaceModel(Iu,$u,Ou),"/")}processOperation(lo,$u){if(lo.type==="callRendererFunction"){const Ru=this.resolveRpcDataContext(lo),Iu=$u?.isUserActivated??lo.isUserActivated??!1,Ou={version:lo.version??"v1.0",callRendererFunction:{functionCallId:lo.functionCallId,callFunction:{call:lo.call,catalogId:lo.catalogId,args:lo.args}}};this.rpc.handleCallRendererFunction(Ou,Ru,Iu).catch(Pu=>{console.error(`Unhandled error in callRendererFunction (${lo.call}):`,Pu)});return}this.applyStateOperation(lo)}async processOperationAsync(lo,$u){if(lo.type==="callRendererFunction"){const Ru=this.resolveRpcDataContext(lo),Iu=$u?.isUserActivated??lo.isUserActivated??!1,Ou={version:lo.version??"v1.0",callRendererFunction:{functionCallId:lo.functionCallId,callFunction:{call:lo.call,catalogId:lo.catalogId,args:lo.args}}};return await this.rpc.handleCallRendererFunction(Ou,Ru,Iu)}return this.applyStateOperation(lo),null}processCreateSurfaceOp(lo){const{surfaceId:$u,catalogId:Ru,theme:Iu,sendDataModel:Ou,components:Pu,dataModel:Du}=lo,Lu=Ru!==void 0?this.catalogs.find(qu=>qu.id===Ru):this.catalogs[0];if(!Lu)throw new A2uiStateError(`Catalog not found: ${Ru}`);const ju=lo.version;if(Lu.protocolVersion&&ju&&!isCatalogVersionCompatible(Lu.protocolVersion,ju))throw new A2uiValidationError(`Surface '${$u}' catalog '${Ru??Lu.id}' specification version (${Lu.protocolVersion}) does not match message protocol version (${ju}).`);if(this.model.getSurface($u))throw new A2uiStateError(`Surface ${$u} already exists.`);let Bu=Iu;if(Iu&&Lu.themeSchema)try{Bu=new PayloadValidator(Lu,this.validationConfig).validateTheme(Iu)}catch(qu){throw qu instanceof A2uiValidationError?new A2uiValidationError(qu.message.replace(/^Validation failed for theme:/,`Validation failed for theme on surface '${$u}':`),qu.details):qu}const Fu=new Map(this.catalogs.filter(qu=>isCatalogVersionCompatible(qu.protocolVersion,Lu.protocolVersion)).map(qu=>[qu.id,qu])),zu=new SurfaceModel($u,Lu,Fu,Bu,Ou??!1,void 0,lo.rootId??"root");this.model.addSurface(zu),Du&&zu.dataModel.set("/",Du),Pu&&Pu.length>0&&this.processUpdateComponentsOp({type:"updateComponents",surfaceId:$u,components:Pu})}processDeleteSurfaceOp(lo){lo.surfaceId&&this.model.deleteSurface(lo.surfaceId)}validateComponentProperties(lo,$u){const{id:Ru,component:Iu}=lo,Ou=lo.catalogId??lo.catalogID;if(typeof Ru!="string"||!Ru)throw new A2uiValidationError(`Component '${Iu}' is missing an 'id'; entries require a valid string 'id'.`);let Pu=$u.defaultCatalog;if(typeof Ou=="string"&&Ou){const Lu=$u.availableCatalogs.get(Ou);if(!Lu){const ju=this.catalogs.find(Bu=>Bu.id===Ou);throw ju?new A2uiValidationError(`Component '${Ru}' catalog '${Ou}' specification version (${ju.protocolVersion}) does not match surface default catalog version (${$u.defaultCatalog.protocolVersion}).`):new A2uiValidationError(`Unknown catalog ID '${Ou}' for component '${Ru}'. Available catalogs: ${this.catalogs.map(Bu=>Bu.id).join(", ")}`)}Pu=Lu}const Du=$u.componentsModel.get(Ru);new PayloadValidator(Pu,this.validationConfig).validateComponent(lo,Du?.type)}applyComponentUpdate(lo,$u){const{id:Ru,component:Iu,...Ou}=lo;if(typeof Ru!="string")return;const Pu=lo.catalogId??lo.catalogID,Du=$u.componentsModel.get(Ru);let Lu=$u.defaultCatalog;if(typeof Pu=="string"&&Pu){const ju=$u.availableCatalogs.get(Pu);ju&&(Lu=ju)}if(Du){const ju=typeof Iu=="string"?Iu:Du.type;if(ju!==Du.type||Pu&&Du.catalog?.id!==Lu.id){$u.componentsModel.removeComponent(Ru);const Bu=new ComponentModel(Ru,ju,Ou,Lu);$u.componentsModel.addComponent(Bu)}else Du.properties=Ou}else{if(typeof Iu!="string"||!Iu)throw new A2uiValidationError(`Cannot create component ${Ru} without a type.`);const ju=new ComponentModel(Ru,Iu,Ou,Lu);$u.componentsModel.addComponent(ju)}}processUpdateComponentsOp(lo){if(!lo.surfaceId)return;const $u=this.model.getSurface(lo.surfaceId);if(!$u)throw new A2uiStateError(`Surface not found for message: ${lo.surfaceId}`);for(const Ru of lo.components)this.validateComponentProperties(Ru,$u);this.validateCompositionConstraints($u,lo.components),this.validateCandidateTopology($u,lo.components);for(const Ru of lo.components)this.applyComponentUpdate(Ru,$u)}processUpdateDataModelOp(lo){if(!lo.surfaceId)return;const $u=this.model.getSurface(lo.surfaceId);if(!$u)throw new A2uiStateError(`Surface not found for message: ${lo.surfaceId}`);const Ru=lo.path||"/",Iu=lo.value;$u.dataModel.set(Ru,Iu)}validateParentConstraints(lo,$u,Ru,Iu){if(!Iu||Iu.length===0){if((lo==="root"||this.validationConfig&&this.validationConfig.allowOrphanComponents===!1)&&!Ru.includes("Surface"))throw new A2uiValidationError(`Component '${lo}' (${$u}) cannot be placed under parent 'Surface' (Surface). Allowed parents: ${JSON.stringify(Ru)}.`,void 0,"UNALLOWED_PARENT");return}for(const Ou of Iu)if(!Ru.includes(Ou.parentType))throw new A2uiValidationError(`Component '${lo}' (${$u}) cannot be placed under parent '${Ou.parentId}' (${Ou.parentType||"unknown"}). Allowed parents: ${JSON.stringify(Ru)}.`,void 0,"UNALLOWED_PARENT")}validateChildConstraints(lo,$u,Ru,Iu,Ou){for(const Pu of Iu){const Du=Ou.get(Pu);if(Du&&!Ru.includes(Du))throw new A2uiValidationError(`Container '${lo}' (${$u}) cannot contain child '${Pu}' (${Du}). Allowed children: ${JSON.stringify(Ru)}.`,void 0,"UNALLOWED_CHILD")}}buildCompositionTopology(lo,$u){const Ru=new Map,Iu=new Map,Ou=new Map;for(const[Du,Lu]of lo.componentsModel.entries){Ru.set(Du,Lu.type),Lu.catalog&&Iu.set(Du,Lu.catalog);const ju=lo.componentsModel.getChildIds(Du);ju.length>0&&Ou.set(Du,ju)}for(const Du of $u){const{id:Lu,component:ju,...Bu}=Du;if(typeof Lu!="string")continue;let Fu=lo.defaultCatalog;const zu=Du.catalogId??Du.catalogID;if(typeof zu=="string"&&zu){const Gu=lo.availableCatalogs.get(zu);Gu&&(Fu=Gu,Iu.set(Lu,Gu))}const qu=lo.componentsModel.get(Lu),Uu=(typeof ju=="string"?ju:qu?.type)??"";Uu&&Ru.set(Lu,Uu);const Hu={id:Lu,component:Uu,...Bu},Vu=Array.from(getComponentReferences(Hu,Fu)).map(([Gu])=>Gu);Vu.length>0?Ou.set(Lu,Vu):Ou.delete(Lu)}const Pu=new Map;for(const[Du,Lu]of Ou.entries()){const ju=Ru.get(Du)||"Unknown";for(const Bu of Lu){const Fu=Pu.get(Bu)??[];Fu.push({parentId:Du,parentType:ju}),Pu.set(Bu,Fu)}}return{typeMap:Ru,compCatalogMap:Iu,childMap:Ou,parentMap:Pu}}validateCompositionConstraints(lo,$u){const{typeMap:Ru,compCatalogMap:Iu,childMap:Ou,parentMap:Pu}=this.buildCompositionTopology(lo,$u);for(const[Du,Lu]of Ru.entries()){const Bu=(Iu.get(Du)??lo.defaultCatalog).components.get(Lu);Bu&&(Bu.allowedParents&&Bu.allowedParents.length>0&&this.validateParentConstraints(Du,Lu,Bu.allowedParents,Pu.get(Du)),Bu.allowedChildren&&Bu.allowedChildren.length>0&&this.validateChildConstraints(Du,Lu,Bu.allowedChildren,Ou.get(Du)||[],Ru))}}validateCandidateTopology(lo,$u){if(!this.validationConfig)return;const Ru=new SurfaceComponentsModel(lo.defaultCatalog);for(const[Iu,Ou]of lo.componentsModel.entries)Ru.addComponent(new ComponentModel(Iu,Ou.type,Ou.properties,Ou.catalog));for(const Iu of $u){const{id:Ou,component:Pu,...Du}=Iu;if(typeof Ou!="string"||!Ou)continue;const Lu=Iu.catalogId??Iu.catalogID;let ju=lo.defaultCatalog;if(typeof Lu=="string"&&Lu){const zu=lo.availableCatalogs.get(Lu);zu&&(ju=zu)}const Bu=Ru.get(Ou),Fu=(typeof Pu=="string"?Pu:Bu?.type)||"";Fu&&(Bu?Fu!==Bu.type||Lu&&Bu.catalog?.id!==ju.id?(Ru.removeComponent(Ou),Ru.addComponent(new ComponentModel(Ou,Fu,Du,ju))):Bu.properties=Du:Ru.addComponent(new ComponentModel(Ou,Fu,Du,ju)))}Ru.validateTopology({...this.validationConfig,rootId:this.validationConfig.rootId??lo.rootId})}}class ComponentContext{constructor(lo,$u,Ru="/",Iu,Ou){const Pu=lo.componentsModel.get($u);if(!Pu)throw new A2uiStateError(`Component not found: ${$u}`);this.componentModel=Pu,this.surfaceComponents=lo.componentsModel,this.theme=lo.theme,this.dataContext=new DataContext(lo,Ru,Ou,Iu),this._actionDispatcher=Du=>lo.dispatchAction(Du,this.componentModel.id)}dispatchAction(lo){return this._actionDispatcher(lo)}}function scrapeSchemaBehavior(Au){return getFieldBehavior(Au)}function unwrapZodSchema(Au){let lo=Au;for(;lo;){const $u=lo._def?.typeName;if($u==="ZodOptional"||$u==="ZodNullable"||$u==="ZodDefault"||$u==="ZodReadonly")lo=lo._def.innerType;else if($u==="ZodEffects")lo=lo._def.schema;else if($u==="ZodBranded")lo=lo._def.type;else if($u==="ZodLazy")lo=lo._def.getter();else break}return lo}function getRefDefName(Au){let lo=Au,$u="";for(;lo&&($u=lo.description??lo._def?.description??"",!$u);){const Iu=lo._def?.typeName;if(Iu==="ZodOptional"||Iu==="ZodNullable"||Iu==="ZodDefault"||Iu==="ZodReadonly")lo=lo._def.innerType;else if(Iu==="ZodEffects")lo=lo._def.schema;else if(Iu==="ZodBranded")lo=lo._def.type;else if(Iu==="ZodLazy")lo=lo._def.getter();else break}if(!$u||!$u.startsWith("REF:"))return"";const Ru=$u.slice(4);return extractRefDefName(Ru.split("|")[0])}function isCheckableField(Au){const lo=getRefDefName(Au);if(lo==="Checkable"||lo==="CheckRule")return!0;const $u=unwrapZodSchema(Au);if($u?._def?.typeName==="ZodArray"){const Ru=$u._def.type;if(getRefDefName(Ru)==="CheckRule")return!0}return!1}function isActionOption(Au){if(getRefDefName(Au)==="Action")return!0;const $u=unwrapZodSchema(Au)._def;return $u?.typeName==="ZodObject"&&!!$u.shape?.().event}function isDynamicOption(Au){const lo=getRefDefName(Au);if(lo==="DataBinding"||lo.startsWith("Dynamic"))return!0;const Ru=unwrapZodSchema(Au)._def;if(Ru?.typeName!=="ZodObject")return!1;const Iu=Ru.shape?.()||{},Ou=Object.values(Iu).some(Pu=>getRefDefName(Pu)==="ComponentId");return!!Iu.path&&!Ou}function isChildListOption(Au){if(childRefKindOf(Au)==="child-list"||getRefDefName(Au)==="ChildList")return!0;const $u=unwrapZodSchema(Au)._def;if($u?.typeName!=="ZodObject")return!1;const Ru=$u.shape?.()||{};return Object.values(Ru).some(Iu=>getRefDefName(Iu)==="ComponentId")}function isDynamicDef(Au,lo){return(Au==="DataBinding"||Au.startsWith("Dynamic"))&&lo!=="ZodObject"&&lo!=="ZodArray"}function matchUnionBehavior(Au){if(Au.some(isActionOption))return{type:"ACTION"};if(Au.some(isDynamicOption))return{type:"DYNAMIC"};if(Au.some(isChildListOption))return{type:"STRUCTURAL"}}function scrapeObjectShape(Au){const lo={};for(const[$u,Ru]of Object.entries(Au))lo[$u]=getFieldBehavior(Ru);return lo}function getFieldBehavior(Au){const lo=getRefDefName(Au);if(isCheckableField(Au))return{type:"CHECKABLE"};if(lo==="Action")return{type:"ACTION"};const $u=unwrapZodSchema(Au);if(childRefKindOf($u)==="child-list"||lo==="ChildList")return{type:"STRUCTURAL"};if(isDynamicDef(lo,$u._def?.typeName))return{type:"DYNAMIC"};if($u._def.typeName==="ZodUnion"){const Ru=matchUnionBehavior($u._def.options);if(Ru)return Ru}return $u._def.typeName==="ZodArray"?{type:"ARRAY",element:getFieldBehavior($u._def.type)}:$u._def.typeName==="ZodObject"?{type:"OBJECT",shape:scrapeObjectShape($u._def.shape())}:{type:"STATIC"}}const MAX_DYNAMIC_CHILD_LIST_SIZE=1e4;function getSafeChildList(Au){return Array.isArray(Au)?Au.length>MAX_DYNAMIC_CHILD_LIST_SIZE?Au.slice(0,MAX_DYNAMIC_CHILD_LIST_SIZE):Au:[]}class GenericBinder{constructor(lo,$u){this.dataListeners=[],this.propsListeners=[],this.currentProps={},this.isConnected=!1,this.actionClosures=new Map,this.context=lo,this.behaviorTree=scrapeSchemaBehavior($u),this.behaviorTree.type!=="OBJECT"&&(this.behaviorTree={type:"OBJECT",shape:{}}),this.resolveInitialProps()}resolveInitialProps(){const lo=this.context.componentModel.properties,$u=this.resolveAndBind(lo,this.behaviorTree,[],!0);this.currentProps={...this.currentProps,...$u||{}}}connect(){if(this.isConnected)return;this.isConnected=!0;const lo=this.context.componentModel.onUpdated.subscribe(()=>{this.rebuildAllBindings()});this.compUnsub=()=>lo.unsubscribe(),this.rebuildAllBindings()}rebuildAllBindings(){this.dataListeners.forEach(Ru=>Ru()),this.dataListeners=[];const lo=this.context.componentModel.properties,$u=this.resolveAndBind(lo,this.behaviorTree,[],!1);this.currentProps={...this.currentProps,...$u||{}},this.notify()}bindDynamicValue(lo,$u,Ru){const Iu=this.context.dataContext.subscribeDynamicValue(lo,Ou=>{this.updateDeepValue($u,Ou),this.notify()});return Ru?Iu.unsubscribe():this.dataListeners.push(()=>Iu.unsubscribe()),Iu.value}resolveDeepSync(lo,$u=0){if(typeof lo!="object"||lo===null)return lo;if($u>MAX_DYNAMIC_VALUE_DEPTH)return;if("path"in lo||"call"in lo)return this.context.dataContext.resolveDynamicValue(lo,$u);if(Array.isArray(lo))return lo.map(Iu=>this.resolveDeepSync(Iu,$u+1));const Ru={};for(const[Iu,Ou]of Object.entries(lo))Ru[Iu]=this.resolveDeepSync(Ou,$u+1);return Ru}resolveEventAction(lo){if(typeof lo!="object"||lo===null)return lo;const $u=lo;if("event"in $u&&typeof $u.event=="object"&&$u.event!==null){const Ru=$u.event,Iu={...Ru,context:Ru.context?this.resolveDeepSync(Ru.context,1):void 0};return Ru.userMessage!==void 0&&(Iu.userMessage=this.resolveDeepSync(Ru.userMessage,1)),{...$u,event:Iu}}if("name"in $u){const Ru={...$u,context:$u.context?this.resolveDeepSync($u.context,1):void 0};return $u.userMessage!==void 0&&(Ru.userMessage=this.resolveDeepSync($u.userMessage,1)),Ru}return this.resolveDeepSync(lo,0)}bindAction(lo,$u){const Ru=$u.join("/"),Iu=this.actionClosures.get(Ru);if(Iu&&jsonEquals(Iu.raw,lo))return Iu.closure;const Ou=()=>{if(lo&&typeof lo=="object"){const Pu=lo,Du=Pu.functionCall&&typeof Pu.functionCall=="object"?Pu.functionCall:Pu;if(typeof Du.call=="string"){this.context.dataContext.resolveDynamicValue(Du);return}}this.context.dispatchAction(this.resolveEventAction(lo))};return this.actionClosures.set(Ru,{raw:lo,closure:Ou}),Ou}mapTemplateChildren(lo,$u,Ru){const Iu=getSafeChildList(lo),Ou=this.context.dataContext.nested(Ru);return Iu.map((Pu,Du)=>({id:$u,basePath:Ou.nested(String(Du)).path}))}bindStructuralTemplate(lo,$u,Ru){if(!lo||typeof lo!="object"||Array.isArray(lo))return lo;const Iu=lo,Ou=typeof Iu.path=="string"?Iu.path:void 0,Pu=typeof Iu.componentId=="string"?Iu.componentId:void 0;if(!Ou||!Pu)return lo;const Du=this.context.dataContext.subscribeDynamicValue({path:Ou},Lu=>{const ju=this.mapTemplateChildren(Lu,Pu,Ou);this.updateDeepValue($u,ju),this.notify()});return Ru?Du.unsubscribe():this.dataListeners.push(()=>Du.unsubscribe()),this.mapTemplateChildren(Du.value,Pu,Ou)}extractValidationResult(lo,$u){if(typeof lo=="object"&&lo!==null&&"valid"in lo){const Ru=lo.message;return{valid:!!lo.valid,message:Ru!=null?String(Ru):$u}}return{valid:!!lo,message:$u}}bindCheckable(lo,$u,Ru){const Iu=Array.isArray(lo)?lo:[],Ou=Iu.map(()=>({valid:!0,message:""})),Pu=$u.slice(0,-1),Du=()=>{const ju=Ou.filter(Bu=>!Bu.valid).map(Bu=>Bu.message);this.updateDeepValue([...Pu,"isValid"],ju.length===0),this.updateDeepValue([...Pu,"validationErrors"],ju),this.notify()};Iu.forEach((ju,Bu)=>{const Fu=typeof ju=="object"&&ju!==null?ju:void 0,zu=Fu&&Fu.condition!==void 0?Fu.condition:ju,qu=typeof Fu?.message=="string"?Fu.message:"Validation failed";Ou[Bu].message=qu;const Uu=this.context.dataContext.subscribeDynamicValue(zu,Hu=>{Ou[Bu]=this.extractValidationResult(Hu,qu),Du()});Ru?Uu.unsubscribe():this.dataListeners.push(()=>Uu.unsubscribe()),Ou[Bu]=this.extractValidationResult(Uu.value,qu)});const Lu=Ou.filter(ju=>!ju.valid).map(ju=>ju.message);return this.updateDeepValue([...Pu,"isValid"],Lu.length===0),this.updateDeepValue([...Pu,"validationErrors"],Lu),lo}bindObject(lo,$u,Ru,Iu){const Ou={};for(const[Pu,Du]of Object.entries(lo)){const Lu=$u[Pu]||{type:"STATIC"};Ou[Pu]=this.resolveAndBind(Du,Lu,[...Ru,Pu],Iu)}for(const[Pu,Du]of Object.entries($u))if(Du.type==="DYNAMIC"){const Lu=`set${Pu.charAt(0).toUpperCase()+Pu.slice(1)}`,ju=lo[Pu];Ou[Lu]=Bu=>{if(ju&&typeof ju=="object"&&"path"in ju){const Fu=ju.path;typeof Fu=="string"&&this.context.dataContext.set(Fu,Bu)}}}return Ou}resolveAndBind(lo,$u,Ru,Iu){if(lo==null)return lo;switch($u.type){case"DYNAMIC":return this.bindDynamicValue(lo,Ru,Iu);case"ACTION":return this.bindAction(lo,Ru);case"STRUCTURAL":return this.bindStructuralTemplate(lo,Ru,Iu);case"CHECKABLE":return this.bindCheckable(lo,Ru,Iu);case"STATIC":return lo;case"ARRAY":return Array.isArray(lo)?lo.map((Ou,Pu)=>this.resolveAndBind(Ou,$u.element,[...Ru,Pu.toString()],Iu)):lo;case"OBJECT":return typeof lo!="object"?lo:this.bindObject(lo,$u.shape,Ru,Iu)}}updateDeepValue(lo,$u){this.currentProps=this.cloneAndUpdate(this.currentProps,lo,$u)}cloneAndUpdate(lo,$u,Ru){if($u.length===0)return Ru;const[Iu,...Ou]=$u;if(Array.isArray(lo)){const Pu=[...lo];return Pu[Number(Iu)]=this.cloneAndUpdate(Pu[Number(Iu)],Ou,Ru),Pu}else{const Pu=typeof lo=="object"&&lo!==null?lo:{};return{...Pu,[Iu]:this.cloneAndUpdate(Pu[Iu],Ou,Ru)}}}dispose(){this.isConnected&&(this.isConnected=!1,this.dataListeners.forEach(lo=>lo()),this.dataListeners=[],this.compUnsub&&(this.compUnsub(),this.compUnsub=void 0))}notify(){this.propsListeners.forEach(lo=>lo(this.currentProps))}subscribe(lo){return this.propsListeners.length===0&&this.connect(),this.propsListeners.push(lo),{unsubscribe:()=>{this.propsListeners=this.propsListeners.filter($u=>$u!==lo),this.propsListeners.length===0&&this.dispose()}}}get snapshot(){return this.currentProps}}function jsonEquals(Au,lo){if(Object.is(Au,lo))return!0;if(typeof Au!="object"||typeof lo!="object"||Au===null||lo===null)return!1;if(Array.isArray(Au)||Array.isArray(lo))return!Array.isArray(Au)||!Array.isArray(lo)||Au.length!==lo.length?!1:Au.every((Iu,Ou)=>jsonEquals(Iu,lo[Ou]));const $u=Object.keys(Au),Ru=Object.keys(lo);return $u.length!==Ru.length?!1:$u.every(Iu=>Object.prototype.hasOwnProperty.call(lo,Iu)&&jsonEquals(Au[Iu],lo[Iu]))}class ResolvedBinding{constructor(lo){this.value=lo}}class WritableBinding extends ResolvedBinding{constructor(lo,$u,Ru){super(lo),this.set=$u,this.path=Ru}}function isWritable(Au){return Au instanceof WritableBinding}function sameBinding(Au,lo){return isWritable(Au)!==isWritable(lo)||isWritable(Au)&&isWritable(lo)&&Au.path!==lo.path?!1:valueEquals(Au.value,lo.value)}function valueEquals(Au,lo){if(Object.is(Au,lo))return!0;if(Array.isArray(Au)&&Array.isArray(lo))return Au.length===lo.length&&Au.every(($u,Ru)=>valueEquals($u,lo[Ru]));if(isPlainObject$2(Au)&&isPlainObject$2(lo)){const $u=Object.keys(Au),Ru=Object.keys(lo);return $u.length===Ru.length&&$u.every(Iu=>Iu in lo&&valueEquals(Au[Iu],lo[Iu]))}return!1}function isPlainObject$2(Au){if(typeof Au!="object"||Au===null)return!1;const lo=Object.getPrototypeOf(Au);return lo===Object.prototype||lo===null}const PLACEHOLDER_TYPE="Placeholder";function isComponentNode(Au){return Au instanceof MutableComponentNode}class MutableComponentNode{constructor(lo,$u,Ru,Iu,Ou,Pu,Du="resolved"){this._onDestroyed=new EventEmitter,this.onDestroyed=this._onDestroyed,this.cleanups=[],this._disposed=!1,this.instanceId=lo,this.componentId=$u,this.type=Ru,this.dataPath=Iu,this.props=signal(Ou),this.impl=Pu,this.state=Du}get disposed(){return this._disposed}get isPlaceholder(){return this.state!=="resolved"}addCleanup(lo){this.cleanups.push(lo)}toJSON(){if(this.isPlaceholder)return{id:this.componentId,type:this.type,state:this.state};const lo={id:this.componentId,type:this.type},$u=peekValue(this.props);for(const[Ru,Iu]of Object.entries($u))lo[Ru]=serializeValue(Iu);return lo}setProps(lo){if(this._disposed)return;const $u=peekValue(this.props);shallowEqual($u,lo)||setValue(this.props,lo)}dispose(){if(!this._disposed){this._disposed=!0;for(const lo of this.cleanups)try{lo()}catch($u){console.error(`ComponentNode cleanup error (${this.instanceId}):`,$u)}this.cleanups=[],this._onDestroyed.emit(),this._onDestroyed.dispose()}}}function serializeValue(Au){if(isComponentNode(Au))return Au.toJSON();if(Au instanceof ResolvedBinding)return serializeValue(Au.value);if(typeof Au=="function")return"<Action>";if(Array.isArray(Au))return Au.map(serializeValue);if(Au&&typeof Au=="object"){const lo={};for(const[$u,Ru]of Object.entries(Au))lo[$u]=serializeValue(Ru);return lo}return Au}function shallowEqual(Au,lo){if(Object.is(Au,lo))return!0;const $u=Object.keys(Au),Ru=Object.keys(lo);if($u.length!==Ru.length)return!1;for(const Iu of $u)if(!Object.is(Au[Iu],lo[Iu]))return!1;return!0}const COMPONENT_ID_REF="REF:common_types.json#/$defs/ComponentId",CHILD_LIST_REF="REF:common_types.json#/$defs/ChildList",EMPTY_REF_FIELDS$1=new Map,refFieldsCache=new WeakMap;function extractRefFields(Au){const lo=refFieldsCache.get(Au);if(lo)return lo;const $u=unwrap(Au);if($u.schema._def.typeName!=="ZodObject")return refFieldsCache.set(Au,EMPTY_REF_FIELDS$1),EMPTY_REF_FIELDS$1;const Ru=new Map,Iu=$u.schema.shape;for(const[Pu,Du]of Object.entries(Iu)){const Lu=unwrap(Du);if(marksChildList(Lu)||isChildListUnion(Lu.schema)){Ru.set(Pu,{kind:"list"});continue}if(marksComponentId(Lu)){Ru.set(Pu,{kind:"single"});continue}if(Lu.schema._def.typeName==="ZodArray"){const ju=unwrap(Lu.schema._def.type);if(marksComponentId(ju)){Ru.set(Pu,{kind:"list"});continue}if(ju.schema._def.typeName==="ZodObject"){const Bu=new Set,Fu=ju.schema.shape;for(const[zu,qu]of Object.entries(Fu))marksComponentId(unwrap(qu))&&Bu.add(zu);Bu.size>0&&Ru.set(Pu,{kind:"nested",keys:Bu})}}}const Ou=Ru;return refFieldsCache.set(Au,Ou),Ou}function unwrap(Au){const lo=[],$u=new Set;let Ru=Au;for(;;){Ru.description&&lo.push(Ru.description);const Iu=childRefKindOf(Ru);Iu&&$u.add(Iu);const Ou=Ru._def.typeName;if(Ou==="ZodOptional"||Ou==="ZodNullable"||Ou==="ZodDefault")Ru=Ru._def.innerType;else if(Ou==="ZodEffects")Ru=Ru._def.schema;else return{schema:Ru,descriptions:lo,refs:$u}}}function marksComponentId(Au){return Au.refs.has("component-id")||hasPointer(Au.descriptions,COMPONENT_ID_REF)}function marksChildList(Au){return Au.refs.has("child-list")||hasPointer(Au.descriptions,CHILD_LIST_REF)}function hasPointer(Au,lo){return Au.some($u=>$u.startsWith(lo))}function isChildListUnion(Au){return Au._def.typeName!=="ZodUnion"?!1:Au._def.options.some($u=>{if($u._def.typeName!=="ZodObject")return!1;const Ru=$u.shape;return Ru.componentId&&Ru.path})}const ROOT_COMPONENT_ID="root",ROOT_DATA_PATH="/",EMPTY_REF_FIELDS=new Map;class NodeResolver{constructor(lo,$u){if(this.records=new Map,this.nodesByEdge=new Map,this.nodesByComponentId=new Map,this.pendingParents=new Map,this.dispatchedErrors=new Map,this.modelSubs=[],this._disposed=!1,$u!==lo.defaultCatalog)throw new A2uiStateError("NodeResolver requires the same catalog instance its surface was constructed with.");this.surface=lo,this.catalog=$u,this.rootId=lo.rootId??ROOT_COMPONENT_ID,this.rootNode=signal(void 0),this.modelSubs.push(lo.componentsModel.onCreated.subscribe(Ru=>this.onComponentCreated(Ru))),this.modelSubs.push(lo.componentsModel.onDeleted.subscribe(Ru=>this.onComponentDeleted(Ru))),lo.componentsModel.get(this.rootId)&&this.buildRoot()}dispatchOnce(lo,$u,Ru,Iu){let Ou=this.dispatchedErrors.get($u);Ou||(Ou=new Map,this.dispatchedErrors.set($u,Ou));let Pu=Ou.get(Ru);Pu||(Pu=new Set,Ou.set(Ru,Pu)),!Pu.has(lo)&&(Pu.add(lo),this.surface.dispatchError({code:lo,message:Iu}))}clearDispatched(lo,$u){const Ru=this.dispatchedErrors.get(lo);Ru?.delete($u)&&Ru.size===0&&this.dispatchedErrors.delete(lo)}get activeNodeCount(){return this.records.size}get disposed(){return this._disposed}dispose(){if(!this._disposed){this._disposed=!0;for(const lo of this.modelSubs)lo.unsubscribe();this.modelSubs.length=0;for(const lo of[...this.records.keys()])this.disposeNode(lo);this.pendingParents.clear(),this.dispatchedErrors.clear(),this.rootRecord=void 0,setValue(this.rootNode,void 0)}}buildRoot(){if(this.rootRecord)return;const lo=`>${escapeIdPart(this.rootId)}>${escapeIdPart(this.rootId)}@/`,$u=this.createNode(this.rootId,ROOT_DATA_PATH,lo,void 0);this.rootRecord=this.records.get($u),setValue(this.rootNode,$u)}onComponentCreated(lo){if(this._disposed)return;if(lo.id===this.rootId){const Ru=this.surface.componentsModel.get(this.rootId);this.rootRecord&&this.rootRecord.componentModel!==Ru&&(this.disposeNode(this.rootRecord.node),this.rootRecord=void 0,Ru||setValue(this.rootNode,void 0)),Ru&&this.buildRoot()}const $u=this.pendingParents.get(lo.id);if($u){this.pendingParents.delete(lo.id);for(const Ru of $u){const Iu=this.records.get(Ru);Iu&&!Ru.disposed&&this.materialize(Iu)}}}onComponentDeleted(lo){if(this._disposed)return;this.dispatchedErrors.delete(lo);const $u=this.surface.componentsModel.get(lo),Ru=this.nodesByComponentId.get(lo);if(!Ru)return;const Iu=new Set;let Ou=!1;for(const Pu of[...Ru]){const Du=this.records.get(Pu);Du&&(Du.parent?Iu.add(Du.parent):Ou=!0)}Ou&&this.rootRecord&&($u?this.rootRecord.componentModel!==$u&&(this.disposeNode(this.rootRecord.node),this.rootRecord=void 0,this.buildRoot()):(this.disposeNode(this.rootRecord.node),this.rootRecord=void 0,setValue(this.rootNode,void 0)));for(const Pu of Iu){const Du=this.records.get(Pu);Du&&!Pu.disposed&&this.materialize(Du)}}createNode(lo,$u,Ru,Iu,Ou=1){const Pu=this.surface.componentsModel.get(lo);if(!Pu){const qu=this.registerNode(new MutableComponentNode(instanceIdFor(lo,$u,Ou),lo,PLACEHOLDER_TYPE,$u,{},void 0,"pending"),{edgeKey:Ru,parent:Iu,occurrence:Ou,refFields:EMPTY_REF_FIELDS});return Iu&&this.registerPendingParent(lo,Iu),qu.node}const Du=(Pu.catalog?.components.size?Pu.catalog:void 0)??this.catalog,Lu=Du.components.get(Pu.type);if(!Lu)return this.dispatchOnce("UNKNOWN_COMPONENT_TYPE",lo,$u,`Component '${lo}' has type '${Pu.type}', which is not in catalog '${Du.id}'.`),this.registerNode(new MutableComponentNode(instanceIdFor(lo,$u,Ou),lo,Pu.type,$u,{},void 0,"unknown-type"),{edgeKey:Ru,parent:Iu,occurrence:Ou,refFields:EMPTY_REF_FIELDS,componentModel:Pu}).node;this.clearDispatched(lo,$u);const ju=Iu?this.records.get(Iu)?.context?.dataContext:void 0,Bu=new ComponentContext(this.surface,lo,$u,ju),Fu=new GenericBinder(Bu,Lu.schema),zu=this.registerNode(new MutableComponentNode(instanceIdFor(lo,$u,Ou),lo,Pu.type,$u,{},Lu),{edgeKey:Ru,parent:Iu,occurrence:Ou,refFields:extractRefFields(Lu.schema),behavior:scrapeSchemaBehavior(Lu.schema),context:Bu,componentModel:Pu,binder:Fu});return zu.binderSub=Fu.subscribe(qu=>{zu.lastBinderProps=qu,this.materialize(zu)}),zu.lastBinderProps=Fu.snapshot,this.materialize(zu),zu.node}registerNode(lo,$u){const Ru={node:lo,edgeKey:$u.edgeKey,parent:$u.parent,occurrence:$u.occurrence,refFields:$u.refFields,behavior:$u.behavior,context:$u.context,componentModel:$u.componentModel,binder:$u.binder,childEdges:new Map};this.records.set(lo,Ru),this.nodesByEdge.set($u.edgeKey,lo);let Iu=this.nodesByComponentId.get(lo.componentId);return Iu||(Iu=new Set,this.nodesByComponentId.set(lo.componentId,Iu)),Iu.add(lo),Ru}childNode(lo,$u,Ru,Iu,Ou=1){const Pu=this.nodesByEdge.get(Ru);if(this.isCyclic(lo,$u,Iu))return Pu&&!Pu.disposed&&Pu.isPlaceholder&&this.records.get(Pu)?.occurrence===Ou?Pu:(Pu&&!Pu.disposed&&this.disposeNode(Pu),this.dispatchOnce("CYCLIC_REFERENCE",lo,$u,`Component '${lo}' at '${$u}' is referenced by one of its own descendants; rendering a placeholder instead.`),this.registerNode(new MutableComponentNode(instanceIdFor(lo,$u,Ou),lo,PLACEHOLDER_TYPE,$u,{},void 0,"cyclic"),{edgeKey:Ru,parent:Iu,occurrence:Ou,refFields:EMPTY_REF_FIELDS}).node);if(Pu&&!Pu.disposed){const Du=this.surface.componentsModel.get(lo),Lu=(Du?.catalog?.components.size?Du.catalog:void 0)??this.catalog,ju=Du?Lu.components.get(Du.type):void 0,Bu=this.records.get(Pu);if(Pu.componentId===lo&&Pu.dataPath===$u&&Bu?.occurrence===Ou&&(Pu.isPlaceholder?Du===void 0&&Pu.state==="pending"||Du!==void 0&&ju===void 0&&Pu.state==="unknown-type"&&Bu?.componentModel===Du:Du!==void 0&&Pu.type===Du.type&&Bu?.componentModel===Du))return Pu.state==="pending"&&this.registerPendingParent(lo,Iu),Pu;this.disposeNode(Pu)}return this.createNode(lo,$u,Ru,Iu,Ou)}registerPendingParent(lo,$u){let Ru=this.pendingParents.get(lo);Ru||(Ru=new Set,this.pendingParents.set(lo,Ru)),Ru.add($u)}isCyclic(lo,$u,Ru){for(let Iu=Ru;Iu;Iu=this.records.get(Iu)?.parent)if(Iu.componentId===lo&&Iu.dataPath===$u)return!0;return!1}materialize(lo){if(lo.node.disposed)return;const Ru={...lo.lastBinderProps??lo.binder?.snapshot??{}},Iu=new Map,Ou=lo.componentModel?.properties;if(Ou)for(const Bu of lo.refFields.keys())Bu in Ru&&!(Bu in Ou)&&delete Ru[Bu];const Pu=new Map,Du=(Bu,Fu,zu)=>{const qu=`${escapeIdPart(Fu)}@${escapeIdPart(zu)}`,Uu=(Pu.get(qu)??0)+1;Pu.set(qu,Uu);const Hu=`${lo.edgeKey}>${Bu}>${qu}`,Vu=this.childNode(Fu,zu,Hu,lo.node,Uu);return Iu.set(Hu,Vu),Vu};for(const[Bu,Fu]of lo.refFields)switch(Fu.kind){case"single":{const zu=Ru[Bu];typeof zu=="string"&&zu&&(Ru[Bu]=Du(escapeIdPart(Bu),zu,lo.node.dataPath));break}case"list":{const zu=Ru[Bu];if(!Array.isArray(zu))break;const qu=getSafeChildList(zu);Ru[Bu]=qu.map((Uu,Hu)=>{if(typeof Uu=="string"&&Uu)return Du(`${escapeIdPart(Bu)}[${Hu}]`,Uu,lo.node.dataPath);if(Uu&&typeof Uu=="object"&&!Array.isArray(Uu)){const Vu=Uu;if(typeof Vu.id=="string"&&typeof Vu.basePath=="string")return Du(`${escapeIdPart(Bu)}[${Hu}]`,Vu.id,Vu.basePath);if(typeof Vu.componentId=="string"&&Vu.componentId)return Du(`${escapeIdPart(Bu)}[${Hu}]`,Vu.componentId,lo.node.dataPath)}return Uu});break}case"nested":{const zu=Ru[Bu];if(!Array.isArray(zu))break;Ru[Bu]=zu.map((qu,Uu)=>{if(!qu||typeof qu!="object"||Array.isArray(qu))return qu;const Hu={...qu};let Vu=!1;for(const Gu of Fu.keys){const Ku=Hu[Gu];typeof Ku=="string"&&Ku&&(Hu[Gu]=Du(`${escapeIdPart(Bu)}[${Uu}].${escapeIdPart(Gu)}`,Ku,lo.node.dataPath),Vu=!0)}return Vu?Hu:qu});break}}for(const[Bu,Fu]of lo.childEdges)if(!Iu.has(Bu)&&(this.disposeNode(Fu),Fu.isPlaceholder&&![...Iu.values()].some(qu=>qu.isPlaceholder&&qu.componentId===Fu.componentId))){const qu=this.pendingParents.get(Fu.componentId);qu&&(qu.delete(lo.node),qu.size===0&&this.pendingParents.delete(Fu.componentId))}lo.childEdges=Iu;const Lu=lo.behavior&&lo.context?wrapDynamicValues(Ru,lo.behavior,Ou??{},lo.context.dataContext):Ru,ju=peekValue(lo.node.props);for(const Bu of Object.keys(Lu))Lu[Bu]=stabilize(ju[Bu],Lu[Bu]);lo.node.setProps(Lu)}disposeNode(lo){if(lo.disposed)return;const $u=this.records.get(lo);if($u){for(const Iu of $u.childEdges.values())this.disposeNode(Iu);$u.childEdges.clear(),$u.binderSub?.unsubscribe(),$u.binderSub=void 0,this.nodesByEdge.get($u.edgeKey)===lo&&this.nodesByEdge.delete($u.edgeKey),this.records.delete(lo)}const Ru=this.nodesByComponentId.get(lo.componentId);Ru&&(Ru.delete(lo),Ru.size===0&&this.nodesByComponentId.delete(lo.componentId));for(const[Iu,Ou]of this.pendingParents)Ou.delete(lo),Ou.size===0&&this.pendingParents.delete(Iu);lo.state==="cyclic"&&this.clearDispatched(lo.componentId,lo.dataPath),lo.dispose()}}const ID_PART_ESCAPES={"~":"~0","#":"~1","[":"~2","]":"~3",">":"~4","@":"~5"};function escapeIdPart(Au){return Au.replace(/[~#[\]>@]/g,lo=>ID_PART_ESCAPES[lo])}function instanceIdFor(Au,lo,$u){const Ru=lo.replace(/\/+$/,"")||ROOT_DATA_PATH,Iu=lo===ROOT_DATA_PATH?escapeIdPart(Au):`${escapeIdPart(Au)}-[${escapeIdPart(Ru)}]`;return $u>1?`${Iu}#${$u}`:Iu}function wrapDynamicValues(Au,lo,$u,Ru){switch(lo.type){case"DYNAMIC":{const Iu=$u&&typeof $u=="object"&&!Array.isArray($u)&&typeof $u.path=="string"?$u.path:void 0;return Iu===void 0?new ResolvedBinding(Au):new WritableBinding(Au,Ou=>Ru.set(Iu,Ou),Iu)}case"ARRAY":{if(!Array.isArray(Au))return Au;const Iu=Array.isArray($u)?$u:[];return Au.map((Ou,Pu)=>wrapDynamicValues(Ou,lo.element,Iu[Pu],Ru))}case"OBJECT":{if(!Au||typeof Au!="object"||Array.isArray(Au))return Au;const Iu=new Set;for(const[Du,Lu]of Object.entries(lo.shape))Lu.type==="DYNAMIC"&&Iu.add(`set${Du.charAt(0).toUpperCase()}${Du.slice(1)}`);const Ou=$u&&typeof $u=="object"&&!Array.isArray($u)?$u:{},Pu={};for(const[Du,Lu]of Object.entries(Au))Iu.has(Du)||(Pu[Du]=wrapDynamicValues(Lu,lo.shape[Du]??{type:"STATIC"},Ou[Du],Ru));for(const[Du,Lu]of Object.entries(lo.shape))Lu.type==="DYNAMIC"&&!(Du in Pu)&&(Pu[Du]=new ResolvedBinding(void 0));return Pu}default:return Au}}function stabilize(Au,lo){if(Object.is(Au,lo))return lo;if(Au instanceof ResolvedBinding&&lo instanceof ResolvedBinding)return sameBinding(Au,lo)?Au:lo;if(isComponentNode(Au)||isComponentNode(lo))return lo;if(Array.isArray(Au)&&Array.isArray(lo)&&Au.length===lo.length){let $u=!0;const Ru=lo.map((Iu,Ou)=>{const Pu=stabilize(Au[Ou],Iu);return Object.is(Pu,Au[Ou])||($u=!1),Pu});return $u?Au:Ru}if(isPlainObject$1(Au)&&isPlainObject$1(lo)){const $u=Object.keys(Au),Ru=Object.keys(lo);if($u.length===Ru.length){let Iu=!0;const Ou={};for(const Pu of Ru){const Du=stabilize(Au[Pu],lo[Pu]);Ou[Pu]=Du,(!(Pu in Au)||!Object.is(Du,Au[Pu]))&&(Iu=!1)}return Iu?Au:Ou}}return lo}function isPlainObject$1(Au){if(!Au||typeof Au!="object"||Array.isArray(Au)||isComponentNode(Au))return!1;const lo=Object.getPrototypeOf(Au);return lo===Object.prototype||lo===null}const ComponentIdSchema=markChildRef(stringType().describe("REF:#/$defs/ComponentId|The unique identifier for a component, used for both definitions and references within the same surface."),"component-id"),DataBindingSchema=objectType({path:stringType().describe("A JSON Pointer path to a value in the data model.")}).strict().describe("REF:#/$defs/DataBinding"),DynamicValueSchema=unionType([stringType(),numberType(),booleanType(),arrayType(anyType()),DataBindingSchema,lazyType(()=>FunctionCallSchema)]).describe("REF:#/$defs/DynamicValue|A value that can be a literal, a path, or a function call returning any type."),FunctionCallSchema=objectType({call:stringType().describe("The name of the function to call."),args:recordType(stringType(),unionType([DynamicValueSchema,recordType(stringType(),anyType()).describe("A literal object argument (e.g. configuration).")])).describe("Arguments passed to the function.").optional(),returnType:enumType(["string","number","boolean","array","object","any","void"]).describe("The expected return type of the function call.").default("boolean")}).describe("REF:#/$defs/FunctionCall|Invokes a named function on the client."),DynamicStringSchema=unionType([stringType(),DataBindingSchema,FunctionCallSchema]).describe("REF:#/$defs/DynamicString|Represents a string"),AccessibilityAttributesSchema=objectType({label:DynamicStringSchema.optional(),description:DynamicStringSchema.optional()}).describe("REF:#/$defs/AccessibilityAttributes|Attributes to enhance accessibility when using assistive technologies like screen readers.");objectType({id:ComponentIdSchema,accessibility:AccessibilityAttributesSchema.optional()}).describe("REF:#/$defs/ComponentCommon");const ChildListSchema=markChildRef(unionType([arrayType(ComponentIdSchema).describe("A static list of child component IDs."),objectType({componentId:ComponentIdSchema,path:stringType().describe("The path to the list of component property objects in the data model.")}).strict().describe("A template for generating a dynamic list of children from a data model list. The `componentId` is the component to use as a template.")]).describe("REF:#/$defs/ChildList"),"child-list"),DynamicNumberSchema=unionType([numberType(),DataBindingSchema,FunctionCallSchema]).describe("REF:#/$defs/DynamicNumber|Represents a value that can be either a literal number, a path to a number in the data model, or a function call returning a number."),DynamicBooleanSchema=unionType([booleanType(),DataBindingSchema,FunctionCallSchema]).describe("REF:#/$defs/DynamicBoolean|A boolean value that can be a literal, a path, or a function call returning a boolean."),DynamicStringListSchema=unionType([arrayType(stringType()),DataBindingSchema,FunctionCallSchema]).describe("REF:#/$defs/DynamicStringList|Represents a value that can be either a literal array of strings, a path to a string array in the data model, or a function call returning a string array."),CheckRuleSchema=objectType({condition:DynamicBooleanSchema,message:stringType().describe("The error message to display if the check fails.")}).strict().describe("REF:#/$defs/CheckRule|A single validation rule applied to an input component.");objectType({checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional()}).describe("REF:#/$defs/Checkable|Properties for components that support client-side checks.");const ActionSchema=unionType([objectType({event:objectType({name:stringType().describe("The name of the action to be dispatched to the server."),context:recordType(stringType(),DynamicValueSchema).describe("A JSON object containing the key-value pairs for the action context. Values can be literals or paths. Use literal values unless the value must be dynamically bound to the data model. Do NOT use paths for static IDs.").optional()}).strict().describe("The event to dispatch to the server.")}).strict().describe("Triggers a server-side event."),objectType({functionCall:FunctionCallSchema}).strict().describe("Executes a local client-side function.")]).describe("REF:#/$defs/Action|Defines an interaction handler that can either trigger a server-side event or execute a local client-side function."),TextApi={name:"Text",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),text:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The text content to display. While simple Markdown formatting is supported (i.e. without HTML, images, or links), utilizing dedicated UI components is generally preferred for a richer and more structured presentation."),variant:enumType(["h1","h2","h3","h4","h5","caption","body"]).default("body").describe("A hint for the base text style.").optional()}).strict()},ImageApi={name:"Image",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),url:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The URL of the image to display."),description:DynamicStringSchema.describe("REF:#/$defs/DynamicString|Accessibility text for the image.").optional(),fit:enumType(["contain","cover","fill","none","scaleDown"]).default("fill").describe("Specifies how the image should be resized to fit its container. This corresponds to the CSS 'object-fit' property.").optional(),variant:enumType(["icon","avatar","smallFeature","mediumFeature","largeFeature","header"]).default("mediumFeature").describe("A hint for the image size and style.").optional()}).strict()},IconApi={name:"Icon",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),name:unionType([enumType(["accountCircle","add","arrowBack","arrowForward","attachFile","calendarToday","call","camera","check","close","delete","download","edit","event","error","fastForward","favorite","favoriteOff","folder","help","home","info","locationOn","lock","lockOpen","mail","menu","moreVert","moreHoriz","notificationsOff","notifications","pause","payment","person","phone","photo","play","print","refresh","rewind","search","send","settings","share","shoppingCart","skipNext","skipPrevious","star","starHalf","starOff","stop","upload","visibility","visibilityOff","volumeDown","volumeMute","volumeOff","volumeUp","warning"]),objectType({svgPath:stringType()}),DataBindingSchema.describe("REF:#/$defs/DataBinding")]).describe("The name of the icon to display.")}).strict()},VideoApi={name:"Video",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),url:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The URL of the video to display.")}).strict()},AudioPlayerApi={name:"AudioPlayer",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),url:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The URL of the audio to be played."),description:DynamicStringSchema.describe("REF:#/$defs/DynamicString|A description of the audio, such as a title or summary.").optional()}).strict()},RowApi={name:"Row",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),children:ChildListSchema.describe("REF:#/$defs/ChildList|Defines the children. Use an array of strings for a fixed set of children, or a template object to generate children from a data list. Children cannot be defined inline, they must be referred to by ID."),justify:enumType(["center","end","spaceAround","spaceBetween","spaceEvenly","start","stretch"]).default("start").describe("Defines the arrangement of children along the main axis (horizontally). Use 'spaceBetween' to push items to the edges, or 'start'/'end'/'center' to pack them together.").optional(),align:enumType(["start","center","end","stretch"]).default("stretch").describe("Defines the alignment of children along the cross axis (vertically). This is similar to the CSS 'align-items' property, but uses camelCase values (e.g., 'start').").optional()}).strict()},ColumnApi={name:"Column",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),children:ChildListSchema.describe("REF:#/$defs/ChildList|Defines the children. Use an array of strings for a fixed set of children, or a template object to generate children from a data list. Children cannot be defined inline, they must be referred to by ID."),justify:enumType(["start","center","end","spaceBetween","spaceAround","spaceEvenly","stretch"]).default("start").describe("Defines the arrangement of children along the main axis (vertically). Use 'spaceBetween' to push items to the edges (e.g. header at top, footer at bottom), or 'start'/'end'/'center' to pack them together.").optional(),align:enumType(["center","end","start","stretch"]).default("stretch").describe("Defines the alignment of children along the cross axis (horizontally). This is similar to the CSS 'align-items' property.").optional()}).strict()},ListApi={name:"List",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),children:ChildListSchema.describe("REF:#/$defs/ChildList|Defines the children. Use an array of strings for a fixed set of children, or a template object to generate children from a data list."),direction:enumType(["vertical","horizontal"]).default("vertical").describe("The direction in which the list items are laid out.").optional(),align:enumType(["start","center","end","stretch"]).default("stretch").describe("Defines the alignment of children along the cross axis.").optional()}).strict()},CardApi={name:"Card",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),child:ComponentIdSchema.describe("REF:#/$defs/ComponentId|The ID of the single child component to be rendered inside the card. To display multiple elements, you MUST wrap them in a layout component (like Column or Row) and pass that container's ID here. Do NOT pass multiple IDs or a non-existent ID.")}).strict()},TabsApi={name:"Tabs",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),tabs:arrayType(objectType({title:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The tab title."),child:ComponentIdSchema.describe("REF:#/$defs/ComponentId|The ID of the child component.")})).min(1).describe("An array of objects, where each object defines a tab with a title and a child component.")}).strict()},ModalApi={name:"Modal",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),trigger:ComponentIdSchema.describe("REF:#/$defs/ComponentId|The ID of the component that opens the modal when interacted with (e.g., a button)."),content:ComponentIdSchema.describe("REF:#/$defs/ComponentId|The ID of the component to be displayed inside the modal.")}).strict()},DividerApi={name:"Divider",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),axis:enumType(["horizontal","vertical"]).default("horizontal").describe("The orientation of the divider.").optional()}).strict()},ButtonApi={name:"Button",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),child:ComponentIdSchema.describe("REF:#/$defs/ComponentId|The ID of the child component. Use a 'Text' component for a labeled button. Only use an 'Icon' if the requirements explicitly ask for an icon-only button."),variant:enumType(["default","primary","borderless"]).default("default").describe("A hint for the button style. If omitted, a default button style is used. 'primary' indicates this is the main call-to-action button. 'borderless' means the button has no visual border or background, making its child content appear like a clickable link.").optional(),action:ActionSchema.describe("REF:#/$defs/Action")}).strict()},TextFieldApi={name:"TextField",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The text label for the input field."),value:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The value of the text field.").optional(),variant:enumType(["longText","number","shortText","obscured"]).default("shortText").describe("The type of input field to display.").optional(),validationRegexp:stringType().describe("A regular expression used for client-side validation of the input.").optional()}).strict()},CheckBoxApi={name:"CheckBox",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The text to display next to the checkbox."),value:DynamicBooleanSchema.describe("REF:#/$defs/DynamicBoolean|The current state of the checkbox (true for checked, false for unchecked).")}).strict()},ChoicePickerApi={name:"ChoicePicker",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The label for the group of options.").optional(),variant:enumType(["multipleSelection","mutuallyExclusive"]).default("mutuallyExclusive").describe("A hint for how the choice picker should be displayed and behave.").optional(),options:arrayType(objectType({label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The text to display for this option."),value:stringType().describe("The stable value associated with this option.")})).describe("The list of available options to choose from."),value:DynamicStringListSchema.describe("REF:#/$defs/DynamicStringList|The list of currently selected values. This should be bound to a string array in the data model."),displayStyle:enumType(["checkbox","chips"]).default("checkbox").describe("The display style of the component.").optional(),filterable:booleanType().default(!1).describe("If true, displays a search input to filter the options.").optional()}).strict()},SliderApi={name:"Slider",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The label for the slider.").optional(),min:numberType().default(0).describe("The minimum value of the slider.").optional(),max:numberType().describe("The maximum value of the slider."),value:DynamicNumberSchema.describe("REF:#/$defs/DynamicNumber|The current value of the slider.")}).strict()},DateTimeInputApi={name:"DateTimeInput",schema:objectType({accessibility:AccessibilityAttributesSchema.describe("REF:#/$defs/AccessibilityAttributes").optional(),weight:numberType().describe("The relative weight of this component within a Row or Column. This is similar to the CSS 'flex-grow' property. Note: this may ONLY be set when the component is a direct descendant of a Row or Column.").optional(),checks:arrayType(CheckRuleSchema).describe("A list of checks to perform. These are function calls that must return a boolean indicating validity.").optional(),value:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The selected date and/or time value in ISO 8601 format. If not yet set, initialize with an empty string."),enableDate:booleanType().default(!1).describe("If true, allows the user to select a date.").optional(),enableTime:booleanType().default(!1).describe("If true, allows the user to select a time.").optional(),min:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The minimum allowed date/time in ISO 8601 format.").optional(),max:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The maximum allowed date/time in ISO 8601 format.").optional(),label:DynamicStringSchema.describe("REF:#/$defs/DynamicString|The text label for the input field.").optional()}).strict()},DEFAULT_CSS=`
3441
3441
  :where(:root) {
3442
3442
  color-scheme: light dark;
3443
3443
  }
@@ -3541,7 +3541,7 @@ Examples:
3541
3541
  `),lo=lo.replace(NULL_RE,"�"),Au.src=lo}function block(Au){let lo;Au.inlineMode?(lo=new Au.Token("inline","",0),lo.content=Au.src,lo.map=[0,1],lo.children=[],Au.tokens.push(lo)):Au.md.block.parse(Au.src,Au.md,Au.env,Au.tokens)}function inline(Au){const lo=Au.tokens;for(let $u=0,Ru=lo.length;$u<Ru;$u++){const Iu=lo[$u];Iu.type==="inline"&&Au.md.inline.parse(Iu.content,Au.md,Au.env,Iu.children)}}function isLinkOpen$1(Au){return/^<a[>\s]/i.test(Au)}function isLinkClose$1(Au){return/^<\/a\s*>/i.test(Au)}function linkify$1(Au){const lo=Au.tokens;if(Au.md.options.linkify)for(let $u=0,Ru=lo.length;$u<Ru;$u++){if(lo[$u].type!=="inline"||!Au.md.linkify.pretest(lo[$u].content))continue;const Iu=lo[$u].children,Ou=[];let Pu=0;for(let Du=Iu.length-1;Du>=0;Du--){const Lu=Iu[Du];if(Lu.type==="link_close"){for(Du--;Iu[Du].level!==Lu.level&&Iu[Du].type!=="link_open";)Du--;continue}if(Lu.type==="html_inline"&&(isLinkOpen$1(Lu.content)&&Pu>0&&Pu--,isLinkClose$1(Lu.content)&&Pu++),!(Pu>0)&&Lu.type==="text"&&Au.md.linkify.test(Lu.content)){const ju=Lu.content;let Bu=Au.md.linkify.match(ju);const Fu=[];let zu=Lu.level,qu=0;Bu.length>0&&Bu[0].index===0&&Du>0&&Iu[Du-1].type==="text_special"&&(Bu=Bu.slice(1));for(let Uu=0;Uu<Bu.length;Uu++){const Hu=Bu[Uu].url,Vu=Au.md.normalizeLink(Hu);if(!Au.md.validateLink(Vu))continue;let Gu=Bu[Uu].text;Bu[Uu].schema?Bu[Uu].schema==="mailto:"&&!/^mailto:/i.test(Gu)?Gu=Au.md.normalizeLinkText("mailto:"+Gu).replace(/^mailto:/,""):Gu=Au.md.normalizeLinkText(Gu):Gu=Au.md.normalizeLinkText("http://"+Gu).replace(/^http:\/\//,"");const Ku=Bu[Uu].index;if(Ku>qu){const ed=new Au.Token("text","",0);ed.content=ju.slice(qu,Ku),ed.level=zu,Fu.push(ed)}const Zu=new Au.Token("link_open","a",1);Zu.attrs=[["href",Vu]],Zu.level=zu++,Zu.markup="linkify",Zu.info="auto",Fu.push(Zu);const Qu=new Au.Token("text","",0);Qu.content=Gu,Qu.level=zu,Fu.push(Qu);const Yu=new Au.Token("link_close","a",-1);Yu.level=--zu,Yu.markup="linkify",Yu.info="auto",Fu.push(Yu),qu=Bu[Uu].lastIndex}if(qu<ju.length){const Uu=new Au.Token("text","",0);Uu.content=ju.slice(qu),Uu.level=zu,Fu.push(Uu)}Ou.push({index:Du,nodes:Fu})}}if(Ou.length>0){let Du=Iu.length;for(const Fu of Ou)Du+=Fu.nodes.length-1;const Lu=new Array(Du);let ju=0,Bu=0;Ou.reverse();for(let Fu=0;Fu<Iu.length;Fu++){const zu=Ou[ju];if(zu?.index===Fu){for(const qu of zu.nodes)Lu[Bu++]=qu;ju++}else Lu[Bu++]=Iu[Fu]}lo[$u].children=Lu}}}const RARE_RE=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,SCOPED_ABBR_TEST_RE=/\((c|tm|r)\)/i,SCOPED_ABBR_RE=/\((c|tm|r)\)/ig,SCOPED_ABBR={c:"©",r:"®",tm:"™"};function replaceFn(Au,lo){return SCOPED_ABBR[lo.toLowerCase()]}function replace_scoped(Au){let lo=0;for(let $u=Au.length-1;$u>=0;$u--){const Ru=Au[$u];Ru.type==="text"&&!lo&&(Ru.content=Ru.content.replace(SCOPED_ABBR_RE,replaceFn)),Ru.type==="link_open"&&Ru.info==="auto"&&lo--,Ru.type==="link_close"&&Ru.info==="auto"&&lo++}}function replace_rare(Au){let lo=0;for(let $u=Au.length-1;$u>=0;$u--){const Ru=Au[$u];Ru.type==="text"&&!lo&&RARE_RE.test(Ru.content)&&(Ru.content=Ru.content.replace(/\+-/g,"±").replace(/\.{2,}/g,"…").replace(/([?!])…/g,"$1..").replace(/([?!]){4,}/g,"$1$1$1").replace(/,{2,}/g,",").replace(/(^|[^-])---(?=[^-]|$)/mg,"$1—").replace(/(^|\s)--(?=\s|$)/mg,"$1–").replace(/(^|[^-\s])--(?=[^-\s]|$)/mg,"$1–")),Ru.type==="link_open"&&Ru.info==="auto"&&lo--,Ru.type==="link_close"&&Ru.info==="auto"&&lo++}}function replace(Au){let lo;if(Au.md.options.typographer)for(lo=Au.tokens.length-1;lo>=0;lo--)Au.tokens[lo].type==="inline"&&(SCOPED_ABBR_TEST_RE.test(Au.tokens[lo].content)&&replace_scoped(Au.tokens[lo].children),RARE_RE.test(Au.tokens[lo].content)&&replace_rare(Au.tokens[lo].children))}const QUOTE_TEST_RE=/['"]/,QUOTE_RE=/['"]/g,APOSTROPHE="’",MAX_OPENERS=1e3;function truncateStack(Au,lo,$u){for(;Au.length>$u;){const Ru=Au.pop();Ru.isSingleQuote?lo.single=Ru.prevSameQuoteIdx:lo.double=Ru.prevSameQuoteIdx}}function addReplacement(Au,lo,$u,Ru){Au[lo]||(Au[lo]=[]),Au[lo].push({pos:$u,ch:Ru})}function applyReplacements(Au,lo){let $u="",Ru=0;lo.sort((Iu,Ou)=>Iu.pos-Ou.pos);for(let Iu=0;Iu<lo.length;Iu++){const Ou=lo[Iu];$u+=Au.slice(Ru,Ou.pos)+Ou.ch,Ru=Ou.pos+1}return $u+Au.slice(Ru)}function process_inlines(Au,lo){let $u;const Ru=[],Iu={single:-1,double:-1},Ou={};for(let Pu=0;Pu<Au.length;Pu++){const Du=Au[Pu],Lu=Au[Pu].level;for($u=Ru.length-1;$u>=0&&!(Ru[$u].level<=Lu);$u--);if(truncateStack(Ru,Iu,$u+1),Du.type!=="text")continue;const ju=Du.content;let Bu=0;const Fu=ju.length;e:for(;Bu<Fu;){QUOTE_RE.lastIndex=Bu;const zu=QUOTE_RE.exec(ju);if(!zu)break;let qu=!0,Uu=!0;Bu=zu.index+1;const Hu=zu[0]==="'";let Vu=32;if(zu.index-1>=0)Vu=ju.charCodeAt(zu.index-1);else for($u=Pu-1;$u>=0&&!(Au[$u].type==="softbreak"||Au[$u].type==="hardbreak");$u--)if(Au[$u].content){Vu=Au[$u].content.charCodeAt(Au[$u].content.length-1);break}let Gu=32;if(Bu<Fu)Gu=ju.charCodeAt(Bu);else for($u=Pu+1;$u<Au.length&&!(Au[$u].type==="softbreak"||Au[$u].type==="hardbreak");$u++)if(Au[$u].content){Gu=Au[$u].content.charCodeAt(0);break}const Ku=isMdAsciiPunct(Vu)||isPunctCharCode(Vu),Zu=isMdAsciiPunct(Gu)||isPunctCharCode(Gu),Qu=isWhiteSpace(Vu),Yu=isWhiteSpace(Gu);if(Yu?qu=!1:Zu&&(Qu||Ku||(qu=!1)),Qu?Uu=!1:Ku&&(Yu||Zu||(Uu=!1)),Gu===34&&zu[0]==='"'&&Vu>=48&&Vu<=57&&(Uu=qu=!1),qu&&Uu&&(qu=Ku,Uu=Zu),!qu&&!Uu){Hu&&addReplacement(Ou,Pu,zu.index,APOSTROPHE);continue}if(Uu&&($u=Hu?Iu.single:Iu.double,$u>=0&&Ru[$u].level===Lu)){const ed=Ru[$u];let Xu,rd;Hu?(Xu=lo.md.options.quotes[2],rd=lo.md.options.quotes[3]):(Xu=lo.md.options.quotes[0],rd=lo.md.options.quotes[1]),addReplacement(Ou,Pu,zu.index,rd),addReplacement(Ou,ed.tokenIdx,ed.contentPos,Xu),truncateStack(Ru,Iu,$u);continue e}if(qu){if(Ru.length>=MAX_OPENERS)return;Ru.push({tokenIdx:Pu,contentPos:zu.index,isSingleQuote:Hu,level:Lu,prevSameQuoteIdx:Hu?Iu.single:Iu.double}),Hu?Iu.single=Ru.length-1:Iu.double=Ru.length-1}else Uu&&Hu&&addReplacement(Ou,Pu,zu.index,APOSTROPHE)}}Object.keys(Ou).forEach(function(Pu){Au[Pu].content=applyReplacements(Au[Pu].content,Ou[Pu])})}function smartquotes(Au){if(Au.md.options.typographer)for(let lo=Au.tokens.length-1;lo>=0;lo--)Au.tokens[lo].type!=="inline"||!QUOTE_TEST_RE.test(Au.tokens[lo].content)||process_inlines(Au.tokens[lo].children,Au)}function text_join(Au){let lo,$u;const Ru=Au.tokens,Iu=Ru.length;for(let Ou=0;Ou<Iu;Ou++){if(Ru[Ou].type!=="inline")continue;const Pu=Ru[Ou].children,Du=Pu.length;for(lo=0;lo<Du;lo++)Pu[lo].type==="text_special"&&(Pu[lo].type="text");for(lo=$u=0;lo<Du;lo++)Pu[lo].type==="text"&&lo+1<Du&&Pu[lo+1].type==="text"?Pu[lo+1].content=Pu[lo].content+Pu[lo+1].content:(lo!==$u&&(Pu[$u]=Pu[lo]),$u++);lo!==$u&&(Pu.length=$u)}}const _rules$2=[["normalize",normalize],["block",block],["inline",inline],["linkify",linkify$1],["replacements",replace],["smartquotes",smartquotes],["text_join",text_join]];function Core(){this.ruler=new Ruler;for(let Au=0;Au<_rules$2.length;Au++)this.ruler.push(_rules$2[Au][0],_rules$2[Au][1])}Core.prototype.process=function(Au){const lo=this.ruler.getRules("");for(let $u=0,Ru=lo.length;$u<Ru;$u++)lo[$u](Au)};Core.prototype.State=StateCore;function StateBlock(Au,lo,$u,Ru){this.src=Au,this.md=lo,this.env=$u,this.tokens=Ru,this.bMarks=[],this.eMarks=[],this.tShift=[],this.sCount=[],this.bsCount=[],this.blkIndent=0,this.line=0,this.lineMax=0,this.tight=!1,this.ddIndent=-1,this.listIndent=-1,this.parentType="root",this.level=0;const Iu=this.src;for(let Ou=0,Pu=0,Du=0,Lu=0,ju=Iu.length,Bu=!1;Pu<ju;Pu++){const Fu=Iu.charCodeAt(Pu);if(!Bu)if(isSpace(Fu)){Du++,Fu===9?Lu+=4-Lu%4:Lu++;continue}else Bu=!0;(Fu===10||Pu===ju-1)&&(Fu!==10&&Pu++,this.bMarks.push(Ou),this.eMarks.push(Pu),this.tShift.push(Du),this.sCount.push(Lu),this.bsCount.push(0),Bu=!1,Du=0,Lu=0,Ou=Pu+1)}this.bMarks.push(Iu.length),this.eMarks.push(Iu.length),this.tShift.push(0),this.sCount.push(0),this.bsCount.push(0),this.lineMax=this.bMarks.length-1}StateBlock.prototype.push=function(Au,lo,$u){const Ru=new Token(Au,lo,$u);return Ru.block=!0,$u<0&&this.level--,Ru.level=this.level,$u>0&&this.level++,this.tokens.push(Ru),Ru};StateBlock.prototype.isEmpty=function Au(lo){return this.bMarks[lo]+this.tShift[lo]>=this.eMarks[lo]};StateBlock.prototype.skipEmptyLines=function Au(lo){for(let $u=this.lineMax;lo<$u&&!(this.bMarks[lo]+this.tShift[lo]<this.eMarks[lo]);lo++);return lo};StateBlock.prototype.skipSpaces=function Au(lo){for(let $u=this.src.length;lo<$u;lo++){const Ru=this.src.charCodeAt(lo);if(!isSpace(Ru))break}return lo};StateBlock.prototype.skipSpacesBack=function Au(lo,$u){if(lo<=$u)return lo;for(;lo>$u;)if(!isSpace(this.src.charCodeAt(--lo)))return lo+1;return lo};StateBlock.prototype.skipChars=function Au(lo,$u){for(let Ru=this.src.length;lo<Ru&&this.src.charCodeAt(lo)===$u;lo++);return lo};StateBlock.prototype.skipCharsBack=function Au(lo,$u,Ru){if(lo<=Ru)return lo;for(;lo>Ru;)if($u!==this.src.charCodeAt(--lo))return lo+1;return lo};StateBlock.prototype.getLines=function Au(lo,$u,Ru,Iu){if(lo>=$u)return"";const Ou=new Array($u-lo);for(let Pu=0,Du=lo;Du<$u;Du++,Pu++){let Lu=0;const ju=this.bMarks[Du];let Bu=ju,Fu;for(Du+1<$u||Iu?Fu=this.eMarks[Du]+1:Fu=this.eMarks[Du];Bu<Fu&&Lu<Ru;){const zu=this.src.charCodeAt(Bu);if(isSpace(zu))zu===9?Lu+=4-(Lu+this.bsCount[Du])%4:Lu++;else if(Bu-ju<this.tShift[Du])Lu++;else break;Bu++}Lu>Ru?Ou[Pu]=new Array(Lu-Ru+1).join(" ")+this.src.slice(Bu,Fu):Ou[Pu]=this.src.slice(Bu,Fu)}return Ou.join("")};StateBlock.prototype.Token=Token;const MAX_AUTOCOMPLETED_CELLS=65536;function getLine(Au,lo){const $u=Au.bMarks[lo]+Au.tShift[lo],Ru=Au.eMarks[lo];return Au.src.slice($u,Ru)}function escapedSplit(Au){const lo=[],$u=Au.length;let Ru=0,Iu=Au.charCodeAt(Ru),Ou=!1,Pu=0,Du="";for(;Ru<$u;)Iu===124&&(Ou?(Du+=Au.substring(Pu,Ru-1),Pu=Ru):(lo.push(Du+Au.substring(Pu,Ru)),Du="",Pu=Ru+1)),Ou=Iu===92,Ru++,Iu=Au.charCodeAt(Ru);return lo.push(Du+Au.substring(Pu)),lo}function table(Au,lo,$u,Ru){if(lo+2>$u)return!1;let Iu=lo+1;if(Au.sCount[Iu]<Au.blkIndent||Au.sCount[Iu]-Au.blkIndent>=4)return!1;let Ou=Au.bMarks[Iu]+Au.tShift[Iu];if(Ou>=Au.eMarks[Iu])return!1;const Pu=Au.src.charCodeAt(Ou++);if(Pu!==124&&Pu!==45&&Pu!==58||Ou>=Au.eMarks[Iu])return!1;const Du=Au.src.charCodeAt(Ou++);if(Du!==124&&Du!==45&&Du!==58&&!isSpace(Du)||Pu===45&&isSpace(Du))return!1;for(;Ou<Au.eMarks[Iu];){const Qu=Au.src.charCodeAt(Ou);if(Qu!==124&&Qu!==45&&Qu!==58&&!isSpace(Qu))return!1;Ou++}let Lu=getLine(Au,lo+1),ju=Lu.split("|");const Bu=[];for(let Qu=0;Qu<ju.length;Qu++){const Yu=ju[Qu].trim();if(!Yu){if(Qu===0||Qu===ju.length-1)continue;return!1}if(!/^:?-+:?$/.test(Yu))return!1;Yu.charCodeAt(Yu.length-1)===58?Bu.push(Yu.charCodeAt(0)===58?"center":"right"):Yu.charCodeAt(0)===58?Bu.push("left"):Bu.push("")}if(Lu=getLine(Au,lo).trim(),Lu.indexOf("|")===-1||Au.sCount[lo]-Au.blkIndent>=4)return!1;ju=escapedSplit(Lu),ju.length&&ju[0]===""&&ju.shift(),ju.length&&ju[ju.length-1]===""&&ju.pop();const Fu=ju.length;if(Fu===0||Fu!==Bu.length)return!1;if(Ru)return!0;const zu=Au.parentType;Au.parentType="table";const qu=Au.md.block.ruler.getRules("blockquote"),Uu=Au.push("table_open","table",1),Hu=[lo,0];Uu.map=Hu;const Vu=Au.push("thead_open","thead",1);Vu.map=[lo,lo+1];const Gu=Au.push("tr_open","tr",1);Gu.map=[lo,lo+1];for(let Qu=0;Qu<ju.length;Qu++){const Yu=Au.push("th_open","th",1);Bu[Qu]&&(Yu.attrs=[["style","text-align:"+Bu[Qu]]]);const ed=Au.push("inline","",0);ed.content=ju[Qu].trim(),ed.children=[],Au.push("th_close","th",-1)}Au.push("tr_close","tr",-1),Au.push("thead_close","thead",-1);let Ku,Zu=0;for(Iu=lo+2;Iu<$u&&!(Au.sCount[Iu]<Au.blkIndent);Iu++){let Qu=!1;for(let ed=0,Xu=qu.length;ed<Xu;ed++)if(qu[ed](Au,Iu,$u,!0)){Qu=!0;break}if(Qu||(Lu=getLine(Au,Iu).trim(),!Lu)||Au.sCount[Iu]-Au.blkIndent>=4||(ju=escapedSplit(Lu),ju.length&&ju[0]===""&&ju.shift(),ju.length&&ju[ju.length-1]===""&&ju.pop(),Zu+=Fu-ju.length,Zu>MAX_AUTOCOMPLETED_CELLS))break;if(Iu===lo+2){const ed=Au.push("tbody_open","tbody",1);ed.map=Ku=[lo+2,0]}const Yu=Au.push("tr_open","tr",1);Yu.map=[Iu,Iu+1];for(let ed=0;ed<Fu;ed++){const Xu=Au.push("td_open","td",1);Bu[ed]&&(Xu.attrs=[["style","text-align:"+Bu[ed]]]);const rd=Au.push("inline","",0);rd.content=ju[ed]?ju[ed].trim():"",rd.children=[],Au.push("td_close","td",-1)}Au.push("tr_close","tr",-1)}return Ku&&(Au.push("tbody_close","tbody",-1),Ku[1]=Iu),Au.push("table_close","table",-1),Hu[1]=Iu,Au.parentType=zu,Au.line=Iu,!0}function code(Au,lo,$u){if(Au.sCount[lo]-Au.blkIndent<4)return!1;let Ru=lo+1,Iu=Ru;for(;Ru<$u;){if(Au.isEmpty(Ru)){Ru++;continue}if(Au.sCount[Ru]-Au.blkIndent>=4){Ru++,Iu=Ru;continue}break}Au.line=Iu;const Ou=Au.push("code_block","code",0);return Ou.content=Au.getLines(lo,Iu,4+Au.blkIndent,!1)+`
3542
3542
  `,Ou.map=[lo,Au.line],!0}function fence(Au,lo,$u,Ru){let Iu=Au.bMarks[lo]+Au.tShift[lo],Ou=Au.eMarks[lo];if(Au.sCount[lo]-Au.blkIndent>=4||Iu+3>Ou)return!1;const Pu=Au.src.charCodeAt(Iu);if(Pu!==126&&Pu!==96)return!1;let Du=Iu;Iu=Au.skipChars(Iu,Pu);let Lu=Iu-Du;if(Lu<3)return!1;const ju=Au.src.slice(Du,Iu),Bu=Au.src.slice(Iu,Ou);if(Pu===96&&Bu.indexOf(String.fromCharCode(Pu))>=0)return!1;if(Ru)return!0;let Fu=lo,zu=!1;for(;Fu++,!(Fu>=$u||(Iu=Du=Au.bMarks[Fu]+Au.tShift[Fu],Ou=Au.eMarks[Fu],Iu<Ou&&Au.sCount[Fu]<Au.blkIndent));)if(Au.src.charCodeAt(Iu)===Pu&&!(Au.sCount[Fu]-Au.blkIndent>=4)&&(Iu=Au.skipChars(Iu,Pu),!(Iu-Du<Lu)&&(Iu=Au.skipSpaces(Iu),!(Iu<Ou)))){zu=!0;break}Lu=Au.sCount[lo],Au.line=Fu+(zu?1:0);const qu=Au.push("fence","code",0);return qu.info=Bu,qu.content=Au.getLines(lo+1,Fu,Lu,!0),qu.markup=ju,qu.map=[lo,Au.line],!0}function blockquote(Au,lo,$u,Ru){let Iu=Au.bMarks[lo]+Au.tShift[lo],Ou=Au.eMarks[lo];const Pu=Au.lineMax;if(Au.sCount[lo]-Au.blkIndent>=4||Au.src.charCodeAt(Iu)!==62)return!1;if(Ru)return!0;const Du=[],Lu=[],ju=[],Bu=[],Fu=Au.md.block.ruler.getRules("blockquote"),zu=Au.parentType;Au.parentType="blockquote";let qu=!1,Uu;for(Uu=lo;Uu<$u;Uu++){const Zu=Au.sCount[Uu]<Au.blkIndent;if(Iu=Au.bMarks[Uu]+Au.tShift[Uu],Ou=Au.eMarks[Uu],Iu>=Ou)break;if(Au.src.charCodeAt(Iu++)===62&&!Zu){let Yu=Au.sCount[Uu]+1,ed,Xu;Au.src.charCodeAt(Iu)===32?(Iu++,Yu++,Xu=!1,ed=!0):Au.src.charCodeAt(Iu)===9?(ed=!0,(Au.bsCount[Uu]+Yu)%4===3?(Iu++,Yu++,Xu=!1):Xu=!0):ed=!1;let rd=Yu;for(Du.push(Au.bMarks[Uu]),Au.bMarks[Uu]=Iu;Iu<Ou;){const nd=Au.src.charCodeAt(Iu);if(isSpace(nd))nd===9?rd+=4-(rd+Au.bsCount[Uu]+(Xu?1:0))%4:rd++;else break;Iu++}qu=Iu>=Ou,Lu.push(Au.bsCount[Uu]),Au.bsCount[Uu]=Au.sCount[Uu]+1+(ed?1:0),ju.push(Au.sCount[Uu]),Au.sCount[Uu]=rd-Yu,Bu.push(Au.tShift[Uu]),Au.tShift[Uu]=Iu-Au.bMarks[Uu];continue}if(qu)break;let Qu=!1;for(let Yu=0,ed=Fu.length;Yu<ed;Yu++)if(Fu[Yu](Au,Uu,$u,!0)){Qu=!0;break}if(Qu){Au.lineMax=Uu,Au.blkIndent!==0&&(Du.push(Au.bMarks[Uu]),Lu.push(Au.bsCount[Uu]),Bu.push(Au.tShift[Uu]),ju.push(Au.sCount[Uu]),Au.sCount[Uu]-=Au.blkIndent);break}Du.push(Au.bMarks[Uu]),Lu.push(Au.bsCount[Uu]),Bu.push(Au.tShift[Uu]),ju.push(Au.sCount[Uu]),Au.sCount[Uu]=-1}const Hu=Au.blkIndent;Au.blkIndent=0;const Vu=Au.push("blockquote_open","blockquote",1);Vu.markup=">";const Gu=[lo,0];Vu.map=Gu,Au.md.block.tokenize(Au,lo,Uu);const Ku=Au.push("blockquote_close","blockquote",-1);Ku.markup=">",Au.lineMax=Pu,Au.parentType=zu,Gu[1]=Au.line;for(let Zu=0;Zu<Bu.length;Zu++)Au.bMarks[Zu+lo]=Du[Zu],Au.tShift[Zu+lo]=Bu[Zu],Au.sCount[Zu+lo]=ju[Zu],Au.bsCount[Zu+lo]=Lu[Zu];return Au.blkIndent=Hu,!0}function hr(Au,lo,$u,Ru){const Iu=Au.eMarks[lo];if(Au.sCount[lo]-Au.blkIndent>=4)return!1;let Ou=Au.bMarks[lo]+Au.tShift[lo];const Pu=Au.src.charCodeAt(Ou++);if(Pu!==42&&Pu!==45&&Pu!==95)return!1;let Du=1;for(;Ou<Iu;){const ju=Au.src.charCodeAt(Ou++);if(ju!==Pu&&!isSpace(ju))return!1;ju===Pu&&Du++}if(Du<3)return!1;if(Ru)return!0;Au.line=lo+1;const Lu=Au.push("hr","hr",0);return Lu.map=[lo,Au.line],Lu.markup=Array(Du+1).join(String.fromCharCode(Pu)),!0}function skipBulletListMarker(Au,lo){const $u=Au.eMarks[lo];let Ru=Au.bMarks[lo]+Au.tShift[lo];const Iu=Au.src.charCodeAt(Ru++);if(Iu!==42&&Iu!==45&&Iu!==43)return-1;if(Ru<$u){const Ou=Au.src.charCodeAt(Ru);if(!isSpace(Ou))return-1}return Ru}function skipOrderedListMarker(Au,lo){const $u=Au.bMarks[lo]+Au.tShift[lo],Ru=Au.eMarks[lo];let Iu=$u;if(Iu+1>=Ru)return-1;let Ou=Au.src.charCodeAt(Iu++);if(Ou<48||Ou>57)return-1;for(;;){if(Iu>=Ru)return-1;if(Ou=Au.src.charCodeAt(Iu++),Ou>=48&&Ou<=57){if(Iu-$u>=10)return-1;continue}if(Ou===41||Ou===46)break;return-1}return Iu<Ru&&(Ou=Au.src.charCodeAt(Iu),!isSpace(Ou))?-1:Iu}function markTightParagraphs(Au,lo){const $u=Au.level+2;for(let Ru=lo+2,Iu=Au.tokens.length-2;Ru<Iu;Ru++)Au.tokens[Ru].level===$u&&Au.tokens[Ru].type==="paragraph_open"&&(Au.tokens[Ru+2].hidden=!0,Au.tokens[Ru].hidden=!0,Ru+=2)}function list(Au,lo,$u,Ru){let Iu,Ou,Pu,Du,Lu=lo,ju=!0;if(Au.sCount[Lu]-Au.blkIndent>=4||Au.listIndent>=0&&Au.sCount[Lu]-Au.listIndent>=4&&Au.sCount[Lu]<Au.blkIndent)return!1;let Bu=!1;Ru&&Au.parentType==="paragraph"&&Au.sCount[Lu]>=Au.blkIndent&&(Bu=!0);let Fu,zu,qu;if((qu=skipOrderedListMarker(Au,Lu))>=0){if(Fu=!0,Pu=Au.bMarks[Lu]+Au.tShift[Lu],zu=Number(Au.src.slice(Pu,qu-1)),Bu&&zu!==1)return!1}else if((qu=skipBulletListMarker(Au,Lu))>=0)Fu=!1;else return!1;if(Bu&&Au.skipSpaces(qu)>=Au.eMarks[Lu])return!1;if(Ru)return!0;const Uu=Au.src.charCodeAt(qu-1),Hu=Au.tokens.length;Fu?(Du=Au.push("ordered_list_open","ol",1),zu!==1&&(Du.attrs=[["start",zu]])):Du=Au.push("bullet_list_open","ul",1);const Vu=[Lu,0];Du.map=Vu,Du.markup=String.fromCharCode(Uu);let Gu=!1;const Ku=Au.md.block.ruler.getRules("list"),Zu=Au.parentType;for(Au.parentType="list";Lu<$u;){Ou=qu,Iu=Au.eMarks[Lu];const Qu=Au.sCount[Lu]+qu-(Au.bMarks[Lu]+Au.tShift[Lu]);let Yu=Qu;for(;Ou<Iu;){const Sd=Au.src.charCodeAt(Ou);if(Sd===9)Yu+=4-(Yu+Au.bsCount[Lu])%4;else if(Sd===32)Yu++;else break;Ou++}const ed=Ou;let Xu;ed>=Iu?Xu=1:Xu=Yu-Qu,Xu>4&&(Xu=1);const rd=Qu+Xu;Du=Au.push("list_item_open","li",1),Du.markup=String.fromCharCode(Uu);const nd=[Lu,0];Du.map=nd,Fu&&(Du.info=Au.src.slice(Pu,qu-1));const od=Au.tight,ad=Au.tShift[Lu],ld=Au.sCount[Lu],fd=Au.listIndent;if(Au.listIndent=Au.blkIndent,Au.blkIndent=rd,Au.tight=!0,Au.tShift[Lu]=ed-Au.bMarks[Lu],Au.sCount[Lu]=Yu,ed>=Iu&&Au.isEmpty(Lu+1)?Au.line=Math.min(Au.line+2,$u):Au.md.block.tokenize(Au,Lu,$u,!0),(!Au.tight||Gu)&&(ju=!1),Gu=Au.line-Lu>1&&Au.isEmpty(Au.line-1),Au.blkIndent=Au.listIndent,Au.listIndent=fd,Au.tShift[Lu]=ad,Au.sCount[Lu]=ld,Au.tight=od,Du=Au.push("list_item_close","li",-1),Du.markup=String.fromCharCode(Uu),Lu=Au.line,nd[1]=Lu,Lu>=$u||Au.sCount[Lu]<Au.blkIndent||Au.sCount[Lu]-Au.blkIndent>=4)break;let pd=!1;for(let Sd=0,wd=Ku.length;Sd<wd;Sd++)if(Ku[Sd](Au,Lu,$u,!0)){pd=!0;break}if(pd)break;if(Fu){if(qu=skipOrderedListMarker(Au,Lu),qu<0)break;Pu=Au.bMarks[Lu]+Au.tShift[Lu]}else if(qu=skipBulletListMarker(Au,Lu),qu<0)break;if(Uu!==Au.src.charCodeAt(qu-1))break}return Fu?Du=Au.push("ordered_list_close","ol",-1):Du=Au.push("bullet_list_close","ul",-1),Du.markup=String.fromCharCode(Uu),Vu[1]=Lu,Au.line=Lu,Au.parentType=Zu,ju&&markTightParagraphs(Au,Hu),!0}function reference(Au,lo,$u,Ru){let Iu=Au.bMarks[lo]+Au.tShift[lo],Ou=Au.eMarks[lo],Pu=lo+1;if(Au.sCount[lo]-Au.blkIndent>=4||Au.src.charCodeAt(Iu)!==91)return!1;function Du(Ku){const Zu=Au.lineMax;if(Ku>=Zu||Au.isEmpty(Ku))return null;let Qu=!1;if(Au.sCount[Ku]-Au.blkIndent>3&&(Qu=!0),Au.sCount[Ku]<0&&(Qu=!0),!Qu){const Xu=Au.md.block.ruler.getRules("reference"),rd=Au.parentType;Au.parentType="reference";let nd=!1;for(let od=0,ad=Xu.length;od<ad;od++)if(Xu[od](Au,Ku,Zu,!0)){nd=!0;break}if(Au.parentType=rd,nd)return null}const Yu=Au.bMarks[Ku]+Au.tShift[Ku],ed=Au.eMarks[Ku];return Au.src.slice(Yu,ed+1)}let Lu=Au.src.slice(Iu,Ou+1);Ou=Lu.length;let ju=-1;for(Iu=1;Iu<Ou;Iu++){const Ku=Lu.charCodeAt(Iu);if(Ku===91)return!1;if(Ku===93){ju=Iu;break}else if(Ku===10){const Zu=Du(Pu);Zu!==null&&(Lu+=Zu,Ou=Lu.length,Pu++)}else if(Ku===92&&(Iu++,Iu<Ou&&Lu.charCodeAt(Iu)===10)){const Zu=Du(Pu);Zu!==null&&(Lu+=Zu,Ou=Lu.length,Pu++)}}if(ju<0||Lu.charCodeAt(ju+1)!==58)return!1;for(Iu=ju+2;Iu<Ou;Iu++){const Ku=Lu.charCodeAt(Iu);if(Ku===10){const Zu=Du(Pu);Zu!==null&&(Lu+=Zu,Ou=Lu.length,Pu++)}else if(!isSpace(Ku))break}const Bu=Au.md.helpers.parseLinkDestination(Lu,Iu,Ou);if(!Bu.ok)return!1;const Fu=Au.md.normalizeLink(Bu.str);if(!Au.md.validateLink(Fu))return!1;Iu=Bu.pos;const zu=Iu,qu=Pu,Uu=Iu;for(;Iu<Ou;Iu++){const Ku=Lu.charCodeAt(Iu);if(Ku===10){const Zu=Du(Pu);Zu!==null&&(Lu+=Zu,Ou=Lu.length,Pu++)}else if(!isSpace(Ku))break}let Hu=Au.md.helpers.parseLinkTitle(Lu,Iu,Ou);for(;Hu.can_continue;){const Ku=Du(Pu);if(Ku===null)break;Lu+=Ku,Iu=Ou,Ou=Lu.length,Pu++,Hu=Au.md.helpers.parseLinkTitle(Lu,Iu,Ou,Hu)}let Vu;for(Iu<Ou&&Uu!==Iu&&Hu.ok?(Vu=Hu.str,Iu=Hu.pos):(Vu="",Iu=zu,Pu=qu);Iu<Ou;){const Ku=Lu.charCodeAt(Iu);if(!isSpace(Ku))break;Iu++}if(Iu<Ou&&Lu.charCodeAt(Iu)!==10&&Vu)for(Vu="",Iu=zu,Pu=qu;Iu<Ou;){const Ku=Lu.charCodeAt(Iu);if(!isSpace(Ku))break;Iu++}if(Iu<Ou&&Lu.charCodeAt(Iu)!==10)return!1;const Gu=normalizeReference(Lu.slice(1,ju));return Gu?(Ru||(typeof Au.env.references>"u"&&(Au.env.references={}),typeof Au.env.references[Gu]>"u"&&(Au.env.references[Gu]={title:Vu,href:Fu}),Au.line=Pu),!0):!1}const block_names=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],attr_name="[a-zA-Z_:][a-zA-Z0-9:._-]*",unquoted="[^\"'=<>`\\x00-\\x20]+",single_quoted="'[^']*'",double_quoted='"[^"]*"',attr_value="(?:"+unquoted+"|"+single_quoted+"|"+double_quoted+")",attribute="(?:\\s+"+attr_name+"(?:\\s*=\\s*"+attr_value+")?)",open_tag="<[A-Za-z][A-Za-z0-9\\-]*"+attribute+"*\\s*\\/?>",close_tag="<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>",comment="<!---?>|<!--(?:[^-]|-[^-]|--[^>])*-->",processing="<[?][\\s\\S]*?[?]>",declaration="<![A-Za-z][^>]*>",cdata="<!\\[CDATA\\[[\\s\\S]*?\\]\\]>",HTML_TAG_RE=new RegExp("^(?:"+open_tag+"|"+close_tag+"|"+comment+"|"+processing+"|"+declaration+"|"+cdata+")"),HTML_OPEN_CLOSE_TAG_RE=new RegExp("^(?:"+open_tag+"|"+close_tag+")"),HTML_SEQUENCES=[[/^<(script|pre|style|textarea)(?=(\s|>|$))/i,/<\/(script|pre|style|textarea)>/i,!0],[/^<!--/,/-->/,!0],[/^<\?/,/\?>/,!0],[/^<![A-Za-z]/,/>/,!0],[/^<!\[CDATA\[/,/\]\]>/,!0],[new RegExp("^</?("+block_names.join("|")+")(?=(\\s|/?>|$))","i"),/^$/,!0],[new RegExp(HTML_OPEN_CLOSE_TAG_RE.source+"\\s*$"),/^$/,!1]];function html_block(Au,lo,$u,Ru){let Iu=Au.bMarks[lo]+Au.tShift[lo],Ou=Au.eMarks[lo];if(Au.sCount[lo]-Au.blkIndent>=4||!Au.md.options.html||Au.src.charCodeAt(Iu)!==60)return!1;let Pu=Au.src.slice(Iu,Ou),Du=0;for(;Du<HTML_SEQUENCES.length&&!HTML_SEQUENCES[Du][0].test(Pu);Du++);if(Du===HTML_SEQUENCES.length)return!1;if(Ru)return HTML_SEQUENCES[Du][2];let Lu=lo+1;const ju=HTML_SEQUENCES[Du][1].test("");if(!HTML_SEQUENCES[Du][1].test(Pu)){for(;Lu<$u&&!(Au.sCount[Lu]<Au.blkIndent&&(ju||!Au.isEmpty(Lu)));Lu++)if(Iu=Au.bMarks[Lu]+Au.tShift[Lu],Ou=Au.eMarks[Lu],Pu=Au.src.slice(Iu,Ou),HTML_SEQUENCES[Du][1].test(Pu)){Pu.length!==0&&Lu++;break}}Au.line=Lu;const Bu=Au.push("html_block","",0);return Bu.map=[lo,Lu],Bu.content=Au.getLines(lo,Lu,Au.blkIndent,!0),!0}function heading(Au,lo,$u,Ru){let Iu=Au.bMarks[lo]+Au.tShift[lo],Ou=Au.eMarks[lo];if(Au.sCount[lo]-Au.blkIndent>=4)return!1;let Pu=Au.src.charCodeAt(Iu);if(Pu!==35||Iu>=Ou)return!1;let Du=1;for(Pu=Au.src.charCodeAt(++Iu);Pu===35&&Iu<Ou&&Du<=6;)Du++,Pu=Au.src.charCodeAt(++Iu);if(Du>6||Iu<Ou&&!isSpace(Pu))return!1;if(Ru)return!0;Ou=Au.skipSpacesBack(Ou,Iu);const Lu=Au.skipCharsBack(Ou,35,Iu);Lu>Iu&&isSpace(Au.src.charCodeAt(Lu-1))&&(Ou=Lu),Au.line=lo+1;const ju=Au.push("heading_open","h"+String(Du),1);ju.markup="########".slice(0,Du),ju.map=[lo,Au.line];const Bu=Au.push("inline","",0);Bu.content=asciiTrim(Au.src.slice(Iu,Ou)),Bu.map=[lo,Au.line],Bu.children=[];const Fu=Au.push("heading_close","h"+String(Du),-1);return Fu.markup="########".slice(0,Du),!0}function lheading(Au,lo,$u){const Ru=Au.md.block.ruler.getRules("paragraph");if(Au.sCount[lo]-Au.blkIndent>=4)return!1;const Iu=Au.parentType;Au.parentType="paragraph";let Ou=0,Pu,Du=lo+1;for(;Du<$u&&!Au.isEmpty(Du);Du++){if(Au.sCount[Du]-Au.blkIndent>3)continue;if(Au.sCount[Du]>=Au.blkIndent){let qu=Au.bMarks[Du]+Au.tShift[Du];const Uu=Au.eMarks[Du];if(qu<Uu&&(Pu=Au.src.charCodeAt(qu),(Pu===45||Pu===61)&&(qu=Au.skipChars(qu,Pu),qu=Au.skipSpaces(qu),qu>=Uu))){Ou=Pu===61?1:2;break}}if(Au.sCount[Du]<0)continue;let zu=!1;for(let qu=0,Uu=Ru.length;qu<Uu;qu++)if(Ru[qu](Au,Du,$u,!0)){zu=!0;break}if(zu)break}if(!Ou)return Au.parentType=Iu,!1;const Lu=asciiTrim(Au.getLines(lo,Du,Au.blkIndent,!1));Au.line=Du+1;const ju=Au.push("heading_open","h"+String(Ou),1);ju.markup=String.fromCharCode(Pu),ju.map=[lo,Au.line];const Bu=Au.push("inline","",0);Bu.content=Lu,Bu.map=[lo,Au.line-1],Bu.children=[];const Fu=Au.push("heading_close","h"+String(Ou),-1);return Fu.markup=String.fromCharCode(Pu),Au.parentType=Iu,!0}function paragraph(Au,lo,$u){const Ru=Au.md.block.ruler.getRules("paragraph"),Iu=Au.parentType;let Ou=lo+1;for(Au.parentType="paragraph";Ou<$u&&!Au.isEmpty(Ou);Ou++){if(Au.sCount[Ou]-Au.blkIndent>3||Au.sCount[Ou]<0)continue;let ju=!1;for(let Bu=0,Fu=Ru.length;Bu<Fu;Bu++)if(Ru[Bu](Au,Ou,$u,!0)){ju=!0;break}if(ju)break}const Pu=asciiTrim(Au.getLines(lo,Ou,Au.blkIndent,!1));Au.line=Ou;const Du=Au.push("paragraph_open","p",1);Du.map=[lo,Au.line];const Lu=Au.push("inline","",0);return Lu.content=Pu,Lu.map=[lo,Au.line],Lu.children=[],Au.push("paragraph_close","p",-1),Au.parentType=Iu,!0}const _rules$1=[["table",table,["paragraph","reference"]],["code",code],["fence",fence,["paragraph","reference","blockquote","list"]],["blockquote",blockquote,["paragraph","reference","blockquote","list"]],["hr",hr,["paragraph","reference","blockquote","list"]],["list",list,["paragraph","reference","blockquote"]],["reference",reference],["html_block",html_block,["paragraph","reference","blockquote"]],["heading",heading,["paragraph","reference","blockquote"]],["lheading",lheading],["paragraph",paragraph]];function ParserBlock(){this.ruler=new Ruler;for(let Au=0;Au<_rules$1.length;Au++)this.ruler.push(_rules$1[Au][0],_rules$1[Au][1],{alt:(_rules$1[Au][2]||[]).slice()})}ParserBlock.prototype.tokenize=function(Au,lo,$u){const Ru=this.ruler.getRules(""),Iu=Ru.length,Ou=Au.md.options.maxNesting;let Pu=lo,Du=!1;for(;Pu<$u&&(Au.line=Pu=Au.skipEmptyLines(Pu),!(Pu>=$u||Au.sCount[Pu]<Au.blkIndent));){if(Au.level>=Ou){Au.line=$u;break}const Lu=Au.line;let ju=!1;for(let Bu=0;Bu<Iu;Bu++)if(ju=Ru[Bu](Au,Pu,$u,!1),ju){if(Lu>=Au.line)throw new Error("block rule didn't increment state.line");break}if(!ju)throw new Error("none of the block rules matched");Au.tight=!Du,Au.isEmpty(Au.line-1)&&(Du=!0),Pu=Au.line,Pu<$u&&Au.isEmpty(Pu)&&(Du=!0,Pu++,Au.line=Pu)}};ParserBlock.prototype.parse=function(Au,lo,$u,Ru){if(!Au)return;const Iu=new this.State(Au,lo,$u,Ru);this.tokenize(Iu,Iu.line,Iu.lineMax)};ParserBlock.prototype.State=StateBlock;function StateInline(Au,lo,$u,Ru){this.src=Au,this.env=$u,this.md=lo,this.tokens=Ru,this.tokens_meta=Array(Ru.length),this.pos=0,this.posMax=this.src.length,this.level=0,this.pending="",this.pendingLevel=0,this.cache={},this.delimiters=[],this._prev_delimiters=[],this.backticks={},this.backticksScanned=!1,this.linkLevel=0}StateInline.prototype.pushPending=function(){const Au=new Token("text","",0);return Au.content=this.pending,Au.level=this.pendingLevel,this.tokens.push(Au),this.pending="",Au};StateInline.prototype.push=function(Au,lo,$u){this.pending&&this.pushPending();const Ru=new Token(Au,lo,$u);let Iu=null;return $u<0&&(this.level--,this.delimiters=this._prev_delimiters.pop()),Ru.level=this.level,$u>0&&(this.level++,this._prev_delimiters.push(this.delimiters),this.delimiters=[],Iu={delimiters:this.delimiters}),this.pendingLevel=this.level,this.tokens.push(Ru),this.tokens_meta.push(Iu),Ru};StateInline.prototype.scanDelims=function(Au,lo){const $u=this.posMax,Ru=this.src.charCodeAt(Au);let Iu;if(Au===0)Iu=32;else if(Au===1)Iu=this.src.charCodeAt(0),(Iu&63488)===55296&&(Iu=65533);else if(Iu=this.src.charCodeAt(Au-1),(Iu&64512)===56320){const Vu=this.src.charCodeAt(Au-2);Iu=(Vu&64512)===55296?65536+(Vu-55296<<10)+(Iu-56320):65533}else(Iu&64512)===55296&&(Iu=65533);let Ou=Au;for(;Ou<$u&&this.src.charCodeAt(Ou)===Ru;)Ou++;const Pu=Ou-Au;let Du=Ou<$u?this.src.charCodeAt(Ou):32;if((Du&64512)===55296){const Vu=this.src.charCodeAt(Ou+1);Du=(Vu&64512)===56320?65536+(Du-55296<<10)+(Vu-56320):65533}else(Du&64512)===56320&&(Du=65533);const Lu=isMdAsciiPunct(Iu)||isPunctCharCode(Iu),ju=isMdAsciiPunct(Du)||isPunctCharCode(Du),Bu=isWhiteSpace(Iu),Fu=isWhiteSpace(Du),zu=!Fu&&(!ju||Bu||Lu),qu=!Bu&&(!Lu||Fu||ju);return{can_open:zu&&(lo||!qu||Lu),can_close:qu&&(lo||!zu||ju),length:Pu}};StateInline.prototype.Token=Token;function isTerminatorChar(Au){switch(Au){case 10:case 33:case 35:case 36:case 37:case 38:case 42:case 43:case 45:case 58:case 60:case 61:case 62:case 64:case 91:case 92:case 93:case 94:case 95:case 96:case 123:case 125:case 126:return!0;default:return!1}}function text$2(Au,lo){let $u=Au.pos;for(;$u<Au.posMax&&!isTerminatorChar(Au.src.charCodeAt($u));)$u++;return $u===Au.pos?!1:(lo||(Au.pending+=Au.src.slice(Au.pos,$u)),Au.pos=$u,!0)}function isAsciiAlpha(Au){return Au>=65&&Au<=90||Au>=97&&Au<=122}function isSchemeChar(Au){return Au>=65&&Au<=90||Au>=97&&Au<=122||Au>=48&&Au<=57||Au===43||Au===45||Au===46}function linkify(Au,lo){if(!Au.md.options.linkify||Au.linkLevel>0)return!1;const $u=Au.pos,Ru=Au.posMax;if($u+3>Ru||Au.src.charCodeAt($u)!==58||Au.src.charCodeAt($u+1)!==47||Au.src.charCodeAt($u+2)!==47)return!1;const Iu=$u-Math.min(10,Au.pending.length,$u);let Ou=$u;for(;Ou>Iu&&isSchemeChar(Au.src.charCodeAt(Ou-1));)Ou--;if(Ou===$u||!isAsciiAlpha(Au.src.charCodeAt(Ou)))return!1;const Pu=$u-Ou,Du=Au.md.linkify.matchAtStart(Au.src.slice(Ou));if(!Du)return!1;let Lu=Du.url;if(Lu.length<=Pu)return!1;let ju=Lu.length;for(;ju>0&&Lu.charCodeAt(ju-1)===42;)ju--;ju!==Lu.length&&(Lu=Lu.slice(0,ju));const Bu=Au.md.normalizeLink(Lu);if(!Au.md.validateLink(Bu))return!1;if(!lo){Au.pending=Au.pending.slice(0,-Pu);const Fu=Au.push("link_open","a",1);Fu.attrs=[["href",Bu]],Fu.markup="linkify",Fu.info="auto";const zu=Au.push("text","",0);zu.content=Au.md.normalizeLinkText(Lu);const qu=Au.push("link_close","a",-1);qu.markup="linkify",qu.info="auto"}return Au.pos+=Lu.length-Pu,!0}function newline(Au,lo){let $u=Au.pos;if(Au.src.charCodeAt($u)!==10)return!1;const Ru=Au.pending.length-1,Iu=Au.posMax;if(!lo)if(Ru>=0&&Au.pending.charCodeAt(Ru)===32)if(Ru>=1&&Au.pending.charCodeAt(Ru-1)===32){let Ou=Ru-1;for(;Ou>=1&&Au.pending.charCodeAt(Ou-1)===32;)Ou--;Au.pending=Au.pending.slice(0,Ou),Au.push("hardbreak","br",0)}else Au.pending=Au.pending.slice(0,-1),Au.push("softbreak","br",0);else Au.push("softbreak","br",0);for($u++;$u<Iu&&isSpace(Au.src.charCodeAt($u));)$u++;return Au.pos=$u,!0}const ESCAPED=[];for(let Au=0;Au<256;Au++)ESCAPED.push(0);"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach(function(Au){ESCAPED[Au.charCodeAt(0)]=1});function escape$1(Au,lo){let $u=Au.pos;const Ru=Au.posMax;if(Au.src.charCodeAt($u)!==92||($u++,$u>=Ru))return!1;let Iu=Au.src.charCodeAt($u);if(Iu===10){for(lo||Au.push("hardbreak","br",0),$u++;$u<Ru&&(Iu=Au.src.charCodeAt($u),!!isSpace(Iu));)$u++;return Au.pos=$u,!0}if(Iu===32){if(!lo){const Du=Au.push("text_special","",0);Du.content="\\",Du.markup="\\",Du.info="escape"}return Au.pos=$u,!0}let Ou=Au.src[$u];if(Iu>=55296&&Iu<=56319&&$u+1<Ru){const Du=Au.src.charCodeAt($u+1);Du>=56320&&Du<=57343&&(Ou+=Au.src[$u+1],$u++)}const Pu="\\"+Ou;if(!lo){const Du=Au.push("text_special","",0);Iu<256&&ESCAPED[Iu]!==0?Du.content=Ou:Du.content=Pu,Du.markup=Pu,Du.info="escape"}return Au.pos=$u+1,!0}function backtick(Au,lo){let $u=Au.pos;if(Au.src.charCodeAt($u)!==96)return!1;const Iu=$u;$u++;const Ou=Au.posMax;for(;$u<Ou&&Au.src.charCodeAt($u)===96;)$u++;const Pu=Au.src.slice(Iu,$u),Du=Pu.length;if(Au.backticksScanned&&(Au.backticks[Du]||0)<=Iu)return lo||(Au.pending+=Pu),Au.pos+=Du,!0;let Lu=$u,ju;for(;(ju=Au.src.indexOf("`",Lu))!==-1;){for(Lu=ju+1;Lu<Ou&&Au.src.charCodeAt(Lu)===96;)Lu++;const Bu=Lu-ju;if(Bu===Du){if(!lo){const Fu=Au.push("code_inline","code",0);Fu.markup=Pu,Fu.content=Au.src.slice($u,ju).replace(/\n/g," ").replace(/^ (.+) $/,"$1")}return Au.pos=Lu,!0}Au.backticks[Bu]=ju}return Au.backticksScanned=!0,lo||(Au.pending+=Pu),Au.pos+=Du,!0}function strikethrough_tokenize(Au,lo){const $u=Au.pos,Ru=Au.src.charCodeAt($u);if(lo||Ru!==126)return!1;const Iu=Au.scanDelims(Au.pos,!0);let Ou=Iu.length;const Pu=String.fromCharCode(Ru);if(Ou<2)return!1;let Du;Ou%2&&(Du=Au.push("text","",0),Du.content=Pu,Ou--);for(let Lu=0;Lu<Ou;Lu+=2)Du=Au.push("text","",0),Du.content=Pu+Pu,Au.delimiters.push({marker:Ru,length:0,token:Au.tokens.length-1,end:-1,open:Iu.can_open,close:Iu.can_close});return Au.pos+=Iu.length,!0}function postProcess$1(Au,lo){let $u;const Ru=[],Iu=lo.length;for(let Ou=0;Ou<Iu;Ou++){const Pu=lo[Ou];if(Pu.marker!==126||Pu.end===-1)continue;const Du=lo[Pu.end];$u=Au.tokens[Pu.token],$u.type="s_open",$u.tag="s",$u.nesting=1,$u.markup="~~",$u.content="",$u=Au.tokens[Du.token],$u.type="s_close",$u.tag="s",$u.nesting=-1,$u.markup="~~",$u.content="",Au.tokens[Du.token-1].type==="text"&&Au.tokens[Du.token-1].content==="~"&&Ru.push(Du.token-1)}for(;Ru.length;){const Ou=Ru.pop();let Pu=Ou+1;for(;Pu<Au.tokens.length&&Au.tokens[Pu].type==="s_close";)Pu++;Pu--,Ou!==Pu&&($u=Au.tokens[Pu],Au.tokens[Pu]=Au.tokens[Ou],Au.tokens[Ou]=$u)}}function strikethrough_postProcess(Au){const lo=Au.tokens_meta,$u=Au.tokens_meta.length;postProcess$1(Au,Au.delimiters);for(let Ru=0;Ru<$u;Ru++)lo[Ru]&&lo[Ru].delimiters&&postProcess$1(Au,lo[Ru].delimiters)}const r_strikethrough={tokenize:strikethrough_tokenize,postProcess:strikethrough_postProcess};function emphasis_tokenize(Au,lo){const $u=Au.pos,Ru=Au.src.charCodeAt($u);if(lo||Ru!==95&&Ru!==42)return!1;const Iu=Au.scanDelims(Au.pos,Ru===42);for(let Ou=0;Ou<Iu.length;Ou++){const Pu=Au.push("text","",0);Pu.content=String.fromCharCode(Ru),Au.delimiters.push({marker:Ru,length:Iu.length,token:Au.tokens.length-1,end:-1,open:Iu.can_open,close:Iu.can_close})}return Au.pos+=Iu.length,!0}function postProcess(Au,lo){const $u=lo.length;for(let Ru=$u-1;Ru>=0;Ru--){const Iu=lo[Ru];if(Iu.marker!==95&&Iu.marker!==42||Iu.end===-1)continue;const Ou=lo[Iu.end],Pu=Ru>0&&lo[Ru-1].end===Iu.end+1&&lo[Ru-1].marker===Iu.marker&&lo[Ru-1].token===Iu.token-1&&lo[Iu.end+1].token===Ou.token+1,Du=String.fromCharCode(Iu.marker),Lu=Au.tokens[Iu.token];Lu.type=Pu?"strong_open":"em_open",Lu.tag=Pu?"strong":"em",Lu.nesting=1,Lu.markup=Pu?Du+Du:Du,Lu.content="";const ju=Au.tokens[Ou.token];ju.type=Pu?"strong_close":"em_close",ju.tag=Pu?"strong":"em",ju.nesting=-1,ju.markup=Pu?Du+Du:Du,ju.content="",Pu&&(Au.tokens[lo[Ru-1].token].content="",Au.tokens[lo[Iu.end+1].token].content="",Ru--)}}function emphasis_post_process(Au){const lo=Au.tokens_meta,$u=Au.tokens_meta.length;postProcess(Au,Au.delimiters);for(let Ru=0;Ru<$u;Ru++)lo[Ru]&&lo[Ru].delimiters&&postProcess(Au,lo[Ru].delimiters)}const r_emphasis={tokenize:emphasis_tokenize,postProcess:emphasis_post_process};function link(Au,lo){let $u,Ru,Iu,Ou,Pu="",Du="",Lu=Au.pos,ju=!0;if(Au.src.charCodeAt(Au.pos)!==91)return!1;const Bu=Au.pos,Fu=Au.posMax,zu=Au.pos+1,qu=Au.md.helpers.parseLinkLabel(Au,Au.pos,!0);if(qu<0)return!1;let Uu=qu+1;if(Uu<Fu&&Au.src.charCodeAt(Uu)===40){for(ju=!1,Uu++;Uu<Fu&&($u=Au.src.charCodeAt(Uu),!(!isSpace($u)&&$u!==10));Uu++);if(Uu>=Fu)return!1;if(Lu=Uu,Iu=Au.md.helpers.parseLinkDestination(Au.src,Uu,Au.posMax),Iu.ok){for(Pu=Au.md.normalizeLink(Iu.str),Au.md.validateLink(Pu)?Uu=Iu.pos:Pu="",Lu=Uu;Uu<Fu&&($u=Au.src.charCodeAt(Uu),!(!isSpace($u)&&$u!==10));Uu++);if(Iu=Au.md.helpers.parseLinkTitle(Au.src,Uu,Au.posMax),Uu<Fu&&Lu!==Uu&&Iu.ok)for(Du=Iu.str,Uu=Iu.pos;Uu<Fu&&($u=Au.src.charCodeAt(Uu),!(!isSpace($u)&&$u!==10));Uu++);}(Uu>=Fu||Au.src.charCodeAt(Uu)!==41)&&(ju=!0),Uu++}if(ju){if(typeof Au.env.references>"u")return!1;if(Uu<Fu&&Au.src.charCodeAt(Uu)===91?(Lu=Uu+1,Uu=Au.md.helpers.parseLinkLabel(Au,Uu),Uu>=0?Ru=Au.src.slice(Lu,Uu++):Uu=qu+1):Uu=qu+1,Ru||(Ru=Au.src.slice(zu,qu)),Ou=Au.env.references[normalizeReference(Ru)],!Ou)return Au.pos=Bu,!1;Pu=Ou.href,Du=Ou.title}if(!lo){Au.pos=zu,Au.posMax=qu;const Hu=Au.push("link_open","a",1),Vu=[["href",Pu]];Hu.attrs=Vu,Du&&Vu.push(["title",Du]),Au.linkLevel++,Au.md.inline.tokenize(Au),Au.linkLevel--,Au.push("link_close","a",-1)}return Au.pos=Uu,Au.posMax=Fu,!0}function image(Au,lo){let $u,Ru,Iu,Ou,Pu,Du,Lu,ju,Bu="";const Fu=Au.pos,zu=Au.posMax;if(Au.src.charCodeAt(Au.pos)!==33||Au.src.charCodeAt(Au.pos+1)!==91)return!1;const qu=Au.pos+2,Uu=Au.md.helpers.parseLinkLabel(Au,Au.pos+1,!1);if(Uu<0)return!1;if(Ou=Uu+1,Ou<zu&&Au.src.charCodeAt(Ou)===40){for(Ou++;Ou<zu&&($u=Au.src.charCodeAt(Ou),!(!isSpace($u)&&$u!==10));Ou++);if(Ou>=zu)return!1;for(ju=Ou,Du=Au.md.helpers.parseLinkDestination(Au.src,Ou,Au.posMax),Du.ok&&(Bu=Au.md.normalizeLink(Du.str),Au.md.validateLink(Bu)?Ou=Du.pos:Bu=""),ju=Ou;Ou<zu&&($u=Au.src.charCodeAt(Ou),!(!isSpace($u)&&$u!==10));Ou++);if(Du=Au.md.helpers.parseLinkTitle(Au.src,Ou,Au.posMax),Ou<zu&&ju!==Ou&&Du.ok)for(Lu=Du.str,Ou=Du.pos;Ou<zu&&($u=Au.src.charCodeAt(Ou),!(!isSpace($u)&&$u!==10));Ou++);else Lu="";if(Ou>=zu||Au.src.charCodeAt(Ou)!==41)return Au.pos=Fu,!1;Ou++}else{if(typeof Au.env.references>"u")return!1;if(Ou<zu&&Au.src.charCodeAt(Ou)===91?(ju=Ou+1,Ou=Au.md.helpers.parseLinkLabel(Au,Ou),Ou>=0?Iu=Au.src.slice(ju,Ou++):Ou=Uu+1):Ou=Uu+1,Iu||(Iu=Au.src.slice(qu,Uu)),Pu=Au.env.references[normalizeReference(Iu)],!Pu)return Au.pos=Fu,!1;Bu=Pu.href,Lu=Pu.title}if(!lo){Ru=Au.src.slice(qu,Uu);const Hu=[];Au.md.inline.parse(Ru,Au.md,Au.env,Hu);const Vu=Au.push("image","img",0),Gu=[["src",Bu],["alt",""]];Vu.attrs=Gu,Vu.children=Hu,Vu.content=Ru,Lu&&Gu.push(["title",Lu])}return Au.pos=Ou,Au.posMax=zu,!0}const EMAIL_RE=/^([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/,AUTOLINK_RE=/^([a-zA-Z][a-zA-Z0-9+.-]{1,31}):([^<>\x00-\x20]*)$/;function autolink(Au,lo){let $u=Au.pos;if(Au.src.charCodeAt($u)!==60)return!1;const Ru=Au.pos,Iu=Au.posMax;for(;;){if(++$u>=Iu)return!1;const Pu=Au.src.charCodeAt($u);if(Pu===60)return!1;if(Pu===62)break}const Ou=Au.src.slice(Ru+1,$u);if(AUTOLINK_RE.test(Ou)){const Pu=Au.md.normalizeLink(Ou);if(!Au.md.validateLink(Pu))return!1;if(!lo){const Du=Au.push("link_open","a",1);Du.attrs=[["href",Pu]],Du.markup="autolink",Du.info="auto";const Lu=Au.push("text","",0);Lu.content=Au.md.normalizeLinkText(Ou);const ju=Au.push("link_close","a",-1);ju.markup="autolink",ju.info="auto"}return Au.pos+=Ou.length+2,!0}if(EMAIL_RE.test(Ou)){const Pu=Au.md.normalizeLink("mailto:"+Ou);if(!Au.md.validateLink(Pu))return!1;if(!lo){const Du=Au.push("link_open","a",1);Du.attrs=[["href",Pu]],Du.markup="autolink",Du.info="auto";const Lu=Au.push("text","",0);Lu.content=Au.md.normalizeLinkText(Ou);const ju=Au.push("link_close","a",-1);ju.markup="autolink",ju.info="auto"}return Au.pos+=Ou.length+2,!0}return!1}function isLinkOpen(Au){return/^<a[>\s]/i.test(Au)}function isLinkClose(Au){return/^<\/a\s*>/i.test(Au)}function isLetter(Au){const lo=Au|32;return lo>=97&&lo<=122}function html_inline(Au,lo){if(!Au.md.options.html)return!1;const $u=Au.posMax,Ru=Au.pos;if(Au.src.charCodeAt(Ru)!==60||Ru+2>=$u)return!1;const Iu=Au.src.charCodeAt(Ru+1);if(Iu!==33&&Iu!==63&&Iu!==47&&!isLetter(Iu))return!1;const Ou=Au.src.slice(Ru).match(HTML_TAG_RE);if(!Ou)return!1;if(!lo){const Pu=Au.push("html_inline","",0);Pu.content=Ou[0],isLinkOpen(Pu.content)&&Au.linkLevel++,isLinkClose(Pu.content)&&Au.linkLevel--}return Au.pos+=Ou[0].length,!0}const DIGITAL_RE=/^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i,NAMED_RE=/^&([a-z][a-z0-9]{1,31});/i;function entity(Au,lo){const $u=Au.pos,Ru=Au.posMax;if(Au.src.charCodeAt($u)!==38||$u+1>=Ru)return!1;if(Au.src.charCodeAt($u+1)===35){const Ou=Au.src.slice($u).match(DIGITAL_RE);if(Ou){if(!lo){const Pu=Ou[1][0].toLowerCase()==="x"?parseInt(Ou[1].slice(1),16):parseInt(Ou[1],10),Du=Au.push("text_special","",0);Du.content=isValidEntityCode(Pu)?fromCodePoint(Pu):fromCodePoint(65533),Du.markup=Ou[0],Du.info="entity"}return Au.pos+=Ou[0].length,!0}}else{const Ou=Au.src.slice($u).match(NAMED_RE);if(Ou){const Pu=decodeHTMLStrict(Ou[0]);if(Pu!==Ou[0]){if(!lo){const Du=Au.push("text_special","",0);Du.content=Pu,Du.markup=Ou[0],Du.info="entity"}return Au.pos+=Ou[0].length,!0}}}return!1}function processDelimiters(Au){const lo={},$u=Au.length;if(!$u)return;let Ru=0,Iu=-2;const Ou=[];for(let Pu=0;Pu<$u;Pu++){const Du=Au[Pu];if(Ou.push(0),(Au[Ru].marker!==Du.marker||Iu!==Du.token-1)&&(Ru=Pu),Iu=Du.token,Du.length=Du.length||0,!Du.close)continue;lo.hasOwnProperty(Du.marker)||(lo[Du.marker]=[-1,-1,-1,-1,-1,-1]);const Lu=lo[Du.marker][(Du.open?3:0)+Du.length%3];let ju=Ru-Ou[Ru]-1,Bu=ju;for(;ju>Lu;ju-=Ou[ju]+1){const Fu=Au[ju];if(Fu.marker===Du.marker&&Fu.open&&Fu.end<0){let zu=!1;if((Fu.close||Du.open)&&(Fu.length+Du.length)%3===0&&(Fu.length%3!==0||Du.length%3!==0)&&(zu=!0),!zu){const qu=ju>0&&!Au[ju-1].open?Ou[ju-1]+1:0;Ou[Pu]=Pu-ju+qu,Ou[ju]=qu,Du.open=!1,Fu.end=Pu,Fu.close=!1,Bu=-1,Iu=-2;break}}}Bu!==-1&&(lo[Du.marker][(Du.open?3:0)+(Du.length||0)%3]=Bu)}}function link_pairs(Au){const lo=Au.tokens_meta,$u=Au.tokens_meta.length;processDelimiters(Au.delimiters);for(let Ru=0;Ru<$u;Ru++)lo[Ru]&&lo[Ru].delimiters&&processDelimiters(lo[Ru].delimiters)}function fragments_join(Au){let lo,$u,Ru=0;const Iu=Au.tokens,Ou=Au.tokens.length;for(lo=$u=0;lo<Ou;lo++)Iu[lo].nesting<0&&Ru--,Iu[lo].level=Ru,Iu[lo].nesting>0&&Ru++,Iu[lo].type==="text"&&lo+1<Ou&&Iu[lo+1].type==="text"?Iu[lo+1].content=Iu[lo].content+Iu[lo+1].content:(lo!==$u&&(Iu[$u]=Iu[lo]),$u++);lo!==$u&&(Iu.length=$u)}const _rules=[["text",text$2],["linkify",linkify],["newline",newline],["escape",escape$1],["backticks",backtick],["strikethrough",r_strikethrough.tokenize],["emphasis",r_emphasis.tokenize],["link",link],["image",image],["autolink",autolink],["html_inline",html_inline],["entity",entity]],_rules2=[["balance_pairs",link_pairs],["strikethrough",r_strikethrough.postProcess],["emphasis",r_emphasis.postProcess],["fragments_join",fragments_join]];function ParserInline(){this.ruler=new Ruler;for(let Au=0;Au<_rules.length;Au++)this.ruler.push(_rules[Au][0],_rules[Au][1]);this.ruler2=new Ruler;for(let Au=0;Au<_rules2.length;Au++)this.ruler2.push(_rules2[Au][0],_rules2[Au][1])}ParserInline.prototype.skipToken=function(Au){const lo=Au.pos,$u=this.ruler.getRules(""),Ru=$u.length,Iu=Au.md.options.maxNesting,Ou=Au.cache;if(typeof Ou[lo]<"u"){Au.pos=Ou[lo];return}let Pu=!1;if(Au.level<Iu){for(let Du=0;Du<Ru;Du++)if(Au.level++,Pu=$u[Du](Au,!0),Au.level--,Pu){if(lo>=Au.pos)throw new Error("inline rule didn't increment state.pos");break}}else Au.pos=Au.posMax;Pu||Au.pos++,Ou[lo]=Au.pos};ParserInline.prototype.tokenize=function(Au){const lo=this.ruler.getRules(""),$u=lo.length,Ru=Au.posMax,Iu=Au.md.options.maxNesting;for(;Au.pos<Ru;){const Ou=Au.pos;let Pu=!1;if(Au.level<Iu){for(let Du=0;Du<$u;Du++)if(Pu=lo[Du](Au,!1),Pu){if(Ou>=Au.pos)throw new Error("inline rule didn't increment state.pos");break}}if(Pu){if(Au.pos>=Ru)break;continue}Au.pending+=Au.src[Au.pos++]}Au.pending&&Au.pushPending()};ParserInline.prototype.parse=function(Au,lo,$u,Ru){const Iu=new this.State(Au,lo,$u,Ru);this.tokenize(Iu);const Ou=this.ruler2.getRules(""),Pu=Ou.length;for(let Du=0;Du<Pu;Du++)Ou[Du](Iu)};ParserInline.prototype.State=StateInline;function reFactory(Au){const lo={};Au=Au||{},lo.src_Any=Any.source,lo.src_Cc=Cc.source,lo.src_Z=Z.source,lo.src_P=P.source,lo.src_ZPCc=[lo.src_Z,lo.src_P,lo.src_Cc].join("|"),lo.src_ZCc=[lo.src_Z,lo.src_Cc].join("|");const $u="[><|]";return lo.src_pseudo_letter=`(?:(?!${$u}|${lo.src_ZPCc})${lo.src_Any})`,lo.src_ip4="(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)",lo.src_auth=`(?:(?:(?!${lo.src_ZCc}|[@/\\[\\]()]).){1,50}@)?`,lo.src_port="(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?",lo.src_host_terminator=`(?=$|${$u}|${lo.src_ZPCc})(?!${Au["---"]?"-(?!--)|":"-|"}_|:\\d|\\.-|\\.(?!$|${lo.src_ZPCc}))`,lo.src_path=`(?:[/?#](?:(?!${lo.src_ZCc}|${$u}|[()[\\]{}.,"'?!\\-;]).|\\[(?:(?!${lo.src_ZCc}|\\]).)*\\]|\\((?:(?!${lo.src_ZCc}|[)]).)*\\)|\\{(?:(?!${lo.src_ZCc}|[}]).)*\\}|\\"(?:(?!${lo.src_ZCc}|["]).)+\\"|\\'(?:(?!${lo.src_ZCc}|[']).)+\\'|\\'(?=${lo.src_pseudo_letter}|[-])|\\.{2,}[a-zA-Z0-9%/&]|\\.(?!${lo.src_ZCc}|[.]|$)|`+(Au["---"]?"\\-(?!--(?:[^-]|$))(?:-*)|":"\\-+|")+`,(?!${lo.src_ZCc}|$)|;(?!${lo.src_ZCc}|$)|\\!+(?!${lo.src_ZCc}|[!]|$)|\\?(?!${lo.src_ZCc}|[?]|$))+|\\/)?`,lo.src_email_name='[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]{0,63}',lo.src_xn="xn--[a-z0-9\\-]{1,59}",lo.src_domain_root="(?:"+lo.src_xn+`|${lo.src_pseudo_letter}{1,63})`,lo.src_domain="(?:"+lo.src_xn+`|(?:${lo.src_pseudo_letter})|(?:${lo.src_pseudo_letter}(?:-|${lo.src_pseudo_letter}){0,61}${lo.src_pseudo_letter}))`,lo.src_host=`(?:(?:(?:(?:${lo.src_domain})\\.)*${lo.src_domain}))`,lo.tpl_host_fuzzy="(?:"+lo.src_ip4+`|(?:(?:(?:${lo.src_domain})\\.)+(?:%TLDS%)))`,lo.tpl_host_no_ip_fuzzy=`(?:(?:(?:${lo.src_domain})\\.)+(?:%TLDS%))`,lo.src_host_strict=lo.src_host+lo.src_host_terminator,lo.tpl_host_fuzzy_strict=lo.tpl_host_fuzzy+lo.src_host_terminator,lo.src_host_port_strict=lo.src_host+lo.src_port+lo.src_host_terminator,lo.tpl_host_port_fuzzy_strict=lo.tpl_host_fuzzy+lo.src_port+lo.src_host_terminator,lo.tpl_host_port_no_ip_fuzzy_strict=lo.tpl_host_no_ip_fuzzy+lo.src_port+lo.src_host_terminator,lo.tpl_host_fuzzy_test=`localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:${lo.src_ZPCc}|>|$))`,lo.tpl_email_fuzzy=`(^|${$u}|"|\\(|${lo.src_ZCc})(${lo.src_email_name}@${lo.tpl_host_fuzzy_strict})`,lo.tpl_link_fuzzy=`(^|(?![.:/\\-_@])(?:[$+<=>^\`||]|${lo.src_ZPCc}))((?![$+<=>^\`||])${lo.tpl_host_port_fuzzy_strict}${lo.src_path})`,lo.tpl_link_no_ip_fuzzy=`(^|(?![.:/\\-_@])(?:[$+<=>^\`||]|${lo.src_ZPCc}))((?![$+<=>^\`||])${lo.tpl_host_port_no_ip_fuzzy_strict}${lo.src_path})`,lo}function assign(Au){return Array.prototype.slice.call(arguments,1).forEach(function($u){$u&&Object.keys($u).forEach(function(Ru){Au[Ru]=$u[Ru]})}),Au}function _class(Au){return Object.prototype.toString.call(Au)}function isString(Au){return _class(Au)==="[object String]"}function isObject(Au){return _class(Au)==="[object Object]"}function isRegExp(Au){return _class(Au)==="[object RegExp]"}function isFunction(Au){return _class(Au)==="[object Function]"}function escapeRE(Au){return Au.replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}const defaultOptions={fuzzyLink:!0,fuzzyEmail:!0,fuzzyIP:!1};function isOptionsObj(Au){return Object.keys(Au||{}).reduce(function(lo,$u){return lo||defaultOptions.hasOwnProperty($u)},!1)}const defaultSchemas={"http:":{validate:function(Au,lo,$u){const Ru=Au.slice(lo);return $u.re.http||($u.re.http=new RegExp(`^\\/\\/${$u.re.src_auth}${$u.re.src_host_port_strict}${$u.re.src_path}`,"i")),$u.re.http.test(Ru)?Ru.match($u.re.http)[0].length:0}},"https:":"http:","ftp:":"http:","//":{validate:function(Au,lo,$u){const Ru=Au.slice(lo);return $u.re.no_http||($u.re.no_http=new RegExp("^"+$u.re.src_auth+`(?:localhost|(?:(?:${$u.re.src_domain})\\.)+${$u.re.src_domain_root})`+$u.re.src_port+$u.re.src_host_terminator+$u.re.src_path,"i")),$u.re.no_http.test(Ru)?lo>=3&&Au[lo-3]===":"||lo>=3&&Au[lo-3]==="/"?0:Ru.match($u.re.no_http)[0].length:0}},"mailto:":{validate:function(Au,lo,$u){const Ru=Au.slice(lo);return $u.re.mailto||($u.re.mailto=new RegExp(`^${$u.re.src_email_name}@${$u.re.src_host_strict}`,"i")),$u.re.mailto.test(Ru)?Ru.match($u.re.mailto)[0].length:0}}},tlds_2ch_src_re="a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]",tlds_default="biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф".split("|");function createValidator(Au){return function(lo,$u){const Ru=lo.slice($u);return Au.test(Ru)?Ru.match(Au)[0].length:0}}function createNormalizer(){return function(Au,lo){lo.normalize(Au)}}function compile(Au){const lo=Au.re=reFactory(Au.__opts__),$u=Au.__tlds__.slice();Au.onCompile(),Au.__tlds_replaced__||$u.push(tlds_2ch_src_re),$u.push(lo.src_xn),lo.src_tlds=$u.join("|");function Ru(Du){return Du.replace("%TLDS%",lo.src_tlds)}lo.email_fuzzy=RegExp(Ru(lo.tpl_email_fuzzy),"i"),lo.email_fuzzy_global=RegExp(Ru(lo.tpl_email_fuzzy),"ig"),lo.link_fuzzy=RegExp(Ru(lo.tpl_link_fuzzy),"i"),lo.link_fuzzy_global=RegExp(Ru(lo.tpl_link_fuzzy),"ig"),lo.link_no_ip_fuzzy=RegExp(Ru(lo.tpl_link_no_ip_fuzzy),"i"),lo.link_no_ip_fuzzy_global=RegExp(Ru(lo.tpl_link_no_ip_fuzzy),"ig"),lo.host_fuzzy_test=RegExp(Ru(lo.tpl_host_fuzzy_test),"i");const Iu=[];Au.__compiled__={};function Ou(Du,Lu){throw new Error(`(LinkifyIt) Invalid schema "${Du}": ${Lu}`)}Object.keys(Au.__schemas__).forEach(function(Du){const Lu=Au.__schemas__[Du];if(Lu===null)return;const ju={validate:null,link:null};if(Au.__compiled__[Du]=ju,isObject(Lu)){isRegExp(Lu.validate)?ju.validate=createValidator(Lu.validate):isFunction(Lu.validate)?ju.validate=Lu.validate:Ou(Du,Lu),isFunction(Lu.normalize)?ju.normalize=Lu.normalize:Lu.normalize?Ou(Du,Lu):ju.normalize=createNormalizer();return}if(isString(Lu)){Iu.push(Du);return}Ou(Du,Lu)}),Iu.forEach(function(Du){Au.__compiled__[Au.__schemas__[Du]]&&(Au.__compiled__[Du].validate=Au.__compiled__[Au.__schemas__[Du]].validate,Au.__compiled__[Du].normalize=Au.__compiled__[Au.__schemas__[Du]].normalize)}),Au.__compiled__[""]={validate:null,normalize:createNormalizer()};const Pu=Object.keys(Au.__compiled__).filter(function(Du){return Du.length>0&&Au.__compiled__[Du]}).map(escapeRE).join("|");Au.re.schema_test=RegExp(`(^|(?!_)(?:[><|]|${lo.src_ZPCc}))(${Pu})`,"i"),Au.re.schema_search=RegExp(`(^|(?!_)(?:[><|]|${lo.src_ZPCc}))(${Pu})`,"ig"),Au.re.schema_at_start=RegExp(`^${Au.re.schema_search.source}`,"i"),Au.re.pretest=RegExp(`(${Au.re.schema_test.source})|(${Au.re.host_fuzzy_test.source})|@`,"i")}function Match(Au,lo,$u,Ru){const Iu=Au.slice($u,Ru);this.schema=lo.toLowerCase(),this.index=$u,this.lastIndex=Ru,this.raw=Iu,this.text=Iu,this.url=Iu}function LinkifyIt(Au,lo){if(!(this instanceof LinkifyIt))return new LinkifyIt(Au,lo);lo||isOptionsObj(Au)&&(lo=Au,Au={}),this.__opts__=assign({},defaultOptions,lo),this.__schemas__=assign({},defaultSchemas,Au),this.__compiled__={},this.__tlds__=tlds_default,this.__tlds_replaced__=!1,this.re={},compile(this)}LinkifyIt.prototype.add=function Au(lo,$u){return this.__schemas__[lo]=$u,compile(this),this};LinkifyIt.prototype.set=function Au(lo){return this.__opts__=assign(this.__opts__,lo),this};LinkifyIt.prototype.test=function Au(lo){if(!lo.length)return!1;let $u,Ru;if(this.re.schema_test.test(lo)){for(Ru=this.re.schema_search,Ru.lastIndex=0;($u=Ru.exec(lo))!==null;)if(this.testSchemaAt(lo,$u[2],Ru.lastIndex))return!0}return!!(this.__opts__.fuzzyLink&&this.__compiled__["http:"]&&lo.search(this.re.host_fuzzy_test)>=0&&lo.match(this.__opts__.fuzzyIP?this.re.link_fuzzy:this.re.link_no_ip_fuzzy)!==null||this.__opts__.fuzzyEmail&&this.__compiled__["mailto:"]&&lo.indexOf("@")>=0&&lo.match(this.re.email_fuzzy)!==null)};LinkifyIt.prototype.pretest=function Au(lo){return this.re.pretest.test(lo)};LinkifyIt.prototype.testSchemaAt=function Au(lo,$u,Ru){return this.__compiled__[$u.toLowerCase()]?this.__compiled__[$u.toLowerCase()].validate(lo,Ru,this):0};LinkifyIt.prototype.match=function Au(lo){const $u=[],Ru=[],Iu=[],Ou=[];let Pu,Du,Lu;function ju(zu,qu){return zu?qu?zu.index!==qu.index?zu.index<qu.index?zu:qu:zu.lastIndex>=qu.lastIndex?zu:qu:zu:qu}if(!lo.length)return null;if(this.re.schema_test.test(lo))for(Lu=this.re.schema_search,Lu.lastIndex=0;(Pu=Lu.exec(lo))!==null;)Du=this.testSchemaAt(lo,Pu[2],Lu.lastIndex),Du&&Ru.push({schema:Pu[2],index:Pu.index+Pu[1].length,lastIndex:Pu.index+Pu[0].length+Du});if(this.__opts__.fuzzyLink&&this.__compiled__["http:"])for(Lu=this.__opts__.fuzzyIP?this.re.link_fuzzy_global:this.re.link_no_ip_fuzzy_global,Lu.lastIndex=0;(Pu=Lu.exec(lo))!==null;)Iu.push({schema:"",index:Pu.index+Pu[1].length,lastIndex:Pu.index+Pu[0].length});if(this.__opts__.fuzzyEmail&&this.__compiled__["mailto:"])for(Lu=this.re.email_fuzzy_global,Lu.lastIndex=0;(Pu=Lu.exec(lo))!==null;)Ou.push({schema:"mailto:",index:Pu.index+Pu[1].length,lastIndex:Pu.index+Pu[0].length});const Bu=[0,0,0];let Fu=0;for(;;){const zu=[Ru[Bu[0]],Ou[Bu[1]],Iu[Bu[2]]],qu=ju(ju(zu[0],zu[1]),zu[2]);if(!qu)break;if(qu===zu[0]?Bu[0]++:qu===zu[1]?Bu[1]++:Bu[2]++,qu.index<Fu)continue;const Uu=new Match(lo,qu.schema,qu.index,qu.lastIndex);this.__compiled__[Uu.schema].normalize(Uu,this),$u.push(Uu),Fu=qu.lastIndex}return $u.length?$u:null};LinkifyIt.prototype.matchAtStart=function Au(lo){if(!lo.length)return null;const $u=this.re.schema_at_start.exec(lo);if(!$u)return null;const Ru=this.testSchemaAt(lo,$u[2],$u[0].length);if(!Ru)return null;const Iu=new Match(lo,$u[2],$u.index+$u[1].length,$u.index+$u[0].length+Ru);return this.__compiled__[Iu.schema].normalize(Iu,this),Iu};LinkifyIt.prototype.tlds=function Au(lo,$u){return lo=Array.isArray(lo)?lo:[lo],$u?(this.__tlds__=this.__tlds__.concat(lo).sort().filter(function(Ru,Iu,Ou){return Ru!==Ou[Iu-1]}).reverse(),compile(this),this):(this.__tlds__=lo.slice(),this.__tlds_replaced__=!0,compile(this),this)};LinkifyIt.prototype.normalize=function Au(lo){lo.schema||(lo.url=`http://${lo.url}`),lo.schema==="mailto:"&&!/^mailto:/i.test(lo.url)&&(lo.url=`mailto:${lo.url}`)};LinkifyIt.prototype.onCompile=function Au(){};const maxInt=2147483647,base$1=36,tMin=1,tMax=26,skew=38,damp=700,initialBias=72,initialN=128,delimiter="-",regexPunycode=/^xn--/,regexNonASCII=/[^\0-\x7F]/,regexSeparators=/[\x2E\u3002\uFF0E\uFF61]/g,errors={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},baseMinusTMin=base$1-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode;function error(Au){throw new RangeError(errors[Au])}function map(Au,lo){const $u=[];let Ru=Au.length;for(;Ru--;)$u[Ru]=lo(Au[Ru]);return $u}function mapDomain(Au,lo){const $u=Au.split("@");let Ru="";$u.length>1&&(Ru=$u[0]+"@",Au=$u[1]),Au=Au.replace(regexSeparators,".");const Iu=Au.split("."),Ou=map(Iu,lo).join(".");return Ru+Ou}function ucs2decode(Au){const lo=[];let $u=0;const Ru=Au.length;for(;$u<Ru;){const Iu=Au.charCodeAt($u++);if(Iu>=55296&&Iu<=56319&&$u<Ru){const Ou=Au.charCodeAt($u++);(Ou&64512)==56320?lo.push(((Iu&1023)<<10)+(Ou&1023)+65536):(lo.push(Iu),$u--)}else lo.push(Iu)}return lo}const ucs2encode=Au=>String.fromCodePoint(...Au),basicToDigit=function(Au){return Au>=48&&Au<58?26+(Au-48):Au>=65&&Au<91?Au-65:Au>=97&&Au<123?Au-97:base$1},digitToBasic=function(Au,lo){return Au+22+75*(Au<26)-((lo!=0)<<5)},adapt=function(Au,lo,$u){let Ru=0;for(Au=$u?floor(Au/damp):Au>>1,Au+=floor(Au/lo);Au>baseMinusTMin*tMax>>1;Ru+=base$1)Au=floor(Au/baseMinusTMin);return floor(Ru+(baseMinusTMin+1)*Au/(Au+skew))},decode=function(Au){const lo=[],$u=Au.length;let Ru=0,Iu=initialN,Ou=initialBias,Pu=Au.lastIndexOf(delimiter);Pu<0&&(Pu=0);for(let Du=0;Du<Pu;++Du)Au.charCodeAt(Du)>=128&&error("not-basic"),lo.push(Au.charCodeAt(Du));for(let Du=Pu>0?Pu+1:0;Du<$u;){const Lu=Ru;for(let Bu=1,Fu=base$1;;Fu+=base$1){Du>=$u&&error("invalid-input");const zu=basicToDigit(Au.charCodeAt(Du++));zu>=base$1&&error("invalid-input"),zu>floor((maxInt-Ru)/Bu)&&error("overflow"),Ru+=zu*Bu;const qu=Fu<=Ou?tMin:Fu>=Ou+tMax?tMax:Fu-Ou;if(zu<qu)break;const Uu=base$1-qu;Bu>floor(maxInt/Uu)&&error("overflow"),Bu*=Uu}const ju=lo.length+1;Ou=adapt(Ru-Lu,ju,Lu==0),floor(Ru/ju)>maxInt-Iu&&error("overflow"),Iu+=floor(Ru/ju),Ru%=ju,lo.splice(Ru++,0,Iu)}return String.fromCodePoint(...lo)},encode=function(Au){const lo=[];Au=ucs2decode(Au);const $u=Au.length;let Ru=initialN,Iu=0,Ou=initialBias;for(const Lu of Au)Lu<128&&lo.push(stringFromCharCode(Lu));const Pu=lo.length;let Du=Pu;for(Pu&&lo.push(delimiter);Du<$u;){let Lu=maxInt;for(const Bu of Au)Bu>=Ru&&Bu<Lu&&(Lu=Bu);const ju=Du+1;Lu-Ru>floor((maxInt-Iu)/ju)&&error("overflow"),Iu+=(Lu-Ru)*ju,Ru=Lu;for(const Bu of Au)if(Bu<Ru&&++Iu>maxInt&&error("overflow"),Bu===Ru){let Fu=Iu;for(let zu=base$1;;zu+=base$1){const qu=zu<=Ou?tMin:zu>=Ou+tMax?tMax:zu-Ou;if(Fu<qu)break;const Uu=Fu-qu,Hu=base$1-qu;lo.push(stringFromCharCode(digitToBasic(qu+Uu%Hu,0))),Fu=floor(Uu/Hu)}lo.push(stringFromCharCode(digitToBasic(Fu,0))),Ou=adapt(Iu,ju,Du===Pu),Iu=0,++Du}++Iu,++Ru}return lo.join("")},toUnicode=function(Au){return mapDomain(Au,function(lo){return regexPunycode.test(lo)?decode(lo.slice(4).toLowerCase()):lo})},toASCII=function(Au){return mapDomain(Au,function(lo){return regexNonASCII.test(lo)?"xn--"+encode(lo):lo})},punycode={version:"2.3.1",ucs2:{decode:ucs2decode,encode:ucs2encode},decode,encode,toASCII,toUnicode},cfg_default={options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkify:!1,typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:100},components:{core:{},block:{},inline:{}}},cfg_zero={options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkify:!1,typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{rules:["normalize","block","inline","text_join"]},block:{rules:["paragraph"]},inline:{rules:["text"],rules2:["balance_pairs","fragments_join"]}}},cfg_commonmark={options:{html:!0,xhtmlOut:!0,breaks:!1,langPrefix:"language-",linkify:!1,typographer:!1,quotes:"“”‘’",highlight:null,maxNesting:20},components:{core:{rules:["normalize","block","inline","text_join"]},block:{rules:["blockquote","code","fence","heading","hr","html_block","lheading","list","reference","paragraph"]},inline:{rules:["autolink","backticks","emphasis","entity","escape","html_inline","image","link","newline","text"],rules2:["balance_pairs","emphasis","fragments_join"]}}},config={default:cfg_default,zero:cfg_zero,commonmark:cfg_commonmark},BAD_PROTO_RE=/^(vbscript|javascript|file|data):/,GOOD_DATA_RE=/^data:image\/(gif|png|jpeg|webp);/;function validateLink(Au){const lo=Au.trim().toLowerCase();return BAD_PROTO_RE.test(lo)?GOOD_DATA_RE.test(lo):!0}const RECODE_HOSTNAME_FOR=["http:","https:","mailto:"];function normalizeLink(Au){const lo=urlParse(Au,!0);if(lo.hostname&&(!lo.protocol||RECODE_HOSTNAME_FOR.indexOf(lo.protocol)>=0))try{lo.hostname=punycode.toASCII(lo.hostname)}catch{}return encode$1(format$1(lo))}function normalizeLinkText(Au){const lo=urlParse(Au,!0);if(lo.hostname&&(!lo.protocol||RECODE_HOSTNAME_FOR.indexOf(lo.protocol)>=0))try{lo.hostname=punycode.toUnicode(lo.hostname)}catch{}return decode$1(format$1(lo),decode$1.defaultChars+"%")}function MarkdownIt(Au,lo){if(!(this instanceof MarkdownIt))return new MarkdownIt(Au,lo);lo||isString$1(Au)||(lo=Au||{},Au="default"),this.inline=new ParserInline,this.block=new ParserBlock,this.core=new Core,this.renderer=new Renderer,this.linkify=new LinkifyIt,this.validateLink=validateLink,this.normalizeLink=normalizeLink,this.normalizeLinkText=normalizeLinkText,this.utils=utils,this.helpers=assign$1({},helpers),this.options={},this.configure(Au),lo&&this.set(lo)}MarkdownIt.prototype.set=function(Au){return assign$1(this.options,Au),this};MarkdownIt.prototype.configure=function(Au){const lo=this;if(isString$1(Au)){const $u=Au;if(Au=config[$u],!Au)throw new Error('Wrong `markdown-it` preset "'+$u+'", check name')}if(!Au)throw new Error("Wrong `markdown-it` preset, can't be empty");return Au.options&&lo.set(Au.options),Au.components&&Object.keys(Au.components).forEach(function($u){Au.components[$u].rules&&lo[$u].ruler.enableOnly(Au.components[$u].rules),Au.components[$u].rules2&&lo[$u].ruler2.enableOnly(Au.components[$u].rules2)}),this};MarkdownIt.prototype.enable=function(Au,lo){let $u=[];Array.isArray(Au)||(Au=[Au]),["core","block","inline"].forEach(function(Iu){$u=$u.concat(this[Iu].ruler.enable(Au,!0))},this),$u=$u.concat(this.inline.ruler2.enable(Au,!0));const Ru=Au.filter(function(Iu){return $u.indexOf(Iu)<0});if(Ru.length&&!lo)throw new Error("MarkdownIt. Failed to enable unknown rule(s): "+Ru);return this};MarkdownIt.prototype.disable=function(Au,lo){let $u=[];Array.isArray(Au)||(Au=[Au]),["core","block","inline"].forEach(function(Iu){$u=$u.concat(this[Iu].ruler.disable(Au,!0))},this),$u=$u.concat(this.inline.ruler2.disable(Au,!0));const Ru=Au.filter(function(Iu){return $u.indexOf(Iu)<0});if(Ru.length&&!lo)throw new Error("MarkdownIt. Failed to disable unknown rule(s): "+Ru);return this};MarkdownIt.prototype.use=function(Au){const lo=[this].concat(Array.prototype.slice.call(arguments,1));return Au.apply(Au,lo),this};MarkdownIt.prototype.parse=function(Au,lo){if(typeof Au!="string")throw new Error("Input data should be a String");const $u=new this.core.State(Au,this,lo);return this.core.process($u),$u.tokens};MarkdownIt.prototype.render=function(Au,lo){return lo=lo||{},this.renderer.render(this.parse(Au,lo),this.options,lo)};MarkdownIt.prototype.parseInline=function(Au,lo){const $u=new this.core.State(Au,this,lo);return $u.inlineMode=!0,this.core.process($u),$u.tokens};MarkdownIt.prototype.renderInline=function(Au,lo){return lo=lo||{},this.renderer.render(this.parseInline(Au,lo),this.options,lo)};class MarkdownItRenderer{constructor(){this.markdownIt=MarkdownIt(),this.registerTagClassMapRules()}registerTagClassMapRules(){const lo=["paragraph_open","heading_open","bullet_list_open","ordered_list_open","list_item_open","link_open","strong_open","em_open"];for(const $u of lo){const Ru=this.markdownIt.renderer.rules[$u];this.markdownIt.renderer.rules[$u]=(Iu,Ou,Pu,Du,Lu)=>{const ju=Iu[Ou],Bu=Du?.tagClassMap;if(Bu){const Fu=Bu[ju.tag]??[];for(const zu of Fu)ju.attrJoin("class",zu)}return Ru?Ru(Iu,Ou,Pu,Du,Lu):Lu.renderToken(Iu,Ou,Pu)}}}render(lo,$u){return this.markdownIt.render(lo,{tagClassMap:$u})}}const rawMarkdownRenderer=new MarkdownItRenderer;function _arrayLikeToArray(Au,lo){(lo==null||lo>Au.length)&&(lo=Au.length);for(var $u=0,Ru=Array(lo);$u<lo;$u++)Ru[$u]=Au[$u];return Ru}function _arrayWithHoles(Au){if(Array.isArray(Au))return Au}function _iterableToArrayLimit(Au,lo){var $u=Au==null?null:typeof Symbol<"u"&&Au[Symbol.iterator]||Au["@@iterator"];if($u!=null){var Ru,Iu,Ou,Pu,Du=[],Lu=!0,ju=!1;try{if(Ou=($u=$u.call(Au)).next,lo!==0)for(;!(Lu=(Ru=Ou.call($u)).done)&&(Du.push(Ru.value),Du.length!==lo);Lu=!0);}catch(Bu){ju=!0,Iu=Bu}finally{try{if(!Lu&&$u.return!=null&&(Pu=$u.return(),Object(Pu)!==Pu))return}finally{if(ju)throw Iu}}return Du}}function _nonIterableRest(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
3543
3543
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _slicedToArray(Au,lo){return _arrayWithHoles(Au)||_iterableToArrayLimit(Au,lo)||_unsupportedIterableToArray(Au,lo)||_nonIterableRest()}function _unsupportedIterableToArray(Au,lo){if(Au){if(typeof Au=="string")return _arrayLikeToArray(Au,lo);var $u={}.toString.call(Au).slice(8,-1);return $u==="Object"&&Au.constructor&&($u=Au.constructor.name),$u==="Map"||$u==="Set"?Array.from(Au):$u==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test($u)?_arrayLikeToArray(Au,lo):void 0}}const entries=Object.entries,setPrototypeOf=Object.setPrototypeOf,isFrozen=Object.isFrozen,getPrototypeOf=Object.getPrototypeOf,getOwnPropertyDescriptor=Object.getOwnPropertyDescriptor;let freeze=Object.freeze,seal=Object.seal,create=Object.create,_ref=typeof Reflect<"u"&&Reflect,apply=_ref.apply,construct=_ref.construct;freeze||(freeze=function(lo){return lo});seal||(seal=function(lo){return lo});apply||(apply=function(lo,$u){for(var Ru=arguments.length,Iu=new Array(Ru>2?Ru-2:0),Ou=2;Ou<Ru;Ou++)Iu[Ou-2]=arguments[Ou];return lo.apply($u,Iu)});construct||(construct=function(lo){for(var $u=arguments.length,Ru=new Array($u>1?$u-1:0),Iu=1;Iu<$u;Iu++)Ru[Iu-1]=arguments[Iu];return new lo(...Ru)});const arrayForEach=unapply(Array.prototype.forEach),arrayLastIndexOf=unapply(Array.prototype.lastIndexOf),arrayPop=unapply(Array.prototype.pop),arrayPush=unapply(Array.prototype.push),arraySplice=unapply(Array.prototype.splice),arrayIsArray=Array.isArray,stringToLowerCase=unapply(String.prototype.toLowerCase),stringToString=unapply(String.prototype.toString),stringMatch=unapply(String.prototype.match),stringReplace=unapply(String.prototype.replace),stringIndexOf=unapply(String.prototype.indexOf),stringTrim=unapply(String.prototype.trim),numberToString=unapply(Number.prototype.toString),booleanToString=unapply(Boolean.prototype.toString),bigintToString=typeof BigInt>"u"?null:unapply(BigInt.prototype.toString),symbolToString=typeof Symbol>"u"?null:unapply(Symbol.prototype.toString),objectHasOwnProperty=unapply(Object.prototype.hasOwnProperty),objectToString=unapply(Object.prototype.toString),regExpTest=unapply(RegExp.prototype.test),typeErrorCreate=unconstruct(TypeError);function unapply(Au){return function(lo){lo instanceof RegExp&&(lo.lastIndex=0);for(var $u=arguments.length,Ru=new Array($u>1?$u-1:0),Iu=1;Iu<$u;Iu++)Ru[Iu-1]=arguments[Iu];return apply(Au,lo,Ru)}}function unconstruct(Au){return function(){for(var lo=arguments.length,$u=new Array(lo),Ru=0;Ru<lo;Ru++)$u[Ru]=arguments[Ru];return construct(Au,$u)}}function addToSet(Au,lo){let $u=arguments.length>2&&arguments[2]!==void 0?arguments[2]:stringToLowerCase;if(setPrototypeOf&&setPrototypeOf(Au,null),!arrayIsArray(lo))return Au;let Ru=lo.length;for(;Ru--;){let Iu=lo[Ru];if(typeof Iu=="string"){const Ou=$u(Iu);Ou!==Iu&&(isFrozen(lo)||(lo[Ru]=Ou),Iu=Ou)}Au[Iu]=!0}return Au}function cleanArray(Au){for(let lo=0;lo<Au.length;lo++)objectHasOwnProperty(Au,lo)||(Au[lo]=null);return Au}function clone(Au){const lo=create(null);for(const Ru of entries(Au)){var $u=_slicedToArray(Ru,2);const Iu=$u[0],Ou=$u[1];objectHasOwnProperty(Au,Iu)&&(arrayIsArray(Ou)?lo[Iu]=cleanArray(Ou):Ou&&typeof Ou=="object"&&Ou.constructor===Object?lo[Iu]=clone(Ou):lo[Iu]=Ou)}return lo}function stringifyValue(Au){switch(typeof Au){case"string":return Au;case"number":return numberToString(Au);case"boolean":return booleanToString(Au);case"bigint":return bigintToString?bigintToString(Au):"0";case"symbol":return symbolToString?symbolToString(Au):"Symbol()";case"undefined":return objectToString(Au);case"function":case"object":{if(Au===null)return objectToString(Au);const lo=Au,$u=lookupGetter(lo,"toString");if(typeof $u=="function"){const Ru=$u(lo);return typeof Ru=="string"?Ru:objectToString(Ru)}return objectToString(Au)}default:return objectToString(Au)}}function lookupGetter(Au,lo){for(;Au!==null;){const Ru=getOwnPropertyDescriptor(Au,lo);if(Ru){if(Ru.get)return unapply(Ru.get);if(typeof Ru.value=="function")return unapply(Ru.value)}Au=getPrototypeOf(Au)}function $u(){return null}return $u}function isRegex(Au){try{return regExpTest(Au,""),!0}catch{return!1}}const html$1=freeze(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),svg$1=freeze(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),svgFilters=freeze(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),svgDisallowed=freeze(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),mathMl$1=freeze(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),mathMlDisallowed=freeze(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),text$1=freeze(["#text"]),html=freeze(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),svg=freeze(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),mathMl=freeze(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),xml=freeze(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),MUSTACHE_EXPR=seal(/{{[\w\W]*|^[\w\W]*}}/g),ERB_EXPR=seal(/<%[\w\W]*|^[\w\W]*%>/g),TMPLIT_EXPR=seal(/\${[\w\W]*/g),DATA_ATTR=seal(/^data-[\-\w.\u00B7-\uFFFF]+$/),ARIA_ATTR=seal(/^aria-[\-\w]+$/),IS_ALLOWED_URI=seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),IS_SCRIPT_OR_DATA=seal(/^(?:\w+script|data):/i),ATTR_WHITESPACE=seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),DOCTYPE_NAME=seal(/^html$/i),CUSTOM_ELEMENT=seal(/^[a-z][.\w]*(-[.\w]+)+$/i),ELEMENT_MARKUP_PROBE=seal(/<[/\w!]/g),COMMENT_MARKUP_PROBE=seal(/<[/\w]/g),FALLBACK_TAG_CLOSE=seal(/<\/no(script|embed|frames)/i),SELF_CLOSING_TAG=seal(/\/>/i),NODE_TYPE={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},getGlobal=function Au(){return typeof window>"u"?null:window},_createTrustedTypesPolicy=function Au(lo,$u){if(typeof lo!="object"||typeof lo.createPolicy!="function")return null;let Ru=null;const Iu="data-tt-policy-suffix";$u&&$u.hasAttribute(Iu)&&(Ru=$u.getAttribute(Iu));const Ou="dompurify"+(Ru?"#"+Ru:"");try{return lo.createPolicy(Ou,{createHTML(Pu){return Pu},createScriptURL(Pu){return Pu}})}catch{return console.warn("TrustedTypes policy "+Ou+" could not be created."),null}},_createHooksMap=function Au(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},_resolveSetOption=function Au(lo,$u,Ru,Iu){return objectHasOwnProperty(lo,$u)&&arrayIsArray(lo[$u])?addToSet(Iu.base?clone(Iu.base):{},lo[$u],Iu.transform):Ru};function createDOMPurify(){let Au=arguments.length>0&&arguments[0]!==void 0?arguments[0]:getGlobal();const lo=Sf=>createDOMPurify(Sf);if(lo.version="3.4.11",lo.removed=[],!Au||!Au.document||Au.document.nodeType!==NODE_TYPE.document||!Au.Element)return lo.isSupported=!1,lo;let $u=Au.document;const Ru=$u,Iu=Ru.currentScript;Au.DocumentFragment;const Ou=Au.HTMLTemplateElement,Pu=Au.Node,Du=Au.Element,Lu=Au.NodeFilter,ju=Au.NamedNodeMap;ju===void 0&&(Au.NamedNodeMap||Au.MozNamedAttrMap),Au.HTMLFormElement;const Bu=Au.DOMParser,Fu=Au.trustedTypes,zu=Du.prototype,qu=lookupGetter(zu,"cloneNode"),Uu=lookupGetter(zu,"remove"),Hu=lookupGetter(zu,"nextSibling"),Vu=lookupGetter(zu,"childNodes"),Gu=lookupGetter(zu,"parentNode"),Ku=lookupGetter(zu,"shadowRoot"),Zu=lookupGetter(zu,"attributes"),Qu=Pu&&Pu.prototype?lookupGetter(Pu.prototype,"nodeType"):null,Yu=Pu&&Pu.prototype?lookupGetter(Pu.prototype,"nodeName"):null;if(typeof Ou=="function"){const Sf=$u.createElement("template");Sf.content&&Sf.content.ownerDocument&&($u=Sf.content.ownerDocument)}let ed,Xu="",rd,nd=!1,od=0;const ad=function(){if(od>0)throw typeErrorCreate('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},ld=function(hh){ad(),od++;try{return ed.createHTML(hh)}finally{od--}},fd=function(hh){ad(),od++;try{return ed.createScriptURL(hh)}finally{od--}},pd=function(){return nd||(rd=_createTrustedTypesPolicy(Fu,Iu),nd=!0),rd},Sd=$u,wd=Sd.implementation,bd=Sd.createNodeIterator,Td=Sd.createDocumentFragment,Pd=Sd.getElementsByTagName,ud=Ru.importNode;let md=_createHooksMap();lo.isSupported=typeof entries=="function"&&typeof Gu=="function"&&wd&&wd.createHTMLDocument!==void 0;const _d=MUSTACHE_EXPR,hd=ERB_EXPR,gd=TMPLIT_EXPR,Ed=DATA_ATTR,xd=ARIA_ATTR,Od=IS_SCRIPT_OR_DATA,Bd=ATTR_WHITESPACE,Gd=CUSTOM_ELEMENT;let Ud=IS_ALLOWED_URI,Md=null;const zd=addToSet({},[...html$1,...svg$1,...svgFilters,...mathMl$1,...text$1]);let Vd=null;const kd=addToSet({},[...html,...svg,...mathMl,...xml]);let Rd=Object.seal(create(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Ld=null,Jd=null;const Xd=Object.seal(create(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let uh=!0,xh=!0,Mh=!1,Rh=!0,bh=!1,_h=!0,eh=!1,Sh=!1,Dd=null,$d=null,jd=!1,Fd=!1,rh=!1,Yd=!1,th=!0,ah=!1;const Ah="user-content-";let Dh=!0,zh=!1,mf={},Zd=null;const Ad=addToSet({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let sh=null;const ih=addToSet({},["audio","video","img","source","image","track"]);let Bh=null;const Yh=addToSet({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Kh="http://www.w3.org/1998/Math/MathML",rf="http://www.w3.org/2000/svg",hf="http://www.w3.org/1999/xhtml";let Rf=hf,Cf=!1,Df=null;const sf=addToSet({},[Kh,rf,hf],stringToString),qf=freeze(["mi","mo","mn","ms","mtext"]);let Uf=addToSet({},qf);const mh=freeze(["annotation-xml"]);let oh=addToSet({},mh);const ph=addToSet({},["title","style","font","a","script"]);let Lh=null;const kh=["application/xhtml+xml","text/html"],vf="text/html";let Jh=null,lf=null;const Yf=$u.createElement("form"),Tf=function(hh){return hh instanceof RegExp||hh instanceof Function},Nf=function(){let hh=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(lf&&lf===hh)return;(!hh||typeof hh!="object")&&(hh={}),hh=clone(hh),Lh=kh.indexOf(hh.PARSER_MEDIA_TYPE)===-1?vf:hh.PARSER_MEDIA_TYPE,Jh=Lh==="application/xhtml+xml"?stringToString:stringToLowerCase,Md=_resolveSetOption(hh,"ALLOWED_TAGS",zd,{transform:Jh}),Vd=_resolveSetOption(hh,"ALLOWED_ATTR",kd,{transform:Jh}),Df=_resolveSetOption(hh,"ALLOWED_NAMESPACES",sf,{transform:stringToString}),Bh=_resolveSetOption(hh,"ADD_URI_SAFE_ATTR",Yh,{transform:Jh,base:Yh}),sh=_resolveSetOption(hh,"ADD_DATA_URI_TAGS",ih,{transform:Jh,base:ih}),Zd=_resolveSetOption(hh,"FORBID_CONTENTS",Ad,{transform:Jh}),Ld=_resolveSetOption(hh,"FORBID_TAGS",clone({}),{transform:Jh}),Jd=_resolveSetOption(hh,"FORBID_ATTR",clone({}),{transform:Jh}),mf=objectHasOwnProperty(hh,"USE_PROFILES")?hh.USE_PROFILES&&typeof hh.USE_PROFILES=="object"?clone(hh.USE_PROFILES):hh.USE_PROFILES:!1,uh=hh.ALLOW_ARIA_ATTR!==!1,xh=hh.ALLOW_DATA_ATTR!==!1,Mh=hh.ALLOW_UNKNOWN_PROTOCOLS||!1,Rh=hh.ALLOW_SELF_CLOSE_IN_ATTR!==!1,bh=hh.SAFE_FOR_TEMPLATES||!1,_h=hh.SAFE_FOR_XML!==!1,eh=hh.WHOLE_DOCUMENT||!1,Fd=hh.RETURN_DOM||!1,rh=hh.RETURN_DOM_FRAGMENT||!1,Yd=hh.RETURN_TRUSTED_TYPE||!1,jd=hh.FORCE_BODY||!1,th=hh.SANITIZE_DOM!==!1,ah=hh.SANITIZE_NAMED_PROPS||!1,Dh=hh.KEEP_CONTENT!==!1,zh=hh.IN_PLACE||!1,Ud=isRegex(hh.ALLOWED_URI_REGEXP)?hh.ALLOWED_URI_REGEXP:IS_ALLOWED_URI,Rf=typeof hh.NAMESPACE=="string"?hh.NAMESPACE:hf,Uf=objectHasOwnProperty(hh,"MATHML_TEXT_INTEGRATION_POINTS")&&hh.MATHML_TEXT_INTEGRATION_POINTS&&typeof hh.MATHML_TEXT_INTEGRATION_POINTS=="object"?clone(hh.MATHML_TEXT_INTEGRATION_POINTS):addToSet({},qf),oh=objectHasOwnProperty(hh,"HTML_INTEGRATION_POINTS")&&hh.HTML_INTEGRATION_POINTS&&typeof hh.HTML_INTEGRATION_POINTS=="object"?clone(hh.HTML_INTEGRATION_POINTS):addToSet({},mh);const jh=objectHasOwnProperty(hh,"CUSTOM_ELEMENT_HANDLING")&&hh.CUSTOM_ELEMENT_HANDLING&&typeof hh.CUSTOM_ELEMENT_HANDLING=="object"?clone(hh.CUSTOM_ELEMENT_HANDLING):create(null);if(Rd=create(null),objectHasOwnProperty(jh,"tagNameCheck")&&Tf(jh.tagNameCheck)&&(Rd.tagNameCheck=jh.tagNameCheck),objectHasOwnProperty(jh,"attributeNameCheck")&&Tf(jh.attributeNameCheck)&&(Rd.attributeNameCheck=jh.attributeNameCheck),objectHasOwnProperty(jh,"allowCustomizedBuiltInElements")&&typeof jh.allowCustomizedBuiltInElements=="boolean"&&(Rd.allowCustomizedBuiltInElements=jh.allowCustomizedBuiltInElements),seal(Rd),bh&&(xh=!1),rh&&(Fd=!0),mf&&(Md=addToSet({},text$1),Vd=create(null),mf.html===!0&&(addToSet(Md,html$1),addToSet(Vd,html)),mf.svg===!0&&(addToSet(Md,svg$1),addToSet(Vd,svg),addToSet(Vd,xml)),mf.svgFilters===!0&&(addToSet(Md,svgFilters),addToSet(Vd,svg),addToSet(Vd,xml)),mf.mathMl===!0&&(addToSet(Md,mathMl$1),addToSet(Vd,mathMl),addToSet(Vd,xml))),Xd.tagCheck=null,Xd.attributeCheck=null,objectHasOwnProperty(hh,"ADD_TAGS")&&(typeof hh.ADD_TAGS=="function"?Xd.tagCheck=hh.ADD_TAGS:arrayIsArray(hh.ADD_TAGS)&&(Md===zd&&(Md=clone(Md)),addToSet(Md,hh.ADD_TAGS,Jh))),objectHasOwnProperty(hh,"ADD_ATTR")&&(typeof hh.ADD_ATTR=="function"?Xd.attributeCheck=hh.ADD_ATTR:arrayIsArray(hh.ADD_ATTR)&&(Vd===kd&&(Vd=clone(Vd)),addToSet(Vd,hh.ADD_ATTR,Jh))),objectHasOwnProperty(hh,"ADD_URI_SAFE_ATTR")&&arrayIsArray(hh.ADD_URI_SAFE_ATTR)&&addToSet(Bh,hh.ADD_URI_SAFE_ATTR,Jh),objectHasOwnProperty(hh,"FORBID_CONTENTS")&&arrayIsArray(hh.FORBID_CONTENTS)&&(Zd===Ad&&(Zd=clone(Zd)),addToSet(Zd,hh.FORBID_CONTENTS,Jh)),objectHasOwnProperty(hh,"ADD_FORBID_CONTENTS")&&arrayIsArray(hh.ADD_FORBID_CONTENTS)&&(Zd===Ad&&(Zd=clone(Zd)),addToSet(Zd,hh.ADD_FORBID_CONTENTS,Jh)),Dh&&(Md["#text"]=!0),eh&&addToSet(Md,["html","head","body"]),Md.table&&(addToSet(Md,["tbody"]),delete Ld.tbody),hh.TRUSTED_TYPES_POLICY){if(typeof hh.TRUSTED_TYPES_POLICY.createHTML!="function")throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof hh.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const Ef=ed;ed=hh.TRUSTED_TYPES_POLICY;try{Xu=ld("")}catch(wf){throw ed=Ef,wf}}else hh.TRUSTED_TYPES_POLICY===null?(ed=void 0,Xu=""):(ed===void 0&&(ed=pd()),ed&&typeof Xu=="string"&&(Xu=ld("")));freeze&&freeze(hh),lf=hh},Qh=addToSet({},[...svg$1,...svgFilters,...svgDisallowed]),kf=addToSet({},[...mathMl$1,...mathMlDisallowed]),yf=function(hh,jh,Ef){return jh.namespaceURI===hf?hh==="svg":jh.namespaceURI===Kh?hh==="svg"&&(Ef==="annotation-xml"||Uf[Ef]):!!Qh[hh]},rp=function(hh,jh,Ef){return jh.namespaceURI===hf?hh==="math":jh.namespaceURI===rf?hh==="math"&&oh[Ef]:!!kf[hh]},up=function(hh,jh,Ef){return jh.namespaceURI===rf&&!oh[Ef]||jh.namespaceURI===Kh&&!Uf[Ef]?!1:!kf[hh]&&(ph[hh]||!Qh[hh])},np=function(hh){let jh=Gu(hh);(!jh||!jh.tagName)&&(jh={namespaceURI:Rf,tagName:"template"});const Ef=stringToLowerCase(hh.tagName),wf=stringToLowerCase(jh.tagName);return Df[hh.namespaceURI]?hh.namespaceURI===rf?yf(Ef,jh,wf):hh.namespaceURI===Kh?rp(Ef,jh,wf):hh.namespaceURI===hf?up(Ef,jh,wf):!!(Lh==="application/xhtml+xml"&&Df[hh.namespaceURI]):!1},kp=function(hh){arrayPush(lo.removed,{element:hh});try{Gu(hh).removeChild(hh)}catch{if(Uu(hh),!Gu(hh))throw typeErrorCreate("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Bf=function(hh){const jh=Vu(hh);if(jh){const wf=[];arrayForEach(jh,gf=>{arrayPush(wf,gf)}),arrayForEach(wf,gf=>{try{Uu(gf)}catch{}})}const Ef=Zu(hh);if(Ef)for(let wf=Ef.length-1;wf>=0;--wf){const gf=Ef[wf],$f=gf&&gf.name;if(typeof $f=="string")try{hh.removeAttribute($f)}catch{}}},zp=function(hh,jh){try{arrayPush(lo.removed,{attribute:jh.getAttributeNode(hh),from:jh})}catch{arrayPush(lo.removed,{attribute:null,from:jh})}if(jh.removeAttribute(hh),hh==="is")if(Fd||rh)try{kp(jh)}catch{}else try{jh.setAttribute(hh,"")}catch{}},Zp=function(hh){const jh=Zu(hh);if(jh)for(let Ef=jh.length-1;Ef>=0;--Ef){const wf=jh[Ef],gf=wf&&wf.name;if(!(typeof gf!="string"||Vd[Jh(gf)]))try{hh.removeAttribute(gf)}catch{}}},sm=function(hh){const jh=[hh];for(;jh.length>0;){const Ef=jh.pop();(Qu?Qu(Ef):Ef.nodeType)===NODE_TYPE.element&&Zp(Ef);const gf=Vu(Ef);if(gf)for(let $f=gf.length-1;$f>=0;--$f)jh.push(gf[$f])}},pp=function(hh){let jh=null,Ef=null;if(jd)hh="<remove></remove>"+hh;else{const $f=stringMatch(hh,/^[\r\n\t ]+/);Ef=$f&&$f[0]}Lh==="application/xhtml+xml"&&Rf===hf&&(hh='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+hh+"</body></html>");const wf=ed?ld(hh):hh;if(Rf===hf)try{jh=new Bu().parseFromString(wf,Lh)}catch{}if(!jh||!jh.documentElement){jh=wd.createDocument(Rf,"template",null);try{jh.documentElement.innerHTML=Cf?Xu:wf}catch{}}const gf=jh.body||jh.documentElement;return hh&&Ef&&gf.insertBefore($u.createTextNode(Ef),gf.childNodes[0]||null),Rf===hf?Pd.call(jh,eh?"html":"body")[0]:eh?jh.documentElement:gf},qp=function(hh){return bd.call(hh.ownerDocument||hh,hh,Lu.SHOW_ELEMENT|Lu.SHOW_COMMENT|Lu.SHOW_TEXT|Lu.SHOW_PROCESSING_INSTRUCTION|Lu.SHOW_CDATA_SECTION,null)},Jf=function(hh){return hh=stringReplace(hh,_d," "),hh=stringReplace(hh,hd," "),hh=stringReplace(hh,gd," "),hh},gp=function(hh){var jh;hh.normalize();const Ef=bd.call(hh.ownerDocument||hh,hh,Lu.SHOW_TEXT|Lu.SHOW_COMMENT|Lu.SHOW_CDATA_SECTION|Lu.SHOW_PROCESSING_INSTRUCTION,null);let wf=Ef.nextNode();for(;wf;)wf.data=Jf(wf.data),wf=Ef.nextNode();const gf=(jh=hh.querySelectorAll)===null||jh===void 0?void 0:jh.call(hh,"template");gf&&arrayForEach(gf,$f=>{Cp($f.content)&&gp($f.content)})},dp=function(hh){const jh=Yu?Yu(hh):null;return typeof jh!="string"||Jh(jh)!=="form"?!1:typeof hh.nodeName!="string"||typeof hh.textContent!="string"||typeof hh.removeChild!="function"||hh.attributes!==Zu(hh)||typeof hh.removeAttribute!="function"||typeof hh.setAttribute!="function"||typeof hh.namespaceURI!="string"||typeof hh.insertBefore!="function"||typeof hh.hasChildNodes!="function"||hh.nodeType!==Qu(hh)||hh.childNodes!==Vu(hh)},Cp=function(hh){if(!Qu||typeof hh!="object"||hh===null)return!1;try{return Qu(hh)===NODE_TYPE.documentFragment}catch{return!1}},Tp=function(hh){if(!Qu||typeof hh!="object"||hh===null)return!1;try{return typeof Qu(hh)=="number"}catch{return!1}};function hp(Sf,hh,jh){Sf.length!==0&&arrayForEach(Sf,Ef=>{Ef.call(lo,hh,jh,lf)})}const Rp=function(hh,jh){return!!(_h&&hh.hasChildNodes()&&!Tp(hh.firstElementChild)&&regExpTest(ELEMENT_MARKUP_PROBE,hh.textContent)&&regExpTest(ELEMENT_MARKUP_PROBE,hh.innerHTML)||_h&&hh.namespaceURI===hf&&jh==="style"&&Tp(hh.firstElementChild)||hh.nodeType===NODE_TYPE.processingInstruction||_h&&hh.nodeType===NODE_TYPE.comment&&regExpTest(COMMENT_MARKUP_PROBE,hh.data))},Qf=function(hh,jh){if(!Ld[jh]&&Np(jh)&&(Rd.tagNameCheck instanceof RegExp&&regExpTest(Rd.tagNameCheck,jh)||Rd.tagNameCheck instanceof Function&&Rd.tagNameCheck(jh)))return!1;if(Dh&&!Zd[jh]){const Ef=Gu(hh),wf=Vu(hh);if(wf&&Ef){const gf=wf.length;for(let $f=gf-1;$f>=0;--$f){const vh=zh?wf[$f]:qu(wf[$f],!0);Ef.insertBefore(vh,Hu(hh))}}}return kp(hh),!0},cm=function(hh){if(hp(md.beforeSanitizeElements,hh,null),dp(hh))return kp(hh),!0;const jh=Jh(Yu?Yu(hh):hh.nodeName);if(hp(md.uponSanitizeElement,hh,{tagName:jh,allowedTags:Md}),Rp(hh,jh))return kp(hh),!0;if(Ld[jh]||!(Xd.tagCheck instanceof Function&&Xd.tagCheck(jh))&&!Md[jh])return Qf(hh,jh);if((Qu?Qu(hh):hh.nodeType)===NODE_TYPE.element&&!np(hh)||(jh==="noscript"||jh==="noembed"||jh==="noframes")&&regExpTest(FALLBACK_TAG_CLOSE,hh.innerHTML))return kp(hh),!0;if(bh&&hh.nodeType===NODE_TYPE.text){const wf=Jf(hh.textContent);hh.textContent!==wf&&(arrayPush(lo.removed,{element:hh.cloneNode()}),hh.textContent=wf)}return hp(md.afterSanitizeElements,hh,null),!1},um=function(hh,jh,Ef){if(Jd[jh]||th&&(jh==="id"||jh==="name")&&(Ef in $u||Ef in Yf))return!1;const wf=Vd[jh]||Xd.attributeCheck instanceof Function&&Xd.attributeCheck(jh,hh);if(!(xh&&regExpTest(Ed,jh))){if(!(uh&&regExpTest(xd,jh))){if(wf){if(!Bh[jh]){if(!regExpTest(Ud,stringReplace(Ef,Bd,""))){if(!((jh==="src"||jh==="xlink:href"||jh==="href")&&hh!=="script"&&stringIndexOf(Ef,"data:")===0&&sh[hh])){if(!(Mh&&!regExpTest(Od,stringReplace(Ef,Bd,"")))){if(Ef)return!1}}}}}else if(!(Np(hh)&&(Rd.tagNameCheck instanceof RegExp&&regExpTest(Rd.tagNameCheck,hh)||Rd.tagNameCheck instanceof Function&&Rd.tagNameCheck(hh))&&(Rd.attributeNameCheck instanceof RegExp&&regExpTest(Rd.attributeNameCheck,jh)||Rd.attributeNameCheck instanceof Function&&Rd.attributeNameCheck(jh,hh))||jh==="is"&&Rd.allowCustomizedBuiltInElements&&(Rd.tagNameCheck instanceof RegExp&&regExpTest(Rd.tagNameCheck,Ef)||Rd.tagNameCheck instanceof Function&&Rd.tagNameCheck(Ef))))return!1}}return!0},Mp=addToSet({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Np=function(hh){return!Mp[stringToLowerCase(hh)]&&regExpTest(Gd,hh)},Em=function(hh,jh,Ef,wf){if(ed&&typeof Fu=="object"&&typeof Fu.getAttributeType=="function"&&!Ef)switch(Fu.getAttributeType(hh,jh)){case"TrustedHTML":return ld(wf);case"TrustedScriptURL":return fd(wf)}return wf},nm=function(hh,jh,Ef,wf){try{Ef?hh.setAttributeNS(Ef,jh,wf):hh.setAttribute(jh,wf),dp(hh)?kp(hh):arrayPop(lo.removed)}catch{zp(jh,hh)}},qm=function(hh){hp(md.beforeSanitizeAttributes,hh,null);const jh=hh.attributes;if(!jh||dp(hh))return;const Ef={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Vd,forceKeepAttr:void 0};let wf=jh.length;const gf=Jh(hh.nodeName);for(;wf--;){const $f=jh[wf],vh=$f.name,Th=$f.namespaceURI,gh=$f.value,Kd=Jh(vh),dh=gh;let $h=vh==="value"?dh:stringTrim(dh);if(Ef.attrName=Kd,Ef.attrValue=$h,Ef.keepAttr=!0,Ef.forceKeepAttr=void 0,hp(md.uponSanitizeAttribute,hh,Ef),$h=Ef.attrValue,ah&&(Kd==="id"||Kd==="name")&&stringIndexOf($h,Ah)!==0&&(zp(vh,hh),$h=Ah+$h),_h&&regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,$h)){zp(vh,hh);continue}if(Kd==="attributename"&&stringMatch($h,"href")){zp(vh,hh);continue}if(!Ef.forceKeepAttr){if(!Ef.keepAttr){zp(vh,hh);continue}if(!Rh&&regExpTest(SELF_CLOSING_TAG,$h)){zp(vh,hh);continue}if(bh&&($h=Jf($h)),!um(gf,Kd,$h)){zp(vh,hh);continue}$h=Em(gf,Kd,Th,$h),$h!==dh&&nm(hh,vh,Th,$h)}}hp(md.afterSanitizeAttributes,hh,null)},Km=function(hh){let jh=null;const Ef=qp(hh);for(hp(md.beforeSanitizeShadowDOM,hh,null);jh=Ef.nextNode();)if(hp(md.uponSanitizeShadowNode,jh,null),cm(jh),qm(jh),Cp(jh.content)&&Km(jh.content),(Qu?Qu(jh):jh.nodeType)===NODE_TYPE.element){const gf=Ku(jh);Cp(gf)&&(Lp(gf),Km(gf))}hp(md.afterSanitizeShadowDOM,hh,null)},Lp=function(hh){const jh=[{node:hh,shadow:null}];for(;jh.length>0;){const Ef=jh.pop();if(Ef.shadow){Km(Ef.shadow);continue}const wf=Ef.node,$f=(Qu?Qu(wf):wf.nodeType)===NODE_TYPE.element,vh=Vu(wf);if(vh)for(let Th=vh.length-1;Th>=0;--Th)jh.push({node:vh[Th],shadow:null});if($f){const Th=Yu?Yu(wf):null;if(typeof Th=="string"&&Jh(Th)==="template"){const gh=wf.content;Cp(gh)&&jh.push({node:gh,shadow:null})}}if($f){const Th=Ku(wf);Cp(Th)&&jh.push({node:null,shadow:Th},{node:Th,shadow:null})}}};return lo.sanitize=function(Sf){let hh=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},jh=null,Ef=null,wf=null,gf=null;if(Cf=!Sf,Cf&&(Sf="<!-->"),typeof Sf!="string"&&!Tp(Sf)&&(Sf=stringifyValue(Sf),typeof Sf!="string"))throw typeErrorCreate("dirty is not a string, aborting");if(!lo.isSupported)return Sf;Sh?(Md=Dd,Vd=$d):Nf(hh),(md.uponSanitizeElement.length>0||md.uponSanitizeAttribute.length>0)&&(Md=clone(Md)),md.uponSanitizeAttribute.length>0&&(Vd=clone(Vd)),lo.removed=[];const $f=zh&&typeof Sf!="string"&&Tp(Sf);if($f){const gh=Yu?Yu(Sf):Sf.nodeName;if(typeof gh=="string"){const Kd=Jh(gh);if(!Md[Kd]||Ld[Kd])throw typeErrorCreate("root node is forbidden and cannot be sanitized in-place")}if(dp(Sf))throw typeErrorCreate("root node is clobbered and cannot be sanitized in-place");try{Lp(Sf)}catch(Kd){throw Bf(Sf),Kd}}else if(Tp(Sf))jh=pp("<!---->"),Ef=jh.ownerDocument.importNode(Sf,!0),Ef.nodeType===NODE_TYPE.element&&Ef.nodeName==="BODY"||Ef.nodeName==="HTML"?jh=Ef:jh.appendChild(Ef),Lp(Ef);else{if(!Fd&&!bh&&!eh&&Sf.indexOf("<")===-1)return ed&&Yd?ld(Sf):Sf;if(jh=pp(Sf),!jh)return Fd?null:Yd?Xu:""}jh&&jd&&kp(jh.firstChild);const vh=qp($f?Sf:jh);try{for(;wf=vh.nextNode();)cm(wf),qm(wf),Cp(wf.content)&&Km(wf.content)}catch(gh){throw $f&&Bf(Sf),gh}if($f)return arrayForEach(lo.removed,gh=>{gh.element&&sm(gh.element)}),bh&&gp(Sf),Sf;if(Fd){if(bh&&gp(jh),rh)for(gf=Td.call(jh.ownerDocument);jh.firstChild;)gf.appendChild(jh.firstChild);else gf=jh;return(Vd.shadowroot||Vd.shadowrootmode)&&(gf=ud.call(Ru,gf,!0)),gf}let Th=eh?jh.outerHTML:jh.innerHTML;return eh&&Md["!doctype"]&&jh.ownerDocument&&jh.ownerDocument.doctype&&jh.ownerDocument.doctype.name&&regExpTest(DOCTYPE_NAME,jh.ownerDocument.doctype.name)&&(Th="<!DOCTYPE "+jh.ownerDocument.doctype.name+`>
3544
- `+Th),bh&&(Th=Jf(Th)),ed&&Yd?ld(Th):Th},lo.setConfig=function(){let Sf=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Nf(Sf),Sh=!0,Dd=Md,$d=Vd},lo.clearConfig=function(){lf=null,Sh=!1,Dd=null,$d=null,ed=rd,Xu=""},lo.isValidAttribute=function(Sf,hh,jh){lf||Nf({});const Ef=Jh(Sf),wf=Jh(hh);return um(Ef,wf,jh)},lo.addHook=function(Sf,hh){typeof hh=="function"&&objectHasOwnProperty(md,Sf)&&arrayPush(md[Sf],hh)},lo.removeHook=function(Sf,hh){if(objectHasOwnProperty(md,Sf)){if(hh!==void 0){const jh=arrayLastIndexOf(md[Sf],hh);return jh===-1?void 0:arraySplice(md[Sf],jh,1)[0]}return arrayPop(md[Sf])}},lo.removeHooks=function(Sf){objectHasOwnProperty(md,Sf)&&(md[Sf]=[])},lo.removeAllHooks=function(){md=_createHooksMap()},lo}var purify$1=createDOMPurify();let purify;function sanitize(Au){if(!purify)if(typeof purify$1.sanitize=="function")purify=purify$1;else{const lo=globalThis.window;if(lo)purify=purify$1(lo);else throw new Error("DOMPurify requires a window object. If testing, provide a jsdom window as `globalThis`.")}return purify.sanitize(Au)}async function renderMarkdown(Au,lo){const $u=rawMarkdownRenderer.render(Au,lo?.tagClassMap);return sanitize($u)}const A2uiMarkdownProvider=({children:Au})=>jsxRuntimeExports.jsx(MarkdownContext.Provider,{value:renderMarkdown,children:Au});function applyA2uiClassFallbacks(Au){Au.querySelectorAll("button").forEach(lo=>{lo.classList.remove("undefined");const $u=lo;if($u.classList.contains("a2ui-tab-button")){$u.style.removeProperty("background"),$u.style.removeProperty("border"),$u.style.removeProperty("color"),$u.style.removeProperty("border-radius");return}if($u.classList.contains("chip")){$u.style.removeProperty("background"),$u.style.removeProperty("background-color"),$u.style.removeProperty("border"),$u.style.removeProperty("color");return}lo.classList.contains("a2ui-button")||lo.classList.add("a2ui-button"),lo.classList.contains("a2ui-button-primary")||lo.classList.add("a2ui-button-primary"),$u.style.removeProperty("background"),$u.style.removeProperty("border"),$u.style.removeProperty("color"),$u.style.removeProperty("border-radius"),$u.style.removeProperty("padding"),$u.style.removeProperty("font-weight"),$u.style.removeProperty("cursor")}),Au.querySelectorAll("input[type='text'], input[type='number'], input[type='password'], input[type='datetime-local'], textarea").forEach(lo=>{lo.classList.remove("undefined"),lo.classList.contains("a2ui-textfield-input")||lo.classList.add("a2ui-textfield-input")}),Au.querySelectorAll("label").forEach(lo=>{lo.classList.remove("undefined"),lo.classList.contains("a2ui-textfield-label")||lo.classList.add("a2ui-textfield-label")}),Au.querySelectorAll("span").forEach(lo=>{lo.textContent&&/invalid|required|error/i.test(lo.textContent)&&(lo.classList.contains("a2ui-textfield-error")||lo.classList.add("a2ui-textfield-error"))}),Au.querySelectorAll(".body, .caption").forEach(lo=>{lo.classList.remove("undefined"),lo.classList.contains("a2ui-text")||lo.classList.add("a2ui-text"),lo.classList.contains("caption")&&!lo.classList.contains("a2ui-caption")&&lo.classList.add("a2ui-caption")})}function A2uiSurfaceComposed({surface:Au}){const lo=reactExports.useRef(null);return reactExports.useEffect(()=>{const $u=lo.current;if(!$u)return;const Ru=()=>applyA2uiClassFallbacks($u);Ru();const Iu=new MutationObserver(()=>{Ru()});return Iu.observe($u,{childList:!0,subtree:!0}),()=>{Iu.disconnect()}},[Au]),jsxRuntimeExports.jsx("div",{ref:lo,children:jsxRuntimeExports.jsx(A2uiSurface,{surface:Au})})}const A2UI_INPUT_SELECTOR="& .a2ui-textfield-input",A2UI_INPUT_FOCUS_SELECTOR="& .a2ui-textfield-input:focus",A2UI_INPUT_HOVER_SELECTOR="& .a2ui-textfield-input:hover",A2UI_RENDER_SCOPE_SX={"--a2ui-icon-size":"1em","& .a2ui-card":{background:"var(--a2ui-card-background, var(--a2ui-color-surface, #f6f8fa))",border:"1px solid var(--a2ui-color-border, #d0d7de)",borderRadius:"var(--a2ui-card-border-radius, 12px)",boxShadow:"var(--a2ui-card-box-shadow, none)"},"& .a2ui-text":{color:"var(--a2ui-color-on-surface, var(--a2ui-color-on-background, #1f2328))",margin:0},"& .a2ui-caption":{color:"var(--a2ui-text-caption-color, var(--a2ui-color-on-surface, #656d76))"},"& .a2ui-button":{appearance:"none",cursor:"pointer",border:"1px solid var(--button-primary-bgColor-rest)",background:"var(--button-primary-bgColor-rest)",color:"var(--button-primary-fgColor-rest)",borderRadius:"var(--a2ui-button-border-radius, 6px)",padding:"var(--a2ui-button-padding, 5px 16px)",fontWeight:"var(--a2ui-button-font-weight, 500)",boxShadow:"var(--a2ui-button-box-shadow, none)",transition:"background-color 0.15s ease, border-color 0.15s ease"},"& .a2ui-button .a2ui-text":{color:"inherit"},"& .a2ui-button:hover":{background:"var(--button-primary-bgColor-hover)",borderColor:"var(--button-primary-bgColor-hover)"},"& .a2ui-button:disabled":{opacity:.6,cursor:"not-allowed"},"& .a2ui-tab-button":{appearance:"none",background:"transparent",border:"none",borderBottom:"2px solid transparent",borderRadius:0,marginBottom:"-1px",padding:"var(--a2ui-tab-padding, 8px 16px)",color:"var(--a2ui-tab-color, var(--a2ui-color-on-surface, #656d76))",cursor:"pointer",fontFamily:"inherit",fontSize:"var(--a2ui-font-size-sm, 14px)",fontWeight:500,boxShadow:"none",transition:"color 0.15s ease, border-color 0.15s ease, background-color 0.15s ease"},"& .a2ui-tab-button:hover":{color:"var(--a2ui-tab-color-hover, var(--a2ui-color-primary, #1f883d))",background:"var(--a2ui-tab-background-hover, var(--a2ui-color-surface, #f6f8fa))"},"& .a2ui-tab-button.active":{color:"var(--a2ui-tab-color-active, var(--a2ui-color-primary, #1f883d))",borderBottomColor:"var(--a2ui-tab-border-active, var(--a2ui-color-primary, #1f883d))",fontWeight:600},"& .chip":{appearance:"none",padding:"var(--a2ui-choicepicker-chip-padding, 4px 12px)",borderRadius:"var(--a2ui-choicepicker-chip-border-radius, 999px)",border:"1px solid var(--a2ui-color-border, #d0d7de)",background:"var(--a2ui-color-surface, #f6f8fa)",color:"var(--a2ui-color-on-surface, #1f2328)",cursor:"pointer",fontFamily:"inherit",fontSize:"var(--a2ui-font-size-sm, 14px)",fontWeight:500,boxShadow:"none",transition:"background-color 0.15s ease, border-color 0.15s ease, color 0.15s ease"},"& .chip:hover":{borderColor:"var(--a2ui-color-border-hover, var(--a2ui-color-primary, #1f883d))"},'& .chip.selected, & .chip[aria-pressed="true"]':{background:"var(--a2ui-color-primary, #1f883d)",borderColor:"var(--a2ui-color-primary, #1f883d)",color:"var(--a2ui-color-on-primary, #ffffff)"},[A2UI_INPUT_SELECTOR]:{width:"100%",minHeight:"var(--a2ui-control-height, 32px)",boxSizing:"border-box",background:"var(--a2ui-textfield-background, var(--a2ui-color-input, var(--a2ui-color-background, #ffffff)))",color:"var(--a2ui-textfield-color, var(--a2ui-color-on-input, var(--a2ui-color-on-background, #1f2328)))",border:"var(--a2ui-textfield-border, 1px solid var(--a2ui-color-border, #d0d7de))",borderRadius:"var(--a2ui-textfield-border-radius, 6px)",padding:"var(--a2ui-textfield-padding, 5px 12px)",fontSize:"var(--a2ui-font-size-sm, 14px)",lineHeight:"20px",transition:"border-color 0.15s ease, box-shadow 0.15s ease"},[A2UI_INPUT_HOVER_SELECTOR]:{borderColor:"var(--a2ui-textfield-color-border-hover, var(--a2ui-color-border-hover, #8c959f))"},[A2UI_INPUT_FOCUS_SELECTOR]:{outline:"none",borderColor:"var(--a2ui-textfield-color-border-focus, var(--a2ui-color-primary, #1f883d))",boxShadow:"0 0 0 3px color-mix(in srgb, var(--a2ui-color-primary, #1f883d) 25%, transparent)"},"& .a2ui-textfield-label":{color:"var(--a2ui-textfield-label-color, var(--a2ui-color-on-surface, var(--a2ui-color-on-background, #1f2328)))",fontWeight:600,fontSize:"var(--a2ui-font-size-xs, 12px)",marginBottom:"var(--a2ui-spacing-xxs, 4px)",display:"inline-block"},"& .a2ui-textfield-error":{color:"var(--a2ui-textfield-color-error, #d1242f)",fontSize:"var(--a2ui-font-size-xs, 12px)",marginTop:"var(--a2ui-spacing-xs, 4px)"},'& input[type="checkbox"]':{accentColor:"var(--a2ui-color-primary, #1f883d)"}},VISIBLE_WHEN="visible_when";function isShown(Au){return Array.isArray(Au)?Au.length>0:!!Au}const OWN_COMPONENT_IDS=Object.values(COMPONENT_CATALOGUE).filter(Au=>!Au.standard).map(Au=>Au.id);function ownComponent(Au){const lo=COMPONENT_CATALOGUE[Au];if(!lo)throw new Error(`The catalog has no component ${Au}.`);if(lo.standard||!lo.properties||!lo.bindings)throw new Error(`${Au} is A2UI's own: its schema is the basic catalog's, not Datalayer's.`);return lo}const BindingSchema=unionType$1([arrayType$1(anyType$1()),recordType$1(stringType$1(),unknownType$1()),stringType$1(),numberType$1(),booleanType$1(),DataBindingSchema]).describe("REF:#/$defs/DynamicValue|Datalayer: what the component shows or sends — a path the application publishes or takes, or a value given in place.");function propertySchema(Au,lo){if(lo.enum)return enumType$1(lo.enum);switch(lo.type){case"string":return stringType$1();case"integer":case"number":return numberType$1();case"boolean":return booleanType$1();case"array":return arrayType$1(anyType$1());case"object":return recordType$1(stringType$1(),unknownType$1());default:throw new Error(`${Au} is typed ${String(lo.type)}, which a component's property cannot be.`)}}function bindingNames(Au){const{shows:lo,sends:$u}=Au.bindings;return[...new Set([...lo,...$u])]}function ownComponentSchema(Au){return componentSchemaOf(ownComponent(Au))}function componentSchemaOf(Au){const lo=Au.id;if(!Au.bindings)throw new Error(`${lo} says nothing of what it shows or sends.`);const $u=Au.properties,Ru=new Set($u.required??[]),Iu={};for(const[Ou,Pu]of Object.entries($u.properties??{})){const Du=propertySchema(Ou,Pu);Iu[Ou]=Ru.has(Ou)?Du:Du.optional()}for(const Ou of bindingNames(Au)){if(Ou in Iu)throw new Error(`${lo} both declares ${Ou} as a property and binds through it.`);Iu[Ou]=BindingSchema.optional()}return Iu.action=ActionSchema.describe("REF:#/$defs/Action|What it dispatches when a person acts on it.").optional(),Iu.weight=numberType$1().describe("The relative weight of this component within a Row or Column.").optional(),objectType$1(Iu).strict()}const DRAWN_OWN_COMPONENTS=["Table","Chart","FileUpload","Chat","Evidence","Form","Download"],CARD_RADIUS="var(--theme-radius-card, 6px)";function BlockFrame({title:Au,label:lo,weight:$u,children:Ru,testId:Iu}){return jsxRuntimeExports.jsxs(Box,{as:"section","aria-label":Au||lo,"data-testid":Iu,display:"flex",flexDirection:"column",gap:2,minWidth:0,boxSizing:"border-box",p:3,border:"1px solid",borderColor:"border.default",borderRadius:CARD_RADIUS,bg:"canvas.default",color:"fg.default",flex:typeof $u=="number"?`${$u}`:void 0,minHeight:typeof $u=="number"?0:void 0,children:[Au?jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,m:0},children:Au}):null,Ru]})}function Problem({children:Au}){return jsxRuntimeExports.jsx(Text$5,{as:"p",role:"status",sx:{m:0,color:"danger.fg",fontSize:1},children:Au})}function Quiet({children:Au}){return jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{m:0,color:"fg.muted",fontSize:1},children:Au})}const isRecord=Au=>typeof Au=="object"&&Au!==null&&!Array.isArray(Au);function asWords(Au){return Au==null?"":typeof Au=="object"?JSON.stringify(Au):String(Au)}function ownImplementation(Au,lo){const $u={name:Au,schema:ownComponentSchema(Au)};return createComponentImplementation($u,lo)}const PAGE_SIZE=20,sameRow=(Au,lo)=>Au!==void 0&&JSON.stringify(Au)===JSON.stringify(lo);function tableRows(Au){if(Au==null)return{rows:[]};if(!Array.isArray(Au))return{problem:"What it shows is not a list of rows."};const lo=Au.findIndex($u=>!isRecord($u));return lo>=0?{problem:`Row ${lo+1} is not a record of the columns' values.`}:{rows:Au}}function TableView({props:Au}){const{title:lo,columns:$u,selectable:Ru=!1,selected:Iu,setSelected:Ou,action:Pu}=Au,Du=Au.page_size??PAGE_SIZE,Lu=reactExports.useMemo(()=>tableRows(Au.rows),[Au.rows]),ju="rows"in Lu?Lu.rows:[],Bu=Math.max(1,Math.ceil(ju.length/Du)),[Fu,zu]=reactExports.useState(0);reactExports.useEffect(()=>{Fu>=Bu&&zu(Bu-1)},[Fu,Bu]);const qu=ju.slice(Fu*Du,(Fu+1)*Du),[Uu,Hu]=reactExports.useState(void 0),Vu=Iu??Uu,Gu=Zu=>{Hu(Zu),Ou(Zu),Pu?.()},Ku=(Zu,Qu)=>{(Zu.key==="Enter"||Zu.key===" ")&&(Zu.preventDefault(),Gu(Qu))};return jsxRuntimeExports.jsxs(BlockFrame,{title:lo,label:"Table",weight:Au.weight,testId:"a2ui-table",children:["problem"in Lu?jsxRuntimeExports.jsx(Problem,{children:Lu.problem}):jsxRuntimeExports.jsxs(Box,{overflowX:"auto",children:[jsxRuntimeExports.jsxs(Box,{as:"table",role:Ru?"grid":void 0,"aria-label":lo||"Table",width:"100%",borderCollapse:"collapse",fontSize:1,sx:{"& th, & td":{textAlign:"left",px:2,py:1,borderBottom:"1px solid",borderColor:"border.muted"},"& th":{color:"fg.muted",fontWeight:"semibold"}},children:[jsxRuntimeExports.jsx("thead",{children:jsxRuntimeExports.jsx("tr",{children:$u.map(Zu=>jsxRuntimeExports.jsx("th",{scope:"col",children:Zu},Zu))})}),jsxRuntimeExports.jsx("tbody",{children:qu.map((Zu,Qu)=>{const Yu=Ru&&sameRow(Vu,Zu);return jsxRuntimeExports.jsx(Box,{as:"tr",...Ru?{tabIndex:0,"aria-selected":Yu,onClick:()=>Gu(Zu),onKeyDown:ed=>Ku(ed,Zu)}:null,cursor:Ru?"pointer":void 0,bg:Yu?"accent.subtle":void 0,focusVisible:{outline:"2px solid",outlineColor:"accent.fg",outlineOffset:"-2px"},hover:Ru?{bg:Yu?"accent.subtle":"canvas.subtle"}:void 0,children:$u.map(ed=>jsxRuntimeExports.jsx("td",{children:asWords(Zu[ed])},ed))},Fu*Du+Qu)})})]}),ju.length===0?jsxRuntimeExports.jsx(Quiet,{children:"No rows yet."}):null]}),Bu>1?jsxRuntimeExports.jsxs(Box,{as:"nav","aria-label":"Pages",display:"flex",alignItems:"center",gap:2,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Fu===0,onClick:()=>zu(Fu-1),children:"Previous"}),jsxRuntimeExports.jsxs(Text$5,{sx:{fontSize:1,color:"fg.muted"},"aria-live":"polite",children:["Page ",Fu+1," of ",Bu]}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Fu>=Bu-1,onClick:()=>zu(Fu+1),children:"Next"})]}):null]})}const Table=ownImplementation("Table",TableView),loadECharts=()=>__vitePreload(()=>import("./chunks/index-74YA-L1Q.js"),[],import.meta.url),chartRefused=Au=>jsxRuntimeExports.jsx(Problem,{children:`The chart could not be drawn: ${Au.message}`}),FALLBACK={series:["#0969da","#1a7f37","#9a6700","#8250df","#cf222e","#bc4c00"],text:"#1f2328",muted:"#59636e",grid:"#d1d9e0"},SERIES_VARIABLES=["--fgColor-accent","--fgColor-success","--fgColor-attention","--fgColor-done","--fgColor-danger","--fgColor-severe"];function readColours(Au){if(!Au)return FALLBACK;const lo=getComputedStyle(Au),$u=(Ru,Iu)=>lo.getPropertyValue(Ru).trim()||Iu;return{series:SERIES_VARIABLES.map((Ru,Iu)=>$u(Ru,FALLBACK.series[Iu])),text:$u("--fgColor-default",FALLBACK.text),muted:$u("--fgColor-muted",FALLBACK.muted),grid:$u("--borderColor-muted",FALLBACK.grid)}}function chartPoints(Au){return Au==null?{points:[]}:!Array.isArray(Au)||Au.some(lo=>!isRecord(lo))?{problem:"What it shows is not a list of points."}:{points:Au}}function chartSeries(Au,lo){if(!lo.series)return[{name:lo.y,points:Au}];const $u=[];for(const Ru of Au){const Iu=asWords(Ru[lo.series]);$u.includes(Iu)||$u.push(Iu)}return $u.map(Ru=>({name:Ru,points:Au.filter(Iu=>asWords(Iu[lo.series])===Ru)}))}function chartOption(Au,lo,$u){const Ru=chartSeries(Au,lo),Iu=lo.kind==="scatter",Ou=[];for(const Du of Au){const Lu=asWords(Du[lo.x]);Ou.includes(Lu)||Ou.push(Lu)}const Pu={axisLine:{lineStyle:{color:$u.grid}},axisLabel:{color:$u.muted},splitLine:{lineStyle:{color:$u.grid}},nameTextStyle:{color:$u.muted}};return{aria:{enabled:!0},animation:!1,color:$u.series,textStyle:{color:$u.text},grid:{left:48,right:16,top:Ru.length>1?48:32,bottom:40},legend:Ru.length>1?{top:0,textStyle:{color:$u.text}}:void 0,tooltip:{trigger:Iu?"item":"axis"},xAxis:Iu?{type:"value",name:lo.x,nameLocation:"middle",nameGap:26,...Pu}:{type:"category",data:Ou,name:lo.x,nameLocation:"middle",nameGap:26,...Pu},yAxis:{type:"value",name:lo.y,...Pu},series:Ru.map(Du=>({name:Du.name,type:lo.kind==="area"?"line":lo.kind,areaStyle:lo.kind==="area"?{}:void 0,data:Iu?Du.points.map(Lu=>[Number(Lu[lo.x]),Number(Lu[lo.y])]):Ou.map(Lu=>{const ju=Du.points.find(Bu=>asWords(Bu[lo.x])===Lu);return ju?Number(ju[lo.y]):null})}))}}function ChartView({props:Au}){const{title:lo,kind:$u,x:Ru,y:Iu,series:Ou}=Au,Pu=reactExports.useMemo(()=>chartPoints(Au.points),[Au.points]),Du=reactExports.useRef(null),[Lu,ju]=reactExports.useState(FALLBACK);reactExports.useLayoutEffect(()=>{ju(readColours(Du.current))},[]);const Bu="points"in Pu?Pu.points:[],Fu=reactExports.useMemo(()=>chartOption(Bu,{kind:$u,x:Ru,y:Iu,series:Ou},Lu),[Bu,$u,Ru,Iu,Ou,Lu]),zu=Ou?[Ru,Ou,Iu]:[Ru,Iu],qu=`${lo||"Chart"}: ${Iu} by ${Ru}, as a ${$u}`;return jsxRuntimeExports.jsx(BlockFrame,{title:lo,label:"Chart",weight:Au.weight,testId:"a2ui-chart",children:jsxRuntimeExports.jsx(Box,{ref:Du,children:"problem"in Pu?jsxRuntimeExports.jsx(Problem,{children:Pu.problem}):Bu.length===0?jsxRuntimeExports.jsx(Quiet,{children:"No points yet."}):jsxRuntimeExports.jsxs(Box,{as:"figure","aria-label":qu,m:0,children:[jsxRuntimeExports.jsx("div",{"aria-hidden":"true",children:jsxRuntimeExports.jsx(ReactorLazy,{load:loadECharts,errorFallback:chartRefused,fallback:jsxRuntimeExports.jsx(Box,{height:240}),props:{option:Fu,style:{height:240,width:"100%"},opts:{renderer:"svg"},notMerge:!0,lazyUpdate:!0}})}),jsxRuntimeExports.jsxs(Box,{as:"details",fontSize:1,children:[jsxRuntimeExports.jsx(Box,{as:"summary",cursor:"pointer",color:"fg.muted",focusVisible:{outline:"2px solid",outlineColor:"accent.fg"},children:jsxRuntimeExports.jsx(Text$5,{children:"The numbers"})}),jsxRuntimeExports.jsxs(Box,{as:"table",mt:1,borderCollapse:"collapse",sx:{"& th, & td":{textAlign:"left",pr:3,py:"2px"},"& th":{color:"fg.muted",fontWeight:"semibold"}},children:[jsxRuntimeExports.jsx("thead",{children:jsxRuntimeExports.jsx("tr",{children:zu.map(Uu=>jsxRuntimeExports.jsx("th",{scope:"col",children:Uu},Uu))})}),jsxRuntimeExports.jsx("tbody",{children:Bu.map((Uu,Hu)=>jsxRuntimeExports.jsx("tr",{children:zu.map(Vu=>jsxRuntimeExports.jsx("td",{children:asWords(Uu[Vu])},Vu))},Hu))})]})]})]})})})}const Chart=ownImplementation("Chart",ChartView),MAX_MB=25;function refusal(Au,lo,$u){return acceptsFile(lo,{name:Au.name,type:Au.type??""})?Au.size>$u*1024*1024?`${Au.name} is larger than ${$u} MB.`:null:`${Au.name} is not one it takes (${(lo??[]).join(", ")}).`}const readFile=Au=>new Promise((lo,$u)=>{const Ru=new FileReader;Ru.onload=()=>lo({name:Au.name,type:Au.type,size:Au.size,data_url:String(Ru.result)}),Ru.onerror=()=>$u(Ru.error),Ru.readAsDataURL(Au)});function FileUploadView({props:Au}){const{label:lo,accept:$u,multiple:Ru=!1,setFiles:Iu,action:Ou}=Au,Pu=Au.max_mb??MAX_MB,Du=reactExports.useRef(null),Lu=reactExports.useId(),[ju,Bu]=reactExports.useState(!1),[Fu,zu]=reactExports.useState([]),qu=Array.isArray(Au.files)?Au.files.filter(isRecord).map(Gu=>String(Gu.name??"")):[],Uu=async Gu=>{const Ku=Array.from(Gu),Zu=Ru?Ku:Ku.slice(0,1),Qu=Zu.map(Yu=>refusal(Yu,$u,Pu)).filter(Yu=>Yu!==null);!Ru&&Ku.length>1&&Qu.push("It takes one file at a time."),zu(Qu),!Qu.length&&(Iu(await Promise.all(Zu.map(readFile))),Ou?.())},Hu=Gu=>{Gu.preventDefault(),Bu(!1),Uu(Gu.dataTransfer.files)},Vu=[$u?.length?`Takes ${$u.join(", ")}`:"Takes any file",`up to ${Pu} MB`,Ru?"several at once":"one at a time"].join(", ");return jsxRuntimeExports.jsxs(BlockFrame,{label:lo,weight:Au.weight,testId:"a2ui-fileupload",children:[jsxRuntimeExports.jsxs(Box,{onDragOver:Gu=>{Gu.preventDefault(),Bu(!0)},onDragLeave:()=>Bu(!1),onDrop:Hu,"data-testid":"a2ui-fileupload-drop",display:"flex",flexDirection:"column",alignItems:"center",gap:2,p:3,border:"1px dashed",borderColor:ju?"accent.fg":"border.default",borderRadius:CARD_RADIUS,bg:ju?"accent.subtle":"canvas.subtle",textAlign:"center",children:[jsxRuntimeExports.jsx(Text$5,{sx:{fontWeight:"semibold"},children:lo}),jsxRuntimeExports.jsx(ButtonComponent,{leadingVisual:UploadIcon,"aria-describedby":Lu,onClick:()=>Du.current?.click(),children:Ru?"Choose files":"Choose a file"}),jsxRuntimeExports.jsxs(Text$5,{id:Lu,sx:{fontSize:0,color:"fg.muted"},children:["or drop ",Ru?"them":"it"," here. ",Vu,"."]}),jsxRuntimeExports.jsx("input",{ref:Du,type:"file",hidden:!0,"aria-label":lo,accept:$u?.join(","),multiple:Ru,onChange:Gu=>{Gu.target.files&&Uu(Gu.target.files),Gu.target.value=""}})]}),Fu.map(Gu=>jsxRuntimeExports.jsx(Problem,{children:Gu},Gu)),qu.length?jsxRuntimeExports.jsxs(Quiet,{children:["Given: ",qu.join(", ")]}):null]})}const FileUpload=ownImplementation("FileUpload",FileUploadView),PLACEHOLDER="Ask anything",AVATARS={userAvatar:jsxRuntimeExports.jsx(PersonIcon,{size:14}),assistantAvatar:jsxRuntimeExports.jsx(DependabotIcon,{size:14}),showAvatars:!0,avatarSize:24,userAvatarBg:"neutral.muted",assistantAvatarBg:"accent.emphasis"},NO_TIME=new Date(0);function chatItems(Au,lo){if(Au==null)return{items:[]};if(!Array.isArray(Au))return{problem:"What it shows is not a list of messages."};const $u=[];for(const[Ru,Iu]of Au.entries()){const Ou=`m${Ru}`;if(!isRecord(Iu))return{problem:`Message ${Ru+1} is not a message.`};if(Iu.role==="tool"){lo&&$u.push({id:Ou,type:"tool-call",toolCallId:Ou,toolName:asWords(Iu.name)||"tool",args:isRecord(Iu.args)?Iu.args:{},result:Iu.result,status:"complete"});continue}if(Iu.role!=="user"&&Iu.role!=="assistant")return{problem:`Message ${Ru+1} is from ${asWords(Iu.role)||"nobody"}: a message is the user's, the assistant's or a tool's.`};$u.push({id:Ou,role:Iu.role,content:asWords(Iu.text??Iu.content),createdAt:NO_TIME})}return{items:$u}}function ChatView({props:Au}){const{welcome:lo,starters:$u=[],setMessage:Ru,action:Iu}=Au,Ou=Au.placeholder??PLACEHOLDER,Pu=Au.show_tools??!0,Du=reactExports.useMemo(()=>chatItems(Au.messages,Pu),[Au.messages,Pu]),[Lu,ju]=reactExports.useState(""),Bu=reactExports.useMemo(()=>reactExports.createRef(),[]),Fu=reactExports.useMemo(()=>reactExports.createRef(),[]),zu=qu=>{const Uu=qu.trim();Uu&&(Ru(Uu),Iu?.(),ju(""))};return jsxRuntimeExports.jsxs(BlockFrame,{label:"Chat",weight:Au.weight,testId:"a2ui-chat",children:["problem"in Du?jsxRuntimeExports.jsx(Problem,{children:Du.problem}):jsxRuntimeExports.jsx(Box,{maxHeight:420,overflowY:"auto",borderRadius:CARD_RADIUS,children:jsxRuntimeExports.jsx(ChatMessageList,{displayItems:Du.items,isLoading:!1,isStreaming:!1,showLoadingIndicator:!1,hideMessagesAfterToolUI:!1,avatarConfig:AVATARS,padding:2,emptyContent:jsxRuntimeExports.jsx(ChatEmptyState,{description:"",emptyState:{title:lo||"Start a conversation"},suggestions:$u.map(qu=>({title:qu,message:qu})),onSuggestionSubmit:qu=>zu(qu.message)}),messagesEndRef:Bu,onRespond:async()=>{}})}),jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"flex-end",gap:2,children:[jsxRuntimeExports.jsx(Box,{flex:1,minWidth:0,children:jsxRuntimeExports.jsx(InputPromptText,{value:Lu,onChange:ju,placeholder:Ou,onSubmit:()=>zu(Lu),inputRef:Fu})}),jsxRuntimeExports.jsx(IconButton,{icon:PaperAirplaneIcon,"aria-label":"Send",variant:"primary",disabled:!Lu.trim(),onClick:()=>zu(Lu)})]})]})}const Chat=ownImplementation("Chat",ChatView),TITLE="Sources",MAX_ITEMS=5;function evidenceSources(Au){if(Au==null)return{sources:[]};if(!Array.isArray(Au))return{problem:"What it shows is not a list of sources."};const lo=[];for(const[$u,Ru]of Au.entries()){if(!isRecord(Ru)||!Ru.title&&!Ru.url)return{problem:`Source ${$u+1} has neither a title nor a link.`};lo.push({title:asWords(Ru.title)||asWords(Ru.url),url:asWords(Ru.url),passage:asWords(Ru.passage)})}return{sources:lo}}function EvidenceView({props:Au}){const{show_passages:lo=!0,action:$u}=Au,Ru=Au.title??TITLE,Iu=Au.max_items??MAX_ITEMS,Ou=reactExports.useMemo(()=>evidenceSources(Au.sources),[Au.sources]),[Pu,Du]=reactExports.useState(!1),Lu="sources"in Ou?Ou.sources:[],ju=Pu?Lu:Lu.slice(0,Iu),Bu=Lu.length-ju.length;return jsxRuntimeExports.jsxs(BlockFrame,{title:Ru,label:"Evidence",weight:Au.weight,testId:"a2ui-evidence",children:["problem"in Ou?jsxRuntimeExports.jsx(Problem,{children:Ou.problem}):Lu.length===0?jsxRuntimeExports.jsx(Quiet,{children:"Nothing cited yet."}):jsxRuntimeExports.jsx(Box,{as:"ol",m:0,pl:3,display:"flex",flexDirection:"column",gap:2,children:ju.map((Fu,zu)=>jsxRuntimeExports.jsxs("li",{children:[Fu.url?jsxRuntimeExports.jsxs(Link$1,{href:Fu.url,target:"_blank",rel:"noreferrer noopener",onClick:()=>$u?.(),sx:{fontWeight:"semibold"},children:[Fu.title," ",jsxRuntimeExports.jsx(LinkExternalIcon,{size:12,"aria-label":"opens in a new tab"})]}):jsxRuntimeExports.jsx(Text$5,{sx:{fontWeight:"semibold"},children:Fu.title}),lo&&Fu.passage?jsxRuntimeExports.jsx(Box,{as:"blockquote",m:0,mt:1,pl:2,borderLeft:"3px solid",borderColor:"border.default",color:"fg.muted",fontSize:1,children:Fu.passage}):null]},`${Fu.url}-${zu}`))}),Bu>0?jsxRuntimeExports.jsx(Box,{children:jsxRuntimeExports.jsxs(ButtonComponent,{size:"small",variant:"invisible",onClick:()=>Du(!0),children:[Bu," more"]})}):null]})}const Evidence=ownImplementation("Evidence",EvidenceView),loadSchemaForm=()=>__vitePreload(()=>import("./chunks/SchemaForm-8b_dpfFK.js"),[],import.meta.url),formRefused=Au=>jsxRuntimeExports.jsx(Problem,{children:`The form could not be drawn: ${Au.message}`}),SUBMIT_LABEL="Send";function FormView({props:Au}){const{title:lo,schema:$u,setValues:Ru,action:Iu}=Au,Ou=Au.submit_label??SUBMIT_LABEL,Pu=isRecord(Au.values)?Au.values:{},[Du,Lu]=reactExports.useState(Pu),[ju,Bu]=reactExports.useState(!1),Fu=JSON.stringify(Pu);reactExports.useEffect(()=>{Lu(JSON.parse(Fu))},[Fu]);const zu=Iu===void 0,qu=JSON.stringify(Au.ui??{}),Uu=reactExports.useMemo(()=>({...JSON.parse(qu),"ui:submitButtonOptions":zu?{norender:!0}:{submitText:Ou}}),[qu,zu,Ou]),Hu=$u.type!==void 0&&$u.type!=="object"?"Its fields are not an object schema: a form asks for several named values.":null;return jsxRuntimeExports.jsx(BlockFrame,{title:lo,label:"Form",weight:Au.weight,testId:"a2ui-form",children:Hu?jsxRuntimeExports.jsx(Problem,{children:Hu}):jsxRuntimeExports.jsx(ReactorLazy,{load:loadSchemaForm,errorFallback:formRefused,props:{schema:$u,uiSchema:Uu,formData:Du,liveValidate:ju,onBlur:()=>Bu(!0),onError:()=>Bu(!0),showErrorList:!1,onChange:Vu=>{const Gu=Vu.formData??{};Lu(Gu),zu&&Ru(Gu)},onSubmit:Vu=>{Ru(Vu.formData??{}),Iu?.()}}})})}const Form=ownImplementation("Form",FormView),SCHEMES=/^(https?:\/\/|data:)/i;function sizeInWords(Au){if(typeof Au!="number"||!Number.isFinite(Au)||Au<0)return"";if(Au<1024)return Au===1?"1 byte":`${Au} bytes`;const lo=["KB","MB","GB"];let $u=Au/1024,Ru=0;for(;$u>=1024&&Ru<lo.length-1;)$u/=1024,Ru+=1;return`${$u<10?$u.toFixed(1):Math.round($u)} ${lo[Ru]}`}function downloadOf(Au){const lo=typeof Au.name=="string"?Au.name.trim():"",$u=typeof Au.url=="string"?Au.url.trim():"";return lo?$u?SCHEMES.test($u)?{name:lo,url:$u}:{problem:`${lo} is not offered: its link is neither an http(s) link nor a data: URL.`}:{problem:`${lo} has no link.`}:{problem:"This file has no name."}}function DownloadView({props:Au}){const{action:lo}=Au,$u=reactExports.useMemo(()=>downloadOf({name:Au.name,url:Au.url}),[Au.name,Au.url]),Ru=[Au.media_type,sizeInWords(Au.size)].filter(Boolean).join(" · ");return jsxRuntimeExports.jsx(BlockFrame,{label:"File to download",weight:Au.weight,testId:"a2ui-download",children:"problem"in $u?jsxRuntimeExports.jsx(Problem,{children:$u.problem}):jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,alignItems:"flex-start",children:[jsxRuntimeExports.jsx(Box,{color:"fg.muted",pt:"2px",children:jsxRuntimeExports.jsx(DownloadIcon,{size:16,"aria-hidden":"true"})}),jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",minWidth:0,children:[jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Link$1,{href:$u.url,download:$u.name,target:"_blank",rel:"noreferrer noopener",onClick:()=>lo?.(),sx:{fontWeight:"semibold",wordBreak:"break-word"},children:$u.name}),Ru?jsxRuntimeExports.jsx(Text$5,{sx:{color:"fg.muted",fontSize:1,ml:2},children:Ru}):null]}),Au.description?jsxRuntimeExports.jsx(Text$5,{sx:{color:"fg.muted",fontSize:1},children:Au.description}):null]})]})})}const Download=ownImplementation("Download",DownloadView),RENDERERS={Table,Chart,FileUpload,Chat,Evidence,Form,Download},OWN_COMPONENTS=(()=>{const Au=DRAWN_OWN_COMPONENTS,lo=OWN_COMPONENT_IDS.filter(Ru=>!Au.includes(Ru));if(lo.length)throw new Error(`The catalog has ${lo.join(", ")}, which no renderer draws.`);const $u=Au.filter(Ru=>!OWN_COMPONENT_IDS.includes(Ru));if($u.length)throw new Error(`A renderer draws ${$u.join(", ")}, which the catalog does not have.`);return OWN_COMPONENT_IDS.map(Ru=>RENDERERS[Ru])})();function nodeIsShown(Au){const lo=Au[VISIBLE_WHEN];if(!(lo instanceof ResolvedBinding))throw new Error(`${VISIBLE_WHEN} resolved to ${String(lo)}, not a binding: the catalog's schema does not declare it.`);return isWritable(lo)?isShown(lo.value):lo.value===void 0||isShown(lo.value)}const VISIBLE_WHEN_SCHEMA=DynamicBooleanSchema.describe("REF:#/$defs/DynamicBoolean|Datalayer: the block is shown only while this is true or not empty — a path the application publishes.").optional();function withVisibleWhen(Au){const lo=Au.view;if(!lo)throw new Error(`${Au.name} has no node view: visible_when is read from the node, and A2uiSurface draws through it.`);const $u=Au.schema;if(!$u.shape||typeof $u.extend!="function")throw new Error(`${Au.name}'s schema is not an object: visible_when cannot be declared on it.`);if(VISIBLE_WHEN in $u.shape)throw new Error(`${Au.name} already declares ${VISIBLE_WHEN}.`);const Ru=({node:Iu,buildChild:Ou})=>{const Pu=useSignalValue(Iu.props);return nodeIsShown(Pu)?jsxRuntimeExports.jsx(lo,{node:Iu,buildChild:Ou}):null};return Ru.displayName=`${Au.name}.visibleWhen`,{...Au,schema:$u.extend({[VISIBLE_WHEN]:VISIBLE_WHEN_SCHEMA}),view:Ru}}const datalayerCatalog=new Catalog(basicCatalog.id,basicCatalog.protocolVersion,[...basicCatalog.components.values(),...OWN_COMPONENTS].map(withVisibleWhen),[...basicCatalog.functions.values()],basicCatalog.themeSchema,basicCatalog.instructions);function catalogOfBlocks(Au,lo=[]){const $u=new Map(lo.map(Ou=>[Ou.name,withVisibleWhen(Ou)])),Ru=[...$u.keys()].filter(Ou=>datalayerCatalog.components.has(Ou));if(Ru.length>0)throw new Error(`${Ru.join(", ")} ${Ru.length===1?"is a component":"are components"} of the catalog: a component of an application's own is named otherwise.`);const Iu=Au.filter(Ou=>!datalayerCatalog.components.has(Ou)&&!$u.has(Ou));if(Iu.length>0)throw new Error(`No renderer draws ${Iu.join(", ")}: a block is contributed by a plugin whose component the catalog draws.`);return new Catalog(datalayerCatalog.id,datalayerCatalog.protocolVersion,Au.map(Ou=>datalayerCatalog.components.get(Ou)??$u.get(Ou)),[...datalayerCatalog.functions.values()],datalayerCatalog.themeSchema,datalayerCatalog.instructions)}function catalogWithOwn(Au){return Au.length===0?datalayerCatalog:catalogOfBlocks([...datalayerCatalog.components.keys(),...Au.map(lo=>lo.name)],Au)}function customComponentEntry(Au,lo){return{id:Au.name,name:Au.name,description:Au.description,category:"custom",emoji:"🧩",version:lo,standard:!1,properties:Au.props,bindings:{shows:[...Au.shows],sends:[...Au.sends]},events:Au.sends.length>0?["send"]:[],...Au.example?{example:Au.example}:{}}}const CUSTOM_FRAME_SANDBOX="allow-scripts",MAX_MODULE_BYTES=2*1024*1024,FRAME_TAG="loop.component";function customFramePolicy(Au){return["default-src 'none'",`script-src 'nonce-${Au}' blob:`,"style-src 'unsafe-inline'","img-src data: blob:","font-src data:","media-src data: blob:","form-action 'none'","base-uri 'none'"].join("; ")}function frameNonce(){const Au=new Uint8Array(16);return crypto.getRandomValues(Au),Array.from(Au,lo=>lo.toString(16).padStart(2,"0")).join("")}function customFrameDocument(Au,lo){const $u=lo.replace(/[&<>"]/g,Ru=>`&#${Ru.charCodeAt(0)};`);return`<!doctype html>
3544
+ `+Th),bh&&(Th=Jf(Th)),ed&&Yd?ld(Th):Th},lo.setConfig=function(){let Sf=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Nf(Sf),Sh=!0,Dd=Md,$d=Vd},lo.clearConfig=function(){lf=null,Sh=!1,Dd=null,$d=null,ed=rd,Xu=""},lo.isValidAttribute=function(Sf,hh,jh){lf||Nf({});const Ef=Jh(Sf),wf=Jh(hh);return um(Ef,wf,jh)},lo.addHook=function(Sf,hh){typeof hh=="function"&&objectHasOwnProperty(md,Sf)&&arrayPush(md[Sf],hh)},lo.removeHook=function(Sf,hh){if(objectHasOwnProperty(md,Sf)){if(hh!==void 0){const jh=arrayLastIndexOf(md[Sf],hh);return jh===-1?void 0:arraySplice(md[Sf],jh,1)[0]}return arrayPop(md[Sf])}},lo.removeHooks=function(Sf){objectHasOwnProperty(md,Sf)&&(md[Sf]=[])},lo.removeAllHooks=function(){md=_createHooksMap()},lo}var purify$1=createDOMPurify();let purify;function sanitize(Au){if(!purify)if(typeof purify$1.sanitize=="function")purify=purify$1;else{const lo=globalThis.window;if(lo)purify=purify$1(lo);else throw new Error("DOMPurify requires a window object. If testing, provide a jsdom window as `globalThis`.")}return purify.sanitize(Au)}async function renderMarkdown(Au,lo){const $u=rawMarkdownRenderer.render(Au,lo?.tagClassMap);return sanitize($u)}const A2uiMarkdownProvider=({children:Au})=>jsxRuntimeExports.jsx(MarkdownContext.Provider,{value:renderMarkdown,children:Au});function applyA2uiClassFallbacks(Au){Au.querySelectorAll("button").forEach(lo=>{lo.classList.remove("undefined");const $u=lo;if($u.classList.contains("a2ui-tab-button")){$u.style.removeProperty("background"),$u.style.removeProperty("border"),$u.style.removeProperty("color"),$u.style.removeProperty("border-radius");return}if($u.classList.contains("chip")){$u.style.removeProperty("background"),$u.style.removeProperty("background-color"),$u.style.removeProperty("border"),$u.style.removeProperty("color");return}lo.classList.contains("a2ui-button")||lo.classList.add("a2ui-button"),lo.classList.contains("a2ui-button-primary")||lo.classList.add("a2ui-button-primary"),$u.style.removeProperty("background"),$u.style.removeProperty("border"),$u.style.removeProperty("color"),$u.style.removeProperty("border-radius"),$u.style.removeProperty("padding"),$u.style.removeProperty("font-weight"),$u.style.removeProperty("cursor")}),Au.querySelectorAll("input[type='text'], input[type='number'], input[type='password'], input[type='datetime-local'], textarea").forEach(lo=>{lo.classList.remove("undefined"),lo.classList.contains("a2ui-textfield-input")||lo.classList.add("a2ui-textfield-input")}),Au.querySelectorAll("label").forEach(lo=>{lo.classList.remove("undefined"),lo.classList.contains("a2ui-textfield-label")||lo.classList.add("a2ui-textfield-label")}),Au.querySelectorAll("span").forEach(lo=>{lo.textContent&&/invalid|required|error/i.test(lo.textContent)&&(lo.classList.contains("a2ui-textfield-error")||lo.classList.add("a2ui-textfield-error"))}),Au.querySelectorAll(".body, .caption").forEach(lo=>{lo.classList.remove("undefined"),lo.classList.contains("a2ui-text")||lo.classList.add("a2ui-text"),lo.classList.contains("caption")&&!lo.classList.contains("a2ui-caption")&&lo.classList.add("a2ui-caption")})}function A2uiSurfaceComposed({surface:Au}){const lo=reactExports.useRef(null);return reactExports.useEffect(()=>{const $u=lo.current;if(!$u)return;const Ru=()=>applyA2uiClassFallbacks($u);Ru();const Iu=new MutationObserver(()=>{Ru()});return Iu.observe($u,{childList:!0,subtree:!0}),()=>{Iu.disconnect()}},[Au]),jsxRuntimeExports.jsx("div",{ref:lo,children:jsxRuntimeExports.jsx(A2uiSurface,{surface:Au})})}const A2UI_INPUT_SELECTOR="& .a2ui-textfield-input",A2UI_INPUT_FOCUS_SELECTOR="& .a2ui-textfield-input:focus",A2UI_INPUT_HOVER_SELECTOR="& .a2ui-textfield-input:hover",A2UI_RENDER_SCOPE_SX={"--a2ui-icon-size":"1em","& .a2ui-card":{background:"var(--a2ui-card-background, var(--a2ui-color-surface, #f6f8fa))",border:"1px solid var(--a2ui-color-border, #d0d7de)",borderRadius:"var(--a2ui-card-border-radius, 12px)",boxShadow:"var(--a2ui-card-box-shadow, none)"},"& .a2ui-text":{color:"var(--a2ui-color-on-surface, var(--a2ui-color-on-background, #1f2328))",margin:0},"& .a2ui-caption":{color:"var(--a2ui-text-caption-color, var(--a2ui-color-on-surface, #656d76))"},"& .a2ui-button":{appearance:"none",cursor:"pointer",border:"1px solid var(--button-primary-bgColor-rest)",background:"var(--button-primary-bgColor-rest)",color:"var(--button-primary-fgColor-rest)",borderRadius:"var(--a2ui-button-border-radius, 6px)",padding:"var(--a2ui-button-padding, 5px 16px)",fontWeight:"var(--a2ui-button-font-weight, 500)",boxShadow:"var(--a2ui-button-box-shadow, none)",transition:"background-color 0.15s ease, border-color 0.15s ease"},"& .a2ui-button .a2ui-text":{color:"inherit"},"& .a2ui-button:hover":{background:"var(--button-primary-bgColor-hover)",borderColor:"var(--button-primary-bgColor-hover)"},"& .a2ui-button:disabled":{opacity:.6,cursor:"not-allowed"},"& .a2ui-tab-button":{appearance:"none",background:"transparent",border:"none",borderBottom:"2px solid transparent",borderRadius:0,marginBottom:"-1px",padding:"var(--a2ui-tab-padding, 8px 16px)",color:"var(--a2ui-tab-color, var(--a2ui-color-on-surface, #656d76))",cursor:"pointer",fontFamily:"inherit",fontSize:"var(--a2ui-font-size-sm, 14px)",fontWeight:500,boxShadow:"none",transition:"color 0.15s ease, border-color 0.15s ease, background-color 0.15s ease"},"& .a2ui-tab-button:hover":{color:"var(--a2ui-tab-color-hover, var(--a2ui-color-primary, #1f883d))",background:"var(--a2ui-tab-background-hover, var(--a2ui-color-surface, #f6f8fa))"},"& .a2ui-tab-button.active":{color:"var(--a2ui-tab-color-active, var(--a2ui-color-primary, #1f883d))",borderBottomColor:"var(--a2ui-tab-border-active, var(--a2ui-color-primary, #1f883d))",fontWeight:600},"& .chip":{appearance:"none",padding:"var(--a2ui-choicepicker-chip-padding, 4px 12px)",borderRadius:"var(--a2ui-choicepicker-chip-border-radius, 999px)",border:"1px solid var(--a2ui-color-border, #d0d7de)",background:"var(--a2ui-color-surface, #f6f8fa)",color:"var(--a2ui-color-on-surface, #1f2328)",cursor:"pointer",fontFamily:"inherit",fontSize:"var(--a2ui-font-size-sm, 14px)",fontWeight:500,boxShadow:"none",transition:"background-color 0.15s ease, border-color 0.15s ease, color 0.15s ease"},"& .chip:hover":{borderColor:"var(--a2ui-color-border-hover, var(--a2ui-color-primary, #1f883d))"},'& .chip.selected, & .chip[aria-pressed="true"]':{background:"var(--a2ui-color-primary, #1f883d)",borderColor:"var(--a2ui-color-primary, #1f883d)",color:"var(--a2ui-color-on-primary, #ffffff)"},[A2UI_INPUT_SELECTOR]:{width:"100%",minHeight:"var(--a2ui-control-height, 32px)",boxSizing:"border-box",background:"var(--a2ui-textfield-background, var(--a2ui-color-input, var(--a2ui-color-background, #ffffff)))",color:"var(--a2ui-textfield-color, var(--a2ui-color-on-input, var(--a2ui-color-on-background, #1f2328)))",border:"var(--a2ui-textfield-border, 1px solid var(--a2ui-color-border, #d0d7de))",borderRadius:"var(--a2ui-textfield-border-radius, 6px)",padding:"var(--a2ui-textfield-padding, 5px 12px)",fontSize:"var(--a2ui-font-size-sm, 14px)",lineHeight:"20px",transition:"border-color 0.15s ease, box-shadow 0.15s ease"},[A2UI_INPUT_HOVER_SELECTOR]:{borderColor:"var(--a2ui-textfield-color-border-hover, var(--a2ui-color-border-hover, #8c959f))"},[A2UI_INPUT_FOCUS_SELECTOR]:{outline:"none",borderColor:"var(--a2ui-textfield-color-border-focus, var(--a2ui-color-primary, #1f883d))",boxShadow:"0 0 0 3px color-mix(in srgb, var(--a2ui-color-primary, #1f883d) 25%, transparent)"},"& .a2ui-textfield-label":{color:"var(--a2ui-textfield-label-color, var(--a2ui-color-on-surface, var(--a2ui-color-on-background, #1f2328)))",fontWeight:600,fontSize:"var(--a2ui-font-size-xs, 12px)",marginBottom:"var(--a2ui-spacing-xxs, 4px)",display:"inline-block"},"& .a2ui-textfield-error":{color:"var(--a2ui-textfield-color-error, #d1242f)",fontSize:"var(--a2ui-font-size-xs, 12px)",marginTop:"var(--a2ui-spacing-xs, 4px)"},'& input[type="checkbox"]':{accentColor:"var(--a2ui-color-primary, #1f883d)"}},VISIBLE_WHEN="visible_when";function isShown(Au){return Array.isArray(Au)?Au.length>0:!!Au}const OWN_COMPONENT_IDS=Object.values(COMPONENT_CATALOGUE).filter(Au=>!Au.standard).map(Au=>Au.id);function ownComponent(Au){const lo=COMPONENT_CATALOGUE[Au];if(!lo)throw new Error(`The catalog has no component ${Au}.`);if(lo.standard||!lo.properties||!lo.bindings)throw new Error(`${Au} is A2UI's own: its schema is the basic catalog's, not Datalayer's.`);return lo}const BindingSchema=unionType$1([arrayType$1(anyType$1()),recordType$1(stringType$1(),unknownType$1()),stringType$1(),numberType$1(),booleanType$1(),DataBindingSchema]).describe("REF:#/$defs/DynamicValue|Datalayer: what the component shows or sends — a path the application publishes or takes, or a value given in place.");function propertySchema(Au,lo){if(lo.enum)return enumType$1(lo.enum);switch(lo.type){case"string":return stringType$1();case"integer":case"number":return numberType$1();case"boolean":return booleanType$1();case"array":return arrayType$1(anyType$1());case"object":return recordType$1(stringType$1(),unknownType$1());default:throw new Error(`${Au} is typed ${String(lo.type)}, which a component's property cannot be.`)}}function bindingNames(Au){const{shows:lo,sends:$u}=Au.bindings;return[...new Set([...lo,...$u])]}function ownComponentSchema(Au){return componentSchemaOf(ownComponent(Au))}function componentSchemaOf(Au){const lo=Au.id;if(!Au.bindings)throw new Error(`${lo} says nothing of what it shows or sends.`);const $u=Au.properties,Ru=new Set($u.required??[]),Iu={};for(const[Ou,Pu]of Object.entries($u.properties??{})){const Du=propertySchema(Ou,Pu);Iu[Ou]=Ru.has(Ou)?Du:Du.optional()}for(const Ou of bindingNames(Au)){if(Ou in Iu)throw new Error(`${lo} both declares ${Ou} as a property and binds through it.`);Iu[Ou]=BindingSchema.optional()}return Iu.action=ActionSchema.describe("REF:#/$defs/Action|What it dispatches when a person acts on it.").optional(),Iu.weight=numberType$1().describe("The relative weight of this component within a Row or Column.").optional(),objectType$1(Iu).strict()}const DRAWN_OWN_COMPONENTS=["Table","Chart","FileUpload","Chat","Evidence","Form","Download"],CARD_RADIUS="var(--theme-radius-card, 6px)";function BlockFrame({title:Au,label:lo,weight:$u,children:Ru,testId:Iu}){return jsxRuntimeExports.jsxs(Box,{as:"section","aria-label":Au||lo,"data-testid":Iu,display:"flex",flexDirection:"column",gap:2,minWidth:0,boxSizing:"border-box",p:3,border:"1px solid",borderColor:"border.default",borderRadius:CARD_RADIUS,bg:"canvas.default",color:"fg.default",flex:typeof $u=="number"?`${$u}`:void 0,minHeight:typeof $u=="number"?0:void 0,children:[Au?jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,m:0},children:Au}):null,Ru]})}function Problem({children:Au}){return jsxRuntimeExports.jsx(Text$5,{as:"p",role:"status",sx:{m:0,color:"danger.fg",fontSize:1},children:Au})}function Quiet({children:Au}){return jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{m:0,color:"fg.muted",fontSize:1},children:Au})}const isRecord=Au=>typeof Au=="object"&&Au!==null&&!Array.isArray(Au);function asWords(Au){return Au==null?"":typeof Au=="object"?JSON.stringify(Au):String(Au)}function ownImplementation(Au,lo){const $u={name:Au,schema:ownComponentSchema(Au)};return createComponentImplementation($u,lo)}const PAGE_SIZE=20,sameRow=(Au,lo)=>Au!==void 0&&JSON.stringify(Au)===JSON.stringify(lo);function tableRows(Au){if(Au==null)return{rows:[]};if(!Array.isArray(Au))return{problem:"What it shows is not a list of rows."};const lo=Au.findIndex($u=>!isRecord($u));return lo>=0?{problem:`Row ${lo+1} is not a record of the columns' values.`}:{rows:Au}}function TableView({props:Au}){const{title:lo,columns:$u,selectable:Ru=!1,selected:Iu,setSelected:Ou,action:Pu}=Au,Du=Au.page_size??PAGE_SIZE,Lu=reactExports.useMemo(()=>tableRows(Au.rows),[Au.rows]),ju="rows"in Lu?Lu.rows:[],Bu=Math.max(1,Math.ceil(ju.length/Du)),[Fu,zu]=reactExports.useState(0);reactExports.useEffect(()=>{Fu>=Bu&&zu(Bu-1)},[Fu,Bu]);const qu=ju.slice(Fu*Du,(Fu+1)*Du),[Uu,Hu]=reactExports.useState(void 0),Vu=Iu??Uu,Gu=Zu=>{Hu(Zu),Ou(Zu),Pu?.()},Ku=(Zu,Qu)=>{(Zu.key==="Enter"||Zu.key===" ")&&(Zu.preventDefault(),Gu(Qu))};return jsxRuntimeExports.jsxs(BlockFrame,{title:lo,label:"Table",weight:Au.weight,testId:"a2ui-table",children:["problem"in Lu?jsxRuntimeExports.jsx(Problem,{children:Lu.problem}):jsxRuntimeExports.jsxs(Box,{overflowX:"auto",children:[jsxRuntimeExports.jsxs(Box,{as:"table",role:Ru?"grid":void 0,"aria-label":lo||"Table",width:"100%",borderCollapse:"collapse",fontSize:1,sx:{"& th, & td":{textAlign:"left",px:2,py:1,borderBottom:"1px solid",borderColor:"border.muted"},"& th":{color:"fg.muted",fontWeight:"semibold"}},children:[jsxRuntimeExports.jsx("thead",{children:jsxRuntimeExports.jsx("tr",{children:$u.map(Zu=>jsxRuntimeExports.jsx("th",{scope:"col",children:Zu},Zu))})}),jsxRuntimeExports.jsx("tbody",{children:qu.map((Zu,Qu)=>{const Yu=Ru&&sameRow(Vu,Zu);return jsxRuntimeExports.jsx(Box,{as:"tr",...Ru?{tabIndex:0,"aria-selected":Yu,onClick:()=>Gu(Zu),onKeyDown:ed=>Ku(ed,Zu)}:null,cursor:Ru?"pointer":void 0,bg:Yu?"accent.subtle":void 0,focusVisible:{outline:"2px solid",outlineColor:"accent.fg",outlineOffset:"-2px"},hover:Ru?{bg:Yu?"accent.subtle":"canvas.subtle"}:void 0,children:$u.map(ed=>jsxRuntimeExports.jsx("td",{children:asWords(Zu[ed])},ed))},Fu*Du+Qu)})})]}),ju.length===0?jsxRuntimeExports.jsx(Quiet,{children:"No rows yet."}):null]}),Bu>1?jsxRuntimeExports.jsxs(Box,{as:"nav","aria-label":"Pages",display:"flex",alignItems:"center",gap:2,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Fu===0,onClick:()=>zu(Fu-1),children:"Previous"}),jsxRuntimeExports.jsxs(Text$5,{sx:{fontSize:1,color:"fg.muted"},"aria-live":"polite",children:["Page ",Fu+1," of ",Bu]}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Fu>=Bu-1,onClick:()=>zu(Fu+1),children:"Next"})]}):null]})}const Table=ownImplementation("Table",TableView),loadECharts=()=>__vitePreload(()=>import("./chunks/index-74YA-L1Q.js"),[],import.meta.url),chartRefused=Au=>jsxRuntimeExports.jsx(Problem,{children:`The chart could not be drawn: ${Au.message}`}),FALLBACK={series:["#0969da","#1a7f37","#9a6700","#8250df","#cf222e","#bc4c00"],text:"#1f2328",muted:"#59636e",grid:"#d1d9e0"},SERIES_VARIABLES=["--fgColor-accent","--fgColor-success","--fgColor-attention","--fgColor-done","--fgColor-danger","--fgColor-severe"];function readColours(Au){if(!Au)return FALLBACK;const lo=getComputedStyle(Au),$u=(Ru,Iu)=>lo.getPropertyValue(Ru).trim()||Iu;return{series:SERIES_VARIABLES.map((Ru,Iu)=>$u(Ru,FALLBACK.series[Iu])),text:$u("--fgColor-default",FALLBACK.text),muted:$u("--fgColor-muted",FALLBACK.muted),grid:$u("--borderColor-muted",FALLBACK.grid)}}function chartPoints(Au){return Au==null?{points:[]}:!Array.isArray(Au)||Au.some(lo=>!isRecord(lo))?{problem:"What it shows is not a list of points."}:{points:Au}}function chartSeries(Au,lo){if(!lo.series)return[{name:lo.y,points:Au}];const $u=[];for(const Ru of Au){const Iu=asWords(Ru[lo.series]);$u.includes(Iu)||$u.push(Iu)}return $u.map(Ru=>({name:Ru,points:Au.filter(Iu=>asWords(Iu[lo.series])===Ru)}))}function chartOption(Au,lo,$u){const Ru=chartSeries(Au,lo),Iu=lo.kind==="scatter",Ou=[];for(const Du of Au){const Lu=asWords(Du[lo.x]);Ou.includes(Lu)||Ou.push(Lu)}const Pu={axisLine:{lineStyle:{color:$u.grid}},axisLabel:{color:$u.muted},splitLine:{lineStyle:{color:$u.grid}},nameTextStyle:{color:$u.muted}};return{aria:{enabled:!0},animation:!1,color:$u.series,textStyle:{color:$u.text},grid:{left:48,right:16,top:Ru.length>1?48:32,bottom:40},legend:Ru.length>1?{top:0,textStyle:{color:$u.text}}:void 0,tooltip:{trigger:Iu?"item":"axis"},xAxis:Iu?{type:"value",name:lo.x,nameLocation:"middle",nameGap:26,...Pu}:{type:"category",data:Ou,name:lo.x,nameLocation:"middle",nameGap:26,...Pu},yAxis:{type:"value",name:lo.y,...Pu},series:Ru.map(Du=>({name:Du.name,type:lo.kind==="area"?"line":lo.kind,areaStyle:lo.kind==="area"?{}:void 0,data:Iu?Du.points.map(Lu=>[Number(Lu[lo.x]),Number(Lu[lo.y])]):Ou.map(Lu=>{const ju=Du.points.find(Bu=>asWords(Bu[lo.x])===Lu);return ju?Number(ju[lo.y]):null})}))}}function ChartView({props:Au}){const{title:lo,kind:$u,x:Ru,y:Iu,series:Ou}=Au,Pu=reactExports.useMemo(()=>chartPoints(Au.points),[Au.points]),Du=reactExports.useRef(null),[Lu,ju]=reactExports.useState(FALLBACK);reactExports.useLayoutEffect(()=>{ju(readColours(Du.current))},[]);const Bu="points"in Pu?Pu.points:[],Fu=reactExports.useMemo(()=>chartOption(Bu,{kind:$u,x:Ru,y:Iu,series:Ou},Lu),[Bu,$u,Ru,Iu,Ou,Lu]),zu=Ou?[Ru,Ou,Iu]:[Ru,Iu],qu=`${lo||"Chart"}: ${Iu} by ${Ru}, as a ${$u}`;return jsxRuntimeExports.jsx(BlockFrame,{title:lo,label:"Chart",weight:Au.weight,testId:"a2ui-chart",children:jsxRuntimeExports.jsx(Box,{ref:Du,children:"problem"in Pu?jsxRuntimeExports.jsx(Problem,{children:Pu.problem}):Bu.length===0?jsxRuntimeExports.jsx(Quiet,{children:"No points yet."}):jsxRuntimeExports.jsxs(Box,{as:"figure","aria-label":qu,m:0,children:[jsxRuntimeExports.jsx("div",{"aria-hidden":"true",children:jsxRuntimeExports.jsx(ReactorLazy,{load:loadECharts,errorFallback:chartRefused,fallback:jsxRuntimeExports.jsx(Box,{height:240}),props:{option:Fu,style:{height:240,width:"100%"},opts:{renderer:"svg"},notMerge:!0,lazyUpdate:!0}})}),jsxRuntimeExports.jsxs(Box,{as:"details",fontSize:1,children:[jsxRuntimeExports.jsx(Box,{as:"summary",cursor:"pointer",color:"fg.muted",focusVisible:{outline:"2px solid",outlineColor:"accent.fg"},children:jsxRuntimeExports.jsx(Text$5,{children:"The numbers"})}),jsxRuntimeExports.jsxs(Box,{as:"table",mt:1,borderCollapse:"collapse",sx:{"& th, & td":{textAlign:"left",pr:3,py:"2px"},"& th":{color:"fg.muted",fontWeight:"semibold"}},children:[jsxRuntimeExports.jsx("thead",{children:jsxRuntimeExports.jsx("tr",{children:zu.map(Uu=>jsxRuntimeExports.jsx("th",{scope:"col",children:Uu},Uu))})}),jsxRuntimeExports.jsx("tbody",{children:Bu.map((Uu,Hu)=>jsxRuntimeExports.jsx("tr",{children:zu.map(Vu=>jsxRuntimeExports.jsx("td",{children:asWords(Uu[Vu])},Vu))},Hu))})]})]})]})})})}const Chart=ownImplementation("Chart",ChartView),MAX_MB=25;function refusal(Au,lo,$u){return acceptsFile(lo,{name:Au.name,type:Au.type??""})?Au.size>$u*1024*1024?`${Au.name} is larger than ${$u} MB.`:null:`${Au.name} is not one it takes (${(lo??[]).join(", ")}).`}const readFile=Au=>new Promise((lo,$u)=>{const Ru=new FileReader;Ru.onload=()=>lo({name:Au.name,type:Au.type,size:Au.size,data_url:String(Ru.result)}),Ru.onerror=()=>$u(Ru.error),Ru.readAsDataURL(Au)});function FileUploadView({props:Au}){const{label:lo,accept:$u,multiple:Ru=!1,setFiles:Iu,action:Ou}=Au,Pu=Au.max_mb??MAX_MB,Du=reactExports.useRef(null),Lu=reactExports.useId(),[ju,Bu]=reactExports.useState(!1),[Fu,zu]=reactExports.useState([]),qu=Array.isArray(Au.files)?Au.files.filter(isRecord).map(Gu=>String(Gu.name??"")):[],Uu=async Gu=>{const Ku=Array.from(Gu),Zu=Ru?Ku:Ku.slice(0,1),Qu=Zu.map(Yu=>refusal(Yu,$u,Pu)).filter(Yu=>Yu!==null);!Ru&&Ku.length>1&&Qu.push("It takes one file at a time."),zu(Qu),!Qu.length&&(Iu(await Promise.all(Zu.map(readFile))),Ou?.())},Hu=Gu=>{Gu.preventDefault(),Bu(!1),Uu(Gu.dataTransfer.files)},Vu=[$u?.length?`Takes ${$u.join(", ")}`:"Takes any file",`up to ${Pu} MB`,Ru?"several at once":"one at a time"].join(", ");return jsxRuntimeExports.jsxs(BlockFrame,{label:lo,weight:Au.weight,testId:"a2ui-fileupload",children:[jsxRuntimeExports.jsxs(Box,{onDragOver:Gu=>{Gu.preventDefault(),Bu(!0)},onDragLeave:()=>Bu(!1),onDrop:Hu,"data-testid":"a2ui-fileupload-drop",display:"flex",flexDirection:"column",alignItems:"center",gap:2,p:3,border:"1px dashed",borderColor:ju?"accent.fg":"border.default",borderRadius:CARD_RADIUS,bg:ju?"accent.subtle":"canvas.subtle",textAlign:"center",children:[jsxRuntimeExports.jsx(Text$5,{sx:{fontWeight:"semibold"},children:lo}),jsxRuntimeExports.jsx(ButtonComponent,{leadingVisual:UploadIcon,"aria-describedby":Lu,onClick:()=>Du.current?.click(),children:Ru?"Choose files":"Choose a file"}),jsxRuntimeExports.jsxs(Text$5,{id:Lu,sx:{fontSize:0,color:"fg.muted"},children:["or drop ",Ru?"them":"it"," here. ",Vu,"."]}),jsxRuntimeExports.jsx("input",{ref:Du,type:"file",hidden:!0,"aria-label":lo,accept:$u?.join(","),multiple:Ru,onChange:Gu=>{Gu.target.files&&Uu(Gu.target.files),Gu.target.value=""}})]}),Fu.map(Gu=>jsxRuntimeExports.jsx(Problem,{children:Gu},Gu)),qu.length?jsxRuntimeExports.jsxs(Quiet,{children:["Given: ",qu.join(", ")]}):null]})}const FileUpload=ownImplementation("FileUpload",FileUploadView),PLACEHOLDER="Ask anything",AVATARS={userAvatar:jsxRuntimeExports.jsx(PersonIcon,{size:14}),assistantAvatar:jsxRuntimeExports.jsx(DependabotIcon,{size:14}),showAvatars:!0,avatarSize:24,userAvatarBg:"neutral.muted",assistantAvatarBg:"accent.emphasis"},NO_TIME=new Date(0);function chatItems(Au,lo){if(Au==null)return{items:[]};if(!Array.isArray(Au))return{problem:"What it shows is not a list of messages."};const $u=[];for(const[Ru,Iu]of Au.entries()){const Ou=`m${Ru}`;if(!isRecord(Iu))return{problem:`Message ${Ru+1} is not a message.`};if(Iu.role==="tool"){lo&&$u.push({id:Ou,type:"tool-call",toolCallId:Ou,toolName:asWords(Iu.name)||"tool",args:isRecord(Iu.args)?Iu.args:{},result:Iu.result,status:"complete"});continue}if(Iu.role!=="user"&&Iu.role!=="assistant")return{problem:`Message ${Ru+1} is from ${asWords(Iu.role)||"nobody"}: a message is the user's, the assistant's or a tool's.`};$u.push({id:Ou,role:Iu.role,content:asWords(Iu.text??Iu.content),createdAt:NO_TIME})}return{items:$u}}function ChatView({props:Au}){const{welcome:lo,starters:$u=[],setMessage:Ru,action:Iu}=Au,Ou=Au.placeholder??PLACEHOLDER,Pu=Au.show_tools??!0,Du=reactExports.useMemo(()=>chatItems(Au.messages,Pu),[Au.messages,Pu]),[Lu,ju]=reactExports.useState(""),Bu=reactExports.useMemo(()=>reactExports.createRef(),[]),Fu=reactExports.useMemo(()=>reactExports.createRef(),[]),zu=qu=>{const Uu=qu.trim();Uu&&(Ru(Uu),Iu?.(),ju(""))};return jsxRuntimeExports.jsxs(BlockFrame,{label:"Chat",weight:Au.weight,testId:"a2ui-chat",children:["problem"in Du?jsxRuntimeExports.jsx(Problem,{children:Du.problem}):jsxRuntimeExports.jsx(Box,{maxHeight:420,overflowY:"auto",borderRadius:CARD_RADIUS,children:jsxRuntimeExports.jsx(ChatMessageList,{displayItems:Du.items,isLoading:!1,isStreaming:!1,showLoadingIndicator:!1,hideMessagesAfterToolUI:!1,avatarConfig:AVATARS,padding:2,emptyContent:jsxRuntimeExports.jsx(ChatEmptyState,{description:"",emptyState:{title:lo||"Start a conversation"},suggestions:$u.map(qu=>({title:qu,message:qu})),onSuggestionSubmit:qu=>zu(qu.message)}),messagesEndRef:Bu,onRespond:async()=>{}})}),jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"flex-end",gap:2,children:[jsxRuntimeExports.jsx(Box,{flex:1,minWidth:0,children:jsxRuntimeExports.jsx(InputPromptText,{value:Lu,onChange:ju,placeholder:Ou,onSubmit:()=>zu(Lu),inputRef:Fu})}),jsxRuntimeExports.jsx(IconButton,{icon:PaperAirplaneIcon,"aria-label":"Send",variant:"primary",disabled:!Lu.trim(),onClick:()=>zu(Lu)})]})]})}const Chat=ownImplementation("Chat",ChatView),TITLE="Sources",MAX_ITEMS=5;function evidenceSources(Au){if(Au==null)return{sources:[]};if(!Array.isArray(Au))return{problem:"What it shows is not a list of sources."};const lo=[];for(const[$u,Ru]of Au.entries()){if(!isRecord(Ru)||!Ru.title&&!Ru.url)return{problem:`Source ${$u+1} has neither a title nor a link.`};lo.push({title:asWords(Ru.title)||asWords(Ru.url),url:asWords(Ru.url),passage:asWords(Ru.passage)})}return{sources:lo}}function EvidenceView({props:Au}){const{show_passages:lo=!0,action:$u}=Au,Ru=Au.title??TITLE,Iu=Au.max_items??MAX_ITEMS,Ou=reactExports.useMemo(()=>evidenceSources(Au.sources),[Au.sources]),[Pu,Du]=reactExports.useState(!1),Lu="sources"in Ou?Ou.sources:[],ju=Pu?Lu:Lu.slice(0,Iu),Bu=Lu.length-ju.length;return jsxRuntimeExports.jsxs(BlockFrame,{title:Ru,label:"Evidence",weight:Au.weight,testId:"a2ui-evidence",children:["problem"in Ou?jsxRuntimeExports.jsx(Problem,{children:Ou.problem}):Lu.length===0?jsxRuntimeExports.jsx(Quiet,{children:"Nothing cited yet."}):jsxRuntimeExports.jsx(Box,{as:"ol",m:0,pl:3,display:"flex",flexDirection:"column",gap:2,children:ju.map((Fu,zu)=>jsxRuntimeExports.jsxs("li",{children:[Fu.url?jsxRuntimeExports.jsxs(Link$1,{href:Fu.url,target:"_blank",rel:"noreferrer noopener",onClick:()=>$u?.(),sx:{fontWeight:"semibold"},children:[Fu.title," ",jsxRuntimeExports.jsx(LinkExternalIcon,{size:12,"aria-label":"opens in a new tab"})]}):jsxRuntimeExports.jsx(Text$5,{sx:{fontWeight:"semibold"},children:Fu.title}),lo&&Fu.passage?jsxRuntimeExports.jsx(Box,{as:"blockquote",m:0,mt:1,pl:2,borderLeft:"3px solid",borderColor:"border.default",color:"fg.muted",fontSize:1,children:Fu.passage}):null]},`${Fu.url}-${zu}`))}),Bu>0?jsxRuntimeExports.jsx(Box,{children:jsxRuntimeExports.jsxs(ButtonComponent,{size:"small",variant:"invisible",onClick:()=>Du(!0),children:[Bu," more"]})}):null]})}const Evidence=ownImplementation("Evidence",EvidenceView),loadSchemaForm=()=>__vitePreload(()=>import("./chunks/SchemaForm-8b_dpfFK.js"),[],import.meta.url),formRefused=Au=>jsxRuntimeExports.jsx(Problem,{children:`The form could not be drawn: ${Au.message}`}),SUBMIT_LABEL="Send";function FormView({props:Au}){const{title:lo,schema:$u,setValues:Ru,action:Iu}=Au,Ou=Au.submit_label??SUBMIT_LABEL,Pu=isRecord(Au.values)?Au.values:{},[Du,Lu]=reactExports.useState(Pu),[ju,Bu]=reactExports.useState(!1),Fu=JSON.stringify(Pu);reactExports.useEffect(()=>{Lu(JSON.parse(Fu))},[Fu]);const zu=Iu===void 0,qu=JSON.stringify(Au.ui??{}),Uu=reactExports.useMemo(()=>({...JSON.parse(qu),"ui:submitButtonOptions":zu?{norender:!0}:{submitText:Ou}}),[qu,zu,Ou]),Hu=$u.type!==void 0&&$u.type!=="object"?"Its fields are not an object schema: a form asks for several named values.":null;return jsxRuntimeExports.jsx(BlockFrame,{title:lo,label:"Form",weight:Au.weight,testId:"a2ui-form",children:Hu?jsxRuntimeExports.jsx(Problem,{children:Hu}):jsxRuntimeExports.jsx(ReactorLazy,{load:loadSchemaForm,errorFallback:formRefused,props:{schema:$u,uiSchema:Uu,formData:Du,liveValidate:ju,onBlur:()=>Bu(!0),onError:()=>Bu(!0),showErrorList:!1,onChange:Vu=>{const Gu=Vu.formData??{};Lu(Gu),zu&&Ru(Gu)},onSubmit:Vu=>{Ru(Vu.formData??{}),Iu?.()}}})})}const Form=ownImplementation("Form",FormView),SCHEMES=/^(https?:\/\/|data:)/i;function sizeInWords(Au){if(typeof Au!="number"||!Number.isFinite(Au)||Au<0)return"";if(Au<1024)return Au===1?"1 byte":`${Au} bytes`;const lo=["KB","MB","GB"];let $u=Au/1024,Ru=0;for(;$u>=1024&&Ru<lo.length-1;)$u/=1024,Ru+=1;return`${$u<10?$u.toFixed(1):Math.round($u)} ${lo[Ru]}`}function downloadOf(Au){const lo=typeof Au.name=="string"?Au.name.trim():"",$u=typeof Au.url=="string"?Au.url.trim():"";return lo?$u?SCHEMES.test($u)?{name:lo,url:$u}:{problem:`${lo} is not offered: its link is neither an http(s) link nor a data: URL.`}:{problem:`${lo} has no link.`}:{problem:"This file has no name."}}function DownloadView({props:Au}){const{action:lo}=Au,$u=reactExports.useMemo(()=>downloadOf({name:Au.name,url:Au.url}),[Au.name,Au.url]),Ru=[Au.media_type,sizeInWords(Au.size)].filter(Boolean).join(" · ");return jsxRuntimeExports.jsx(BlockFrame,{label:"File to download",weight:Au.weight,testId:"a2ui-download",children:"problem"in $u?jsxRuntimeExports.jsx(Problem,{children:$u.problem}):jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,alignItems:"flex-start",children:[jsxRuntimeExports.jsx(Box,{color:"fg.muted",pt:"2px",children:jsxRuntimeExports.jsx(DownloadIcon,{size:16,"aria-hidden":"true"})}),jsxRuntimeExports.jsxs(Box,{display:"flex",flexDirection:"column",minWidth:0,children:[jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Link$1,{href:$u.url,download:$u.name,target:"_blank",rel:"noreferrer noopener",onClick:()=>lo?.(),sx:{fontWeight:"semibold",wordBreak:"break-word"},children:$u.name}),Ru?jsxRuntimeExports.jsx(Text$5,{sx:{color:"fg.muted",fontSize:1,ml:2},children:Ru}):null]}),Au.description?jsxRuntimeExports.jsx(Text$5,{sx:{color:"fg.muted",fontSize:1},children:Au.description}):null]})]})})}const Download=ownImplementation("Download",DownloadView),RENDERERS={Table,Chart,FileUpload,Chat,Evidence,Form,Download},OWN_COMPONENTS=(()=>{const Au=DRAWN_OWN_COMPONENTS,lo=OWN_COMPONENT_IDS.filter(Ru=>!Au.includes(Ru));if(lo.length)throw new Error(`The catalog has ${lo.join(", ")}, which no renderer draws.`);const $u=Au.filter(Ru=>!OWN_COMPONENT_IDS.includes(Ru));if($u.length)throw new Error(`A renderer draws ${$u.join(", ")}, which the catalog does not have.`);return OWN_COMPONENT_IDS.map(Ru=>RENDERERS[Ru])})();function nodeIsShown(Au){const lo=Au[VISIBLE_WHEN];if(!(lo instanceof ResolvedBinding))throw new Error(`${VISIBLE_WHEN} resolved to ${String(lo)}, not a binding: the catalog's schema does not declare it.`);return isWritable(lo)?isShown(lo.value):lo.value===void 0||isShown(lo.value)}const VISIBLE_WHEN_SCHEMA=DynamicBooleanSchema.describe("REF:#/$defs/DynamicBoolean|Datalayer: the block is shown only while this is true or not empty — a path the application publishes.").optional();function withVisibleWhen(Au){const lo=Au.view;if(!lo)throw new Error(`${Au.name} has no node view: visible_when is read from the node, and A2uiSurface draws through it.`);const $u=Au.schema;if(!$u.shape||typeof $u.extend!="function")throw new Error(`${Au.name}'s schema is not an object: visible_when cannot be declared on it.`);if(VISIBLE_WHEN in $u.shape)throw new Error(`${Au.name} already declares ${VISIBLE_WHEN}.`);const Ru=({node:Iu,buildChild:Ou})=>{const Pu=useSignalValue(Iu.props);return nodeIsShown(Pu)?jsxRuntimeExports.jsx(lo,{node:Iu,buildChild:Ou}):null};return Ru.displayName=`${Au.name}.visibleWhen`,{...Au,schema:$u.extend({[VISIBLE_WHEN]:VISIBLE_WHEN_SCHEMA}),view:Ru}}const datalayerCatalog=new Catalog(basicCatalog.id,basicCatalog.protocolVersion,[...basicCatalog.components.values(),...OWN_COMPONENTS].map(withVisibleWhen),[...basicCatalog.functions.values()],basicCatalog.themeSchema,basicCatalog.instructions);function catalogOfBlocks(Au,lo=[]){const $u=new Map(lo.map(Ou=>[Ou.name,withVisibleWhen(Ou)])),Ru=[...$u.keys()].filter(Ou=>datalayerCatalog.components.has(Ou));if(Ru.length>0)throw new Error(`${Ru.join(", ")} ${Ru.length===1?"is a component":"are components"} of the catalog: a component of an application's own is named otherwise.`);const Iu=Au.filter(Ou=>!datalayerCatalog.components.has(Ou)&&!$u.has(Ou));if(Iu.length>0)throw new Error(`No renderer draws ${Iu.join(", ")}: a block is contributed by a plugin whose component the catalog draws.`);return new Catalog(datalayerCatalog.id,datalayerCatalog.protocolVersion,Au.map(Ou=>datalayerCatalog.components.get(Ou)??$u.get(Ou)),[...datalayerCatalog.functions.values()],datalayerCatalog.themeSchema,datalayerCatalog.instructions)}function catalogWithOwn(Au){return Au.length===0?datalayerCatalog:catalogOfBlocks([...datalayerCatalog.components.keys(),...Au.map(lo=>lo.name)],Au)}const CUSTOM_FILE=/^(?:\.\/)?(?:[A-Za-z0-9_][A-Za-z0-9_.-]*\/)*[A-Za-z0-9_][A-Za-z0-9_.-]*\.m?js$/,isFolderSource=Au=>!/^[a-z][a-z0-9+.-]*:/.test(Au)&&CUSTOM_FILE.test(Au),folderSourceUrl=(Au,lo)=>new URL(Au.replace(/^\.\//,""),lo.endsWith("/")?lo:`${lo}/`).href,hasFolderModules=Au=>(Au.interface.customComponents??[]).some(lo=>isFolderSource(lo.source));function customComponentEntry(Au,lo){return{id:Au.name,name:Au.name,description:Au.description,category:"custom",emoji:"🧩",version:lo,standard:!1,properties:Au.props,bindings:{shows:[...Au.shows],sends:[...Au.sends]},events:Au.sends.length>0?["send"]:[],...Au.example?{example:Au.example}:{}}}const CUSTOM_FRAME_SANDBOX="allow-scripts",MAX_MODULE_BYTES=2*1024*1024,FRAME_TAG="loop.component";function customFramePolicy(Au){return["default-src 'none'",`script-src 'nonce-${Au}' blob:`,"style-src 'unsafe-inline'","img-src data: blob:","font-src data:","media-src data: blob:","form-action 'none'","base-uri 'none'"].join("; ")}function frameNonce(){const Au=new Uint8Array(16);return crypto.getRandomValues(Au),Array.from(Au,lo=>lo.toString(16).padStart(2,"0")).join("")}function customFrameDocument(Au,lo){const $u=lo.replace(/[&<>"]/g,Ru=>`&#${Ru.charCodeAt(0)};`);return`<!doctype html>
3545
3545
  <html lang="en">
3546
3546
  <head>
3547
3547
  <meta charset="utf-8">
@@ -3589,14 +3589,14 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
3589
3589
  <\/script>
3590
3590
  </body>
3591
3591
  </html>`}function fromFrame(Au,lo){if(!lo||Au.source!==lo)return null;const $u=Au.data;if(!$u||typeof $u!="object"||$u.tag!==FRAME_TAG)return null;switch($u.kind){case"ready":case"drawn":return{kind:$u.kind};case"failed":return{kind:"failed",message:String($u.message??"")};case"send":return typeof $u.name=="string"?{kind:"send",name:$u.name,value:$u.value}:null;default:return null}}const ALGORITHMS={sha256:"SHA-256",sha384:"SHA-384",sha512:"SHA-512"};function base64(Au){let lo="";for(const $u of new Uint8Array(Au))lo+=String.fromCharCode($u);return btoa(lo)}async function integrityHolds(Au,lo){const $u=lo.indexOf("-"),Ru=ALGORITHMS[lo.slice(0,$u)];if($u<0||!Ru)return!1;const Iu=await crypto.subtle.digest(Ru,Au);return base64(Iu)===lo.slice($u+1)}const MODULES=new Map;function customModule(Au,lo,$u=fetch){const Ru=`${Au}
3592
- ${lo}`;let Iu=MODULES.get(Ru);return Iu||(Iu=(async()=>{const Ou=await $u(Au,{credentials:"omit",mode:"cors"});if(!Ou.ok)throw new Error(`Its module could not be fetched from ${Au} (${Ou.status}).`);const Pu=await Ou.arrayBuffer();if(Pu.byteLength>MAX_MODULE_BYTES)throw new Error(`Its module is larger than ${MAX_MODULE_BYTES/1024/1024} MB.`);if(lo&&!await integrityHolds(Pu,lo))throw new Error("Its module is not the one reviewed: its hash differs from its integrity.");return new TextDecoder().decode(Pu)})(),Iu.catch(()=>MODULES.delete(Ru)),MODULES.set(Ru,Iu)),Iu}function givenToFrame(Au,lo){const $u=Object.keys(Au.props.properties??{}),Ru=new Set([...$u,...Au.shows,...Au.sends]);return Object.fromEntries(Object.entries(lo).filter(([Iu,Ou])=>Ru.has(Iu)&&typeof Ou!="function"))}const setterOf=Au=>`set${Au.charAt(0).toUpperCase()}${Au.slice(1)}`;function CustomComponentView({component:Au,props:lo,fetcher:$u}){const Ru=reactExports.useRef(null),[Iu,Ou]=reactExports.useState(null),[Pu,Du]=reactExports.useState(!1),Lu=reactExports.useMemo(()=>customFrameDocument(frameNonce(),Au.name),[Au.name]),ju=JSON.stringify(givenToFrame(Au,lo)),Bu=reactExports.useMemo(()=>JSON.parse(ju),[ju]),Fu=reactExports.useRef(lo);Fu.current=lo;const zu=qu=>Ru.current?.contentWindow?.postMessage(qu,"*");return reactExports.useEffect(()=>{const qu=Uu=>{const Hu=fromFrame(Uu,Ru.current?.contentWindow);if(Hu){if(Hu.kind==="ready")customModule(Au.source,Au.integrity,$u).then(Vu=>{zu({tag:FRAME_TAG,kind:"props",props:givenToFrame(Au,Fu.current)}),zu({tag:FRAME_TAG,kind:"module",code:Vu}),Du(!0)}).catch(Vu=>Ou(Vu instanceof Error?Vu.message:String(Vu)));else if(Hu.kind==="failed")Ou(`It could not be drawn: ${Hu.message}.`);else if(Hu.kind==="send"){if(!Au.sends.includes(Hu.name)){Ou(`It sent “${Hu.name}”, which it does not declare under \`sends\`.`);return}const Vu=Fu.current[setterOf(Hu.name)];typeof Vu=="function"&&Vu(Hu.value),Fu.current.action?.()}}};return window.addEventListener("message",qu),()=>window.removeEventListener("message",qu)},[Au,$u]),reactExports.useEffect(()=>{Pu&&zu({tag:FRAME_TAG,kind:"props",props:Bu})},[Pu,Bu]),jsxRuntimeExports.jsxs(BlockFrame,{label:Au.description||Au.name,weight:lo.weight,testId:`custom-${Au.name}`,children:[Iu?jsxRuntimeExports.jsx(Problem,{children:Iu}):null,jsxRuntimeExports.jsx("iframe",{ref:Ru,title:Au.description||Au.name,sandbox:CUSTOM_FRAME_SANDBOX,srcDoc:Lu,referrerPolicy:"no-referrer",style:{width:"100%",height:`${Au.height}px`,border:0,display:"block"}})]})}function customImplementation(Au,lo="0.0.0",$u){const Ru=customComponentEntry(Au,lo),Iu={name:Au.name,schema:componentSchemaOf(Ru)};return createComponentImplementation(Iu,({props:Pu})=>jsxRuntimeExports.jsx(CustomComponentView,{component:Au,props:Pu,fetcher:$u}))}const SURFACE_CATALOG_ID=datalayerCatalog.id,INHERIT_THEME={"--a2ui-color-surface":"var(--bgColor-muted)","--a2ui-color-on-surface":"var(--fgColor-default)","--a2ui-color-primary":"var(--fgColor-accent)","--a2ui-color-outline":"var(--borderColor-default)"};function InlineSurface({messages:Au,onAction:lo,validationError:$u,data:Ru,catalog:Iu=datalayerCatalog,onSurface:Ou}){const Pu=reactExports.useRef(lo);Pu.current=lo;const Du=reactExports.useMemo(()=>new MessageProcessor([Iu],Gu=>Pu.current(Gu,Lu.current?.model.getSurface(Gu.surfaceId))),[]),Lu=reactExports.useRef(void 0);Lu.current=Du;const[ju,Bu]=reactExports.useState([]),Fu=reactExports.useRef(Ou);Fu.current=Ou,reactExports.useEffect(()=>{const Gu=Du.onSurfaceCreated(Zu=>{Bu(Qu=>[...Qu,Zu]),Fu.current?.(Zu)}),Ku=Du.onSurfaceDeleted(Zu=>Bu(Qu=>Qu.filter(Yu=>Yu.id!==Zu)));return()=>{Gu.unsubscribe(),Ku.unsubscribe()}},[Du]);const zu=reactExports.useRef(!1),[qu,Uu]=reactExports.useState(null);reactExports.useEffect(()=>{if(!zu.current){zu.current=!0;try{Du.processMessages(Au)}catch(Gu){Uu(`This surface could not be drawn: ${Gu instanceof Error?Gu.message:String(Gu)}`)}}},[Au,Du]);const Hu=reactExports.useRef({});reactExports.useEffect(()=>{if(!Ru)return;const Gu=Hu.current;for(const[Ku,Zu]of Object.entries(Ru))if(!Object.is(Gu[Ku],Zu)){Gu[Ku]=Zu;for(const Qu of Du.model.surfacesMap.values())Qu.dataModel.set(Ku,Zu)}},[Ru,Du]);const Vu=$u||qu;return ju.length===0&&!Vu?null:jsxRuntimeExports.jsx(A2uiMarkdownProvider,{children:jsxRuntimeExports.jsxs(Box,{style:INHERIT_THEME,sx:{...A2UI_RENDER_SCOPE_SX,display:"flex",flexDirection:"column",gap:2},children:[Vu?jsxRuntimeExports.jsx(Box,{role:"alert",px:3,py:2,borderRadius:2,bg:"danger.subtle",border:"1px solid",borderColor:"danger.muted",color:"danger.fg",fontSize:1,children:Vu}):null,ju.map(Gu=>jsxRuntimeExports.jsx(Box,{border:"1px solid",borderColor:"border.default",borderRadius:2,p:3,bg:"canvas.default",children:jsxRuntimeExports.jsx(A2uiSurfaceComposed,{surface:Gu})},Gu.id))]})})}function useOwnComponents(){const Au=useOptionalReactorPlatform();return reactExports.useMemo(()=>Au?Au.getContributions(LoopA2uiComponent).map(lo=>lo.value.implementation):[],[Au])}function useOwnCatalog(){const Au=useOwnComponents();return reactExports.useMemo(()=>catalogWithOwn(Au),[Au])}const APP_PAGE_SURFACE="app-page",APP_PAGE_SURFACE_ID="app",APP={path:"/app",meaning:"The application's name.",words:"Its name"},STATUS={path:"/status",meaning:"Where its answer stands, in a word: Ready, Thinking, Answering, Answered or Stopped.",words:"Where its answer stands"},DRAFT={path:"/draft",meaning:"A message written on the page, which a Send button sends.",words:"A message to send"},SEND={name:"send",meaning:"Send a message to the application: the context’s message, or what is written at /draft.",words:"Send the message",context:["message"],asks:{message:"The message it sends"}},MESSAGES={path:"/messages",meaning:"The conversation so far, in order: each message {role: user or assistant, text}, each tool called {role: tool, name, args, result}.",words:"The conversation",list:!0},FILES={path:"/files",meaning:"The files given on the page, each {name, type, size, data_url}: they go to the application’s session with the next run, put in its sandbox when it has a shell, a text file in the message when it has none.",words:"The files given",list:!0},STOP={name:"stop",meaning:"Stop the answer being written.",words:"Stop the answer",context:[],asks:{}},APP_KIND_PATHS={chat:{publishes:[APP,{path:"/question",meaning:"The question last asked.",words:"The question last asked"},{path:"/answer",meaning:"Its answer to it, as it is written.",words:"Its answer"},STATUS,MESSAGES],accepts:[DRAFT],actions:[SEND,STOP,{name:"new",meaning:"Start the conversation over.",words:"Start over",context:[],asks:{}}],inputs:!0},widget:{publishes:[APP,{path:"/output",meaning:"What it gave for the inputs last run, as it is written.",words:"What it gave"},STATUS],accepts:[FILES],actions:[{name:"run",meaning:"Run it on its inputs: every value written under /inputs is sent, and each file at /files, with the context’s message when there is one.",words:"Run it on its inputs",context:["message"],asks:{message:"What it says before the inputs"}},{name:"upload",meaning:"Run it on the files just given — the context’s files, else those at /files — with its inputs.",words:"Run it on the files given",context:["files"],asks:{files:"The files it runs on"}},STOP],inputs:!0},worker:{publishes:[APP,{path:"/goal",meaning:"What it works toward.",words:"What it works toward"},{path:"/activity",meaning:"What it is doing right now, in a short line, or nothing.",words:"What it is doing now"},{path:"/report",meaning:"What it last said, as it is written.",words:"What it last said"},STATUS],accepts:[DRAFT],actions:[SEND,STOP],inputs:!1}},isAppPageKind=Au=>Object.prototype.hasOwnProperty.call(APP_KIND_PATHS,Au),inputPath=Au=>`/inputs/${Au}`;function settingFields(Au){const lo=Au?.properties;return!lo||typeof lo!="object"?[]:Object.entries(lo).filter($u=>typeof $u[1]=="object"&&$u[1]!==null)}const settingTitle=(Au,lo)=>typeof lo.title=="string"&&lo.title?lo.title:Au;function settingDefaults(Au){return Object.fromEntries(settingFields(Au).filter(([,lo])=>lo.default!==void 0).map(([lo,$u])=>[lo,$u.default]))}function appKindPaths(Au){if(!isAppPageKind(Au.kind))return{publishes:[],accepts:[],actions:[],inputs:!1};const lo=APP_KIND_PATHS[Au.kind];if(!lo.inputs)return lo;const $u=settingFields(Au.interface.settings).map(([Pu,Du])=>({path:inputPath(Pu),meaning:`The setting “${settingTitle(Pu,Du)}”.`,words:settingTitle(Pu,Du)})),Ru=pageOf(Au);if(!Ru)return{...lo,publishes:[...lo.publishes,...$u],accepts:[...lo.accepts,...$u]};const Iu=settingFields(Ru.inputs).map(([Pu,Du])=>({path:inputPath(Pu),meaning:`The input “${settingTitle(Pu,Du)}” of its page.`,words:settingTitle(Pu,Du)})),Ou=Ru.outputs.map(Pu=>({path:outputPath(Pu.name),meaning:`What its page shows as “${Pu.title||Pu.name}”, drawn with a ${Pu.component}, for its inputs.`,words:Pu.title||Pu.name,...Pu.component==="Table"||Pu.component==="Chart"?{list:!0}:{}}));return{...lo,publishes:[...lo.publishes,...$u,...Iu,...Ou],accepts:[...lo.accepts,...$u,...Iu],actions:[...lo.actions,PAGE]}}const pageOf=Au=>Au.kind==="widget"?Au.interface.page:void 0,outputPath=Au=>`/outputs/${Au}`,PAGE_ACTION="page",PAGE={name:PAGE_ACTION,meaning:"Run its page on its inputs: every value written under /inputs, its outputs shown in place at /outputs.",words:"Run its page",context:[],asks:{}},surfaceComponents=Au=>Au.interface.surface?.components??[];function hasAppPage(Au){return!Au.agent||!isAppPageKind(Au.kind)?!1:Au.interface.layout!=="chat"}const STATUS_WORDS={idle:"Ready",thinking:"Thinking",streaming:"Answering",done:"Answered",error:"Stopped"};function appPageData(Au,lo,$u){const Ru={"/app":Au.name,"/status":STATUS_WORDS[lo.status]??""};switch(Au.kind){case"chat":Ru["/question"]=lo.user??"",Ru["/answer"]=lo.assistant??"",Ru["/messages"]=$u;break;case"widget":Ru["/output"]=lo.assistant??"";break;case"worker":Ru["/goal"]=Au.goal,Ru["/activity"]=lo.activity??"",Ru["/report"]=lo.assistant??"";break}return Ru}function appPageInitialData(Au){const lo={};for(const[Ru,Iu]of Object.entries(appPageData(Au,{status:"idle"},[])))lo[Ru.slice(1)]=Iu;const $u=appKindPaths(Au);if($u.inputs){const Ru={...settingDefaults(Au.interface.settings),...settingDefaults(pageOf(Au)?.inputs)};for(const Iu of Au.interface.surface?.components??[]){const Ou=Iu.value?.path,Pu=typeof Ou=="string"&&Ou.startsWith("/inputs/")?Ou.slice(8):void 0;Iu.component==="ChoicePicker"&&Pu&&Pu in Ru&&(Ru[Pu]=Array.isArray(Ru[Pu])?Ru[Pu]:[Ru[Pu]])}lo.inputs=Ru}return pageOf(Au)&&(lo.outputs={}),$u.accepts.some(Ru=>Ru.path===DRAFT.path)&&(lo.draft=""),$u.accepts.some(Ru=>Ru.path===FILES.path)&&(lo.files=[]),lo}function inputWords(Au,lo){const $u=Array.isArray(lo)?lo.map(String).join(", "):typeof lo=="boolean"?lo?"yes":"no":lo==null?"":String(lo);return $u.trim()?`${Au}: ${$u}`:""}function inputsInWords(Au,lo){const $u=lo&&typeof lo=="object"?lo:{},Ru=[],Iu=new Set;for(const[Ou,Pu]of settingFields(Au.interface.settings))Iu.add(Ou),Ru.push(inputWords(settingTitle(Ou,Pu),$u[Ou]));for(const[Ou,Pu]of Object.entries($u))Iu.has(Ou)||Ru.push(inputWords(Ou,Pu));return Ru.filter(Boolean).join(`
3592
+ ${lo}`;let Iu=MODULES.get(Ru);return Iu||(Iu=(async()=>{const Ou=await $u(Au,{credentials:"omit",mode:"cors"});if(!Ou.ok)throw new Error(`Its module could not be fetched from ${Au} (${Ou.status}).`);const Pu=await Ou.arrayBuffer();if(Pu.byteLength>MAX_MODULE_BYTES)throw new Error(`Its module is larger than ${MAX_MODULE_BYTES/1024/1024} MB.`);if(lo&&!await integrityHolds(Pu,lo))throw new Error("Its module is not the one reviewed: its hash differs from its integrity.");return new TextDecoder().decode(Pu)})(),Iu.catch(()=>MODULES.delete(Ru)),MODULES.set(Ru,Iu)),Iu}function givenToFrame(Au,lo){const $u=Object.keys(Au.props.properties??{}),Ru=new Set([...$u,...Au.shows,...Au.sends]);return Object.fromEntries(Object.entries(lo).filter(([Iu,Ou])=>Ru.has(Iu)&&typeof Ou!="function"))}const setterOf=Au=>`set${Au.charAt(0).toUpperCase()}${Au.slice(1)}`;function useAppFilesBase(Au){const lo=useOptionalReactorPlatform(),$u=reactExports.useCallback(Iu=>lo?lo.subscribe(Iu):()=>{},[lo]),Ru=reactExports.useSyncExternalStore($u,()=>lo?.getRevision()??0);return reactExports.useMemo(()=>lo?.getContributions(LoopAppFiles).find(Iu=>Iu.value.app===Au)?.value.base,[lo,Ru,Au])}function CustomComponentView({component:Au,props:lo,fetcher:$u,appId:Ru=""}){const Iu=reactExports.useRef(null),[Ou,Pu]=reactExports.useState(null),[Du,Lu]=reactExports.useState(!1),[ju,Bu]=reactExports.useState(!1),Fu=isFolderSource(Au.source),zu=useAppFilesBase(Ru),qu=Fu?zu?folderSourceUrl(Au.source,zu):void 0:Au.source,Uu=reactExports.useMemo(()=>customFrameDocument(frameNonce(),Au.name),[Au.name]),Hu=JSON.stringify(givenToFrame(Au,lo)),Vu=reactExports.useMemo(()=>JSON.parse(Hu),[Hu]),Gu=reactExports.useRef(lo);Gu.current=lo;const Ku=Zu=>Iu.current?.contentWindow?.postMessage(Zu,"*");return reactExports.useEffect(()=>{const Zu=Qu=>{const Yu=fromFrame(Qu,Iu.current?.contentWindow);if(Yu){if(Yu.kind==="ready")Bu(!0);else if(Yu.kind==="failed")Pu(`It could not be drawn: ${Yu.message}.`);else if(Yu.kind==="send"){if(!Au.sends.includes(Yu.name)){Pu(`It sent “${Yu.name}”, which it does not declare under \`sends\`.`);return}const ed=Gu.current[setterOf(Yu.name)];typeof ed=="function"&&ed(Yu.value),Gu.current.action?.()}}};return window.addEventListener("message",Zu),()=>window.removeEventListener("message",Zu)},[Au]),reactExports.useEffect(()=>{if(!ju||!qu)return;let Zu=!0;return customModule(qu,Au.integrity,$u).then(Qu=>{Zu&&(Ku({tag:FRAME_TAG,kind:"props",props:givenToFrame(Au,Gu.current)}),Ku({tag:FRAME_TAG,kind:"module",code:Qu}),Lu(!0))}).catch(Qu=>{Zu&&Pu(Qu instanceof Error?Qu.message:String(Qu))}),()=>{Zu=!1}},[ju,qu,Au,$u]),reactExports.useEffect(()=>{Du&&Ku({tag:FRAME_TAG,kind:"props",props:Vu})},[Du,Vu]),jsxRuntimeExports.jsxs(BlockFrame,{label:Au.description||Au.name,weight:lo.weight,testId:`custom-${Au.name}`,children:[Ou?jsxRuntimeExports.jsx(Problem,{children:Ou}):null,!Ou&&Fu&&!qu?jsxRuntimeExports.jsx(Problem,{children:`Its module “${Au.source}” is a file of its application's folder: it is drawn once the server running the application serves its package (loop apps package, installed beside that server).`}):null,jsxRuntimeExports.jsx("iframe",{ref:Iu,title:Au.description||Au.name,sandbox:CUSTOM_FRAME_SANDBOX,srcDoc:Uu,referrerPolicy:"no-referrer",style:{width:"100%",height:`${Au.height}px`,border:0,display:"block"}})]})}function customImplementation(Au,lo="0.0.0",$u,Ru=""){const Iu=customComponentEntry(Au,lo),Ou={name:Au.name,schema:componentSchemaOf(Iu)};return createComponentImplementation(Ou,({props:Du})=>jsxRuntimeExports.jsx(CustomComponentView,{component:Au,props:Du,fetcher:$u,appId:Ru}))}const SURFACE_CATALOG_ID=datalayerCatalog.id,INHERIT_THEME={"--a2ui-color-surface":"var(--bgColor-muted)","--a2ui-color-on-surface":"var(--fgColor-default)","--a2ui-color-primary":"var(--fgColor-accent)","--a2ui-color-outline":"var(--borderColor-default)"};function InlineSurface({messages:Au,onAction:lo,validationError:$u,data:Ru,catalog:Iu=datalayerCatalog,onSurface:Ou}){const Pu=reactExports.useRef(lo);Pu.current=lo;const Du=reactExports.useMemo(()=>new MessageProcessor([Iu],Gu=>Pu.current(Gu,Lu.current?.model.getSurface(Gu.surfaceId))),[]),Lu=reactExports.useRef(void 0);Lu.current=Du;const[ju,Bu]=reactExports.useState([]),Fu=reactExports.useRef(Ou);Fu.current=Ou,reactExports.useEffect(()=>{const Gu=Du.onSurfaceCreated(Zu=>{Bu(Qu=>[...Qu,Zu]),Fu.current?.(Zu)}),Ku=Du.onSurfaceDeleted(Zu=>Bu(Qu=>Qu.filter(Yu=>Yu.id!==Zu)));return()=>{Gu.unsubscribe(),Ku.unsubscribe()}},[Du]);const zu=reactExports.useRef(!1),[qu,Uu]=reactExports.useState(null);reactExports.useEffect(()=>{if(!zu.current){zu.current=!0;try{Du.processMessages(Au)}catch(Gu){Uu(`This surface could not be drawn: ${Gu instanceof Error?Gu.message:String(Gu)}`)}}},[Au,Du]);const Hu=reactExports.useRef({});reactExports.useEffect(()=>{if(!Ru)return;const Gu=Hu.current;for(const[Ku,Zu]of Object.entries(Ru))if(!Object.is(Gu[Ku],Zu)){Gu[Ku]=Zu;for(const Qu of Du.model.surfacesMap.values())Qu.dataModel.set(Ku,Zu)}},[Ru,Du]);const Vu=$u||qu;return ju.length===0&&!Vu?null:jsxRuntimeExports.jsx(A2uiMarkdownProvider,{children:jsxRuntimeExports.jsxs(Box,{style:INHERIT_THEME,sx:{...A2UI_RENDER_SCOPE_SX,display:"flex",flexDirection:"column",gap:2},children:[Vu?jsxRuntimeExports.jsx(Box,{role:"alert",px:3,py:2,borderRadius:2,bg:"danger.subtle",border:"1px solid",borderColor:"danger.muted",color:"danger.fg",fontSize:1,children:Vu}):null,ju.map(Gu=>jsxRuntimeExports.jsx(Box,{border:"1px solid",borderColor:"border.default",borderRadius:2,p:3,bg:"canvas.default",children:jsxRuntimeExports.jsx(A2uiSurfaceComposed,{surface:Gu})},Gu.id))]})})}function useOwnComponents(){const Au=useOptionalReactorPlatform();return reactExports.useMemo(()=>Au?Au.getContributions(LoopA2uiComponent).map(lo=>lo.value.implementation):[],[Au])}function useOwnCatalog(){const Au=useOwnComponents();return reactExports.useMemo(()=>catalogWithOwn(Au),[Au])}const APP_PAGE_SURFACE="app-page",APP_PAGE_SURFACE_ID="app",APP={path:"/app",meaning:"The application's name.",words:"Its name"},STATUS={path:"/status",meaning:"Where its answer stands, in a word: Ready, Thinking, Answering, Answered or Stopped.",words:"Where its answer stands"},DRAFT={path:"/draft",meaning:"A message written on the page, which a Send button sends.",words:"A message to send"},SEND={name:"send",meaning:"Send a message to the application: the context’s message, or what is written at /draft.",words:"Send the message",context:["message"],asks:{message:"The message it sends"}},MESSAGES={path:"/messages",meaning:"The conversation so far, in order: each message {role: user or assistant, text}, each tool called {role: tool, name, args, result}.",words:"The conversation",list:!0},FILES={path:"/files",meaning:"The files given on the page, each {name, type, size, data_url}: they go to the application’s session with the next run, put in its sandbox when it has a shell, a text file in the message when it has none.",words:"The files given",list:!0},STOP={name:"stop",meaning:"Stop the answer being written.",words:"Stop the answer",context:[],asks:{}},APP_KIND_PATHS={chat:{publishes:[APP,{path:"/question",meaning:"The question last asked.",words:"The question last asked"},{path:"/answer",meaning:"Its answer to it, as it is written.",words:"Its answer"},STATUS,MESSAGES],accepts:[DRAFT],actions:[SEND,STOP,{name:"new",meaning:"Start the conversation over.",words:"Start over",context:[],asks:{}}],inputs:!0},widget:{publishes:[APP,{path:"/output",meaning:"What it gave for the inputs last run, as it is written.",words:"What it gave"},STATUS],accepts:[FILES],actions:[{name:"run",meaning:"Run it on its inputs: every value written under /inputs is sent, and each file at /files, with the context’s message when there is one.",words:"Run it on its inputs",context:["message"],asks:{message:"What it says before the inputs"}},{name:"upload",meaning:"Run it on the files just given — the context’s files, else those at /files — with its inputs.",words:"Run it on the files given",context:["files"],asks:{files:"The files it runs on"}},STOP],inputs:!0},worker:{publishes:[APP,{path:"/goal",meaning:"What it works toward.",words:"What it works toward"},{path:"/activity",meaning:"What it is doing right now, in a short line, or nothing.",words:"What it is doing now"},{path:"/report",meaning:"What it last said, as it is written.",words:"What it last said"},STATUS],accepts:[DRAFT],actions:[SEND,STOP],inputs:!1}},isAppPageKind=Au=>Object.prototype.hasOwnProperty.call(APP_KIND_PATHS,Au),inputPath=Au=>`/inputs/${Au}`;function settingFields(Au){const lo=Au?.properties;return!lo||typeof lo!="object"?[]:Object.entries(lo).filter($u=>typeof $u[1]=="object"&&$u[1]!==null)}const settingTitle=(Au,lo)=>typeof lo.title=="string"&&lo.title?lo.title:Au;function settingDefaults(Au){return Object.fromEntries(settingFields(Au).filter(([,lo])=>lo.default!==void 0).map(([lo,$u])=>[lo,$u.default]))}function appKindPaths(Au){if(!isAppPageKind(Au.kind))return{publishes:[],accepts:[],actions:[],inputs:!1};const lo=APP_KIND_PATHS[Au.kind];if(!lo.inputs)return lo;const $u=settingFields(Au.interface.settings).map(([Pu,Du])=>({path:inputPath(Pu),meaning:`The setting “${settingTitle(Pu,Du)}”.`,words:settingTitle(Pu,Du)})),Ru=pageOf(Au);if(!Ru)return{...lo,publishes:[...lo.publishes,...$u],accepts:[...lo.accepts,...$u]};const Iu=settingFields(Ru.inputs).map(([Pu,Du])=>({path:inputPath(Pu),meaning:`The input “${settingTitle(Pu,Du)}” of its page.`,words:settingTitle(Pu,Du)})),Ou=Ru.outputs.map(Pu=>({path:outputPath(Pu.name),meaning:`What its page shows as “${Pu.title||Pu.name}”, drawn with a ${Pu.component}, for its inputs.`,words:Pu.title||Pu.name,...Pu.component==="Table"||Pu.component==="Chart"?{list:!0}:{}}));return{...lo,publishes:[...lo.publishes,...$u,...Iu,...Ou],accepts:[...lo.accepts,...$u,...Iu],actions:[...lo.actions,PAGE]}}const pageOf=Au=>Au.kind==="widget"?Au.interface.page:void 0,outputPath=Au=>`/outputs/${Au}`,PAGE_ACTION="page",PAGE={name:PAGE_ACTION,meaning:"Run its page on its inputs: every value written under /inputs, its outputs shown in place at /outputs.",words:"Run its page",context:[],asks:{}},surfaceComponents=Au=>Au.interface.surface?.components??[];function hasAppPage(Au){return!Au.agent||!isAppPageKind(Au.kind)?!1:Au.interface.layout!=="chat"}const STATUS_WORDS={idle:"Ready",thinking:"Thinking",streaming:"Answering",done:"Answered",error:"Stopped"};function appPageData(Au,lo,$u){const Ru={"/app":Au.name,"/status":STATUS_WORDS[lo.status]??""};switch(Au.kind){case"chat":Ru["/question"]=lo.user??"",Ru["/answer"]=lo.assistant??"",Ru["/messages"]=$u;break;case"widget":Ru["/output"]=lo.assistant??"";break;case"worker":Ru["/goal"]=Au.goal,Ru["/activity"]=lo.activity??"",Ru["/report"]=lo.assistant??"";break}return Ru}function appPageInitialData(Au){const lo={};for(const[Ru,Iu]of Object.entries(appPageData(Au,{status:"idle"},[])))lo[Ru.slice(1)]=Iu;const $u=appKindPaths(Au);if($u.inputs){const Ru={...settingDefaults(Au.interface.settings),...settingDefaults(pageOf(Au)?.inputs)};for(const Iu of Au.interface.surface?.components??[]){const Ou=Iu.value?.path,Pu=typeof Ou=="string"&&Ou.startsWith("/inputs/")?Ou.slice(8):void 0;Iu.component==="ChoicePicker"&&Pu&&Pu in Ru&&(Ru[Pu]=Array.isArray(Ru[Pu])?Ru[Pu]:[Ru[Pu]])}lo.inputs=Ru}return pageOf(Au)&&(lo.outputs={}),$u.accepts.some(Ru=>Ru.path===DRAFT.path)&&(lo.draft=""),$u.accepts.some(Ru=>Ru.path===FILES.path)&&(lo.files=[]),lo}function inputWords(Au,lo){const $u=Array.isArray(lo)?lo.map(String).join(", "):typeof lo=="boolean"?lo?"yes":"no":lo==null?"":String(lo);return $u.trim()?`${Au}: ${$u}`:""}function inputsInWords(Au,lo){const $u=lo&&typeof lo=="object"?lo:{},Ru=[],Iu=new Set;for(const[Ou,Pu]of settingFields(Au.interface.settings))Iu.add(Ou),Ru.push(inputWords(settingTitle(Ou,Pu),$u[Ou]));for(const[Ou,Pu]of Object.entries($u))Iu.has(Ou)||Ru.push(inputWords(Ou,Pu));return Ru.filter(Boolean).join(`
3593
3593
  `)}const MAX_FILE_BYTES=25*1024*1024;function givenFiles(Au){if(Au==null)return{files:[]};if(!Array.isArray(Au))return{refused:"What was given as files is not a list of files."};const lo=[];for(const[$u,Ru]of Au.entries()){const Iu=Ru??{};if(typeof Iu.name!="string"||typeof Iu.data_url!="string")return{refused:`File ${$u+1} is not a file as File upload gives it ({name, type, size, data_url}).`};const Ou=typeof Iu.size=="number"?Iu.size:0;if(Ou>MAX_FILE_BYTES)return{refused:`${Iu.name} is ${Ou.toLocaleString("en")} bytes: a session takes files of at most ${MAX_FILE_BYTES.toLocaleString("en")}.`};lo.push({name:Iu.name,type:typeof Iu.type=="string"?Iu.type:"",size:Ou,data_url:Iu.data_url})}return{files:lo}}function settingsOf(Au,lo){return formValuesOf(Au.interface.settings,lo)}function pageInputsOf(Au,lo){return formValuesOf(pageOf(Au)?.inputs,lo)}function formValuesOf(Au,lo){const $u=lo&&typeof lo=="object"?lo:{},Ru={};for(const[Iu,Ou]of settingFields(Au)){const Pu=$u[Iu];if(Pu==null)continue;if(Ou.type==="array"||Ou.type==="object"){Ru[Iu]=Pu;continue}const Du=Array.isArray(Pu)?Pu[0]:Pu;if(Du!=null)switch(Ou.type){case"integer":case"number":Du!==""&&!Number.isNaN(Number(Du))&&(Ru[Iu]=Number(Du));break;case"boolean":Ru[Iu]=!!Du;break;default:(Du!==""||!Array.isArray(Ou.enum))&&(Ru[Iu]=typeof Du=="string"?Du:String(Du))}}return Ru}function appPageAction(Au,lo,$u,Ru=""){const Iu=appKindPaths(Au);if(!Iu.actions.some(Fu=>Fu.name===lo.name)){const Fu=Iu.actions.map(zu=>zu.name).join(", ");return{refused:Fu?`“${lo.name}” is not something ${Au.name} does: it does ${Fu}.`:`${Au.name} handles no button.`}}const Ou=lo.context?.message,Pu=typeof Ou=="string"?Ou.trim():"",Du=Iu.inputs?inputsInWords(Au,$u("/inputs")):"",Lu=Iu.inputs?settingsOf(Au,$u("/inputs")):void 0,ju=Object.fromEntries(Object.entries(lo.context??{}).filter(([Fu])=>Fu!=="message"&&Fu!=="files")),Bu=Fu=>({action:{name:lo.name,payload:ju},...Fu&&Fu.length>0?{files:Fu}:{},...Lu?{settings:Lu}:{}});switch(lo.name){case PAGE_ACTION:return{runPage:pageInputsOf(Au,$u("/inputs"))};case"stop":return{stop:!0};case"new":return{newChat:!0};case"run":case"upload":{const Fu=lo.context?.files,zu=givenFiles(lo.name==="upload"&&Fu!==void 0?Fu:$u(FILES.path));if("refused"in zu)return zu;if(lo.name==="upload"&&zu.files.length===0)return{refused:"No file was given: choose one first."};const qu=zu.files.map(Hu=>Hu.name).join(", "),Uu=[Pu,Du].filter(Boolean).join(`
3594
3594
  `)||(qu?`Run on ${qu}.`:"");return Uu?{send:Uu,inputs:Du,clear:[],loop:Bu(zu.files)}:{refused:`${Au.name} has no inputs to run on: set one first.`}}default:{const Fu=$u(DRAFT.path),zu=Pu||(typeof Fu=="string"?Fu.trim():"");return zu?{send:Du&&Du!==Ru?`${zu}
3595
3595
 
3596
3596
  ${Du}`:zu,inputs:Du,clear:Pu?[]:[DRAFT.path],loop:Bu()}:{refused:"Nothing to send: write a message first."}}}}const text=(Au,lo,$u)=>({id:Au,component:"Text",text:{path:lo},...$u?{variant:$u}:{}}),button=(Au,lo,$u,Ru=!1)=>[{id:Au,component:"Button",child:`${Au}-label`,...Ru?{variant:"primary"}:{},action:{event:{name:$u}}},{id:`${Au}-label`,component:"Text",text:lo}];function settingsForm(Au){const lo=pageOf(Au);return lo?pageForm(Au,lo):Au.interface.settings&&settingFields(Au.interface.settings).length?[{id:"settings",component:"Form",schema:Au.interface.settings,...Au.interface.settingsUi?{ui:Au.interface.settingsUi}:{},values:{path:"/inputs"}}]:[]}function pageForm(Au,lo){const $u=Au.interface.settings,Ru={...lo.inputs,type:"object",properties:{...$u?.properties,...lo.inputs.properties},required:[...$u?.required??[],...lo.inputs.required??[]]},Iu={...Au.interface.settingsUi,...lo.inputsUi},Ou=lo.outputs.flatMap(Pu=>[...Pu.title?[{id:`output-${Pu.name}-title`,component:"Text",text:Pu.title,variant:"h4"}]:[],{...Pu.props,id:`output-${Pu.name}`,component:Pu.component,[pageOutputShows(Pu.component,Au.interface.customComponents)??"text"]:{path:outputPath(Pu.name)}}]);return[{id:"inputs",component:"Form",schema:Ru,...Object.keys(Iu).length>0?{ui:Iu}:{},values:{path:"/inputs"}},...lo.live?[]:button("run-page","Run",PAGE_ACTION,!0),...Ou]}function defaultAppSurface(Au){const lo=appKindPaths(Au).inputs?settingsForm(Au):[],$u=[];switch(Au.kind){case"chat":$u.push(text("question","/question","h3"),text("answer","/answer"),text("status","/status","caption"),...lo);break;case"widget":if(pageOf(Au)){$u.push(...lo);break}$u.push(...lo,{id:"actions",component:"Row",children:["run","stop"]},...button("run","Run","run",!0),...button("stop","Stop","stop"),text("status","/status","caption"),text("output","/output"));break;case"worker":$u.push(text("goal","/goal","h3"),text("status","/status","caption"),text("activity","/activity","caption"),text("report","/report"));break}const Ru=new Set($u.flatMap(Iu=>[...Array.isArray(Iu.children)?Iu.children:[],Iu.child].filter(Ou=>typeof Ou=="string")));return[{id:"root",component:"Column",children:$u.map(Iu=>Iu.id).filter(Iu=>!Ru.has(Iu))},...$u]}function appPageMessages(Au,lo){const $u=surfaceComponents(Au);return[{version:"v0.9",createSurface:{surfaceId:APP_PAGE_SURFACE_ID,catalogId:lo}},{version:"v0.9",updateComponents:{surfaceId:APP_PAGE_SURFACE_ID,components:$u.length>0?$u:defaultAppSurface(Au)}},{version:"v0.9",updateDataModel:{surfaceId:APP_PAGE_SURFACE_ID,path:"/",value:appPageInitialData(Au)}}]}const LOOP_PAGE="loop.page";function streamEvents(Au){const lo=[];for(const $u of Au.split(`
3597
3597
 
3598
3598
  `)){const Ru=$u.split(`
3599
- `).filter(Iu=>Iu.startsWith("data:")).map(Iu=>Iu.slice(5).trim()).join("");if(Ru)try{lo.push(JSON.parse(Ru))}catch{}}return lo}function pageTurnOf(Au){let lo=null;for(const $u of streamEvents(Au)){if($u.type==="RUN_ERROR")return{refused:String($u.message??"Its page could not run.")};if($u.type==="CUSTOM"&&$u.name===LOOP_PAGE){const Ru=$u.value??{};lo={outputs:Ru.outputs??{},inputs:Ru.inputs??{}}}}return lo??{refused:"Its page showed nothing: its code answered no outputs."}}const base=Au=>`${Au.serverUrl.replace(/\/+$/,"")}/api/v1/apps/sessions`;async function posted(Au,lo,$u){const Ru=await(Au.fetcher??fetch)(lo,{method:"POST",headers:{"content-type":"application/json",...Au.token?{Authorization:`Bearer ${Au.token}`}:{}},body:JSON.stringify($u)});if(!Ru.ok){let Iu="";try{const Ou=await Ru.json();Iu=typeof Ou.detail=="string"?Ou.detail:""}catch{}throw new Error(Iu||`Its page was refused (${Ru.status}).`)}return Ru.text()}async function openPageSession(Au){const lo=await posted(Au,base(Au),{agent:Au.agentId});for(const $u of streamEvents(lo))if($u.type==="CUSTOM"&&$u.name==="loop.session"){const Ru=$u.value?.uid;if(typeof Ru=="string"&&Ru)return Ru}throw new Error("The runtime opened no session for its page.")}async function runPageIn(Au,lo,$u){try{const Ru=await posted(Au,`${base(Au)}/${encodeURIComponent(lo)}/actions`,{name:"page",payload:{inputs:$u}});return pageTurnOf(Ru)}catch(Ru){return{refused:Ru instanceof Error?Ru.message:String(Ru)}}}function outputsData(Au){return Object.fromEntries(Object.entries(Au).map(([lo,$u])=>[`/outputs/${lo}`,$u]))}const PAGE_RUN_DELAY_MS=300,NO_TURN$6=signal$2({id:0,status:"idle"}),NO_CONVERSATION$2=signal$2([]);function componentsOnPage(Au){const lo=new Set;for(const $u of Au){const Ru=$u.updateComponents;for(const Iu of Ru?.components??[])lo.add(String(Iu.component))}return[...lo]}function blocksMissing(Au,lo){const $u=new Set(lo),Ru=Au.filter(Iu=>!$u.has(Iu));return Ru.length===0?null:`This page places ${Ru.join(", ")}, which no enabled plugin contributes: ${Ru.length===1?"it is":"they are"} drawn once the plugin that contributes ${Ru.length===1?"it":"them"} is on.`}function AppPage({app:Au,workspace:lo}){const $u=useContributions(LoopChatTurn),Ru=useSignalValue$1($u[0]?.value.turn??NO_TURN$6),Iu=useSignalValue$1($u[0]?.value.conversation??NO_CONVERSATION$2),Ou=reactExports.useMemo(()=>appPageMessages(Au,SURFACE_CATALOG_ID),[Au]),Pu=useContributions(LoopCanvasBlock),Du=[...new Set(Pu.map(bd=>bd.value.id))].sort(),Lu=Du.join(","),ju=useOwnComponents(),Bu=reactExports.useMemo(()=>{const bd=blocksMissing(componentsOnPage(Ou),Du);if(bd)return{problem:bd};try{return{catalog:catalogOfBlocks(Du,ju)}}catch(Td){return{problem:Td instanceof Error?Td.message:String(Td)}}},[Ou,Lu,ju]),[Fu,zu]=reactExports.useState(null),qu=pageOf(Au),[Uu,Hu]=reactExports.useState({}),Vu=reactExports.useMemo(()=>({...appPageData(Au,Ru,Iu),...outputsData(Uu)}),[Au,Ru,Iu,Uu]),Gu=useIAMStore(bd=>bd.token)??"",Ku=useChatWords(),Zu=agentServerOf(lo.sandbox,lo.serverUrl),Qu=reactExports.useRef(null);Qu.current=Zu===void 0?null:{serverUrl:Zu,agentId:lo.agentId||Au.id,token:Gu||void 0};const Yu=reactExports.useRef("");Yu.current=Zu===void 0?noRuntimeSaid(lo.sandbox,Ku):"";const ed=reactExports.useRef(null),Xu=reactExports.useRef(!1),rd=reactExports.useRef(null),nd=reactExports.useRef(""),od=reactExports.useRef(!0),ad=reactExports.useCallback(bd=>{rd.current=bd,!Xu.current&&(Xu.current=!0,(async()=>{for(;rd.current&&od.current;){const Td=rd.current;rd.current=null;const Pd=Qu.current;if(!Pd){zu(Yu.current);continue}try{ed.current??=openPageSession(Pd);const ud=await runPageIn(Pd,await ed.current,Td);if(!od.current)break;"refused"in ud?zu(ud.refused):(zu(null),Hu(ud.outputs))}catch(ud){ed.current=null,od.current&&zu(ud instanceof Error?ud.message:String(ud))}}Xu.current=!1})())},[]),ld=reactExports.useRef(null);reactExports.useEffect(()=>(od.current=!0,()=>{od.current=!1,ld.current?.()}),[]);const fd=reactExports.useCallback(bd=>{if(!qu?.live)return;ld.current?.();let Td;const Pd=md=>{const _d=pageInputsOf(Au,md),hd=JSON.stringify(_d);hd!==nd.current&&(clearTimeout(Td),Td=setTimeout(()=>{nd.current=hd,ad(_d)},PAGE_RUN_DELAY_MS))},ud=bd.dataModel.subscribe("/inputs",Pd);Pd(ud.value),ld.current=()=>{clearTimeout(Td),ud.unsubscribe()}},[Au,qu?.live,ad]),pd=reactExports.useRef(lo);pd.current=lo;const Sd=reactExports.useRef(""),wd=reactExports.useCallback((bd,Td)=>{const Pd=appPageAction(Au,{name:bd.name,context:bd.context??{}},md=>Td?.dataModel.get(md),Sd.current),ud=pd.current.viewControls;if("refused"in Pd){zu(Pd.refused);return}if(zu(null),"runPage"in Pd)ad(Pd.runPage);else if("stop"in Pd)ud.stop?.();else if("newChat"in Pd)ud.newChat?.();else{if(ud.send){const md=ud.send(Pd.send,{loop:Pd.loop});if(md){zu(md);return}}else if(Pd.loop.files){zu("The conversation is not ready for a file yet: try again.");return}else pd.current.prompts.submit(Pd.send);Sd.current=Pd.inputs;for(const md of Pd.clear)Td?.dataModel.set(md,"")}},[Au,ad]);return jsxRuntimeExports.jsx(Box,{"data-testid":"app-page",height:"100%",minHeight:0,overflow:"auto",p:3,children:"problem"in Bu?jsxRuntimeExports.jsx(Box,{role:"status",color:"fg.muted",fontSize:1,children:Bu.problem}):jsxRuntimeExports.jsx(InlineSurface,{messages:Ou,data:Vu,onAction:wd,validationError:Fu,catalog:Bu.catalog,...qu?{onSurface:fd}:{}},Lu)})}const APP_PAGE_PLUGIN_NAME="@datalayer/loop-plugin-app-page";function defineAppPagePlugin(Au){function lo({workspace:Ru}){return jsxRuntimeExports.jsx(AppPage,{app:Au,workspace:Ru})}return{name:`${APP_PAGE_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: its page`,description:`The page of ${Au.name}, drawn beside its conversation.`,octicon:"browser",emoji:Au.emoji||void 0,contributes:[contribution(LoopEditorView,{surfaceId:APP_PAGE_SURFACE,title:Au.name,icon:BrowserIcon,order:-10,load:async()=>({default:lo})},{id:APP_PAGE_SURFACE,order:-10})]}}const APP_HOST_PAGE_VIEW="app-page";function defineAppHostPagePlugin(Au,lo){function $u({workspace:Iu}){return jsxRuntimeExports.jsx(lo,{app:Au,workspace:Iu})}return{name:`${APP_PAGE_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: its page`,description:`The page of ${Au.name}, drawn by its host.`,octicon:"browser",emoji:Au.emoji||void 0,contributes:[contribution(LoopViewType,{viewType:APP_HOST_PAGE_VIEW,title:Au.name,icon:BrowserIcon,order:-10,load:async()=>({default:$u})},{id:APP_HOST_PAGE_VIEW,order:-10})]}}const canvasBlocksPluginName=Au=>`@datalayer/loop-plugin-ui-${Au}`;function uiPluginBlocks(Au){return{name:canvasBlocksPluginName(Au.id),displayName:Au.name,description:`The blocks of ${Au.name} on the Canvas: ${Au.components.map(lo=>lo.name).join(", ")}.`,octicon:"apps",contributes:Au.components.map(lo=>contribution(LoopCanvasBlock,{id:lo.id,uiPlugin:Au.id,component:lo},{id:lo.id}))}}const CANVAS_BLOCK_PLUGINS=listUIPlugins().filter(Au=>Au.enabled&&Au.components.length>0).map(uiPluginBlocks),MANAGER_PLUGIN_NAME="@datalayer/reactor-manager",MANAGER_ACTIONS_SLOT="manager-actions",ManagerPluginSource=defineContributionPoint("manager.pluginSource");function usePluginRows(Au,lo){const $u=useReactorPlatform(),Ru=reactExports.useSyncExternalStore($u.subscribe,()=>$u.getRevision());return reactExports.useMemo(()=>$u.listPlugins().filter(Iu=>!lo.has(Iu)).map(Iu=>{const Ou=$u.getManifest(Iu);return{name:Iu,displayName:Ou?.displayName??Iu,description:Ou?.description,emoji:Ou?.emoji,version:Ou?.version,enabled:$u.isEnabled(Iu),disabledBy:Ou?.disabledBy,changeable:!Au.has(Iu),details:[{label:"Delivered by",values:Ou?.extension?[Ou.extension]:[]},{label:"Contributes to",values:Ou?.contributesTo??[]},{label:"Offers contribution points",values:Ou?.contributionPoints??[]},{label:"Requires backend plugins",values:Ou?.requiredBackendPlugins??[]},{label:"Uses if available",values:Ou?.optionalBackendPlugins??[]},{label:"Activates on",values:Ou?.activationEvents??[]}]}}),[$u,Ru,Au,lo])}function pluginMatches(Au,lo){if(!lo)return!0;const $u=lo.trim().toLowerCase();return[Au.name,Au.displayName,Au.description??""].join(" ").toLowerCase().includes($u)}const PluginHoverContext=reactExports.createContext(null);function usePluginHoverControl(){const[Au,lo]=reactExports.useState(null),$u=reactExports.useRef(void 0);return reactExports.useEffect(()=>()=>clearTimeout($u.current),[]),reactExports.useMemo(()=>({openName:Au,show:Ru=>{clearTimeout($u.current),lo(Ru)},hide:()=>{clearTimeout($u.current),$u.current=setTimeout(()=>lo(null),200)}}),[Au])}function useHoverControl(){const Au=reactExports.useContext(PluginHoverContext),lo=usePluginHoverControl();return Au??lo}function PluginDetails({row:Au}){const lo=(Au.details??[]).filter($u=>$u.values.length>0);return jsxRuntimeExports.jsxs(Box,{sx:{p:3,maxWidth:360,display:"grid",gap:2},children:[jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",alignItems:"center",gap:2},children:[Au.emoji?jsxRuntimeExports.jsx(Text$5,{"aria-hidden":!0,children:Au.emoji}):null,jsxRuntimeExports.jsx(Text$5,{sx:{fontWeight:"semibold"},children:Au.displayName}),Au.version?jsxRuntimeExports.jsxs(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:["v",Au.version]}):null]}),jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted",wordBreak:"break-all"},children:Au.name}),Au.description?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0},children:Au.description}):null,lo.map($u=>jsxRuntimeExports.jsxs(Box,{sx:{display:"grid",gap:1},children:[jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,fontWeight:"semibold"},children:$u.label}),$u.values.map(Ru=>jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted",wordBreak:"break-all"},children:Ru},Ru))]},$u.label)),Au.disabledBy==="dependency"?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"attention.fg"},children:"Off because something it depends on is off. It comes back when that does."}):null,Au.changeable?null:jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"attention.fg"},children:"This one cannot be switched off."})]})}const OVERLAY_TAKES_NO_FOCUS={preventFocusOnOpen:!0,sx:{pointerEvents:"none"},returnFocusRef:{current:null}};function PluginRowView({row:Au,size:lo,onToggle:$u}){const Ru=`plugin-name-${Au.name.replace(/[^a-zA-Z0-9]+/g,"-")}`,Iu=useHoverControl(),Ou=Iu.openName===Au.name,Pu=()=>Iu.show(Au.name),Du=()=>Iu.hide();return jsxRuntimeExports.jsx(AnchoredOverlay,{open:Ou,onOpen:Pu,onClose:Du,focusZoneSettings:{disabled:!0},focusTrapSettings:{disabled:!0},overlayProps:OVERLAY_TAKES_NO_FOCUS,side:"outside-right",renderAnchor:Lu=>jsxRuntimeExports.jsxs(Box,{...Lu,onMouseEnter:Pu,onMouseLeave:Du,onFocus:Pu,onBlur:Du,sx:{display:"flex",alignItems:"flex-start",gap:2,py:2,borderBottom:"1px solid",borderColor:"border.muted"},children:[jsxRuntimeExports.jsxs(Box,{sx:{minWidth:0,flex:1},children:[jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",alignItems:"center",gap:1},children:[Au.emoji?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:1},"aria-hidden":!0,children:Au.emoji}):null,jsxRuntimeExports.jsx(Text$5,{id:Ru,sx:{fontSize:1,fontWeight:"semibold",minWidth:0},children:jsxRuntimeExports.jsx(Truncate,{title:Au.name,maxWidth:"100%",inline:!0,children:Au.displayName})})]}),Au.description?jsxRuntimeExports.jsx(Text$5,{sx:{display:"block",fontSize:0,color:"fg.muted"},children:jsxRuntimeExports.jsx(Truncate,{title:Au.description,maxWidth:"100%",inline:!0,children:Au.description})}):null]}),jsxRuntimeExports.jsx(ToggleSwitch,{size:lo,checked:Au.enabled,disabled:!Au.changeable||Au.disabledBy==="dependency","aria-labelledby":Ru,onClick:()=>{Au.changeable&&Au.disabledBy!=="dependency"&&$u(Au.name,!Au.enabled)}})]}),children:jsxRuntimeExports.jsx(PluginDetails,{row:Au})})}function PluginList({plugins:Au,query:lo="",switchSize:$u="small",onToggle:Ru,emptyMessage:Iu}){const Ou=reactExports.useMemo(()=>Au.filter(Pu=>pluginMatches(Pu,lo)),[Au,lo]);return Ou.length===0?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:Iu??`No plugin matches “${lo}”.`}):jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Ou.map(Pu=>jsxRuntimeExports.jsx(PluginRowView,{row:Pu,size:$u,onToggle:Ru},Pu.name))})}function PluginsManagerView({protectedPlugins:Au,hiddenPlugins:lo,switchSize:$u,width:Ru,...Iu}){const Ou=useReactorPlatform(),Pu=Ou.getConfig(MANAGER_PLUGIN_NAME)??{},Du=reactExports.useMemo(()=>new Set(Au??Pu.protected??[MANAGER_PLUGIN_NAME]),[Au,Pu.protected]),Lu=reactExports.useMemo(()=>new Set(lo??Pu.hidden??[]),[lo,Pu.hidden]),ju=usePluginHoverControl(),Bu=usePluginRows(Du,Lu),[Fu,zu]=reactExports.useState(""),qu=$u??Pu.switchSize??"small",Uu=useContributions(ManagerPluginSource),Hu=reactExports.useMemo(()=>[...Uu].map(Vu=>Vu.value).sort((Vu,Gu)=>(Vu.order??100)-(Gu.order??100)),[Uu]);return jsxRuntimeExports.jsx(PluginHoverContext.Provider,{value:ju,children:jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",flexDirection:"column",gap:3,width:Ru??Pu.width??"100%",maxWidth:"100%",minWidth:0},children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:MANAGER_ACTIONS_SLOT,props:Iu}),jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$5,{as:"h2",sx:{fontSize:1,fontWeight:"semibold",display:"block",mb:2},children:Pu.title??"Plugins"}),jsxRuntimeExports.jsx(TextInput$1,{leadingVisual:SearchIcon,value:Fu,onChange:Vu=>zu(Vu.target.value),"aria-label":"Filter plugins",placeholder:"Filter…",block:!0,size:"small"})]}),jsxRuntimeExports.jsx(Box,{children:jsxRuntimeExports.jsx(PluginList,{plugins:Bu,query:Fu,switchSize:qu,onToggle:(Vu,Gu)=>Gu?Ou.enable(Vu):Ou.disable(Vu)})}),Hu.map(Vu=>jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$5,{as:"h3",sx:{fontSize:1,fontWeight:"semibold",display:"block",mb:2},children:Vu.title}),jsxRuntimeExports.jsx(Vu.Component,{query:Fu,switchSize:qu})]},Vu.title))]})})}const PLUGINS_PANEL_PLUGIN_NAME="@datalayer/loop-plugin-plugins-panel",SIDEBAR_WIDTH=420,REACTOR_GRAPH_PLUGIN_NAME="@datalayer/reactor-graph",PluginsPanelPlugin={name:PLUGINS_PANEL_PLUGIN_NAME,displayName:"Plugins panel",description:"Switch plugins on and off while the workspace runs.",octicon:"plug",emoji:"🔌",build:()=>({components:[{id:"plugins-panel",slot:LoopSlots.sidebar,order:900,Component:({workspace:Au})=>jsxRuntimeExports.jsx(PluginsManagerView,{protectedPlugins:[PLUGINS_PANEL_PLUGIN_NAME],hiddenPlugins:[REACTOR_GRAPH_PLUGIN_NAME],width:SIDEBAR_WIDTH,workspace:Au})}]})};function ViewSwitcher({views:Au,workspace:lo,compact:$u=!1}){return Au.length<2?null:jsxRuntimeExports.jsx(Box,{role:"tablist","aria-label":"Workspace views",display:"inline-flex",alignItems:"center",bg:"neutral.muted",borderRadius:"6px",p:"2px",gap:"1px",children:Au.map(Ru=>{const Iu=Ru.value,Ou=canOpenView(Iu,lo),Pu=lo.activeViewType===Iu.viewType,Du=Iu.icon,Lu=Ou?Iu.title:`${Iu.title} — ${Iu.unavailableReason?.(lo)??"unavailable"}`;return jsxRuntimeExports.jsx(Tooltip,{text:Lu,direction:"n",children:jsxRuntimeExports.jsxs(Box,{as:"button",role:"tab","aria-selected":Pu,"aria-disabled":!Ou,onClick:()=>Ou&&lo.setActiveViewType(Iu.viewType),display:"inline-flex",alignItems:"center",gap:1,border:"none",borderRadius:"5px",px:2,py:"4px",fontSize:0,cursor:Ou?"pointer":"not-allowed",opacity:Ou?1:.5,bg:Pu?"canvas.default":"transparent",color:Pu?"fg.default":"fg.muted",boxShadow:Pu?"shadow.small":"none",children:[Du?jsxRuntimeExports.jsx(Du,{size:14}):null,$u&&Du?null:Iu.title]})},Iu.viewType)})})}const paneOpenKeyframes=Au=>Au==="left"?"loopPaneOpenLeft":"loopPaneOpenRight",paneOpenAnimation=Au=>`${paneOpenKeyframes(Au)} var(--theme-motion-pane, 0ms) var(--theme-motion-easing, ease) both`;function paneOpening(Au){const lo="12px";return{animation:paneOpenAnimation(Au),[`@keyframes ${paneOpenKeyframes(Au)}`]:{from:{opacity:0,transform:`translateX(${lo})`},to:{opacity:1,transform:"none"}},"@media (prefers-reduced-motion: reduce)":{animation:"none"}}}function railItemsOf(Au){return Au.map(lo=>({id:lo.id,label:lo.rail?.label??lo.id,icon:lo.rail?.icon??SidebarExpandIcon}))}function railChoiceAfter(Au,lo){return Au===lo?null:lo}const RAIL_WIDTH=48;function SidebarRail({components:Au,props:lo,width:$u}){const Ru=railItemsOf(Au),[Iu,Ou]=reactExports.useState(Ru[0]?.id??null),Pu=Ru.some(Du=>Du.id===Iu)?Iu:null;return jsxRuntimeExports.jsxs(Box,{as:"aside","data-loop-rail-sidebar":"",flex:"0 0 auto",display:"flex",minHeight:0,children:[jsxRuntimeExports.jsx(Box,{"data-loop-rail-panel":Pu??void 0,display:Pu?"block":"none",width:`${$u}px`,minWidth:0,borderLeft:"var(--theme-hairline, 1px) solid",borderColor:"border.default",overflowY:"auto",px:3,py:3,children:Au.map(Du=>{const{Component:Lu}=Du,ju=Du.id===Pu;return jsxRuntimeExports.jsx(Box,{id:`loop-rail-panel-${Du.id}`,role:"region","aria-label":railItemsOf([Du])[0].label,hidden:!ju,sx:ju?paneOpening("right"):void 0,children:jsxRuntimeExports.jsx(Lu,{...lo})},Du.id)})}),jsxRuntimeExports.jsx(Box,{as:"nav","aria-label":"Panels",width:`${RAIL_WIDTH}px`,flex:`0 0 ${RAIL_WIDTH}px`,display:"flex",flexDirection:"column",alignItems:"center",gap:1,py:2,borderLeft:"var(--theme-hairline, 1px) solid",borderColor:"border.default",children:Ru.map(Du=>{const Lu=Du.icon,ju=Du.id===Pu;return jsxRuntimeExports.jsx(Box,{as:"button",type:"button","data-loop-rail-item":Du.id,"aria-label":Du.label,title:Du.label,"aria-pressed":ju,"aria-controls":`loop-rail-panel-${Du.id}`,onClick:()=>Ou(railChoiceAfter(Pu,Du.id)),width:32,height:32,display:"inline-flex",alignItems:"center",justifyContent:"center",p:0,border:"none",borderRadius:2,cursor:"pointer",color:ju?"fg.default":"fg.muted",bg:ju?"neutral.muted":"transparent",hover:{color:"fg.default",bg:"neutral.subtle"},focusVisible:{outline:"2px solid",outlineColor:"var(--focus-outlineColor, #0969da)",outlineOffset:"1px"},children:jsxRuntimeExports.jsx(Lu,{size:16})},Du.id)})})]})}function buildLoopReactor(Au){return buildReactorFromPlugins(Au)}function LoopWorkspace(Au){const{serverUrl:lo,agentId:$u,conversationId:Ru,model:Iu,sandbox:Ou={state:"idle"},extensions:Pu=[],reactor:Du,manageReactor:Lu=!0,initialViewType:ju,onSend:Bu,layout:Fu="page",showViewSelector:zu=!0,showHeader:qu=!0,chatHeaderActions:Uu,headerActions:Hu,headerContainer:Vu,sidebarRail:Gu=!1}=Au,Ku=reactExports.useMemo(()=>Du??buildLoopReactor(Pu),[Du]);return useReactor(Ku,{autoStart:Lu}),jsxRuntimeExports.jsx(WorkspaceBody,{serverUrl:lo,agentId:$u,conversationId:Ru,model:Iu,initialSandbox:Ou,initialViewType:ju,onSend:Bu,layout:Fu,showViewSelector:zu,showHeader:qu,chatHeaderActions:Uu,headerActions:Hu,headerContainer:Vu,sidebarRail:Gu})}function WorkspaceBody({serverUrl:Au,agentId:lo,conversationId:$u,model:Ru,initialSandbox:Iu,initialViewType:Ou,onSend:Pu,layout:Du="page",showViewSelector:Lu=!0,showHeader:ju=!0,chatHeaderActions:Bu,headerActions:Fu,headerContainer:zu,sidebarRail:qu=!1}){const[Uu,Hu]=reactExports.useState(lo),Vu=reactExports.useRef(loopSurfaceId($u??`session-${Date.now().toString(36)}`));reactExports.useEffect(()=>{Hu(lo)},[lo]);const[Gu,Ku]=reactExports.useState(Ou??""),[Zu,Qu]=reactExports.useState(Iu),[Yu]=reactExports.useState(createPromptChannel),[ed,Xu]=reactExports.useState({}),rd=reactExports.useCallback(Pd=>{Xu(Pd??{})},[]),nd=useContributions(LoopViewType),od=useContributions(LoopCommand),ad=useSlotComponents(LoopSlots.sidebar),ld=reactExports.useRef(od),fd=reactExports.useRef(null),pd=Du==="panel",Sd=reactExports.useCallback(async Pd=>{const ud=parseCommand(Pd);if(!ud)return Pu?.(Pd,fd.current),Yu.submit(Pd)||Pu?{handled:!0}:{handled:!1,reason:"Nothing is listening for prompts in this view yet."};const md=ld.current.find(hd=>hd.value.name===ud.name||(hd.value.aliases??[]).includes(ud.name));if(!md)return{handled:!1,command:ud.name,reason:`Unknown command: /${ud.name}. Type /help to see what there is.`};const _d=await md.value.run({workspace:fd.current,argv:ud.argv});return _d?.prompt&&(Pu?.(_d.prompt,fd.current),Yu.submit(_d.prompt)),{handled:!0,command:ud.name,result:_d??void 0}},[Pu,Yu]),wd=reactExports.useMemo(()=>({serverUrl:Au,agentId:Uu,surfaceId:Vu.current,setAgentId:Hu,conversationId:$u,model:Ru,sandbox:Zu,setSandbox:Qu,activeViewType:Gu,setActiveViewType:Ku,prompts:Yu,submit:Sd,viewControls:ed,setViewControls:rd,chatHeaderActions:Bu}),[Au,Uu,$u,Ru,Zu,Gu,Yu,Sd,ed,rd,Bu]);fd.current=wd,ld.current=od;const bd=reactExports.useMemo(()=>Gu||(nd.find(ud=>canOpenView(ud.value,wd))?.value.viewType??""),[Gu,nd,wd]);useReactorEvent(bd?onView(bd):void 0);const Td=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Fu,jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.header,props:{workspace:wd}}),Lu?jsxRuntimeExports.jsx(ViewSwitcher,{views:nd,workspace:wd,compact:pd}):null]});return jsxRuntimeExports.jsxs(Box,{"data-loop-workspace":"",display:"flex",flexDirection:"column",height:"100%",minHeight:0,position:"relative",bg:"canvas.default",color:"fg.default",children:[ju&&zu?reactDomExports.createPortal(jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",flexWrap:"wrap",gap:2,children:Td}),zu):null,ju&&zu===void 0?jsxRuntimeExports.jsx(Box,{as:"header",display:"flex",alignItems:"center",justifyContent:pd?"flex-start":"space-between",flexWrap:"wrap",gap:2,px:pd?2:3,py:2,borderBottom:"1px solid",borderColor:"border.default",flex:"0 0 auto",children:Td}):null,jsxRuntimeExports.jsxs(Box,{flex:"1 1 auto",minHeight:0,display:"flex",children:[jsxRuntimeExports.jsx(Box,{flex:"1 1 auto",minWidth:0,minHeight:0,position:"relative",children:jsxRuntimeExports.jsx(ReactorViewHost,{point:LoopViewType,active:bd,props:{viewType:bd,workspace:wd},fallback:jsxRuntimeExports.jsx(Centered,{children:"Loading…"}),empty:jsxRuntimeExports.jsx(Centered,{children:"No view is available yet."}),errorFallback:Pd=>jsxRuntimeExports.jsxs(Centered,{children:["This view failed to load: ",Pd.message]})})}),ad.length>0&&qu&&!pd?jsxRuntimeExports.jsx(SidebarRail,{components:ad,props:{workspace:wd},width:SIDEBAR_WIDTH}):ad.length>0?jsxRuntimeExports.jsx(Box,{as:"aside",flex:"0 0 auto",width:pd?"100%":`${SIDEBAR_WIDTH}px`,minWidth:0,borderLeft:pd?"none":"1px solid",borderTop:pd?"1px solid":"none",borderColor:"border.default",bg:"canvas.subtle",overflowY:"auto",px:3,py:3,children:jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.sidebar,props:{workspace:wd}})}):null]}),jsxRuntimeExports.jsxs(Box,{flex:"0 0 auto",children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.footer,props:{workspace:wd}}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.status,props:{workspace:wd}})]}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.root,props:{workspace:wd}})]})}function Centered({children:Au}){return jsxRuntimeExports.jsx(Box,{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"fg.muted",fontSize:1,px:3,textAlign:"center",children:Au})}function resolveTopOffset(Au){if(typeof Au=="number")return Au;if(!Au||typeof document>"u")return 0;const lo=document.querySelector(Au);return lo?Math.max(0,Math.round(lo.getBoundingClientRect().bottom)):0}function fullScreenNode(Au){return Au?.closest("[data-loop-fullscreen-root]")??Au?.closest("[data-loop-workspace]")??Au}function useWorkspaceFullScreen(Au,lo={}){const{forceOverlay:$u=!1,paintOverlay:Ru=!1,topOffset:Iu=0}=lo,[Ou,Pu]=reactExports.useState(!1),Du=reactExports.useRef(!1);reactExports.useEffect(()=>{const Fu=()=>{if(!Du.current)return;const zu=!!document.fullscreenElement&&!!Au.current&&document.fullscreenElement.contains(Au.current);Pu(zu),zu||(Du.current=!1)};return document.addEventListener("fullscreenchange",Fu),()=>document.removeEventListener("fullscreenchange",Fu)},[Au]);const Lu=reactExports.useCallback(()=>{const Fu=fullScreenNode(Au.current);if(Ou){Du.current&&document.fullscreenElement?document.exitFullscreen():Pu(!1);return}if($u||Ru||!Fu?.requestFullscreen){Pu(!0);return}Du.current=!0,Fu.requestFullscreen().then(()=>Pu(!0),()=>{Du.current=!1,Pu(!0)})},[Au,Ou,$u,Ru]),[ju,Bu]=reactExports.useState(0);return reactExports.useEffect(()=>{if(!Ou||Du.current){Bu(0);return}const Fu=()=>Bu(resolveTopOffset(Iu));return Fu(),window.addEventListener("resize",Fu),()=>window.removeEventListener("resize",Fu)},[Ou,Iu]),reactExports.useEffect(()=>{if(!Ru||!Ou||Du.current)return;const Fu=fullScreenNode(Au.current);if(!Fu)return;const zu=Fu.getAttribute("style");return Fu.style.position="fixed",Fu.style.top=`${ju}px`,Fu.style.right="0",Fu.style.bottom="0",Fu.style.left="0",Fu.style.height="auto",Fu.style.zIndex="1000",()=>{zu===null?Fu.removeAttribute("style"):Fu.setAttribute("style",zu)}},[Ru,Ou,Au,ju]),reactExports.useEffect(()=>{if(!Ou||Du.current)return;const Fu=zu=>{zu.key==="Escape"&&!zu.defaultPrevented&&Pu(!1)};return window.addEventListener("keydown",Fu),()=>window.removeEventListener("keydown",Fu)},[Ou]),{fullScreen:Ou,usingApi:Du,toggle:Lu,topOffsetPx:ju}}function messageText(Au){const lo=Au.content;return typeof lo=="string"?lo:lo.map($u=>typeof $u=="string"?$u:$u.text??"").join("")}const isToolCall=Au=>Au.type==="tool-call";function conversationOf(Au){const lo=[];for(const $u of Au){if(isToolCall($u)){lo.push({role:"tool",name:$u.toolName,args:$u.args??{},...$u.result===void 0?{}:{result:$u.result}});continue}if($u.role!=="user"&&$u.role!=="assistant")continue;const Ru=messageText($u);Ru.trim()&&lo.push({role:$u.role,text:Ru})}return lo}const sameConversation=(Au,lo)=>Au.length===lo.length&&Au.every(($u,Ru)=>JSON.stringify($u)===JSON.stringify(lo[Ru])),IDLE={id:0,status:"idle"};function createTurnFeed(){const Au=signal$2(IDLE),lo=signal$2([]),$u=signal$2("idle");return{turn:Au,conversation:lo,presence:$u,setPresence:Ru=>{$u.value!==Ru&&($u.value=Ru)},items:Ru=>{const Iu=conversationOf(Ru);sameConversation(lo.value,Iu)||(lo.value=Iu)},begin:(Ru,Iu)=>{Au.value={id:Au.value.id+1,user:Ru,...Iu?{thread:Iu}:{},status:"thinking",usage:Au.value.usage}},assistant:Ru=>{const Iu=Au.value;Iu.status==="idle"||Iu.assistant===Ru||(Au.value={...Iu,assistant:Ru,status:Iu.status==="done"||Iu.status==="error"?Iu.status:Ru?"streaming":Iu.status})},usage:Ru=>{const Iu=Au.value;Iu.usage!==Ru&&(Au.value={...Iu,usage:Ru})},activity:Ru=>{const Iu=Au.value;Iu.status==="idle"||Iu.activity===Ru||(Au.value={...Iu,activity:Ru})},end:(Ru="done")=>{const Iu=Au.value;Iu.status!=="idle"&&(Au.value={...Iu,status:Ru,activity:void 0})}}}const TURN_WRITERS=Symbol.for("loop.chat.turn.writers");function feedWriters(Au){return{[TURN_WRITERS]:Au}}function turnWritersOf(Au){return Au?.[TURN_WRITERS]}function agentAction(Au,lo){const{prompt:$u,...Ru}=lo;return{...Ru,type:"button",group:"agent",onClick:()=>Au.workspace.prompts.submit($u)}}const CHAT_PLUGIN_NAME="@datalayer/loop-plugin-chat",ChatPlugin={name:CHAT_PLUGIN_NAME,config:{placeholder:"",defaultSurface:"notebook",showSurfaceSelector:!0,hideHeader:!1,headerButtons:{newChat:!1,clear:!1},hidePrompt:!1,promptPlacement:"bottom",autoFocusPrompt:!0,suggestionLabels:!0,fullScreenTopOffset:0},displayName:"Chat",description:"The conversation, the prompt, and the point editors plug into.",octicon:"comment-discussion",emoji:"💬",contributionPoints:[LoopAgentGate,LoopFrontendTool,LoopChatComposer,LoopChatHeader,LoopChatSuggestion,LoopChatExtras,LoopChatTurn],build:Au=>{const lo=createTurnFeed();return Au.contribute(LoopChatTurn,{id:"chat-turn",turn:lo.turn,conversation:lo.conversation,presence:lo.presence,...feedWriters(lo)},{id:"chat-turn"}),{}},contributes:[contribution(LoopViewType,{viewType:"chat",title:"Chat",icon:CommentDiscussionIcon,order:0,load:()=>__vitePreload(()=>import("./chunks/ChatView-DE-jo1oJ.js"),[],import.meta.url)},{id:"chat",order:0}),contribution(LoopCommand,{name:"chat",description:"Show the conversation",group:"Session",keybinding:"Mod+Alt+K",run:async({workspace:Au})=>{Au.setActiveViewType("chat")}},{id:"chat"}),contribution(LoopNotebookToolbarItem,{items:Au=>[agentAction(Au,{key:"loop-compact",ariaLabel:"Compact this notebook",title:"Ask @NotebookCompactor to shorten it without changing results",icon:FoldIcon,order:200,prompt:"@NotebookCompactor compact this notebook without changing what it computes."}),agentAction(Au,{key:"loop-reproduce",ariaLabel:"Check reproducibility",title:"Ask @NotebookReproducer to run it on a fresh sandbox",icon:SyncIcon,order:201,prompt:"@NotebookReproducer run this notebook top to bottom on a fresh sandbox and report what does not reproduce."})]},{id:"agent-actions",order:200}),contribution(LoopDocumentToolbarItem,{items:Au=>[agentAction(Au,{key:"loop-summarise",ariaLabel:"Summarise this document",title:"Ask the agent for a summary of what this document says",icon:SparkleFillIcon,order:200,prompt:"Summarise this document in a short paragraph."})]},{id:"agent-actions",order:200})]};function WorkspaceFullScreenAction(){const Au=reactExports.useRef(null),$u=useReactorPlatform().getConfig(CHAT_PLUGIN_NAME)?.fullScreenTopOffset??0,{fullScreen:Ru,toggle:Iu}=useWorkspaceFullScreen(Au,{paintOverlay:!!$u,topOffset:$u});return jsxRuntimeExports.jsx(IconButton,{ref:Au,icon:Ru?ScreenNormalIcon:ScreenFullIcon,"aria-label":Ru?"Exit full screen":"Enter full screen",variant:"invisible",size:"small",sx:{order:2},onClick:Iu})}const THEME_PLUGIN_NAME="@datalayer/primer-theme",TOGGLE_COLOR_MODE_COMMAND="theme.toggleColorMode",ThemePlugin={name:THEME_PLUGIN_NAME,displayName:"Theme",description:"Keeps Primer portals in the application’s color mode, and toggles it.",octicon:"sun",emoji:"🌗",commands:[{id:TOGGLE_COLOR_MODE_COMMAND,name:"Toggle the color mode",description:"Switch between light and dark",emoji:"🌗",category:"Appearance",keybinding:"Mod+Alt+C",execute:()=>{const Au=useThemeStore.getState(),lo=Au.colorMode==="auto"?typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light":Au.colorMode;Au.setColorMode(lo==="dark"?"light":"dark")}}],register:()=>{if(typeof document>"u")return;setupPrimerPortals(useThemeStore.getState().colorMode);const Au=useThemeStore.subscribe((Ru,Iu)=>{Ru.colorMode!==Iu.colorMode&&setupPrimerPortals(Ru.colorMode)}),lo=window.matchMedia("(prefers-color-scheme: dark)"),$u=()=>{useThemeStore.getState().colorMode==="auto"&&setupPrimerPortals("auto")};return lo.addEventListener("change",$u),()=>{Au(),lo.removeEventListener("change",$u)}}},pageLayoutPanelOpen=signal$2(!1),pageLayoutSheet=signal$2("page"),pageLayoutActivity=signal$2(void 0);function openPagePanel(){pageLayoutPanelOpen.value=!0}const PAGE_SHEET_WIDTH=920,PAGE_PANEL_WIDTH=400,PAGE_SIZE_FORMATS={letter:{width:816,height:1056},a4:{width:794,height:1123}};function resolvePageSize(Au,lo=PAGE_SHEET_WIDTH){const $u=Au?.format&&Au.format!=="free"?PAGE_SIZE_FORMATS[Au.format]:void 0;return{width:Au?.width??$u?.width??lo,height:Au?.height??$u?.height}}const CANVAS_PX=[2,3,4];function ActivityLine({label:Au}){return jsxRuntimeExports.jsxs(Box$1,{"data-page-activity":"",role:"status",sx:{position:"sticky",top:0,zIndex:2,alignSelf:"flex-start",display:"inline-flex",alignItems:"center",gap:2,px:2,py:"4px",borderRadius:"999px",border:"1px solid",borderColor:"accent.muted",bg:"accent.subtle",color:"accent.fg",fontSize:0,fontWeight:"semibold",whiteSpace:"nowrap",boxShadow:"0 4px 12px -6px rgba(0,0,0,0.3)"},children:[jsxRuntimeExports.jsx(Box$1,{as:"span","aria-hidden":"true",sx:{width:7,height:7,borderRadius:"50%",bg:"accent.fg",animation:"page-activity-dot 1.1s ease-in-out infinite","@keyframes page-activity-dot":{"0%, 100%":{opacity:1},"50%":{opacity:.3}}}}),jsxRuntimeExports.jsx(Text$5,{children:Au})]})}function panelOpening(Au){const lo=Au==="left"?"pagePanelOpenLeft":"pagePanelOpenRight";return{animation:`${lo} var(--theme-motion-pane, 0ms) var(--theme-motion-easing, ease) both`,[`@keyframes ${lo}`]:{from:{opacity:0,transform:`translateX(${Au==="left"?"-12px":"12px"})`},to:{opacity:1,transform:"none"}},"@media (prefers-reduced-motion: reduce)":{animation:"none"}}}function PageLayout({page:Au,hasPage:lo=Au!=null,panel:$u,band:Ru,chips:Iu,picker:Ou,transient:Pu,activity:Du,bandMode:Lu="docked",panelMode:ju="docked",panelSide:Bu="right",sheetWidth:Fu=PAGE_SHEET_WIDTH,pageSize:zu,panelWidth:qu=PAGE_PANEL_WIDTH}){const Uu=Lu==="panel",Hu=Ru!=null,{width:Vu,height:Gu}=resolvePageSize(zu,Fu),Zu=useSignalValue$1(pageLayoutPanelOpen)||Uu&&Hu,Qu=useSignalValue$1(pageLayoutActivity),Yu=Du??Qu,ed=lo?"page":"panel";return reactExports.useEffect(()=>{pageLayoutSheet.value=ed},[ed]),jsxRuntimeExports.jsxs(Box$1,{"data-page-layout":"",sx:{position:"relative",flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column"},children:[Ou,jsxRuntimeExports.jsxs(Box$1,{sx:{flex:"1 1 auto",minHeight:0,display:"flex",bg:"canvas.inset"},children:[jsxRuntimeExports.jsxs(Box$1,{sx:{flex:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:[Ru&&Lu==="docked"?jsxRuntimeExports.jsx(Box$1,{"data-page-band":"","data-page-prompt-dock":"",sx:{flex:"0 0 auto",display:"flex",justifyContent:"center",px:CANVAS_PX,bg:"canvas.subtle",borderBottom:"1px solid",borderColor:"border.default"},children:jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,minWidth:0},children:Ru})}):null,jsxRuntimeExports.jsxs(Box$1,{"data-page-canvas":"",sx:{flex:"1 1 auto",minWidth:0,minHeight:0,overflowY:lo?"auto":"hidden",overflowX:"hidden",display:"flex",flexDirection:"column",alignItems:"center",pt:3,pb:6,px:CANVAS_PX},children:[Ru&&Iu&&!Uu?jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,mb:3,display:"flex",justifyContent:"center","& > *":{justifyContent:"center"}},children:Iu}):null,Yu?jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,display:"flex",justifyContent:"flex-end",mb:2},children:jsxRuntimeExports.jsx(ActivityLine,{label:Yu})}):null,jsxRuntimeExports.jsx(Sheet,{"data-page-sheet":"",sx:{width:"100%",maxWidth:Vu,flex:lo?"1 0 auto":"1 1 auto",px:lo?[3,4,"56px"]:[2,3,4],py:lo?[3,4,4]:2,position:"relative",display:"flex",minHeight:lo?Gu??480:0,"& > *":{flex:"1 1 auto",minWidth:0}},children:lo?Au:$u}),lo||!Au?null:jsxRuntimeExports.jsx(Box$1,{"aria-hidden":"true",sx:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",zIndex:-1,display:"flex"},children:Au})]})]}),!lo||!$u?null:jsxRuntimeExports.jsxs(Box$1,{"data-page-panel":Zu?"":void 0,"data-page-panel-mode":ju,"aria-hidden":Zu?void 0:"true",sx:{minWidth:0,minHeight:0,display:"flex",flexDirection:"column",bg:"canvas.default",borderColor:"border.default",...Zu?ju==="docked"?{flex:`0 0 ${qu}px`,maxWidth:"45%",order:Bu==="left"?-1:void 0,[Bu==="left"?"borderRight":"borderLeft"]:"1px solid",zIndex:1}:ju==="overlay"?{position:"absolute",top:0,bottom:0,[Bu]:0,width:qu,maxWidth:"85%",[Bu==="left"?"borderRight":"borderLeft"]:"1px solid",boxShadow:"shadow.large",zIndex:5}:{position:"absolute",[Bu]:16,bottom:16,width:qu,maxWidth:"calc(100% - 32px)",height:"min(70%, 560px)",border:"1px solid",borderRadius:2,boxShadow:"shadow.large",overflow:"hidden",zIndex:5}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",overflow:"visible"}},children:[jsxRuntimeExports.jsx(Box$1,{sx:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column","& > *":{flex:"1 1 auto",minHeight:0},...Zu?panelOpening(Bu):null},children:$u}),Hu&&Lu!=="docked"?jsxRuntimeExports.jsxs(Box$1,{"data-page-panel-band":Uu?"":void 0,sx:Uu?{flex:"0 0 auto",borderTop:"1px solid",borderColor:"border.default",visibility:"visible",pointerEvents:"auto","& > *":{justifyContent:"center"}}:{position:"absolute",inset:0,visibility:"visible",pointerEvents:"none","& > *":{pointerEvents:"auto"}},children:[Uu?Iu:null,Ru]}):null]})]}),Pu]})}function PagePanelToggle({panelName:Au="panel",icon:lo=SidebarExpandIcon,sx:$u}){const Ru=useSignalValue$1(pageLayoutPanelOpen);return useSignalValue$1(pageLayoutSheet)==="panel"?null:jsxRuntimeExports.jsx(IconButton,{icon:lo,size:"small",variant:Ru?"default":"invisible","aria-label":Ru?`Hide the ${Au}`:`Show the ${Au}`,"aria-pressed":Ru,onClick:()=>{Ru?pageLayoutPanelOpen.value=!1:openPagePanel()},sx:{color:Ru?"accent.fg":"fg.muted",...$u}})}const INPUT_PROMPT_PLUGIN_NAME="@datalayer/loop-plugin-input-prompt",LazyComposerView=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/ComposerView-DcubnPoo.js"),[],import.meta.url));function ComposerView(Au){return jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(LazyComposerView,{...Au})})}const InputPromptPlugin={name:INPUT_PROMPT_PLUGIN_NAME,config:{},displayName:"Input Prompt",description:"The composer under (or over) the conversation.",octicon:"pencil",emoji:"✏️",contributionPoints:[LoopPromptPanel],contributes:[contribution(LoopChatComposer,{id:"input-prompt",Component:ComposerView},{id:"input-prompt"})]},AGENT_ICONS={agent:ForwardRef$3,beaker:BeakerIcon,bell:BellIcon,book:BookIcon,briefcase:BriefcaseIcon,browser:BrowserIcon,bug:BugIcon,clock:ClockIcon,code:CodeIcon,"comment-discussion":CommentDiscussionIcon,cpu:CpuIcon,"credit-card":CreditCardIcon,database:DatabaseIcon,file:FileIcon,checklist:ChecklistIcon,"code-review":CodeReviewIcon,fold:FoldIcon,"git-branch":GitBranchIcon,globe:GlobeIcon,graph:GraphIcon,heart:HeartIcon,"issue-opened":IssueOpenedIcon,lightbulb:LightBulbIcon,"light-bulb":LightBulbIcon,"list-unordered":ListUnorderedIcon,mail:MailIcon,megaphone:MegaphoneIcon,"mortar-board":MortarBoardIcon,note:NoteIcon,organization:OrganizationIcon,package:PackageIcon,pencil:PencilIcon,people:PeopleIcon,play:PlayIcon,pulse:PulseIcon,rss:RssIcon,search:SearchIcon,"share-2":ShareAndroidIcon,shield:ShieldIcon,"shield-check":ShieldCheckIcon,sliders:SlidersIcon,sun:SunIcon,sync:SyncIcon,table:TableIcon,tag:TagIcon,tasklist:TasklistIcon,telescope:TelescopeIcon,tools:ToolsIcon,"trending-up":GraphIcon,rocket:RocketIcon,zap:ZapIcon};function agentIcon(Au){return(Au?AGENT_ICONS[Au]:void 0)??ForwardRef$3}function useOptionalSandboxService(){return useReactorPlatform().getOutput(AGENTS_PLUGIN_NAME)?.sandbox}function useSandboxService(){const Au=useOptionalSandboxService();if(!Au)throw new Error(`The code sandbox plugin (${AGENTS_PLUGIN_NAME}) is not mounted. A view that needs a sandbox must declare it as a dependency.`);return Au}function SandboxStatusBridge({workspace:Au}){const lo=useOptionalSandboxService(),$u=useSignalValue$1(lo?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Ru=useSignalValue$1(lo?.target??IDLE_SANDBOX_TARGET_SIGNAL),{setSandbox:Iu,agentId:Ou}=Au;return reactExports.useEffect(()=>lo?.connect(Ou),[lo,Ou]),reactExports.useEffect(()=>{lo&&Iu({...$u,target:Ru})},[lo,$u,Ru,Iu]),null}const DatalayerAgentBridge=reactExports.lazy(async()=>({default:(await __vitePreload(()=>import("./chunks/DatalayerAgentBridge-BhxfUyb7.js"),[],import.meta.url)).DatalayerAgentBridge}));function DatalayerAgentMount(){return jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(DatalayerAgentBridge,{})})}const CREATING_STATUSES=new Set(["creating","starting","launching","connecting","pending","resuming"]),MAX_AGENT_NAME_LENGTH=32,toSandboxStatusUrl=Au=>{const lo=String(Au||"").trim();if(lo)try{const $u=new URL(lo);return $u.pathname=`${$u.pathname.replace(/\/$/,"")}/api`,$u.toString()}catch{const $u=lo.replace(/\/$/,"");return $u.endsWith("/api")?$u:`${$u}/api`}},OVERLAY_WIDTH=360,AgentSummary=({summary:Au,title:lo="Active Agent"})=>{const[$u,Ru]=reactExports.useState(!1),[Iu,Ou]=reactExports.useState(!1),Pu=reactExports.useRef(null),Du=reactExports.useRef(null),Lu=()=>{Du.current!==null&&(window.clearTimeout(Du.current),Du.current=null)},ju=()=>{Lu();const Yu=Pu.current?.getBoundingClientRect();Ou(!!(Yu&&Yu.left+OVERLAY_WIDTH>window.innerWidth)),Ru(!0)},Bu=()=>{Lu(),Du.current=window.setTimeout(()=>{Ru(!1),Du.current=null},300)};reactExports.useEffect(()=>()=>{Lu()},[]);const Fu=Au?.baseUrl?(()=>{const Yu=Au.baseUrl.replace(/\/$/,"");return Yu.endsWith("/api/v1")?Yu:`${Yu}/api/v1`})():void 0,zu=Fu?`${Fu}/runtime/status`:void 0,qu=toSandboxStatusUrl(Au?.sandboxBaseUrl);if(!Au)return null;const Uu=(Au.status||"").toLowerCase(),Hu=!Au.isReady&&!Au.agentId&&CREATING_STATUSES.has(Uu),Vu=!!Au.error,Gu=!!Au.agentId||Hu,Ku=strip(Au.agentName,MAX_AGENT_NAME_LENGTH),Zu=`${Au.agentName} · ${Au.location}`,Qu=`${Ku} · ${Au.location}`;return jsxRuntimeExports.jsxs(Box,{ref:Pu,position:"relative",onMouseEnter:ju,onMouseLeave:Bu,children:[jsxRuntimeExports.jsxs(Box,{as:"button",type:"button",title:Zu,px:2,py:"6px",maxWidth:280,minWidth:0,border:"1px solid",borderColor:Vu?"danger.emphasis":"border.default",borderRadius:2,bg:Vu?"danger.subtle":"canvas.default",color:Vu?"danger.fg":"fg.default",fontSize:0,cursor:"default",display:"flex",alignItems:"center",gap:1,children:[Hu&&jsxRuntimeExports.jsx(StyledSpinner,{size:"small",sx:{width:12,height:12}}),Vu&&jsxRuntimeExports.jsx("span",{"aria-hidden":!0,children:"⚠"}),jsxRuntimeExports.jsx(Box,{as:"span",display:"block",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",children:Qu})]}),$u&&jsxRuntimeExports.jsxs(Box,{position:"absolute",top:"calc(100% + 8px)",width:OVERLAY_WIDTH,p:2,border:"1px solid",borderColor:"border.default",borderRadius:2,bg:"canvas.overlay",boxShadow:"shadow.large",zIndex:120,fontSize:0,color:"fg.default",right:Iu?0:void 0,left:Iu?void 0:0,children:[jsxRuntimeExports.jsx(Box,{mb:1,fontWeight:600,children:lo}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Name: ",Au.agentName]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Location: ",Au.location]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Spec: ",Au.specId||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Harness: ",Au.harness||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Variant: ",Au.variant||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Status: ",Hu?"creating":Au.status||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Agent base URL: ",Au.baseUrl||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Code sandbox base URL:"," ",Au.sandboxBaseUrl?jsxRuntimeExports.jsx(Box,{as:"a",href:Au.sandboxBaseUrl,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:Au.sandboxBaseUrl}):"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",display:"flex",alignItems:"center",gap:1,children:["Agent ID:"," ",Au.agentId?Au.agentId:Hu?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(StyledSpinner,{size:"small",sx:{width:12,height:12}}),"Creating…"]}):"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Agent status:"," ",Gu&&zu?jsxRuntimeExports.jsx(Box,{as:"a",href:zu,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:zu}):"n/a"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Code sandbox status:"," ",qu?jsxRuntimeExports.jsx(Box,{as:"a",href:qu,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:qu}):"n/a"]}),Vu&&jsxRuntimeExports.jsxs(Box,{mt:1,p:1,border:"1px solid",borderColor:"danger.muted",borderRadius:2,bg:"danger.subtle",color:"danger.fg",wordBreak:"break-word",children:["Error: ",Au.error]})]})]})},insideJupyterLab=()=>loadJupyterConfig().insideJupyterLab;function collect(Au,lo){const $u=Au?.header?.msg_type,Ru=Au?.content??{};$u==="stream"?(lo.stdout.push(String(Ru.text??"")),lo.outputs.push({output_type:"stream",text:Ru.text})):$u==="execute_result"||$u==="display_data"?lo.outputs.push({output_type:$u,data:Ru.data}):$u==="error"&&(lo.error=`${Ru.ename??"Error"}: ${Ru.evalue??""}`,lo.outputs.push({output_type:"error",ename:Ru.ename,evalue:Ru.evalue,traceback:Ru.traceback}))}function browserSource(){let Au;return{variant:"pyodide",acquire:async()=>{const{createLiteServiceManager:lo,jupyterReactStore:$u,loadJupyterConfig:Ru}=await __vitePreload(async()=>{const{createLiteServiceManager:Ou,jupyterReactStore:Pu,loadJupyterConfig:Du}=await import("./chunks/index-CNx_s591.js").then(Lu=>Lu.r);return{createLiteServiceManager:Ou,jupyterReactStore:Pu,loadJupyterConfig:Du}},[],import.meta.url);Au=Au??{baseUrl:libExports$5.PageConfig.getOption("baseUrl"),wsUrl:libExports$5.PageConfig.getOption("wsUrl")},Ru({lite:!0});const Iu=await lo();return $u.getState().setServiceManager(Iu),Iu},release:()=>{Au&&(libExports$5.PageConfig.setOption("baseUrl",Au.baseUrl),libExports$5.PageConfig.setOption("wsUrl",Au.wsUrl),Au=void 0)},owned:!0}}function createBrowserSandboxService(Au=browserSource()){const lo=signal$2(null),$u=signal$2("idle"),Ru=signal$2(null),Iu=computed$1(()=>({state:$u.value,variant:Au.variant,kernelId:lo.value?.kernel_id})),Ou=computed$1(()=>$u.value==="running");let Pu=null,Du=null,Lu=null,ju=null;async function Bu(){if(Du)return;$u.value="starting",Pu=await Au.acquire();const Fu=await Pu.sessions.startNew({name:"loop",path:"loop.ipynb",type:"notebook",kernel:{name:"python"}});Lu=Fu.kernel,Du=Fu.kernel,lo.value={variant:Au.variant,sandbox_running:!0,kernel_id:Du?.id,kernel_name:"python"},$u.value="running"}return{kind:"browser",snapshot:Iu,status:lo,ready:Ou,lastExecution:Ru,serverUrl:"",getServiceManager:()=>Pu,getKernelConnection:()=>Lu,report(Fu){lo.value=Fu},setState(Fu){$u.value=Fu},connect(){return ju=ju??Bu().catch(Fu=>{throw $u.value="error",lo.value=null,ju=null,Fu}),()=>{Du?.shutdown?.(),Du=null,Lu=null,Pu=Au.owned?null:Pu,Au.release?.(),ju=null,$u.value="idle",lo.value=null}},async execute(Fu){const zu=Date.now();try{if(await(ju??Bu()),!Du)throw new Error("The browser kernel did not start");const qu={outputs:[],stdout:[],error:""},Uu=Du.requestExecute({code:Fu});Uu.onIOPub=Vu=>collect(Vu,qu),await Uu.done;const Hu={code:Fu,success:!qu.error,stdout:qu.stdout.join(""),error:qu.error||void 0,outputs:qu.outputs,startedAt:zu,finishedAt:Date.now()};return Ru.value=Hu,Hu}catch(qu){const Uu={code:Fu,success:!1,error:qu instanceof Error?qu.message:String(qu),startedAt:zu,finishedAt:Date.now()};return Ru.value=Uu,Uu}}}}function summarize(Au,lo){if(!Au)return{state:lo};const $u=Au.variant==="jupyter-server"||Au.variant==="datalayer";return{state:!!Au.sandbox_running||$u&&!!Au.jupyter_connected?"running":lo==="running"?"idle":lo,variant:Au.variant,kernelId:Au.kernel_id,jupyterUrl:Au.jupyter_url,jupyterToken:Au.jupyter_token,agentBaseUrl:Au.agent_base_url}}const RECONNECT_BASE_MS=1e3,RECONNECT_MAX_MS=3e4;function createServerSandboxService(Au){const lo=signal$2(null),$u=signal$2("idle"),Ru=signal$2(void 0),Iu=signal$2(null),Ou=computed$1(()=>({...summarize(lo.value,$u.value),errorReason:$u.value==="error"?Ru.value:void 0})),Pu=computed$1(()=>Ou.value.state==="running");return{kind:"server",connect(Du){if(typeof WebSocket>"u")return()=>{};let Lu=null,ju=null,Bu=0,Fu=!1;const zu=()=>{if(Fu)return;const qu=Au.replace(/^http/,"ws"),Uu=Du?`?agent_id=${encodeURIComponent(Du)}`:"";Lu=new WebSocket(`${qu}/api/v1/configure/sandbox/ws${Uu}`),Lu.onopen=()=>{Bu=0},Lu.onmessage=Hu=>{try{lo.value=JSON.parse(String(Hu.data))}catch{}},Lu.onclose=()=>{if(Fu)return;lo.value=null,Bu+=1;const Hu=Math.min(RECONNECT_BASE_MS*2**(Bu-1),RECONNECT_MAX_MS);ju=setTimeout(zu,Hu)}};return zu(),()=>{Fu=!0,ju&&clearTimeout(ju),Lu?.close(),Lu=null}},snapshot:Ou,status:lo,ready:Pu,lastExecution:Iu,serverUrl:Au,report(Du){lo.value=Du},setState(Du,Lu){$u.value=Du,Ru.value=Du==="error"?Lu:void 0},async execute(Du){const Lu=Date.now();try{const ju=await fetch(`${Au}/api/v1/sandbox/execute`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:Du})}),Bu=ju.ok?await ju.json():null,Fu={code:Du,success:ju.ok&&!Bu?.error,stdout:Bu?.stdout,stderr:Bu?.stderr,error:ju.ok?Bu?.error:`Execution failed: ${ju.status}`,outputs:Bu?.outputs,startedAt:Lu,finishedAt:Date.now()};return Iu.value=Fu,Fu}catch(ju){const Bu={code:Du,success:!1,error:ju instanceof Error?ju.message:String(ju),startedAt:Lu,finishedAt:Date.now()};return Iu.value=Bu,Bu}}}}const ANONYMOUS_JUPYTER_URL="https://prod1.datalayer.run/api/jupyter-server",ANONYMOUS_JUPYTER_TOKEN="60c1661cc408f978c309d04157af55c9588ff9557c9380e4fb50785750703da6",SANDBOX_TARGETS=["browser","local","jupyter","datalayer"];function heldTargetReason(Au,lo){if(Au==="local"&&!lo&&!insideJupyterLab())return"Not offered on the web for now: a local agent and the Jupyter server it starts run beside JupyterLab, not in a page."}const TARGET_SPECS={browser:{label:"Browser",hint:"Python in this page (Pyodide), with the agent loop running here too. Only the model is asked over the network.",hasAgent:!0,noAgentReason:""},local:{label:"Local",hint:"A local agent, with the Jupyter server it starts beside itself.",hasAgent:!0,noAgentReason:"",configure:{variant:"jupyter-server",jupyter_url:"",jupyter_token:""}},jupyter:{label:"Jupyter",hint:"A named Jupyter server: the anonymous one on prod1.datalayer.run.",hasAgent:!1,noAgentReason:"No agent on an anonymous Jupyter server",configure:{variant:"jupyter-server",jupyter_url:ANONYMOUS_JUPYTER_URL,jupyter_token:ANONYMOUS_JUPYTER_TOKEN}},datalayer:{label:"Datalayer",hint:"A Datalayer runtime running the agent this workspace asks for.",hasAgent:!0,noAgentReason:""}};function targetHasAgent(Au){return TARGET_SPECS[Au]?.hasAgent??!1}function targetRunsAgentInPage(Au){return Au==="browser"}function createSwitchableSandboxService({serverUrl:Au,initialTarget:lo="local",kernelSource:$u,localAgent:Ru,blueprint:Iu}){const Ou=signal$2(lo),Pu=createServerSandboxService(Au),Du=createBrowserSandboxService($u??browserSource()),Lu=computed$1(()=>Ou.value==="browser"?Du:Pu);let ju=null,Bu;const Fu=computed$1(()=>Lu.value.snapshot.value),zu=computed$1(()=>Lu.value.status.value),qu=computed$1(()=>Lu.value.ready.value),Uu=computed$1(()=>Lu.value.lastExecution.value);async function Hu(Ku){if(Ku==="local"){const Xu=Iu?.()??Ru?.createPayload;Xu&&await Vu(Xu)}const Zu=TARGET_SPECS[Ku]?.configure;if(!Zu)return;const Qu=TARGET_SPECS[Ku].label;let Yu;try{Yu=await fetch(`${Au}/api/v1/agents/sandbox/configure`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Zu)})}catch(Xu){throw new Error(`${Qu} needs an agent-runtimes server at ${Au}, and nothing answered there. Start one and try again. (${Xu instanceof Error?Xu.message:String(Xu)})`,{cause:Xu})}if(!Yu.ok)throw new Error(`The server could not switch to ${Qu} (${Yu.status} ${Yu.statusText}). `+await detail(Yu));const ed=await fetch(`${Au}/api/v1/agents/sandbox/restart`,{method:"POST"});if(!ed.ok)throw new Error(`The server could not start ${Qu} (${ed.status} ${ed.statusText}). `+await detail(ed))}function Vu(Ku){return ensureServerAgent(Au,Bu,Ku)}function Gu(){if(ju?.(),Ou.peek()==="datalayer"){ju=null,Pu.setState("starting");return}ju=Lu.peek().connect(Bu)}return{get kind(){return Ou.peek()==="browser"?"browser":"server"},target:Ou,snapshot:Fu,status:zu,ready:qu,lastExecution:Uu,serverUrl:Au,getServiceManager:()=>Ou.peek()==="browser"?Du.getServiceManager():null,getKernelConnection:()=>Ou.peek()==="browser"?Du.getKernelConnection():null,report(Ku){Lu.peek().report(Ku)},setState(Ku){Lu.peek().setState(Ku)},execute(Ku){return Lu.peek().execute(Ku)},connect(Ku){Bu=Ku;const Zu=Ou.peek()==="local"&&Ku?Iu?.()??Ru?.createPayload:void 0;if(!Zu)return Gu(),()=>{ju?.(),ju=null};let Qu=!1;return Pu.setState("starting"),Vu(Zu).then(()=>{Qu||Gu()},Yu=>{Qu||(Pu.setState("error"),console.error("[loop] Local agent could not be started:",Yu))}),()=>{Qu=!0,ju?.(),ju=null}},async setTarget(Ku){const Zu=Ou.peek();if(Ku===Zu)return;const Qu=heldTargetReason(Ku,Au);if(Qu)throw new Error(Qu);ju?.(),ju=null;try{await Hu(Ku)}catch(Yu){throw Gu(),Yu}Ou.value=Ku,Gu()}}}async function ensureServerAgent(Au,lo,$u){const Ru=lo?.trim();if(!Ru)throw new Error("Local needs an agent id before its runtime can start.");let Iu;try{Iu=await fetch(`${Au}/api/v1/agents/${encodeURIComponent(Ru)}`)}catch(Pu){throw new Error(`Local needs an agent-runtimes server at ${Au}, and nothing answered there. Start one and try again. (${Pu instanceof Error?Pu.message:String(Pu)})`,{cause:Pu})}if(Iu.ok){await ensureServerSandbox(Au,Ru);return}if(Iu.status!==404)throw new Error(`The server could not inspect local agent ${Ru} (${Iu.status} ${Iu.statusText}). `+await detail(Iu));const Ou=await fetch(`${Au}/api/v1/agents`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({transport:"ag-ui",sandbox_variant:"jupyter-server",...$u,name:Ru})});if(!Ou.ok&&Ou.status!==409)throw new Error(`The server could not launch local agent ${Ru} (${Ou.status} ${Ou.statusText}). `+await detail(Ou));Ou.status===409&&await ensureServerSandbox(Au,Ru)}async function ensureServerSandbox(Au,lo){const $u=await fetch(`${Au}/api/v1/agents/${encodeURIComponent(lo)}/sandbox/ensure`,{method:"POST"});if(!$u.ok)throw new Error(`The server could not start a sandbox for local agent ${lo} (${$u.status} ${$u.statusText}). `+await detail($u))}async function detail(Au){try{const lo=await Au.json();return typeof lo.detail=="string"?lo.detail:""}catch{return""}}function useOptionalTeamSelection(){return useReactorPlatform().getOutput(AGENTS_PLUGIN_NAME)?.team}const NO_TARGET={value:void 0,peek:()=>{}},NO_MEMBER={value:void 0,peek:()=>{}};function AgentSummaryPanel({workspace:Au}){const lo=useSandboxService(),$u=useSignalValue$1(lo?.target??NO_TARGET),Ru=useOptionalTeamSelection(),Iu=useSignalValue$1(Ru?.active??NO_MEMBER);if(!lo)return null;const Ou=Au.sandbox,Pu=Iu?.specId||Au.agentId,Du=AGENTSPECS$1[Pu],Lu={agentName:Iu?.name||Du?.name||Au.agentId,location:$u?TARGET_SPECS[$u].label:"—",specId:Pu,harness:Du?.harness,variant:Ou.variant,status:Ou.state,baseUrl:Ou.agentBaseUrl||Au.serverUrl,sandboxBaseUrl:Ou.jupyterUrl,agentId:Au.agentId,isReady:Ou.state==="running"};return jsxRuntimeExports.jsx(AgentSummary,{summary:Lu})}const RING=14,STROKE=2.5,RADIUS=(RING-STROKE)/2,CIRCUMFERENCE=2*Math.PI*RADIUS,DEFAULT_WARN_AT=.25,DEFAULT_DANGER_AT=.1,DEFAULT_PULSE_AT=.05,PULSE_MS=1200;function format(Au){const lo=Math.max(0,Math.ceil(Au/1e3)),$u=Math.floor(lo/60),Ru=lo%60;return`${$u}:${String(Ru).padStart(2,"0")}`}function AnonymousKeyTimer({expiresAt:Au,grantedMs:lo,label:$u="Trial key",warnAt:Ru=DEFAULT_WARN_AT,dangerAt:Iu=DEFAULT_DANGER_AT,pulseAt:Ou=DEFAULT_PULSE_AT,onExpire:Pu}){const[Du,Lu]=reactExports.useState(()=>Date.now()),ju=reactExports.useRef(lo??Math.max(1,Au-Date.now())),Bu=reactExports.useRef(!1);reactExports.useEffect(()=>{const Hu=window.setInterval(()=>{Lu(Vu=>{const Gu=Date.now(),Ku=Zu=>Math.ceil((Au-Zu)/1e3);return Ku(Gu)===Ku(Vu)?Vu:Gu})},250);return()=>window.clearInterval(Hu)},[Au]);const Fu=Math.max(0,Au-Du);reactExports.useEffect(()=>{Fu>0||Bu.current||(Bu.current=!0,Pu?.())},[Fu,Pu]);const zu=Math.min(1,Math.max(0,Fu/ju.current)),qu=zu<=Ou,Uu=zu<=Iu?"danger.fg":zu<=Ru?"attention.fg":"fg.muted";return jsxRuntimeExports.jsxs(Box,{display:"inline-flex",alignItems:"center",gap:1,px:2,py:"2px",borderRadius:"999px",border:"1px solid",borderColor:"border.muted",bg:"canvas.subtle",color:Uu,fontVariantNumeric:"tabular-nums",sx:{...qu?{"@keyframes dla-key-pulse":{"0%, 100%":{opacity:1},"50%":{opacity:.45}},animation:`dla-key-pulse ${PULSE_MS}ms ease-in-out infinite`,"@media (prefers-reduced-motion: reduce)":{animation:"none"}}:null},title:`${$u}: this workspace is talking to the agent on a temporary key issued to nobody in particular. When it runs out the chat asks you to sign in. Sign in now for an account of your own.`,children:[jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",color:Uu,children:jsxRuntimeExports.jsx(KeyIcon,{size:12})}),jsxRuntimeExports.jsxs(Box,{as:"svg","aria-hidden":"true",focusable:"false",width:RING,height:RING,viewBox:`0 0 ${RING} ${RING}`,display:"block",flexShrink:0,children:[jsxRuntimeExports.jsx("circle",{cx:RING/2,cy:RING/2,r:RADIUS,fill:"none",stroke:"currentColor",strokeWidth:STROKE,opacity:.2}),jsxRuntimeExports.jsx("circle",{cx:RING/2,cy:RING/2,r:RADIUS,fill:"none",stroke:"currentColor",strokeWidth:STROKE,strokeLinecap:"round",strokeDasharray:CIRCUMFERENCE,strokeDashoffset:CIRCUMFERENCE*(1-zu),transform:`rotate(-90 ${RING/2} ${RING/2})`,style:{transition:"stroke-dashoffset 0.5s linear"}})]}),jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:Uu,fontWeight:"semibold"},children:format(Fu)})]})}function AnonymousKeyHeaderBadge({workspace:Au}){return jsxRuntimeExports.jsx(Box,{order:1,display:"inline-flex",alignItems:"center",children:jsxRuntimeExports.jsx(AnonymousKeyBadge,{workspace:Au})})}function AnonymousKeyBadge({workspace:Au}){const lo=useAnonymousSession(),$u=Au.sandbox.target??"local";return!targetRunsAgentInPage($u)||lo.status==="idle"||lo.status==="expired"?null:lo.expiresAt?jsxRuntimeExports.jsx(AnonymousKeyTimer,{expiresAt:lo.expiresAt,grantedMs:lo.grantedMs,onExpire:()=>useAnonymousSessionStore.getState().expire()}):jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:lo.error?"danger.fg":"fg.muted"},title:lo.error,children:lo.error?"No trial key":"Getting a trial key…"})}function SandboxSelector(Au){const lo=useOptionalSandboxService(),[$u,Ru]=reactExports.useState(!1),[Iu,Ou]=reactExports.useState(null),Pu=useSignalValue$1(lo?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Du=useSignalValue$1(lo?.status??EMPTY_STATUS),Lu=useSignalValue$1(lo?.target??DEFAULT_TARGET),ju=reactExports.useCallback(async Fu=>{if(!(!lo||Fu===Lu)){Ru(!0),Ou(null);try{await lo.setTarget(Fu)}catch(zu){Ou(zu instanceof Error?zu.message:String(zu))}finally{Ru(!1)}}},[lo,Lu]);if(!lo)return null;const Bu=Math.max(0,SANDBOX_TARGETS.indexOf(Lu));return jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,minWidth:0,children:[jsxRuntimeExports.jsx(Box,{width:16,flexShrink:0,display:"flex",justifyContent:"center",children:$u?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):null}),jsxRuntimeExports.jsx(KernelIndicator,{state:sandboxIndicatorState(Pu.state,Du?.execution_state,Du?.is_executing),kernelId:Pu.kernelId??Du?.kernel_id,kernelName:Du?.kernel_name,serverUrl:Pu.jupyterUrl??Du?.jupyter_url,websocketUrl:toWebsocketUrl(Pu.jupyterUrl??Du?.jupyter_url),environmentName:TARGET_SPECS[Lu].label,overlayTitle:`${TARGET_SPECS[Lu].label} Kernel`,position:"se",bordered:!1}),jsxRuntimeExports.jsx(SegmentedControl,{"aria-label":"Where code runs",size:"small",style:{listStyle:"none",margin:0,padding:0},sx:{listStyle:"none",m:0,p:0,"& > li":{listStyle:"none"},"& > li::marker":{content:"none"}},children:SANDBOX_TARGETS.map((Fu,zu)=>{const qu=heldTargetReason(Fu,lo?.serverUrl??"");return jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:zu===Bu,"aria-disabled":qu?!0:void 0,"data-sandbox-target":Fu,"data-sandbox-target-held":qu?"":void 0,sx:{listStyle:"none",...qu?{color:"fg.subtle",cursor:"not-allowed"}:null},title:qu??TARGET_SPECS[Fu].hint,onClick:()=>qu?void 0:void ju(Fu),children:TARGET_SPECS[Fu].label},Fu)})}),Iu||Pu.errorReason?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"danger.fg",lineHeight:1.3,maxWidth:280,minWidth:0},title:Iu??Pu.errorReason,children:Iu??Pu.errorReason}):jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},title:TARGET_SPECS[SANDBOX_TARGETS[Bu]].hint,children:Pu.state})]})}function toWebsocketUrl(Au){return Au?.replace(/^http/,"ws")}const EMPTY_STATUS={value:null,peek:()=>null},DEFAULT_TARGET={value:"local",peek:()=>"local"};function MemberIcon({icon:Au}){const lo=agentIcon(Au);return jsxRuntimeExports.jsx(lo,{})}function TeamMemberPicker(){const Au=useOptionalTeamSelection();return!Au||Au.members.length<2?null:jsxRuntimeExports.jsx(TeamMemberMenu,{selection:Au})}function TeamMemberMenu({selection:Au}){const[lo,$u]=reactExports.useState(!1),Ru=useSignalValue$1(Au.selected),Iu=Au.members.find(Ou=>Ou.id===Ru);return jsxRuntimeExports.jsx(AnchoredOverlay,{width:"large",open:lo,onOpen:()=>$u(!0),onClose:()=>$u(!1),renderAnchor:Ou=>jsxRuntimeExports.jsx(IconButton,{...Ou,"aria-labelledby":void 0,icon:ForwardRef$3,"aria-label":Iu?`Talking to ${Iu.name}. Choose another agent.`:"Choose an agent",variant:"invisible",size:"small"}),children:jsxRuntimeExports.jsx(Box,{width:440,maxWidth:"calc(100vw - 16px)",children:jsxRuntimeExports.jsxs(ActionList,{selectionVariant:"single",role:"listbox","aria-label":`Agents in ${Au.team.name}`,children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:Au.team.name}),Au.members.map(Ou=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Ou.id===Ru,onSelect:()=>{Au.select(Ou.id),$u(!1)},children:[jsxRuntimeExports.jsx(ActionList.LeadingVisual,{children:jsxRuntimeExports.jsx(MemberIcon,{icon:Ou.icon})}),jsxRuntimeExports.jsxs(Box,{as:"span",display:"flex",alignItems:"center",gap:2,children:[Ou.name,Ou.isSupervisor?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:"supervisor"}):null]}),Ou.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",sx:{display:"block",whiteSpace:"normal",overflowWrap:"anywhere",minWidth:0},children:Ou.description}):null]},Ou.id))]})})})}function specIdOf(Au){return(Au??"").split(":")[0]??""}function teamMembers(Au){const lo=specIdOf(Au.supervisor?.ref),$u=Iu=>{const Ou=AGENTSPECS$1[Iu];return{description:Ou?.description,emoji:Ou?.emoji,icon:Ou?.icon}},Ru=(Au.agents??[]).map(Iu=>{const Ou=specIdOf(Iu.ref);return{id:Iu.id,name:Iu.name||Ou||Iu.id,specId:Ou,isSupervisor:Ou!==""&&Ou===lo,...$u(Ou)}});return[...Ru.filter(Iu=>Iu.isSupervisor),...Ru.filter(Iu=>!Iu.isSupervisor)]}function createTeamSelection(Au){const lo=TEAM_SPECS[Au];if(!lo)return;const $u=teamMembers(lo);if($u.length===0)return;const Ru=signal$2($u[0].id);return{team:lo,members:$u,selected:Ru,select:Iu=>{$u.some(Ou=>Ou.id===Iu)&&(Ru.value=Iu)},sharing:lo.context?.sharing??"shared",active:computed$1(()=>$u.find(Iu=>Iu.id===Ru.value))}}function subagentsFor(Au,lo){const $u=teamMembers(Au),Ru=$u.find(Lu=>Lu.id===lo);if(!Ru)return[];const Iu=(Lu,ju,Bu)=>{const Fu=AGENTSPECS$1[ju];if(Fu)return{name:Lu,description:Bu||Fu.description||Lu,instructions:Fu.systemPrompt,model:Fu.model,icon:Fu.icon}},Ou=Ru.isSupervisor||Au.delegation?.allowPeerDelegation?$u.filter(Lu=>Lu.id!==lo).map(Lu=>Iu(Lu.name,Lu.specId,Lu.description)):[],Du=((Au.agents??[]).find(Lu=>Lu.id===lo)?.subagents??[]).map(Lu=>Iu(Lu.name,(Lu.ref??"").split(":")[0]??"",Lu.description));return[...Ou,...Du].filter(Boolean)}const AGENTS_PLUGIN_NAME="@datalayer/loop-plugin-agents",offeredTarget=(Au,lo)=>heldTargetReason(Au,lo)?"browser":Au,AgentsPlugin={name:AGENTS_PLUGIN_NAME,displayName:"Agents",description:"Where the agent and its code run: this page, a local server, or a Datalayer runtime.",octicon:"container",emoji:"📦",config:{serverUrl:"",target:"local"},contributionPoints:[LoopAgentBlueprint],preserveOutput:!0,build({config:Au,reactor:lo}){const $u=Au.showAgentVariants??!0,Ru=Au.teamId?createTeamSelection(Au.teamId):void 0;return{team:Ru,sandbox:createSwitchableSandboxService({serverUrl:Au.serverUrl,initialTarget:offeredTarget(($u||Au.targetFixed?Au.target:"browser")??"local",Au.serverUrl),kernelSource:Au.kernelSource,localAgent:Au.localAgent,blueprint:()=>{const Iu=lo.getContributions(LoopAgentBlueprint)[0]?.value;if(Iu)return{...Iu.specId?{agent_spec_id:Iu.specId}:null,...Iu.createPayload}}}),components:[{slot:LoopSlots.status,id:"sandbox-status",Component:SandboxStatusBridge},{slot:LoopSlots.status,id:"datalayer-agent",Component:DatalayerAgentMount},...Ru&&Au.showTeamPicker!==!1?[{slot:LoopSlots.header,id:"team-member-picker",Component:TeamMemberPicker}]:[],...$u?[{slot:LoopSlots.header,id:"sandbox-selector",Component:SandboxSelector}]:[],...Au.showAgentSummary===!1?[]:[{slot:LoopSlots.header,id:"agent-summary",Component:AgentSummaryPanel}],{slot:LoopSlots.chatHeader,id:"anonymous-key",Component:AnonymousKeyBadge},{slot:LoopSlots.header,id:"anonymous-key-header",Component:AnonymousKeyHeaderBadge}]}},register({contribute:Au,state:lo}){const $u=lo.getOutput()?.sandbox;if($u)return Au(LoopAgentGate,{check:Ru=>{const Iu=Ru.sandbox.target??$u.target.peek();return targetHasAgent(Iu)||TARGET_SPECS[Iu].noAgentReason}},{id:"sandbox-target"})},contributes:[contribution(LoopViewType,{viewType:"sandbox",title:"Sandbox",icon:ServerIcon,order:40,load:()=>__vitePreload(()=>import("./chunks/SandboxView-IYT-IKM6.js"),[],import.meta.url)},{id:"sandbox",order:40}),contribution(LoopCommand,{name:"sandbox",aliases:["code-sandbox"],description:"Show the code sandbox: variant, kernel, Jupyter server",group:"Capabilities",run:async({workspace:Au})=>{Au.setActiveViewType("sandbox")}},{id:"sandbox"})]},PULSE_ANIMATION="loop-subagent-pulse",KEYFRAMES=`@keyframes ${PULSE_ANIMATION} {
3599
+ `).filter(Iu=>Iu.startsWith("data:")).map(Iu=>Iu.slice(5).trim()).join("");if(Ru)try{lo.push(JSON.parse(Ru))}catch{}}return lo}function pageTurnOf(Au){let lo=null;for(const $u of streamEvents(Au)){if($u.type==="RUN_ERROR")return{refused:String($u.message??"Its page could not run.")};if($u.type==="CUSTOM"&&$u.name===LOOP_PAGE){const Ru=$u.value??{};lo={outputs:Ru.outputs??{},inputs:Ru.inputs??{}}}}return lo??{refused:"Its page showed nothing: its code answered no outputs."}}const base=Au=>`${Au.serverUrl.replace(/\/+$/,"")}/api/v1/apps/sessions`;async function posted(Au,lo,$u){const Ru=await(Au.fetcher??fetch)(lo,{method:"POST",headers:{"content-type":"application/json",...Au.token?{Authorization:`Bearer ${Au.token}`}:{}},body:JSON.stringify($u)});if(!Ru.ok){let Iu="";try{const Ou=await Ru.json();Iu=typeof Ou.detail=="string"?Ou.detail:""}catch{}throw new Error(Iu||`Its page was refused (${Ru.status}).`)}return Ru.text()}async function openPageSession(Au){const lo=await posted(Au,base(Au),{agent:Au.agentId});for(const $u of streamEvents(lo))if($u.type==="CUSTOM"&&$u.name==="loop.session"){const Ru=$u.value?.uid;if(typeof Ru=="string"&&Ru)return Ru}throw new Error("The runtime opened no session for its page.")}async function runPageIn(Au,lo,$u){try{const Ru=await posted(Au,`${base(Au)}/${encodeURIComponent(lo)}/actions`,{name:"page",payload:{inputs:$u}});return pageTurnOf(Ru)}catch(Ru){return{refused:Ru instanceof Error?Ru.message:String(Ru)}}}function outputsData(Au){return Object.fromEntries(Object.entries(Au).map(([lo,$u])=>[`/outputs/${lo}`,$u]))}const PAGE_RUN_DELAY_MS=300,NO_TURN$6=signal$2({id:0,status:"idle"}),NO_CONVERSATION$2=signal$2([]);function componentsOnPage(Au){const lo=new Set;for(const $u of Au){const Ru=$u.updateComponents;for(const Iu of Ru?.components??[])lo.add(String(Iu.component))}return[...lo]}function blocksMissing(Au,lo){const $u=new Set(lo),Ru=Au.filter(Iu=>!$u.has(Iu));return Ru.length===0?null:`This page places ${Ru.join(", ")}, which no enabled plugin contributes: ${Ru.length===1?"it is":"they are"} drawn once the plugin that contributes ${Ru.length===1?"it":"them"} is on.`}function AppPage({app:Au,workspace:lo}){const $u=useContributions(LoopChatTurn),Ru=useSignalValue$1($u[0]?.value.turn??NO_TURN$6),Iu=useSignalValue$1($u[0]?.value.conversation??NO_CONVERSATION$2),Ou=reactExports.useMemo(()=>appPageMessages(Au,SURFACE_CATALOG_ID),[Au]),Pu=useContributions(LoopCanvasBlock),Du=[...new Set(Pu.map(bd=>bd.value.id))].sort(),Lu=Du.join(","),ju=useOwnComponents(),Bu=reactExports.useMemo(()=>{const bd=blocksMissing(componentsOnPage(Ou),Du);if(bd)return{problem:bd};try{return{catalog:catalogOfBlocks(Du,ju)}}catch(Td){return{problem:Td instanceof Error?Td.message:String(Td)}}},[Ou,Lu,ju]),[Fu,zu]=reactExports.useState(null),qu=pageOf(Au),[Uu,Hu]=reactExports.useState({}),Vu=reactExports.useMemo(()=>({...appPageData(Au,Ru,Iu),...outputsData(Uu)}),[Au,Ru,Iu,Uu]),Gu=useIAMStore(bd=>bd.token)??"",Ku=useChatWords(),Zu=agentServerOf(lo.sandbox,lo.serverUrl),Qu=reactExports.useRef(null);Qu.current=Zu===void 0?null:{serverUrl:Zu,agentId:lo.agentId||Au.id,token:Gu||void 0};const Yu=reactExports.useRef("");Yu.current=Zu===void 0?noRuntimeSaid(lo.sandbox,Ku):"";const ed=reactExports.useRef(null),Xu=reactExports.useRef(!1),rd=reactExports.useRef(null),nd=reactExports.useRef(""),od=reactExports.useRef(!0),ad=reactExports.useCallback(bd=>{rd.current=bd,!Xu.current&&(Xu.current=!0,(async()=>{for(;rd.current&&od.current;){const Td=rd.current;rd.current=null;const Pd=Qu.current;if(!Pd){zu(Yu.current);continue}try{ed.current??=openPageSession(Pd);const ud=await runPageIn(Pd,await ed.current,Td);if(!od.current)break;"refused"in ud?zu(ud.refused):(zu(null),Hu(ud.outputs))}catch(ud){ed.current=null,od.current&&zu(ud instanceof Error?ud.message:String(ud))}}Xu.current=!1})())},[]),ld=reactExports.useRef(null);reactExports.useEffect(()=>(od.current=!0,()=>{od.current=!1,ld.current?.()}),[]);const fd=reactExports.useCallback(bd=>{if(!qu?.live)return;ld.current?.();let Td;const Pd=md=>{const _d=pageInputsOf(Au,md),hd=JSON.stringify(_d);hd!==nd.current&&(clearTimeout(Td),Td=setTimeout(()=>{nd.current=hd,ad(_d)},PAGE_RUN_DELAY_MS))},ud=bd.dataModel.subscribe("/inputs",Pd);Pd(ud.value),ld.current=()=>{clearTimeout(Td),ud.unsubscribe()}},[Au,qu?.live,ad]),pd=reactExports.useRef(lo);pd.current=lo;const Sd=reactExports.useRef(""),wd=reactExports.useCallback((bd,Td)=>{const Pd=appPageAction(Au,{name:bd.name,context:bd.context??{}},md=>Td?.dataModel.get(md),Sd.current),ud=pd.current.viewControls;if("refused"in Pd){zu(Pd.refused);return}if(zu(null),"runPage"in Pd)ad(Pd.runPage);else if("stop"in Pd)ud.stop?.();else if("newChat"in Pd)ud.newChat?.();else{if(ud.send){const md=ud.send(Pd.send,{loop:Pd.loop});if(md){zu(md);return}}else if(Pd.loop.files){zu("The conversation is not ready for a file yet: try again.");return}else pd.current.prompts.submit(Pd.send);Sd.current=Pd.inputs;for(const md of Pd.clear)Td?.dataModel.set(md,"")}},[Au,ad]);return jsxRuntimeExports.jsx(Box,{"data-testid":"app-page",height:"100%",minHeight:0,overflow:"auto",p:3,children:"problem"in Bu?jsxRuntimeExports.jsx(Box,{role:"status",color:"fg.muted",fontSize:1,children:Bu.problem}):jsxRuntimeExports.jsx(InlineSurface,{messages:Ou,data:Vu,onAction:wd,validationError:Fu,catalog:Bu.catalog,...qu?{onSurface:fd}:{}},Lu)})}const APP_PAGE_PLUGIN_NAME="@datalayer/loop-plugin-app-page";function defineAppPagePlugin(Au){function lo({workspace:Ru}){return jsxRuntimeExports.jsx(AppPage,{app:Au,workspace:Ru})}return{name:`${APP_PAGE_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: its page`,description:`The page of ${Au.name}, drawn beside its conversation.`,octicon:"browser",emoji:Au.emoji||void 0,contributes:[contribution(LoopEditorView,{surfaceId:APP_PAGE_SURFACE,title:Au.name,icon:BrowserIcon,order:-10,load:async()=>({default:lo})},{id:APP_PAGE_SURFACE,order:-10})]}}const APP_HOST_PAGE_VIEW="app-page";function defineAppHostPagePlugin(Au,lo){function $u({workspace:Iu}){return jsxRuntimeExports.jsx(lo,{app:Au,workspace:Iu})}return{name:`${APP_PAGE_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: its page`,description:`The page of ${Au.name}, drawn by its host.`,octicon:"browser",emoji:Au.emoji||void 0,contributes:[contribution(LoopViewType,{viewType:APP_HOST_PAGE_VIEW,title:Au.name,icon:BrowserIcon,order:-10,load:async()=>({default:$u})},{id:APP_HOST_PAGE_VIEW,order:-10})]}}const canvasBlocksPluginName=Au=>`@datalayer/loop-plugin-ui-${Au}`;function uiPluginBlocks(Au){return{name:canvasBlocksPluginName(Au.id),displayName:Au.name,description:`The blocks of ${Au.name} on the Canvas: ${Au.components.map(lo=>lo.name).join(", ")}.`,octicon:"apps",contributes:Au.components.map(lo=>contribution(LoopCanvasBlock,{id:lo.id,uiPlugin:Au.id,component:lo},{id:lo.id}))}}const CANVAS_BLOCK_PLUGINS=listUIPlugins().filter(Au=>Au.enabled&&Au.components.length>0).map(uiPluginBlocks),MANAGER_PLUGIN_NAME="@datalayer/reactor-manager",MANAGER_ACTIONS_SLOT="manager-actions",ManagerPluginSource=defineContributionPoint("manager.pluginSource");function usePluginRows(Au,lo){const $u=useReactorPlatform(),Ru=reactExports.useSyncExternalStore($u.subscribe,()=>$u.getRevision());return reactExports.useMemo(()=>$u.listPlugins().filter(Iu=>!lo.has(Iu)).map(Iu=>{const Ou=$u.getManifest(Iu);return{name:Iu,displayName:Ou?.displayName??Iu,description:Ou?.description,emoji:Ou?.emoji,version:Ou?.version,enabled:$u.isEnabled(Iu),disabledBy:Ou?.disabledBy,changeable:!Au.has(Iu),details:[{label:"Delivered by",values:Ou?.extension?[Ou.extension]:[]},{label:"Contributes to",values:Ou?.contributesTo??[]},{label:"Offers contribution points",values:Ou?.contributionPoints??[]},{label:"Requires backend plugins",values:Ou?.requiredBackendPlugins??[]},{label:"Uses if available",values:Ou?.optionalBackendPlugins??[]},{label:"Activates on",values:Ou?.activationEvents??[]}]}}),[$u,Ru,Au,lo])}function pluginMatches(Au,lo){if(!lo)return!0;const $u=lo.trim().toLowerCase();return[Au.name,Au.displayName,Au.description??""].join(" ").toLowerCase().includes($u)}const PluginHoverContext=reactExports.createContext(null);function usePluginHoverControl(){const[Au,lo]=reactExports.useState(null),$u=reactExports.useRef(void 0);return reactExports.useEffect(()=>()=>clearTimeout($u.current),[]),reactExports.useMemo(()=>({openName:Au,show:Ru=>{clearTimeout($u.current),lo(Ru)},hide:()=>{clearTimeout($u.current),$u.current=setTimeout(()=>lo(null),200)}}),[Au])}function useHoverControl(){const Au=reactExports.useContext(PluginHoverContext),lo=usePluginHoverControl();return Au??lo}function PluginDetails({row:Au}){const lo=(Au.details??[]).filter($u=>$u.values.length>0);return jsxRuntimeExports.jsxs(Box,{sx:{p:3,maxWidth:360,display:"grid",gap:2},children:[jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",alignItems:"center",gap:2},children:[Au.emoji?jsxRuntimeExports.jsx(Text$5,{"aria-hidden":!0,children:Au.emoji}):null,jsxRuntimeExports.jsx(Text$5,{sx:{fontWeight:"semibold"},children:Au.displayName}),Au.version?jsxRuntimeExports.jsxs(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:["v",Au.version]}):null]}),jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted",wordBreak:"break-all"},children:Au.name}),Au.description?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0},children:Au.description}):null,lo.map($u=>jsxRuntimeExports.jsxs(Box,{sx:{display:"grid",gap:1},children:[jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,fontWeight:"semibold"},children:$u.label}),$u.values.map(Ru=>jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted",wordBreak:"break-all"},children:Ru},Ru))]},$u.label)),Au.disabledBy==="dependency"?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"attention.fg"},children:"Off because something it depends on is off. It comes back when that does."}):null,Au.changeable?null:jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"attention.fg"},children:"This one cannot be switched off."})]})}const OVERLAY_TAKES_NO_FOCUS={preventFocusOnOpen:!0,sx:{pointerEvents:"none"},returnFocusRef:{current:null}};function PluginRowView({row:Au,size:lo,onToggle:$u}){const Ru=`plugin-name-${Au.name.replace(/[^a-zA-Z0-9]+/g,"-")}`,Iu=useHoverControl(),Ou=Iu.openName===Au.name,Pu=()=>Iu.show(Au.name),Du=()=>Iu.hide();return jsxRuntimeExports.jsx(AnchoredOverlay,{open:Ou,onOpen:Pu,onClose:Du,focusZoneSettings:{disabled:!0},focusTrapSettings:{disabled:!0},overlayProps:OVERLAY_TAKES_NO_FOCUS,side:"outside-right",renderAnchor:Lu=>jsxRuntimeExports.jsxs(Box,{...Lu,onMouseEnter:Pu,onMouseLeave:Du,onFocus:Pu,onBlur:Du,sx:{display:"flex",alignItems:"flex-start",gap:2,py:2,borderBottom:"1px solid",borderColor:"border.muted"},children:[jsxRuntimeExports.jsxs(Box,{sx:{minWidth:0,flex:1},children:[jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",alignItems:"center",gap:1},children:[Au.emoji?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:1},"aria-hidden":!0,children:Au.emoji}):null,jsxRuntimeExports.jsx(Text$5,{id:Ru,sx:{fontSize:1,fontWeight:"semibold",minWidth:0},children:jsxRuntimeExports.jsx(Truncate,{title:Au.name,maxWidth:"100%",inline:!0,children:Au.displayName})})]}),Au.description?jsxRuntimeExports.jsx(Text$5,{sx:{display:"block",fontSize:0,color:"fg.muted"},children:jsxRuntimeExports.jsx(Truncate,{title:Au.description,maxWidth:"100%",inline:!0,children:Au.description})}):null]}),jsxRuntimeExports.jsx(ToggleSwitch,{size:lo,checked:Au.enabled,disabled:!Au.changeable||Au.disabledBy==="dependency","aria-labelledby":Ru,onClick:()=>{Au.changeable&&Au.disabledBy!=="dependency"&&$u(Au.name,!Au.enabled)}})]}),children:jsxRuntimeExports.jsx(PluginDetails,{row:Au})})}function PluginList({plugins:Au,query:lo="",switchSize:$u="small",onToggle:Ru,emptyMessage:Iu}){const Ou=reactExports.useMemo(()=>Au.filter(Pu=>pluginMatches(Pu,lo)),[Au,lo]);return Ou.length===0?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:Iu??`No plugin matches “${lo}”.`}):jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Ou.map(Pu=>jsxRuntimeExports.jsx(PluginRowView,{row:Pu,size:$u,onToggle:Ru},Pu.name))})}function PluginsManagerView({protectedPlugins:Au,hiddenPlugins:lo,switchSize:$u,width:Ru,...Iu}){const Ou=useReactorPlatform(),Pu=Ou.getConfig(MANAGER_PLUGIN_NAME)??{},Du=reactExports.useMemo(()=>new Set(Au??Pu.protected??[MANAGER_PLUGIN_NAME]),[Au,Pu.protected]),Lu=reactExports.useMemo(()=>new Set(lo??Pu.hidden??[]),[lo,Pu.hidden]),ju=usePluginHoverControl(),Bu=usePluginRows(Du,Lu),[Fu,zu]=reactExports.useState(""),qu=$u??Pu.switchSize??"small",Uu=useContributions(ManagerPluginSource),Hu=reactExports.useMemo(()=>[...Uu].map(Vu=>Vu.value).sort((Vu,Gu)=>(Vu.order??100)-(Gu.order??100)),[Uu]);return jsxRuntimeExports.jsx(PluginHoverContext.Provider,{value:ju,children:jsxRuntimeExports.jsxs(Box,{sx:{display:"flex",flexDirection:"column",gap:3,width:Ru??Pu.width??"100%",maxWidth:"100%",minWidth:0},children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:MANAGER_ACTIONS_SLOT,props:Iu}),jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$5,{as:"h2",sx:{fontSize:1,fontWeight:"semibold",display:"block",mb:2},children:Pu.title??"Plugins"}),jsxRuntimeExports.jsx(TextInput$1,{leadingVisual:SearchIcon,value:Fu,onChange:Vu=>zu(Vu.target.value),"aria-label":"Filter plugins",placeholder:"Filter…",block:!0,size:"small"})]}),jsxRuntimeExports.jsx(Box,{children:jsxRuntimeExports.jsx(PluginList,{plugins:Bu,query:Fu,switchSize:qu,onToggle:(Vu,Gu)=>Gu?Ou.enable(Vu):Ou.disable(Vu)})}),Hu.map(Vu=>jsxRuntimeExports.jsxs(Box,{children:[jsxRuntimeExports.jsx(Text$5,{as:"h3",sx:{fontSize:1,fontWeight:"semibold",display:"block",mb:2},children:Vu.title}),jsxRuntimeExports.jsx(Vu.Component,{query:Fu,switchSize:qu})]},Vu.title))]})})}const PLUGINS_PANEL_PLUGIN_NAME="@datalayer/loop-plugin-plugins-panel",SIDEBAR_WIDTH=420,REACTOR_GRAPH_PLUGIN_NAME="@datalayer/reactor-graph",PluginsPanelPlugin={name:PLUGINS_PANEL_PLUGIN_NAME,displayName:"Plugins panel",description:"Switch plugins on and off while the workspace runs.",octicon:"plug",emoji:"🔌",build:()=>({components:[{id:"plugins-panel",slot:LoopSlots.sidebar,order:900,Component:({workspace:Au})=>jsxRuntimeExports.jsx(PluginsManagerView,{protectedPlugins:[PLUGINS_PANEL_PLUGIN_NAME],hiddenPlugins:[REACTOR_GRAPH_PLUGIN_NAME],width:SIDEBAR_WIDTH,workspace:Au})}]})};function ViewSwitcher({views:Au,workspace:lo,compact:$u=!1}){return Au.length<2?null:jsxRuntimeExports.jsx(Box,{role:"tablist","aria-label":"Workspace views",display:"inline-flex",alignItems:"center",bg:"neutral.muted",borderRadius:"6px",p:"2px",gap:"1px",children:Au.map(Ru=>{const Iu=Ru.value,Ou=canOpenView(Iu,lo),Pu=lo.activeViewType===Iu.viewType,Du=Iu.icon,Lu=Ou?Iu.title:`${Iu.title} — ${Iu.unavailableReason?.(lo)??"unavailable"}`;return jsxRuntimeExports.jsx(Tooltip,{text:Lu,direction:"n",children:jsxRuntimeExports.jsxs(Box,{as:"button",role:"tab","aria-selected":Pu,"aria-disabled":!Ou,onClick:()=>Ou&&lo.setActiveViewType(Iu.viewType),display:"inline-flex",alignItems:"center",gap:1,border:"none",borderRadius:"5px",px:2,py:"4px",fontSize:0,cursor:Ou?"pointer":"not-allowed",opacity:Ou?1:.5,bg:Pu?"canvas.default":"transparent",color:Pu?"fg.default":"fg.muted",boxShadow:Pu?"shadow.small":"none",children:[Du?jsxRuntimeExports.jsx(Du,{size:14}):null,$u&&Du?null:Iu.title]})},Iu.viewType)})})}const paneOpenKeyframes=Au=>Au==="left"?"loopPaneOpenLeft":"loopPaneOpenRight",paneOpenAnimation=Au=>`${paneOpenKeyframes(Au)} var(--theme-motion-pane, 0ms) var(--theme-motion-easing, ease) both`;function paneOpening(Au){const lo="12px";return{animation:paneOpenAnimation(Au),[`@keyframes ${paneOpenKeyframes(Au)}`]:{from:{opacity:0,transform:`translateX(${lo})`},to:{opacity:1,transform:"none"}},"@media (prefers-reduced-motion: reduce)":{animation:"none"}}}function railItemsOf(Au){return Au.map(lo=>({id:lo.id,label:lo.rail?.label??lo.id,icon:lo.rail?.icon??SidebarExpandIcon}))}function railChoiceAfter(Au,lo){return Au===lo?null:lo}const RAIL_WIDTH=48;function SidebarRail({components:Au,props:lo,width:$u}){const Ru=railItemsOf(Au),[Iu,Ou]=reactExports.useState(Ru[0]?.id??null),Pu=Ru.some(Du=>Du.id===Iu)?Iu:null;return jsxRuntimeExports.jsxs(Box,{as:"aside","data-loop-rail-sidebar":"",flex:"0 0 auto",display:"flex",minHeight:0,children:[jsxRuntimeExports.jsx(Box,{"data-loop-rail-panel":Pu??void 0,display:Pu?"block":"none",width:`${$u}px`,minWidth:0,borderLeft:"var(--theme-hairline, 1px) solid",borderColor:"border.default",overflowY:"auto",px:3,py:3,children:Au.map(Du=>{const{Component:Lu}=Du,ju=Du.id===Pu;return jsxRuntimeExports.jsx(Box,{id:`loop-rail-panel-${Du.id}`,role:"region","aria-label":railItemsOf([Du])[0].label,hidden:!ju,sx:ju?paneOpening("right"):void 0,children:jsxRuntimeExports.jsx(Lu,{...lo})},Du.id)})}),jsxRuntimeExports.jsx(Box,{as:"nav","aria-label":"Panels",width:`${RAIL_WIDTH}px`,flex:`0 0 ${RAIL_WIDTH}px`,display:"flex",flexDirection:"column",alignItems:"center",gap:1,py:2,borderLeft:"var(--theme-hairline, 1px) solid",borderColor:"border.default",children:Ru.map(Du=>{const Lu=Du.icon,ju=Du.id===Pu;return jsxRuntimeExports.jsx(Box,{as:"button",type:"button","data-loop-rail-item":Du.id,"aria-label":Du.label,title:Du.label,"aria-pressed":ju,"aria-controls":`loop-rail-panel-${Du.id}`,onClick:()=>Ou(railChoiceAfter(Pu,Du.id)),width:32,height:32,display:"inline-flex",alignItems:"center",justifyContent:"center",p:0,border:"none",borderRadius:2,cursor:"pointer",color:ju?"fg.default":"fg.muted",bg:ju?"neutral.muted":"transparent",hover:{color:"fg.default",bg:"neutral.subtle"},focusVisible:{outline:"2px solid",outlineColor:"var(--focus-outlineColor, #0969da)",outlineOffset:"1px"},children:jsxRuntimeExports.jsx(Lu,{size:16})},Du.id)})})]})}function buildLoopReactor(Au){return buildReactorFromPlugins(Au)}function LoopWorkspace(Au){const{serverUrl:lo,agentId:$u,conversationId:Ru,model:Iu,sandbox:Ou={state:"idle"},extensions:Pu=[],reactor:Du,manageReactor:Lu=!0,initialViewType:ju,onSend:Bu,layout:Fu="page",showViewSelector:zu=!0,showHeader:qu=!0,chatHeaderActions:Uu,headerActions:Hu,headerContainer:Vu,sidebarRail:Gu=!1}=Au,Ku=reactExports.useMemo(()=>Du??buildLoopReactor(Pu),[Du]);return useReactor(Ku,{autoStart:Lu}),jsxRuntimeExports.jsx(WorkspaceBody,{serverUrl:lo,agentId:$u,conversationId:Ru,model:Iu,initialSandbox:Ou,initialViewType:ju,onSend:Bu,layout:Fu,showViewSelector:zu,showHeader:qu,chatHeaderActions:Uu,headerActions:Hu,headerContainer:Vu,sidebarRail:Gu})}function WorkspaceBody({serverUrl:Au,agentId:lo,conversationId:$u,model:Ru,initialSandbox:Iu,initialViewType:Ou,onSend:Pu,layout:Du="page",showViewSelector:Lu=!0,showHeader:ju=!0,chatHeaderActions:Bu,headerActions:Fu,headerContainer:zu,sidebarRail:qu=!1}){const[Uu,Hu]=reactExports.useState(lo),Vu=reactExports.useRef(loopSurfaceId($u??`session-${Date.now().toString(36)}`));reactExports.useEffect(()=>{Hu(lo)},[lo]);const[Gu,Ku]=reactExports.useState(Ou??""),[Zu,Qu]=reactExports.useState(Iu),[Yu]=reactExports.useState(createPromptChannel),[ed,Xu]=reactExports.useState({}),rd=reactExports.useCallback(Pd=>{Xu(Pd??{})},[]),nd=useContributions(LoopViewType),od=useContributions(LoopCommand),ad=useSlotComponents(LoopSlots.sidebar),ld=reactExports.useRef(od),fd=reactExports.useRef(null),pd=Du==="panel",Sd=reactExports.useCallback(async Pd=>{const ud=parseCommand(Pd);if(!ud)return Pu?.(Pd,fd.current),Yu.submit(Pd)||Pu?{handled:!0}:{handled:!1,reason:"Nothing is listening for prompts in this view yet."};const md=ld.current.find(hd=>hd.value.name===ud.name||(hd.value.aliases??[]).includes(ud.name));if(!md)return{handled:!1,command:ud.name,reason:`Unknown command: /${ud.name}. Type /help to see what there is.`};const _d=await md.value.run({workspace:fd.current,argv:ud.argv});return _d?.prompt&&(Pu?.(_d.prompt,fd.current),Yu.submit(_d.prompt)),{handled:!0,command:ud.name,result:_d??void 0}},[Pu,Yu]),wd=reactExports.useMemo(()=>({serverUrl:Au,agentId:Uu,surfaceId:Vu.current,setAgentId:Hu,conversationId:$u,model:Ru,sandbox:Zu,setSandbox:Qu,activeViewType:Gu,setActiveViewType:Ku,prompts:Yu,submit:Sd,viewControls:ed,setViewControls:rd,chatHeaderActions:Bu}),[Au,Uu,$u,Ru,Zu,Gu,Yu,Sd,ed,rd,Bu]);fd.current=wd,ld.current=od;const bd=reactExports.useMemo(()=>Gu||(nd.find(ud=>canOpenView(ud.value,wd))?.value.viewType??""),[Gu,nd,wd]);useReactorEvent(bd?onView(bd):void 0);const Td=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Fu,jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.header,props:{workspace:wd}}),Lu?jsxRuntimeExports.jsx(ViewSwitcher,{views:nd,workspace:wd,compact:pd}):null]});return jsxRuntimeExports.jsxs(Box,{"data-loop-workspace":"",display:"flex",flexDirection:"column",height:"100%",minHeight:0,position:"relative",bg:"canvas.default",color:"fg.default",children:[ju&&zu?reactDomExports.createPortal(jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",flexWrap:"wrap",gap:2,children:Td}),zu):null,ju&&zu===void 0?jsxRuntimeExports.jsx(Box,{as:"header",display:"flex",alignItems:"center",justifyContent:pd?"flex-start":"space-between",flexWrap:"wrap",gap:2,px:pd?2:3,py:2,borderBottom:"1px solid",borderColor:"border.default",flex:"0 0 auto",children:Td}):null,jsxRuntimeExports.jsxs(Box,{flex:"1 1 auto",minHeight:0,display:"flex",children:[jsxRuntimeExports.jsx(Box,{flex:"1 1 auto",minWidth:0,minHeight:0,position:"relative",children:jsxRuntimeExports.jsx(ReactorViewHost,{point:LoopViewType,active:bd,props:{viewType:bd,workspace:wd},fallback:jsxRuntimeExports.jsx(Centered,{children:"Loading…"}),empty:jsxRuntimeExports.jsx(Centered,{children:"No view is available yet."}),errorFallback:Pd=>jsxRuntimeExports.jsxs(Centered,{children:["This view failed to load: ",Pd.message]})})}),ad.length>0&&qu&&!pd?jsxRuntimeExports.jsx(SidebarRail,{components:ad,props:{workspace:wd},width:SIDEBAR_WIDTH}):ad.length>0?jsxRuntimeExports.jsx(Box,{as:"aside",flex:"0 0 auto",width:pd?"100%":`${SIDEBAR_WIDTH}px`,minWidth:0,borderLeft:pd?"none":"1px solid",borderTop:pd?"1px solid":"none",borderColor:"border.default",bg:"canvas.subtle",overflowY:"auto",px:3,py:3,children:jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.sidebar,props:{workspace:wd}})}):null]}),jsxRuntimeExports.jsxs(Box,{flex:"0 0 auto",children:[jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.footer,props:{workspace:wd}}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.status,props:{workspace:wd}})]}),jsxRuntimeExports.jsx(ReactorSlot,{slot:LoopSlots.root,props:{workspace:wd}})]})}function Centered({children:Au}){return jsxRuntimeExports.jsx(Box,{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"fg.muted",fontSize:1,px:3,textAlign:"center",children:Au})}function resolveTopOffset(Au){if(typeof Au=="number")return Au;if(!Au||typeof document>"u")return 0;const lo=document.querySelector(Au);return lo?Math.max(0,Math.round(lo.getBoundingClientRect().bottom)):0}function fullScreenNode(Au){return Au?.closest("[data-loop-fullscreen-root]")??Au?.closest("[data-loop-workspace]")??Au}function useWorkspaceFullScreen(Au,lo={}){const{forceOverlay:$u=!1,paintOverlay:Ru=!1,topOffset:Iu=0}=lo,[Ou,Pu]=reactExports.useState(!1),Du=reactExports.useRef(!1);reactExports.useEffect(()=>{const Fu=()=>{if(!Du.current)return;const zu=!!document.fullscreenElement&&!!Au.current&&document.fullscreenElement.contains(Au.current);Pu(zu),zu||(Du.current=!1)};return document.addEventListener("fullscreenchange",Fu),()=>document.removeEventListener("fullscreenchange",Fu)},[Au]);const Lu=reactExports.useCallback(()=>{const Fu=fullScreenNode(Au.current);if(Ou){Du.current&&document.fullscreenElement?document.exitFullscreen():Pu(!1);return}if($u||Ru||!Fu?.requestFullscreen){Pu(!0);return}Du.current=!0,Fu.requestFullscreen().then(()=>Pu(!0),()=>{Du.current=!1,Pu(!0)})},[Au,Ou,$u,Ru]),[ju,Bu]=reactExports.useState(0);return reactExports.useEffect(()=>{if(!Ou||Du.current){Bu(0);return}const Fu=()=>Bu(resolveTopOffset(Iu));return Fu(),window.addEventListener("resize",Fu),()=>window.removeEventListener("resize",Fu)},[Ou,Iu]),reactExports.useEffect(()=>{if(!Ru||!Ou||Du.current)return;const Fu=fullScreenNode(Au.current);if(!Fu)return;const zu=Fu.getAttribute("style");return Fu.style.position="fixed",Fu.style.top=`${ju}px`,Fu.style.right="0",Fu.style.bottom="0",Fu.style.left="0",Fu.style.height="auto",Fu.style.zIndex="1000",()=>{zu===null?Fu.removeAttribute("style"):Fu.setAttribute("style",zu)}},[Ru,Ou,Au,ju]),reactExports.useEffect(()=>{if(!Ou||Du.current)return;const Fu=zu=>{zu.key==="Escape"&&!zu.defaultPrevented&&Pu(!1)};return window.addEventListener("keydown",Fu),()=>window.removeEventListener("keydown",Fu)},[Ou]),{fullScreen:Ou,usingApi:Du,toggle:Lu,topOffsetPx:ju}}function messageText(Au){const lo=Au.content;return typeof lo=="string"?lo:lo.map($u=>typeof $u=="string"?$u:$u.text??"").join("")}const isToolCall=Au=>Au.type==="tool-call";function conversationOf(Au){const lo=[];for(const $u of Au){if(isToolCall($u)){lo.push({role:"tool",name:$u.toolName,args:$u.args??{},...$u.result===void 0?{}:{result:$u.result}});continue}if($u.role!=="user"&&$u.role!=="assistant")continue;const Ru=messageText($u);Ru.trim()&&lo.push({role:$u.role,text:Ru})}return lo}const sameConversation=(Au,lo)=>Au.length===lo.length&&Au.every(($u,Ru)=>JSON.stringify($u)===JSON.stringify(lo[Ru])),IDLE={id:0,status:"idle"};function createTurnFeed(){const Au=signal$2(IDLE),lo=signal$2([]),$u=signal$2("idle");return{turn:Au,conversation:lo,presence:$u,setPresence:Ru=>{$u.value!==Ru&&($u.value=Ru)},items:Ru=>{const Iu=conversationOf(Ru);sameConversation(lo.value,Iu)||(lo.value=Iu)},begin:(Ru,Iu)=>{Au.value={id:Au.value.id+1,user:Ru,...Iu?{thread:Iu}:{},status:"thinking",usage:Au.value.usage}},assistant:Ru=>{const Iu=Au.value;Iu.status==="idle"||Iu.assistant===Ru||(Au.value={...Iu,assistant:Ru,status:Iu.status==="done"||Iu.status==="error"?Iu.status:Ru?"streaming":Iu.status})},usage:Ru=>{const Iu=Au.value;Iu.usage!==Ru&&(Au.value={...Iu,usage:Ru})},activity:Ru=>{const Iu=Au.value;Iu.status==="idle"||Iu.activity===Ru||(Au.value={...Iu,activity:Ru})},end:(Ru="done")=>{const Iu=Au.value;Iu.status!=="idle"&&(Au.value={...Iu,status:Ru,activity:void 0})}}}const TURN_WRITERS=Symbol.for("loop.chat.turn.writers");function feedWriters(Au){return{[TURN_WRITERS]:Au}}function turnWritersOf(Au){return Au?.[TURN_WRITERS]}function agentAction(Au,lo){const{prompt:$u,...Ru}=lo;return{...Ru,type:"button",group:"agent",onClick:()=>Au.workspace.prompts.submit($u)}}const CHAT_PLUGIN_NAME="@datalayer/loop-plugin-chat",ChatPlugin={name:CHAT_PLUGIN_NAME,config:{placeholder:"",defaultSurface:"notebook",showSurfaceSelector:!0,hideHeader:!1,headerButtons:{newChat:!1,clear:!1},hidePrompt:!1,promptPlacement:"bottom",autoFocusPrompt:!0,suggestionLabels:!0,fullScreenTopOffset:0},displayName:"Chat",description:"The conversation, the prompt, and the point editors plug into.",octicon:"comment-discussion",emoji:"💬",contributionPoints:[LoopAgentGate,LoopFrontendTool,LoopChatComposer,LoopChatHeader,LoopChatSuggestion,LoopChatExtras,LoopChatTurn],build:Au=>{const lo=createTurnFeed();return Au.contribute(LoopChatTurn,{id:"chat-turn",turn:lo.turn,conversation:lo.conversation,presence:lo.presence,...feedWriters(lo)},{id:"chat-turn"}),{}},contributes:[contribution(LoopViewType,{viewType:"chat",title:"Chat",icon:CommentDiscussionIcon,order:0,load:()=>__vitePreload(()=>import("./chunks/ChatView-Bqiq0mvd.js"),[],import.meta.url)},{id:"chat",order:0}),contribution(LoopCommand,{name:"chat",description:"Show the conversation",group:"Session",keybinding:"Mod+Alt+K",run:async({workspace:Au})=>{Au.setActiveViewType("chat")}},{id:"chat"}),contribution(LoopNotebookToolbarItem,{items:Au=>[agentAction(Au,{key:"loop-compact",ariaLabel:"Compact this notebook",title:"Ask @NotebookCompactor to shorten it without changing results",icon:FoldIcon,order:200,prompt:"@NotebookCompactor compact this notebook without changing what it computes."}),agentAction(Au,{key:"loop-reproduce",ariaLabel:"Check reproducibility",title:"Ask @NotebookReproducer to run it on a fresh sandbox",icon:SyncIcon,order:201,prompt:"@NotebookReproducer run this notebook top to bottom on a fresh sandbox and report what does not reproduce."})]},{id:"agent-actions",order:200}),contribution(LoopDocumentToolbarItem,{items:Au=>[agentAction(Au,{key:"loop-summarise",ariaLabel:"Summarise this document",title:"Ask the agent for a summary of what this document says",icon:SparkleFillIcon,order:200,prompt:"Summarise this document in a short paragraph."})]},{id:"agent-actions",order:200})]};function WorkspaceFullScreenAction(){const Au=reactExports.useRef(null),$u=useReactorPlatform().getConfig(CHAT_PLUGIN_NAME)?.fullScreenTopOffset??0,{fullScreen:Ru,toggle:Iu}=useWorkspaceFullScreen(Au,{paintOverlay:!!$u,topOffset:$u});return jsxRuntimeExports.jsx(IconButton,{ref:Au,icon:Ru?ScreenNormalIcon:ScreenFullIcon,"aria-label":Ru?"Exit full screen":"Enter full screen",variant:"invisible",size:"small",sx:{order:2},onClick:Iu})}const THEME_PLUGIN_NAME="@datalayer/primer-theme",TOGGLE_COLOR_MODE_COMMAND="theme.toggleColorMode",ThemePlugin={name:THEME_PLUGIN_NAME,displayName:"Theme",description:"Keeps Primer portals in the application’s color mode, and toggles it.",octicon:"sun",emoji:"🌗",commands:[{id:TOGGLE_COLOR_MODE_COMMAND,name:"Toggle the color mode",description:"Switch between light and dark",emoji:"🌗",category:"Appearance",keybinding:"Mod+Alt+C",execute:()=>{const Au=useThemeStore.getState(),lo=Au.colorMode==="auto"?typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light":Au.colorMode;Au.setColorMode(lo==="dark"?"light":"dark")}}],register:()=>{if(typeof document>"u")return;setupPrimerPortals(useThemeStore.getState().colorMode);const Au=useThemeStore.subscribe((Ru,Iu)=>{Ru.colorMode!==Iu.colorMode&&setupPrimerPortals(Ru.colorMode)}),lo=window.matchMedia("(prefers-color-scheme: dark)"),$u=()=>{useThemeStore.getState().colorMode==="auto"&&setupPrimerPortals("auto")};return lo.addEventListener("change",$u),()=>{Au(),lo.removeEventListener("change",$u)}}},pageLayoutPanelOpen=signal$2(!1),pageLayoutSheet=signal$2("page"),pageLayoutActivity=signal$2(void 0);function openPagePanel(){pageLayoutPanelOpen.value=!0}const PAGE_SHEET_WIDTH=920,PAGE_PANEL_WIDTH=400,PAGE_SIZE_FORMATS={letter:{width:816,height:1056},a4:{width:794,height:1123}};function resolvePageSize(Au,lo=PAGE_SHEET_WIDTH){const $u=Au?.format&&Au.format!=="free"?PAGE_SIZE_FORMATS[Au.format]:void 0;return{width:Au?.width??$u?.width??lo,height:Au?.height??$u?.height}}const CANVAS_PX=[2,3,4];function ActivityLine({label:Au}){return jsxRuntimeExports.jsxs(Box$1,{"data-page-activity":"",role:"status",sx:{position:"sticky",top:0,zIndex:2,alignSelf:"flex-start",display:"inline-flex",alignItems:"center",gap:2,px:2,py:"4px",borderRadius:"999px",border:"1px solid",borderColor:"accent.muted",bg:"accent.subtle",color:"accent.fg",fontSize:0,fontWeight:"semibold",whiteSpace:"nowrap",boxShadow:"0 4px 12px -6px rgba(0,0,0,0.3)"},children:[jsxRuntimeExports.jsx(Box$1,{as:"span","aria-hidden":"true",sx:{width:7,height:7,borderRadius:"50%",bg:"accent.fg",animation:"page-activity-dot 1.1s ease-in-out infinite","@keyframes page-activity-dot":{"0%, 100%":{opacity:1},"50%":{opacity:.3}}}}),jsxRuntimeExports.jsx(Text$5,{children:Au})]})}function panelOpening(Au){const lo=Au==="left"?"pagePanelOpenLeft":"pagePanelOpenRight";return{animation:`${lo} var(--theme-motion-pane, 0ms) var(--theme-motion-easing, ease) both`,[`@keyframes ${lo}`]:{from:{opacity:0,transform:`translateX(${Au==="left"?"-12px":"12px"})`},to:{opacity:1,transform:"none"}},"@media (prefers-reduced-motion: reduce)":{animation:"none"}}}function PageLayout({page:Au,hasPage:lo=Au!=null,panel:$u,band:Ru,chips:Iu,picker:Ou,transient:Pu,activity:Du,bandMode:Lu="docked",panelMode:ju="docked",panelSide:Bu="right",sheetWidth:Fu=PAGE_SHEET_WIDTH,pageSize:zu,panelWidth:qu=PAGE_PANEL_WIDTH}){const Uu=Lu==="panel",Hu=Ru!=null,{width:Vu,height:Gu}=resolvePageSize(zu,Fu),Zu=useSignalValue$1(pageLayoutPanelOpen)||Uu&&Hu,Qu=useSignalValue$1(pageLayoutActivity),Yu=Du??Qu,ed=lo?"page":"panel";return reactExports.useEffect(()=>{pageLayoutSheet.value=ed},[ed]),jsxRuntimeExports.jsxs(Box$1,{"data-page-layout":"",sx:{position:"relative",flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column"},children:[Ou,jsxRuntimeExports.jsxs(Box$1,{sx:{flex:"1 1 auto",minHeight:0,display:"flex",bg:"canvas.inset"},children:[jsxRuntimeExports.jsxs(Box$1,{sx:{flex:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:[Ru&&Lu==="docked"?jsxRuntimeExports.jsx(Box$1,{"data-page-band":"","data-page-prompt-dock":"",sx:{flex:"0 0 auto",display:"flex",justifyContent:"center",px:CANVAS_PX,bg:"canvas.subtle",borderBottom:"1px solid",borderColor:"border.default"},children:jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,minWidth:0},children:Ru})}):null,jsxRuntimeExports.jsxs(Box$1,{"data-page-canvas":"",sx:{flex:"1 1 auto",minWidth:0,minHeight:0,overflowY:lo?"auto":"hidden",overflowX:"hidden",display:"flex",flexDirection:"column",alignItems:"center",pt:3,pb:6,px:CANVAS_PX},children:[Ru&&Iu&&!Uu?jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,mb:3,display:"flex",justifyContent:"center","& > *":{justifyContent:"center"}},children:Iu}):null,Yu?jsxRuntimeExports.jsx(Box$1,{sx:{width:"100%",maxWidth:Vu,display:"flex",justifyContent:"flex-end",mb:2},children:jsxRuntimeExports.jsx(ActivityLine,{label:Yu})}):null,jsxRuntimeExports.jsx(Sheet,{"data-page-sheet":"",sx:{width:"100%",maxWidth:Vu,flex:lo?"1 0 auto":"1 1 auto",px:lo?[3,4,"56px"]:[2,3,4],py:lo?[3,4,4]:2,position:"relative",display:"flex",minHeight:lo?Gu??480:0,"& > *":{flex:"1 1 auto",minWidth:0}},children:lo?Au:$u}),lo||!Au?null:jsxRuntimeExports.jsx(Box$1,{"aria-hidden":"true",sx:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",zIndex:-1,display:"flex"},children:Au})]})]}),!lo||!$u?null:jsxRuntimeExports.jsxs(Box$1,{"data-page-panel":Zu?"":void 0,"data-page-panel-mode":ju,"aria-hidden":Zu?void 0:"true",sx:{minWidth:0,minHeight:0,display:"flex",flexDirection:"column",bg:"canvas.default",borderColor:"border.default",...Zu?ju==="docked"?{flex:`0 0 ${qu}px`,maxWidth:"45%",order:Bu==="left"?-1:void 0,[Bu==="left"?"borderRight":"borderLeft"]:"1px solid",zIndex:1}:ju==="overlay"?{position:"absolute",top:0,bottom:0,[Bu]:0,width:qu,maxWidth:"85%",[Bu==="left"?"borderRight":"borderLeft"]:"1px solid",boxShadow:"shadow.large",zIndex:5}:{position:"absolute",[Bu]:16,bottom:16,width:qu,maxWidth:"calc(100% - 32px)",height:"min(70%, 560px)",border:"1px solid",borderRadius:2,boxShadow:"shadow.large",overflow:"hidden",zIndex:5}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",overflow:"visible"}},children:[jsxRuntimeExports.jsx(Box$1,{sx:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column","& > *":{flex:"1 1 auto",minHeight:0},...Zu?panelOpening(Bu):null},children:$u}),Hu&&Lu!=="docked"?jsxRuntimeExports.jsxs(Box$1,{"data-page-panel-band":Uu?"":void 0,sx:Uu?{flex:"0 0 auto",borderTop:"1px solid",borderColor:"border.default",visibility:"visible",pointerEvents:"auto","& > *":{justifyContent:"center"}}:{position:"absolute",inset:0,visibility:"visible",pointerEvents:"none","& > *":{pointerEvents:"auto"}},children:[Uu?Iu:null,Ru]}):null]})]}),Pu]})}function PagePanelToggle({panelName:Au="panel",icon:lo=SidebarExpandIcon,sx:$u}){const Ru=useSignalValue$1(pageLayoutPanelOpen);return useSignalValue$1(pageLayoutSheet)==="panel"?null:jsxRuntimeExports.jsx(IconButton,{icon:lo,size:"small",variant:Ru?"default":"invisible","aria-label":Ru?`Hide the ${Au}`:`Show the ${Au}`,"aria-pressed":Ru,onClick:()=>{Ru?pageLayoutPanelOpen.value=!1:openPagePanel()},sx:{color:Ru?"accent.fg":"fg.muted",...$u}})}const INPUT_PROMPT_PLUGIN_NAME="@datalayer/loop-plugin-input-prompt",LazyComposerView=reactExports.lazy(()=>__vitePreload(()=>import("./chunks/ComposerView-DcubnPoo.js"),[],import.meta.url));function ComposerView(Au){return jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(LazyComposerView,{...Au})})}const InputPromptPlugin={name:INPUT_PROMPT_PLUGIN_NAME,config:{},displayName:"Input Prompt",description:"The composer under (or over) the conversation.",octicon:"pencil",emoji:"✏️",contributionPoints:[LoopPromptPanel],contributes:[contribution(LoopChatComposer,{id:"input-prompt",Component:ComposerView},{id:"input-prompt"})]},AGENT_ICONS={agent:ForwardRef$3,beaker:BeakerIcon,bell:BellIcon,book:BookIcon,briefcase:BriefcaseIcon,browser:BrowserIcon,bug:BugIcon,clock:ClockIcon,code:CodeIcon,"comment-discussion":CommentDiscussionIcon,cpu:CpuIcon,"credit-card":CreditCardIcon,database:DatabaseIcon,file:FileIcon,checklist:ChecklistIcon,"code-review":CodeReviewIcon,fold:FoldIcon,"git-branch":GitBranchIcon,globe:GlobeIcon,graph:GraphIcon,heart:HeartIcon,"issue-opened":IssueOpenedIcon,lightbulb:LightBulbIcon,"light-bulb":LightBulbIcon,"list-unordered":ListUnorderedIcon,mail:MailIcon,megaphone:MegaphoneIcon,"mortar-board":MortarBoardIcon,note:NoteIcon,organization:OrganizationIcon,package:PackageIcon,pencil:PencilIcon,people:PeopleIcon,play:PlayIcon,pulse:PulseIcon,rss:RssIcon,search:SearchIcon,"share-2":ShareAndroidIcon,shield:ShieldIcon,"shield-check":ShieldCheckIcon,sliders:SlidersIcon,sun:SunIcon,sync:SyncIcon,table:TableIcon,tag:TagIcon,tasklist:TasklistIcon,telescope:TelescopeIcon,tools:ToolsIcon,"trending-up":GraphIcon,rocket:RocketIcon,zap:ZapIcon};function agentIcon(Au){return(Au?AGENT_ICONS[Au]:void 0)??ForwardRef$3}function useOptionalSandboxService(){return useReactorPlatform().getOutput(AGENTS_PLUGIN_NAME)?.sandbox}function useSandboxService(){const Au=useOptionalSandboxService();if(!Au)throw new Error(`The code sandbox plugin (${AGENTS_PLUGIN_NAME}) is not mounted. A view that needs a sandbox must declare it as a dependency.`);return Au}function SandboxStatusBridge({workspace:Au}){const lo=useOptionalSandboxService(),$u=useSignalValue$1(lo?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Ru=useSignalValue$1(lo?.target??IDLE_SANDBOX_TARGET_SIGNAL),{setSandbox:Iu,agentId:Ou}=Au;return reactExports.useEffect(()=>lo?.connect(Ou),[lo,Ou]),reactExports.useEffect(()=>{lo&&Iu({...$u,target:Ru})},[lo,$u,Ru,Iu]),null}const DatalayerAgentBridge=reactExports.lazy(async()=>({default:(await __vitePreload(()=>import("./chunks/DatalayerAgentBridge-BhxfUyb7.js"),[],import.meta.url)).DatalayerAgentBridge}));function DatalayerAgentMount(){return jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:null,children:jsxRuntimeExports.jsx(DatalayerAgentBridge,{})})}const CREATING_STATUSES=new Set(["creating","starting","launching","connecting","pending","resuming"]),MAX_AGENT_NAME_LENGTH=32,toSandboxStatusUrl=Au=>{const lo=String(Au||"").trim();if(lo)try{const $u=new URL(lo);return $u.pathname=`${$u.pathname.replace(/\/$/,"")}/api`,$u.toString()}catch{const $u=lo.replace(/\/$/,"");return $u.endsWith("/api")?$u:`${$u}/api`}},OVERLAY_WIDTH=360,AgentSummary=({summary:Au,title:lo="Active Agent"})=>{const[$u,Ru]=reactExports.useState(!1),[Iu,Ou]=reactExports.useState(!1),Pu=reactExports.useRef(null),Du=reactExports.useRef(null),Lu=()=>{Du.current!==null&&(window.clearTimeout(Du.current),Du.current=null)},ju=()=>{Lu();const Yu=Pu.current?.getBoundingClientRect();Ou(!!(Yu&&Yu.left+OVERLAY_WIDTH>window.innerWidth)),Ru(!0)},Bu=()=>{Lu(),Du.current=window.setTimeout(()=>{Ru(!1),Du.current=null},300)};reactExports.useEffect(()=>()=>{Lu()},[]);const Fu=Au?.baseUrl?(()=>{const Yu=Au.baseUrl.replace(/\/$/,"");return Yu.endsWith("/api/v1")?Yu:`${Yu}/api/v1`})():void 0,zu=Fu?`${Fu}/runtime/status`:void 0,qu=toSandboxStatusUrl(Au?.sandboxBaseUrl);if(!Au)return null;const Uu=(Au.status||"").toLowerCase(),Hu=!Au.isReady&&!Au.agentId&&CREATING_STATUSES.has(Uu),Vu=!!Au.error,Gu=!!Au.agentId||Hu,Ku=strip(Au.agentName,MAX_AGENT_NAME_LENGTH),Zu=`${Au.agentName} · ${Au.location}`,Qu=`${Ku} · ${Au.location}`;return jsxRuntimeExports.jsxs(Box,{ref:Pu,position:"relative",onMouseEnter:ju,onMouseLeave:Bu,children:[jsxRuntimeExports.jsxs(Box,{as:"button",type:"button",title:Zu,px:2,py:"6px",maxWidth:280,minWidth:0,border:"1px solid",borderColor:Vu?"danger.emphasis":"border.default",borderRadius:2,bg:Vu?"danger.subtle":"canvas.default",color:Vu?"danger.fg":"fg.default",fontSize:0,cursor:"default",display:"flex",alignItems:"center",gap:1,children:[Hu&&jsxRuntimeExports.jsx(StyledSpinner,{size:"small",sx:{width:12,height:12}}),Vu&&jsxRuntimeExports.jsx("span",{"aria-hidden":!0,children:"⚠"}),jsxRuntimeExports.jsx(Box,{as:"span",display:"block",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",children:Qu})]}),$u&&jsxRuntimeExports.jsxs(Box,{position:"absolute",top:"calc(100% + 8px)",width:OVERLAY_WIDTH,p:2,border:"1px solid",borderColor:"border.default",borderRadius:2,bg:"canvas.overlay",boxShadow:"shadow.large",zIndex:120,fontSize:0,color:"fg.default",right:Iu?0:void 0,left:Iu?void 0:0,children:[jsxRuntimeExports.jsx(Box,{mb:1,fontWeight:600,children:lo}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Name: ",Au.agentName]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Location: ",Au.location]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Spec: ",Au.specId||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Harness: ",Au.harness||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Variant: ",Au.variant||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",children:["Status: ",Hu?"creating":Au.status||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Agent base URL: ",Au.baseUrl||"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Code sandbox base URL:"," ",Au.sandboxBaseUrl?jsxRuntimeExports.jsx(Box,{as:"a",href:Au.sandboxBaseUrl,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:Au.sandboxBaseUrl}):"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",display:"flex",alignItems:"center",gap:1,children:["Agent ID:"," ",Au.agentId?Au.agentId:Hu?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(StyledSpinner,{size:"small",sx:{width:12,height:12}}),"Creating…"]}):"—"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Agent status:"," ",Gu&&zu?jsxRuntimeExports.jsx(Box,{as:"a",href:zu,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:zu}):"n/a"]}),jsxRuntimeExports.jsxs(Box,{color:"fg.muted",wordBreak:"break-all",children:["Code sandbox status:"," ",qu?jsxRuntimeExports.jsx(Box,{as:"a",href:qu,target:"_blank",rel:"noopener noreferrer",color:"accent.fg",textDecoration:"underline",children:qu}):"n/a"]}),Vu&&jsxRuntimeExports.jsxs(Box,{mt:1,p:1,border:"1px solid",borderColor:"danger.muted",borderRadius:2,bg:"danger.subtle",color:"danger.fg",wordBreak:"break-word",children:["Error: ",Au.error]})]})]})},insideJupyterLab=()=>loadJupyterConfig().insideJupyterLab;function collect(Au,lo){const $u=Au?.header?.msg_type,Ru=Au?.content??{};$u==="stream"?(lo.stdout.push(String(Ru.text??"")),lo.outputs.push({output_type:"stream",text:Ru.text})):$u==="execute_result"||$u==="display_data"?lo.outputs.push({output_type:$u,data:Ru.data}):$u==="error"&&(lo.error=`${Ru.ename??"Error"}: ${Ru.evalue??""}`,lo.outputs.push({output_type:"error",ename:Ru.ename,evalue:Ru.evalue,traceback:Ru.traceback}))}function browserSource(){let Au;return{variant:"pyodide",acquire:async()=>{const{createLiteServiceManager:lo,jupyterReactStore:$u,loadJupyterConfig:Ru}=await __vitePreload(async()=>{const{createLiteServiceManager:Ou,jupyterReactStore:Pu,loadJupyterConfig:Du}=await import("./chunks/index-CNx_s591.js").then(Lu=>Lu.r);return{createLiteServiceManager:Ou,jupyterReactStore:Pu,loadJupyterConfig:Du}},[],import.meta.url);Au=Au??{baseUrl:libExports$5.PageConfig.getOption("baseUrl"),wsUrl:libExports$5.PageConfig.getOption("wsUrl")},Ru({lite:!0});const Iu=await lo();return $u.getState().setServiceManager(Iu),Iu},release:()=>{Au&&(libExports$5.PageConfig.setOption("baseUrl",Au.baseUrl),libExports$5.PageConfig.setOption("wsUrl",Au.wsUrl),Au=void 0)},owned:!0}}function createBrowserSandboxService(Au=browserSource()){const lo=signal$2(null),$u=signal$2("idle"),Ru=signal$2(null),Iu=computed$1(()=>({state:$u.value,variant:Au.variant,kernelId:lo.value?.kernel_id})),Ou=computed$1(()=>$u.value==="running");let Pu=null,Du=null,Lu=null,ju=null;async function Bu(){if(Du)return;$u.value="starting",Pu=await Au.acquire();const Fu=await Pu.sessions.startNew({name:"loop",path:"loop.ipynb",type:"notebook",kernel:{name:"python"}});Lu=Fu.kernel,Du=Fu.kernel,lo.value={variant:Au.variant,sandbox_running:!0,kernel_id:Du?.id,kernel_name:"python"},$u.value="running"}return{kind:"browser",snapshot:Iu,status:lo,ready:Ou,lastExecution:Ru,serverUrl:"",getServiceManager:()=>Pu,getKernelConnection:()=>Lu,report(Fu){lo.value=Fu},setState(Fu){$u.value=Fu},connect(){return ju=ju??Bu().catch(Fu=>{throw $u.value="error",lo.value=null,ju=null,Fu}),()=>{Du?.shutdown?.(),Du=null,Lu=null,Pu=Au.owned?null:Pu,Au.release?.(),ju=null,$u.value="idle",lo.value=null}},async execute(Fu){const zu=Date.now();try{if(await(ju??Bu()),!Du)throw new Error("The browser kernel did not start");const qu={outputs:[],stdout:[],error:""},Uu=Du.requestExecute({code:Fu});Uu.onIOPub=Vu=>collect(Vu,qu),await Uu.done;const Hu={code:Fu,success:!qu.error,stdout:qu.stdout.join(""),error:qu.error||void 0,outputs:qu.outputs,startedAt:zu,finishedAt:Date.now()};return Ru.value=Hu,Hu}catch(qu){const Uu={code:Fu,success:!1,error:qu instanceof Error?qu.message:String(qu),startedAt:zu,finishedAt:Date.now()};return Ru.value=Uu,Uu}}}}function summarize(Au,lo){if(!Au)return{state:lo};const $u=Au.variant==="jupyter-server"||Au.variant==="datalayer";return{state:!!Au.sandbox_running||$u&&!!Au.jupyter_connected?"running":lo==="running"?"idle":lo,variant:Au.variant,kernelId:Au.kernel_id,jupyterUrl:Au.jupyter_url,jupyterToken:Au.jupyter_token,agentBaseUrl:Au.agent_base_url}}const RECONNECT_BASE_MS=1e3,RECONNECT_MAX_MS=3e4;function createServerSandboxService(Au){const lo=signal$2(null),$u=signal$2("idle"),Ru=signal$2(void 0),Iu=signal$2(null),Ou=computed$1(()=>({...summarize(lo.value,$u.value),errorReason:$u.value==="error"?Ru.value:void 0})),Pu=computed$1(()=>Ou.value.state==="running");return{kind:"server",connect(Du){if(typeof WebSocket>"u")return()=>{};let Lu=null,ju=null,Bu=0,Fu=!1;const zu=()=>{if(Fu)return;const qu=Au.replace(/^http/,"ws"),Uu=Du?`?agent_id=${encodeURIComponent(Du)}`:"";Lu=new WebSocket(`${qu}/api/v1/configure/sandbox/ws${Uu}`),Lu.onopen=()=>{Bu=0},Lu.onmessage=Hu=>{try{lo.value=JSON.parse(String(Hu.data))}catch{}},Lu.onclose=()=>{if(Fu)return;lo.value=null,Bu+=1;const Hu=Math.min(RECONNECT_BASE_MS*2**(Bu-1),RECONNECT_MAX_MS);ju=setTimeout(zu,Hu)}};return zu(),()=>{Fu=!0,ju&&clearTimeout(ju),Lu?.close(),Lu=null}},snapshot:Ou,status:lo,ready:Pu,lastExecution:Iu,serverUrl:Au,report(Du){lo.value=Du},setState(Du,Lu){$u.value=Du,Ru.value=Du==="error"?Lu:void 0},async execute(Du){const Lu=Date.now();try{const ju=await fetch(`${Au}/api/v1/sandbox/execute`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:Du})}),Bu=ju.ok?await ju.json():null,Fu={code:Du,success:ju.ok&&!Bu?.error,stdout:Bu?.stdout,stderr:Bu?.stderr,error:ju.ok?Bu?.error:`Execution failed: ${ju.status}`,outputs:Bu?.outputs,startedAt:Lu,finishedAt:Date.now()};return Iu.value=Fu,Fu}catch(ju){const Bu={code:Du,success:!1,error:ju instanceof Error?ju.message:String(ju),startedAt:Lu,finishedAt:Date.now()};return Iu.value=Bu,Bu}}}}const ANONYMOUS_JUPYTER_URL="https://prod1.datalayer.run/api/jupyter-server",ANONYMOUS_JUPYTER_TOKEN="60c1661cc408f978c309d04157af55c9588ff9557c9380e4fb50785750703da6",SANDBOX_TARGETS=["browser","local","jupyter","datalayer"];function heldTargetReason(Au,lo){if(Au==="local"&&!lo&&!insideJupyterLab())return"Not offered on the web for now: a local agent and the Jupyter server it starts run beside JupyterLab, not in a page."}const TARGET_SPECS={browser:{label:"Browser",hint:"Python in this page (Pyodide), with the agent loop running here too. Only the model is asked over the network.",hasAgent:!0,noAgentReason:""},local:{label:"Local",hint:"A local agent, with the Jupyter server it starts beside itself.",hasAgent:!0,noAgentReason:"",configure:{variant:"jupyter-server",jupyter_url:"",jupyter_token:""}},jupyter:{label:"Jupyter",hint:"A named Jupyter server: the anonymous one on prod1.datalayer.run.",hasAgent:!1,noAgentReason:"No agent on an anonymous Jupyter server",configure:{variant:"jupyter-server",jupyter_url:ANONYMOUS_JUPYTER_URL,jupyter_token:ANONYMOUS_JUPYTER_TOKEN}},datalayer:{label:"Datalayer",hint:"A Datalayer runtime running the agent this workspace asks for.",hasAgent:!0,noAgentReason:""}};function targetHasAgent(Au){return TARGET_SPECS[Au]?.hasAgent??!1}function targetRunsAgentInPage(Au){return Au==="browser"}function createSwitchableSandboxService({serverUrl:Au,initialTarget:lo="local",kernelSource:$u,localAgent:Ru,blueprint:Iu}){const Ou=signal$2(lo),Pu=createServerSandboxService(Au),Du=createBrowserSandboxService($u??browserSource()),Lu=computed$1(()=>Ou.value==="browser"?Du:Pu);let ju=null,Bu;const Fu=computed$1(()=>Lu.value.snapshot.value),zu=computed$1(()=>Lu.value.status.value),qu=computed$1(()=>Lu.value.ready.value),Uu=computed$1(()=>Lu.value.lastExecution.value);async function Hu(Ku){if(Ku==="local"){const Xu=Iu?.()??Ru?.createPayload;Xu&&await Vu(Xu)}const Zu=TARGET_SPECS[Ku]?.configure;if(!Zu)return;const Qu=TARGET_SPECS[Ku].label;let Yu;try{Yu=await fetch(`${Au}/api/v1/agents/sandbox/configure`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Zu)})}catch(Xu){throw new Error(`${Qu} needs an agent-runtimes server at ${Au}, and nothing answered there. Start one and try again. (${Xu instanceof Error?Xu.message:String(Xu)})`,{cause:Xu})}if(!Yu.ok)throw new Error(`The server could not switch to ${Qu} (${Yu.status} ${Yu.statusText}). `+await detail(Yu));const ed=await fetch(`${Au}/api/v1/agents/sandbox/restart`,{method:"POST"});if(!ed.ok)throw new Error(`The server could not start ${Qu} (${ed.status} ${ed.statusText}). `+await detail(ed))}function Vu(Ku){return ensureServerAgent(Au,Bu,Ku)}function Gu(){if(ju?.(),Ou.peek()==="datalayer"){ju=null,Pu.setState("starting");return}ju=Lu.peek().connect(Bu)}return{get kind(){return Ou.peek()==="browser"?"browser":"server"},target:Ou,snapshot:Fu,status:zu,ready:qu,lastExecution:Uu,serverUrl:Au,getServiceManager:()=>Ou.peek()==="browser"?Du.getServiceManager():null,getKernelConnection:()=>Ou.peek()==="browser"?Du.getKernelConnection():null,report(Ku){Lu.peek().report(Ku)},setState(Ku){Lu.peek().setState(Ku)},execute(Ku){return Lu.peek().execute(Ku)},connect(Ku){Bu=Ku;const Zu=Ou.peek()==="local"&&Ku?Iu?.()??Ru?.createPayload:void 0;if(!Zu)return Gu(),()=>{ju?.(),ju=null};let Qu=!1;return Pu.setState("starting"),Vu(Zu).then(()=>{Qu||Gu()},Yu=>{Qu||(Pu.setState("error"),console.error("[loop] Local agent could not be started:",Yu))}),()=>{Qu=!0,ju?.(),ju=null}},async setTarget(Ku){const Zu=Ou.peek();if(Ku===Zu)return;const Qu=heldTargetReason(Ku,Au);if(Qu)throw new Error(Qu);ju?.(),ju=null;try{await Hu(Ku)}catch(Yu){throw Gu(),Yu}Ou.value=Ku,Gu()}}}async function ensureServerAgent(Au,lo,$u){const Ru=lo?.trim();if(!Ru)throw new Error("Local needs an agent id before its runtime can start.");let Iu;try{Iu=await fetch(`${Au}/api/v1/agents/${encodeURIComponent(Ru)}`)}catch(Pu){throw new Error(`Local needs an agent-runtimes server at ${Au}, and nothing answered there. Start one and try again. (${Pu instanceof Error?Pu.message:String(Pu)})`,{cause:Pu})}if(Iu.ok){await ensureServerSandbox(Au,Ru);return}if(Iu.status!==404)throw new Error(`The server could not inspect local agent ${Ru} (${Iu.status} ${Iu.statusText}). `+await detail(Iu));const Ou=await fetch(`${Au}/api/v1/agents`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({transport:"ag-ui",sandbox_variant:"jupyter-server",...$u,name:Ru})});if(!Ou.ok&&Ou.status!==409)throw new Error(`The server could not launch local agent ${Ru} (${Ou.status} ${Ou.statusText}). `+await detail(Ou));Ou.status===409&&await ensureServerSandbox(Au,Ru)}async function ensureServerSandbox(Au,lo){const $u=await fetch(`${Au}/api/v1/agents/${encodeURIComponent(lo)}/sandbox/ensure`,{method:"POST"});if(!$u.ok)throw new Error(`The server could not start a sandbox for local agent ${lo} (${$u.status} ${$u.statusText}). `+await detail($u))}async function detail(Au){try{const lo=await Au.json();return typeof lo.detail=="string"?lo.detail:""}catch{return""}}function useOptionalTeamSelection(){return useReactorPlatform().getOutput(AGENTS_PLUGIN_NAME)?.team}const NO_TARGET={value:void 0,peek:()=>{}},NO_MEMBER={value:void 0,peek:()=>{}};function AgentSummaryPanel({workspace:Au}){const lo=useSandboxService(),$u=useSignalValue$1(lo?.target??NO_TARGET),Ru=useOptionalTeamSelection(),Iu=useSignalValue$1(Ru?.active??NO_MEMBER);if(!lo)return null;const Ou=Au.sandbox,Pu=Iu?.specId||Au.agentId,Du=AGENTSPECS$1[Pu],Lu={agentName:Iu?.name||Du?.name||Au.agentId,location:$u?TARGET_SPECS[$u].label:"—",specId:Pu,harness:Du?.harness,variant:Ou.variant,status:Ou.state,baseUrl:Ou.agentBaseUrl||Au.serverUrl,sandboxBaseUrl:Ou.jupyterUrl,agentId:Au.agentId,isReady:Ou.state==="running"};return jsxRuntimeExports.jsx(AgentSummary,{summary:Lu})}const RING=14,STROKE=2.5,RADIUS=(RING-STROKE)/2,CIRCUMFERENCE=2*Math.PI*RADIUS,DEFAULT_WARN_AT=.25,DEFAULT_DANGER_AT=.1,DEFAULT_PULSE_AT=.05,PULSE_MS=1200;function format(Au){const lo=Math.max(0,Math.ceil(Au/1e3)),$u=Math.floor(lo/60),Ru=lo%60;return`${$u}:${String(Ru).padStart(2,"0")}`}function AnonymousKeyTimer({expiresAt:Au,grantedMs:lo,label:$u="Trial key",warnAt:Ru=DEFAULT_WARN_AT,dangerAt:Iu=DEFAULT_DANGER_AT,pulseAt:Ou=DEFAULT_PULSE_AT,onExpire:Pu}){const[Du,Lu]=reactExports.useState(()=>Date.now()),ju=reactExports.useRef(lo??Math.max(1,Au-Date.now())),Bu=reactExports.useRef(!1);reactExports.useEffect(()=>{const Hu=window.setInterval(()=>{Lu(Vu=>{const Gu=Date.now(),Ku=Zu=>Math.ceil((Au-Zu)/1e3);return Ku(Gu)===Ku(Vu)?Vu:Gu})},250);return()=>window.clearInterval(Hu)},[Au]);const Fu=Math.max(0,Au-Du);reactExports.useEffect(()=>{Fu>0||Bu.current||(Bu.current=!0,Pu?.())},[Fu,Pu]);const zu=Math.min(1,Math.max(0,Fu/ju.current)),qu=zu<=Ou,Uu=zu<=Iu?"danger.fg":zu<=Ru?"attention.fg":"fg.muted";return jsxRuntimeExports.jsxs(Box,{display:"inline-flex",alignItems:"center",gap:1,px:2,py:"2px",borderRadius:"999px",border:"1px solid",borderColor:"border.muted",bg:"canvas.subtle",color:Uu,fontVariantNumeric:"tabular-nums",sx:{...qu?{"@keyframes dla-key-pulse":{"0%, 100%":{opacity:1},"50%":{opacity:.45}},animation:`dla-key-pulse ${PULSE_MS}ms ease-in-out infinite`,"@media (prefers-reduced-motion: reduce)":{animation:"none"}}:null},title:`${$u}: this workspace is talking to the agent on a temporary key issued to nobody in particular. When it runs out the chat asks you to sign in. Sign in now for an account of your own.`,children:[jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",color:Uu,children:jsxRuntimeExports.jsx(KeyIcon,{size:12})}),jsxRuntimeExports.jsxs(Box,{as:"svg","aria-hidden":"true",focusable:"false",width:RING,height:RING,viewBox:`0 0 ${RING} ${RING}`,display:"block",flexShrink:0,children:[jsxRuntimeExports.jsx("circle",{cx:RING/2,cy:RING/2,r:RADIUS,fill:"none",stroke:"currentColor",strokeWidth:STROKE,opacity:.2}),jsxRuntimeExports.jsx("circle",{cx:RING/2,cy:RING/2,r:RADIUS,fill:"none",stroke:"currentColor",strokeWidth:STROKE,strokeLinecap:"round",strokeDasharray:CIRCUMFERENCE,strokeDashoffset:CIRCUMFERENCE*(1-zu),transform:`rotate(-90 ${RING/2} ${RING/2})`,style:{transition:"stroke-dashoffset 0.5s linear"}})]}),jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:Uu,fontWeight:"semibold"},children:format(Fu)})]})}function AnonymousKeyHeaderBadge({workspace:Au}){return jsxRuntimeExports.jsx(Box,{order:1,display:"inline-flex",alignItems:"center",children:jsxRuntimeExports.jsx(AnonymousKeyBadge,{workspace:Au})})}function AnonymousKeyBadge({workspace:Au}){const lo=useAnonymousSession(),$u=Au.sandbox.target??"local";return!targetRunsAgentInPage($u)||lo.status==="idle"||lo.status==="expired"?null:lo.expiresAt?jsxRuntimeExports.jsx(AnonymousKeyTimer,{expiresAt:lo.expiresAt,grantedMs:lo.grantedMs,onExpire:()=>useAnonymousSessionStore.getState().expire()}):jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:lo.error?"danger.fg":"fg.muted"},title:lo.error,children:lo.error?"No trial key":"Getting a trial key…"})}function SandboxSelector(Au){const lo=useOptionalSandboxService(),[$u,Ru]=reactExports.useState(!1),[Iu,Ou]=reactExports.useState(null),Pu=useSignalValue$1(lo?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Du=useSignalValue$1(lo?.status??EMPTY_STATUS),Lu=useSignalValue$1(lo?.target??DEFAULT_TARGET),ju=reactExports.useCallback(async Fu=>{if(!(!lo||Fu===Lu)){Ru(!0),Ou(null);try{await lo.setTarget(Fu)}catch(zu){Ou(zu instanceof Error?zu.message:String(zu))}finally{Ru(!1)}}},[lo,Lu]);if(!lo)return null;const Bu=Math.max(0,SANDBOX_TARGETS.indexOf(Lu));return jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,minWidth:0,children:[jsxRuntimeExports.jsx(Box,{width:16,flexShrink:0,display:"flex",justifyContent:"center",children:$u?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):null}),jsxRuntimeExports.jsx(KernelIndicator,{state:sandboxIndicatorState(Pu.state,Du?.execution_state,Du?.is_executing),kernelId:Pu.kernelId??Du?.kernel_id,kernelName:Du?.kernel_name,serverUrl:Pu.jupyterUrl??Du?.jupyter_url,websocketUrl:toWebsocketUrl(Pu.jupyterUrl??Du?.jupyter_url),environmentName:TARGET_SPECS[Lu].label,overlayTitle:`${TARGET_SPECS[Lu].label} Kernel`,position:"se",bordered:!1}),jsxRuntimeExports.jsx(SegmentedControl,{"aria-label":"Where code runs",size:"small",style:{listStyle:"none",margin:0,padding:0},sx:{listStyle:"none",m:0,p:0,"& > li":{listStyle:"none"},"& > li::marker":{content:"none"}},children:SANDBOX_TARGETS.map((Fu,zu)=>{const qu=heldTargetReason(Fu,lo?.serverUrl??"");return jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:zu===Bu,"aria-disabled":qu?!0:void 0,"data-sandbox-target":Fu,"data-sandbox-target-held":qu?"":void 0,sx:{listStyle:"none",...qu?{color:"fg.subtle",cursor:"not-allowed"}:null},title:qu??TARGET_SPECS[Fu].hint,onClick:()=>qu?void 0:void ju(Fu),children:TARGET_SPECS[Fu].label},Fu)})}),Iu||Pu.errorReason?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"danger.fg",lineHeight:1.3,maxWidth:280,minWidth:0},title:Iu??Pu.errorReason,children:Iu??Pu.errorReason}):jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},title:TARGET_SPECS[SANDBOX_TARGETS[Bu]].hint,children:Pu.state})]})}function toWebsocketUrl(Au){return Au?.replace(/^http/,"ws")}const EMPTY_STATUS={value:null,peek:()=>null},DEFAULT_TARGET={value:"local",peek:()=>"local"};function MemberIcon({icon:Au}){const lo=agentIcon(Au);return jsxRuntimeExports.jsx(lo,{})}function TeamMemberPicker(){const Au=useOptionalTeamSelection();return!Au||Au.members.length<2?null:jsxRuntimeExports.jsx(TeamMemberMenu,{selection:Au})}function TeamMemberMenu({selection:Au}){const[lo,$u]=reactExports.useState(!1),Ru=useSignalValue$1(Au.selected),Iu=Au.members.find(Ou=>Ou.id===Ru);return jsxRuntimeExports.jsx(AnchoredOverlay,{width:"large",open:lo,onOpen:()=>$u(!0),onClose:()=>$u(!1),renderAnchor:Ou=>jsxRuntimeExports.jsx(IconButton,{...Ou,"aria-labelledby":void 0,icon:ForwardRef$3,"aria-label":Iu?`Talking to ${Iu.name}. Choose another agent.`:"Choose an agent",variant:"invisible",size:"small"}),children:jsxRuntimeExports.jsx(Box,{width:440,maxWidth:"calc(100vw - 16px)",children:jsxRuntimeExports.jsxs(ActionList,{selectionVariant:"single",role:"listbox","aria-label":`Agents in ${Au.team.name}`,children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:Au.team.name}),Au.members.map(Ou=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Ou.id===Ru,onSelect:()=>{Au.select(Ou.id),$u(!1)},children:[jsxRuntimeExports.jsx(ActionList.LeadingVisual,{children:jsxRuntimeExports.jsx(MemberIcon,{icon:Ou.icon})}),jsxRuntimeExports.jsxs(Box,{as:"span",display:"flex",alignItems:"center",gap:2,children:[Ou.name,Ou.isSupervisor?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:"supervisor"}):null]}),Ou.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",sx:{display:"block",whiteSpace:"normal",overflowWrap:"anywhere",minWidth:0},children:Ou.description}):null]},Ou.id))]})})})}function specIdOf(Au){return(Au??"").split(":")[0]??""}function teamMembers(Au){const lo=specIdOf(Au.supervisor?.ref),$u=Iu=>{const Ou=AGENTSPECS$1[Iu];return{description:Ou?.description,emoji:Ou?.emoji,icon:Ou?.icon}},Ru=(Au.agents??[]).map(Iu=>{const Ou=specIdOf(Iu.ref);return{id:Iu.id,name:Iu.name||Ou||Iu.id,specId:Ou,isSupervisor:Ou!==""&&Ou===lo,...$u(Ou)}});return[...Ru.filter(Iu=>Iu.isSupervisor),...Ru.filter(Iu=>!Iu.isSupervisor)]}function createTeamSelection(Au){const lo=TEAM_SPECS[Au];if(!lo)return;const $u=teamMembers(lo);if($u.length===0)return;const Ru=signal$2($u[0].id);return{team:lo,members:$u,selected:Ru,select:Iu=>{$u.some(Ou=>Ou.id===Iu)&&(Ru.value=Iu)},sharing:lo.context?.sharing??"shared",active:computed$1(()=>$u.find(Iu=>Iu.id===Ru.value))}}function subagentsFor(Au,lo){const $u=teamMembers(Au),Ru=$u.find(Lu=>Lu.id===lo);if(!Ru)return[];const Iu=(Lu,ju,Bu)=>{const Fu=AGENTSPECS$1[ju];if(Fu)return{name:Lu,description:Bu||Fu.description||Lu,instructions:Fu.systemPrompt,model:Fu.model,icon:Fu.icon}},Ou=Ru.isSupervisor||Au.delegation?.allowPeerDelegation?$u.filter(Lu=>Lu.id!==lo).map(Lu=>Iu(Lu.name,Lu.specId,Lu.description)):[],Du=((Au.agents??[]).find(Lu=>Lu.id===lo)?.subagents??[]).map(Lu=>Iu(Lu.name,(Lu.ref??"").split(":")[0]??"",Lu.description));return[...Ou,...Du].filter(Boolean)}const AGENTS_PLUGIN_NAME="@datalayer/loop-plugin-agents",offeredTarget=(Au,lo)=>heldTargetReason(Au,lo)?"browser":Au,AgentsPlugin={name:AGENTS_PLUGIN_NAME,displayName:"Agents",description:"Where the agent and its code run: this page, a local server, or a Datalayer runtime.",octicon:"container",emoji:"📦",config:{serverUrl:"",target:"local"},contributionPoints:[LoopAgentBlueprint],preserveOutput:!0,build({config:Au,reactor:lo}){const $u=Au.showAgentVariants??!0,Ru=Au.teamId?createTeamSelection(Au.teamId):void 0;return{team:Ru,sandbox:createSwitchableSandboxService({serverUrl:Au.serverUrl,initialTarget:offeredTarget(($u||Au.targetFixed?Au.target:"browser")??"local",Au.serverUrl),kernelSource:Au.kernelSource,localAgent:Au.localAgent,blueprint:()=>{const Iu=lo.getContributions(LoopAgentBlueprint)[0]?.value;if(Iu)return{...Iu.specId?{agent_spec_id:Iu.specId}:null,...Iu.createPayload}}}),components:[{slot:LoopSlots.status,id:"sandbox-status",Component:SandboxStatusBridge},{slot:LoopSlots.status,id:"datalayer-agent",Component:DatalayerAgentMount},...Ru&&Au.showTeamPicker!==!1?[{slot:LoopSlots.header,id:"team-member-picker",Component:TeamMemberPicker}]:[],...$u?[{slot:LoopSlots.header,id:"sandbox-selector",Component:SandboxSelector}]:[],...Au.showAgentSummary===!1?[]:[{slot:LoopSlots.header,id:"agent-summary",Component:AgentSummaryPanel}],{slot:LoopSlots.chatHeader,id:"anonymous-key",Component:AnonymousKeyBadge},{slot:LoopSlots.header,id:"anonymous-key-header",Component:AnonymousKeyHeaderBadge}]}},register({contribute:Au,state:lo}){const $u=lo.getOutput()?.sandbox;if($u)return Au(LoopAgentGate,{check:Ru=>{const Iu=Ru.sandbox.target??$u.target.peek();return targetHasAgent(Iu)||TARGET_SPECS[Iu].noAgentReason}},{id:"sandbox-target"})},contributes:[contribution(LoopViewType,{viewType:"sandbox",title:"Sandbox",icon:ServerIcon,order:40,load:()=>__vitePreload(()=>import("./chunks/SandboxView-IYT-IKM6.js"),[],import.meta.url)},{id:"sandbox",order:40}),contribution(LoopCommand,{name:"sandbox",aliases:["code-sandbox"],description:"Show the code sandbox: variant, kernel, Jupyter server",group:"Capabilities",run:async({workspace:Au})=>{Au.setActiveViewType("sandbox")}},{id:"sandbox"})]},PULSE_ANIMATION="loop-subagent-pulse",KEYFRAMES=`@keyframes ${PULSE_ANIMATION} {
3600
3600
  0%, 100% { opacity: 0.25; }
3601
3601
  50% { opacity: 1; }
3602
3602
  }`;function SubagentPulse(){const Au=useAgentRuntimeActiveSubagentToolCallId(),lo=useAgentRuntimeSubagentActivity(Au??void 0),$u=useOptionalReactorPlatform(),Ru=lo[0]?.subagentName??Au??"",Iu=$u?.getOutput(AGENTS_PLUGIN_NAME)?.team?.members.find(Lu=>Lu.name===Ru),Ou=agentIcon(Iu?.icon);if(!Au)return null;const Du=lo.some(Lu=>Lu.transport==="a2a")?`${Ru} is working over A2A…`:`${Ru} is working…`;return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("style",{children:KEYFRAMES}),jsxRuntimeExports.jsx(Tooltip,{text:Du,direction:"n",children:jsxRuntimeExports.jsx(Box,{as:"button",type:"button","aria-label":Du,"data-subagent-pulse":Ru,display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,p:0,border:0,bg:"transparent",color:"accent.fg",cursor:"default",animation:`${PULSE_ANIMATION} 1.4s ease-in-out infinite`,children:jsxRuntimeExports.jsx(Ou,{size:16})})})]})}const SUBAGENT_ACTIVITY_PLUGIN_NAME="@datalayer/loop-plugin-subagent-activity",SubagentActivityPlugin={name:SUBAGENT_ACTIVITY_PLUGIN_NAME,displayName:"Subagent activity",description:"A delegated agent's icon, pulsing in the prompt's header while it works.",octicon:"people",emoji:"👥",dependencies:[InputPromptPlugin],build:()=>({components:[{id:"subagent-pulse",slot:LoopSlots.inpromptMenu,order:0,Component:SubagentPulse}]})},A2UI_PLUGIN_NAME="@datalayer/loop-plugin-a2ui",A2uiPlugin={name:A2UI_PLUGIN_NAME,displayName:"A2UI surfaces",description:"The last execution, rendered as a surface rather than dumped.",octicon:"browser",emoji:"🖼",dependencies:[AgentsPlugin],contributes:[contribution(LoopViewType,{viewType:"a2ui",title:"Surface",icon:BrowserIcon,order:30,canOpen:Au=>Au.sandbox.state==="running"&&Au.sandbox.variant!=="pyodide",unavailableReason:Au=>Au.sandbox.variant==="pyodide"?"Surfaces are rendered by the server; this sandbox runs in the browser":"Needs a running sandbox",load:()=>__vitePreload(()=>import("./chunks/A2uiView-BmARc3pT.js"),[],import.meta.url)},{id:"a2ui",order:30}),contribution(LoopCommand,{name:"a2ui",aliases:["surface"],description:"Show the last execution as a rendered surface",group:"Open",keybinding:"Mod+Alt+U",run:async({workspace:Au})=>{Au.setActiveViewType("a2ui")}},{id:"a2ui"})]},NONE_VIEW="none";let state={viewId:NONE_VIEW,options:[],allowNone:!0},announcer=()=>!0;const listeners=new Set;function notify(){for(const Au of[...listeners])Au()}function getViewChoice(){return state}function subscribeViewChoice(Au){return listeners.add(Au),()=>{listeners.delete(Au)}}function setViewAnnouncer(Au){const lo=announcer;return announcer=Au,()=>{announcer=lo}}function setViewOptions(Au,lo=!0){if(lo===state.allowNone&&Au.length===state.options.length&&Au.every((Ru,Iu)=>Ru===state.options[Iu]))return;state={viewId:!lo&&!Au.includes(state.viewId)?Au[0]??NONE_VIEW:state.viewId,options:Au,allowNone:lo},notify()}function chooseView(Au){return state={...state,viewId:Au},notify(),announcer(Au)}function seedViewChoice(Au){state.viewId!==Au&&(state={...state,viewId:Au},notify())}function nextView(){const Au=state.allowNone?[NONE_VIEW,...state.options]:[...state.options];if(Au.length===0)return NONE_VIEW;const lo=Au.indexOf(state.viewId);return Au[(lo+1)%Au.length]}function ViewSelector({point:Au,describe:lo,context:$u,noneLabel:Ru,ariaLabel:Iu,allowNone:Ou=!0}){const Pu=useContributions(Au),Du=reactExports.useSyncExternalStore(subscribeViewChoice,getViewChoice),[Lu,ju]=reactExports.useState(null),Bu=reactExports.useRef(null),Fu=()=>{Bu.current!==null&&(window.clearTimeout(Bu.current),Bu.current=null)},zu=Vu=>{Fu(),ju(Vu)},qu=()=>{Fu(),Bu.current=window.setTimeout(()=>{ju(null),Bu.current=null},250)};reactExports.useEffect(()=>Fu,[]);const Uu=reactExports.useMemo(()=>Pu.map(Vu=>lo(Vu.value,$u)).sort((Vu,Gu)=>(Vu.order??100)-(Gu.order??100)),[Pu,lo,$u]);if(reactExports.useEffect(()=>{setViewOptions(Uu.map(Vu=>Vu.id),Ou)},[Uu,Ou]),Uu.length<(Ou?1:2))return null;const Hu=Uu.find(Vu=>Vu.id===Lu&&Vu.details);return jsxRuntimeExports.jsxs(Box$1,{sx:{marginLeft:"auto",display:"flex",alignItems:"center",position:"relative"},children:[jsxRuntimeExports.jsxs(SegmentedControl,{"aria-label":Iu,size:"small",children:[Ou?jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:Du.viewId===NONE_VIEW,onClick:()=>chooseView(NONE_VIEW),children:Ru}):null,Uu.map(Vu=>jsxRuntimeExports.jsx(SegmentedControl.Button,{selected:Du.viewId===Vu.id,"aria-disabled":Vu.disabled||void 0,title:Vu.disabled?Vu.disabledReason:Vu.title,leadingIcon:Vu.icon,onMouseEnter:Vu.details?()=>zu(Vu.id):void 0,onMouseLeave:Vu.details?qu:void 0,onClick:()=>{Vu.disabled||chooseView(Vu.id)},children:Vu.badge?`${Vu.title} (${Vu.badge})`:Vu.title},Vu.id))]}),Hu?jsxRuntimeExports.jsx(Box$1,{onMouseEnter:Fu,onMouseLeave:qu,sx:{position:"absolute",top:"calc(100% + 6px)",right:0,minWidth:260,maxWidth:380,maxHeight:320,overflowY:"auto",p:2,bg:"canvas.overlay",border:"1px solid",borderColor:"border.default",borderRadius:2,boxShadow:"shadow.large",zIndex:40,fontSize:0,color:"fg.default",textAlign:"left"},children:Hu.details}):null]})}const SHELL_PLUGIN_NAME$1="@datalayer/reactor-shell",ShellView=defineContributionPoint("reactor.shell.view"),describeAsIs=Au=>Au,ShellPlugin$1={name:SHELL_PLUGIN_NAME$1,displayName:"Shell",description:"A view point, its selector, and the choice as a command.",octicon:"columns",emoji:"📑",config:{point:ShellView,describe:describeAsIs,slot:"header",defaultView:NONE_VIEW,showSelector:!0,allowNone:!0,noneLabel:"None",ariaLabel:"View",announce:()=>!0,commandId:"shell.cycleView",commandName:"Switch the view",commandDescription:"Cycle through the contributed views, and none",keybinding:"Mod+Alt+E"},contributionPoints:[ShellView],register:({config:Au,registerCommand:lo})=>{const $u=setViewAnnouncer(Au.announce),Ru=lo({id:Au.commandId,name:Au.commandName,description:Au.commandDescription,emoji:"📑",category:"Workspace",keybinding:Au.keybinding||void 0,execute:()=>{chooseView(nextView())}});return()=>{$u(),Ru()}},build:({config:Au})=>(seedViewChoice(Au.defaultView||NONE_VIEW),{components:Au.showSelector?[{id:"view-selector",slot:Au.slot,Component:lo=>jsxRuntimeExports.jsx(ViewSelector,{point:Au.point,describe:Au.describe,context:lo,noneLabel:Au.noneLabel,allowNone:Au.allowNone,ariaLabel:Au.ariaLabel})}]:[]})};setViewAnnouncer(requestSurface);const NONE_EDITOR=NONE_VIEW;let mappedFor=null,mapped=null;function getEditorChoice(){const Au=getViewChoice();return(Au!==mappedFor||!mapped)&&(mappedFor=Au,mapped={editorId:Au.viewId,options:Au.options}),mapped}const subscribeEditorChoice=subscribeViewChoice,setEditorOptions=setViewOptions,chooseEditor=chooseView,seedEditorChoice=seedViewChoice,nextEditor=nextView;let jupyterReact=null;function loadJupyterReact(){return jupyterReact?Promise.resolve(jupyterReact):__vitePreload(()=>import("./chunks/index-CNx_s591.js").then(Au=>Au.r),[],import.meta.url).then(Au=>(jupyterReact=Au,Au))}const PREVIEW_LENGTH=56;function stripped(Au){const $u=(Au.split(`
@@ -3759,14 +3759,14 @@ ${Du}`:zu,inputs:Du,clear:Pu?[]:[DRAFT.path],loop:Bu()}:{refused:"Nothing to sen
3759
3759
  }
3760
3760
  `;function usePaletteStyles(){reactExports.useEffect(()=>{if(typeof document>"u"||document.getElementById(STYLE_ELEMENT_ID))return;const Au=document.createElement("style");Au.id=STYLE_ELEMENT_ID,Au.textContent=PALETTE_CSS,document.head.appendChild(Au)},[])}function rank(Au,lo){if(!lo)return{command:Au,score:0};const $u=lo.toLowerCase(),Ru=[[Au.name.toLowerCase(),0],[Au.id.toLowerCase(),100],[(Au.category??"").toLowerCase(),200],[(Au.description??"").toLowerCase(),300]];for(const[Iu,Ou]of Ru){const Pu=Iu.indexOf($u);if(Pu>=0)return{command:Au,score:Ou+Pu}}return null}const PRIMER_PORTAL_ROOT_ID="__primerPortalRoot__";function paletteRoot(){return document.getElementById(PRIMER_PORTAL_ROOT_ID)??document.body}const LIST_ID="dla-cmdk-list",optionId=Au=>`dla-cmdk-option-${Au}`,PALETTE_KEYBINDING="Mod+K",PALETTE_CHORD=parseKeybinding(PALETTE_KEYBINDING);function CommandPalette(){const Au=useReactorPlatform(),lo=useCommands();usePaletteStyles();const[$u,Ru]=reactExports.useState(!1),[Iu,Ou]=reactExports.useState(""),[Pu,Du]=reactExports.useState(0),[Lu,ju]=reactExports.useState(null),[Bu,Fu]=reactExports.useState(null),zu=reactExports.useRef(null),qu=reactExports.useMemo(()=>lo.map(Ku=>rank(Ku,Iu)).filter(Ku=>Ku!==null).sort((Ku,Zu)=>Ku.score-Zu.score).map(Ku=>Ku.command),[lo,Iu]),Uu=reactExports.useCallback(()=>{Ru(!1),Ou(""),Du(0),Fu(null)},[]),Hu=reactExports.useCallback(async Ku=>{ju(Ku.id),Fu(null);try{await Au.executeCommand(Ku.id),Uu()}catch(Zu){Fu(Zu instanceof Error?Zu.message:String(Zu))}finally{ju(null)}},[Uu,Au]);if(reactExports.useEffect(()=>{const Ku=lo.map(Yu=>{const ed=Yu.keybinding?parseKeybinding(Yu.keybinding):null;return ed?{chord:ed,id:Yu.id}:null}).filter(Yu=>Yu!==null),Zu=isApplePlatform();function Qu(Yu){if(PALETTE_CHORD&&matchesKeybinding(Yu,PALETTE_CHORD,Zu)){Yu.preventDefault(),Yu.stopPropagation(),Ru(ed=>!ed);return}if(Yu.key==="Escape"){Ru(ed=>ed&&!1);return}if(!$u){for(const ed of Ku)if(matchesKeybinding(Yu,ed.chord,Zu)){Yu.preventDefault(),Yu.stopPropagation();const Xu=Au.getCommand(ed.id);Xu&&Xu.isEnabled?.()!==!1&&Au.executeCommand(ed.id).catch(rd=>{console.error(`Command ${ed.id} failed`,rd)});return}}}return document.addEventListener("keydown",Qu,{capture:!0}),()=>document.removeEventListener("keydown",Qu,{capture:!0})},[lo,$u,Au]),reactExports.useEffect(()=>{if(!$u)return;Ou(""),Du(0),Fu(null);const Ku=window.requestAnimationFrame(()=>zu.current?.focus());return()=>window.cancelAnimationFrame(Ku)},[$u]),reactExports.useEffect(()=>{Du(Ku=>Ku>=qu.length?0:Ku)},[qu.length]),!$u||typeof document>"u")return null;const Vu=Ku=>{if(Ku.key==="ArrowDown")Ku.preventDefault(),Du(Zu=>qu.length===0?0:(Zu+1)%qu.length);else if(Ku.key==="ArrowUp")Ku.preventDefault(),Du(Zu=>qu.length===0?0:(Zu-1+qu.length)%qu.length);else if(Ku.key==="Enter"){Ku.preventDefault();const Zu=qu[Pu];Zu&&Zu.isEnabled?.()!==!1&&Hu(Zu)}},Gu=jsxRuntimeExports.jsx("div",{className:"dla-cmdk-backdrop",onClick:Uu,children:jsxRuntimeExports.jsxs("div",{className:"dla-cmdk-panel",role:"dialog","aria-modal":"true","aria-label":"Command palette",onClick:Ku=>Ku.stopPropagation(),children:[jsxRuntimeExports.jsx("div",{className:"dla-cmdk-search",children:jsxRuntimeExports.jsx("input",{ref:zu,className:"dla-cmdk-input",type:"text",placeholder:"Run a command…","aria-label":"Search commands",autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1,role:"combobox","aria-expanded":!0,"aria-controls":LIST_ID,"aria-autocomplete":"list","aria-activedescendant":qu.length>0?optionId(Pu):void 0,value:Iu,onChange:Ku=>Ou(Ku.target.value),onKeyDown:Vu})}),Bu!==null&&jsxRuntimeExports.jsx("div",{className:"dla-cmdk-error",children:Bu}),jsxRuntimeExports.jsx("ul",{className:"dla-cmdk-list",id:LIST_ID,role:"listbox",children:qu.length===0?jsxRuntimeExports.jsx("li",{className:"dla-cmdk-empty",children:lo.length===0?"No plugin has registered a command yet.":`Nothing matches “${Iu}”.`}):qu.map((Ku,Zu)=>{const Qu=Ku.isEnabled?.()!==!1;return jsxRuntimeExports.jsx("li",{children:jsxRuntimeExports.jsxs("button",{type:"button",className:"dla-cmdk-item",id:optionId(Zu),role:"option","aria-selected":Zu===Pu,"aria-disabled":!Qu,disabled:!Qu,onMouseEnter:()=>Du(Zu),onClick:()=>{Hu(Ku)},children:[jsxRuntimeExports.jsx("span",{className:"dla-cmdk-mark","aria-hidden":"true",children:Ku.emoji??"·"}),jsxRuntimeExports.jsxs("span",{className:"dla-cmdk-text",children:[jsxRuntimeExports.jsx("span",{className:"dla-cmdk-name",children:Ku.name}),Ku.description&&jsxRuntimeExports.jsx("p",{className:"dla-cmdk-description",children:Ku.description})]}),Lu===Ku.id&&jsxRuntimeExports.jsx("span",{className:"dla-cmdk-meta",children:"running…"}),Ku.keybinding&&jsxRuntimeExports.jsx("kbd",{className:"dla-cmdk-key",children:formatKeybinding(Ku.keybinding)}),Ku.category&&jsxRuntimeExports.jsx("span",{className:"dla-cmdk-meta",children:Ku.category})]})},Ku.id)})}),jsxRuntimeExports.jsxs("div",{className:"dla-cmdk-footer",children:[jsxRuntimeExports.jsxs("span",{children:["↑↓ to move · ↵ to run · esc to close ·"," ",jsxRuntimeExports.jsx("kbd",{className:"dla-cmdk-key",children:formatKeybinding(PALETTE_KEYBINDING)})," ","to reopen"]}),jsxRuntimeExports.jsxs("span",{children:[qu.length," of ",lo.length]})]})]})});return reactDomExports.createPortal(Gu,paletteRoot())}const CommandsPlugin={name:"@datalayer/reactor-commands",version:"1.0.0",displayName:"Commands",description:"A command palette: Ctrl-K opens a floating search over every command plugins have registered.",octicon:"command-palette",emoji:"⌘",build(){return{components:[{slot:"root",id:"command-palette",Component:CommandPalette}]}},commands:[{id:"commands.showPalette",name:"Show the command palette",description:"The same thing Ctrl-K does — listed so it is discoverable",emoji:"⌘",category:"Commands",keybinding:PALETTE_KEYBINDING,execute:()=>{document.dispatchEvent(new KeyboardEvent("keydown",{key:"k",ctrlKey:!0,bubbles:!0}))}}]},COMMANDS_PLUGIN_NAME="@datalayer/loop-plugin-commands",DEFAULT_CATEGORY="Workspace",GROUP_EMOJI={Agents:"🤖",Open:"📂",Session:"🧭",Workspace:"🪟"};function LoopCommandBridge({workspace:Au,sync:lo}){const $u=useContributions(LoopCommand);return reactExports.useEffect(()=>{lo($u,Au)},[$u,Au,lo]),null}const LoopCommandsPlugin={name:COMMANDS_PLUGIN_NAME,displayName:"Command palette",description:"Puts the workspace commands in a Ctrl-K palette, beside every plugin that registers one.",octicon:"command-palette",emoji:"⌘",dependencies:[CommandsPlugin,ThemePlugin],build:Au=>{const lo=new Map;let $u="",Ru;const Iu=(Ou,Pu)=>{const Du=Pu?Ou.map(Lu=>`${Lu.plugin}:${Lu.value.name}`).join("|"):"";if(!(Du===$u&&Pu===Ru)){$u=Du,Ru=Pu;for(const Lu of lo.values())Lu();if(lo.clear(),!!Pu)for(const Lu of Ou){const ju=Lu.value,Bu=ju.group??DEFAULT_CATEGORY;lo.set(ju.name,Au.registerCommand({id:`loop.${ju.name}`,name:ju.description,description:`/${ju.name}`,emoji:GROUP_EMOJI[Bu]??"💠",category:Bu,keybinding:ju.keybinding,execute:async()=>{await ju.run({workspace:Pu,argv:""})}}))}}};return{components:[{id:"loop-command-bridge",slot:LoopSlots.status,Component:({workspace:Ou})=>jsxRuntimeExports.jsx(LoopCommandBridge,{workspace:Ou,sync:Iu})}]}}},MODELS_PLUGIN_NAME="@datalayer/loop-plugin-models",ModelsPlugin={name:MODELS_PLUGIN_NAME,displayName:"Models",description:"Which model answers, from the agentspecs catalog.",octicon:"cpu",emoji:"🧠",contributes:[contribution(LoopCommand,{name:"models",aliases:["model"],description:"Show the models available to this session",group:"Agents",keybinding:"Mod+Alt+M",run:async({workspace:Au})=>{const lo=await fetch(`${Au.serverUrl}/api/v1/configure/models`);if(!lo.ok)return{content:"The model catalogue is unavailable."};const $u=await lo.json();return{content:`${($u.models??[]).filter(Iu=>Iu.available!==!1).length} of ${($u.models??[]).length} models are ready. Pick one under the prompt.`}}},{id:"models"})]},WINDOW_CONTROLS_SLOT="loop.window.controls",WINDOW_ACTIONS_SLOT="loop.window.actions";function WindowFrame({children:Au,title:lo,height:$u,slotProps:Ru={}}){const Iu=useOptionalSlotComponents(WINDOW_ACTIONS_SLOT);return jsxRuntimeExports.jsxs(Box,{position:"relative",borderRadius:"14px",overflow:"hidden",border:"1px solid",borderColor:"border.default",bg:"canvas.default",boxShadow:"0 24px 60px -28px rgba(0, 0, 0, 0.55)",height:$u===void 0?"100%":void 0,display:$u===void 0?"flex":void 0,flexDirection:$u===void 0?"column":void 0,children:[jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",gap:2,px:3,py:2,borderBottom:"1px solid",borderColor:"border.default",bg:"canvas.subtle",flexWrap:"wrap",rowGap:2,flex:"0 0 auto",children:[jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",gap:"6px",mr:1,flexShrink:0,children:jsxRuntimeExports.jsx(ReactorSlot,{slot:WINDOW_CONTROLS_SLOT,props:Ru})}),jsxRuntimeExports.jsx(Box,{minWidth:0,flex:"1 1 auto",children:lo}),Iu.length>0?jsxRuntimeExports.jsx(Box,{display:"flex",alignItems:"center",gap:2,flexShrink:0,ml:"auto",children:jsxRuntimeExports.jsx(ReactorSlot,{slot:WINDOW_ACTIONS_SLOT,props:Ru})}):null]}),jsxRuntimeExports.jsx(Box,{sx:$u===void 0?{flex:"1 1 auto",minHeight:0}:{height:$u,minHeight:0},children:Au})]})}const WINDOW_FRAME_PLUGIN_NAME="@datalayer/loop-plugin-window-frame";function WindowControls(){return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:["danger.emphasis","attention.emphasis","success.emphasis"].map(Au=>jsxRuntimeExports.jsx(Box,{width:10,height:10,borderRadius:"50%",bg:Au},Au))})}const WindowFramePlugin={name:WINDOW_FRAME_PLUGIN_NAME,displayName:"Window frame",description:"Draws Loop as a window, and opens its title bar to controls and actions.",octicon:"browser",emoji:"🪟",build:()=>({components:[{id:"window-controls",slot:WINDOW_CONTROLS_SLOT,Component:WindowControls},{id:"full-screen",slot:LoopSlots.header,Component:WorkspaceFullScreenAction}]})},DOCUMENT_PLUGIN_NAME="@datalayer/loop-plugin-document",DocumentPlugin={name:DOCUMENT_PLUGIN_NAME,displayName:"Document editor",description:"A rich-text document beside the chat, driven by the agent.",octicon:"file",emoji:"📄",dependencies:[AgentsPlugin],contributionPoints:[LoopDocumentToolbar,LoopOpeningDocument],contributes:[contribution(LoopEditorView,{surfaceId:"document",title:"Document",icon:FileIcon,order:20,canOpen:Au=>Au.sandbox.state==="running",unavailableReason:()=>"Needs a running sandbox",load:()=>__vitePreload(()=>import("./chunks/DocumentView-BKzeMFBq.js"),[],import.meta.url)},{id:"document",order:20}),contribution(LoopCommand,{name:"document",description:"Open the document beside the chat",group:"Open",keybinding:"Mod+Alt+O",run:async({workspace:Au})=>{if(Au.setActiveViewType("chat"),!requestSurface("document"))throw new Error("No chat is on screen to open the document beside.")}},{id:"document"})],build:Au=>(__vitePreload(async()=>{const{createLexicalTools:lo}=await import("./chunks/lexicalHooks-kxLGr2aO.js");return{createLexicalTools:lo}},[],import.meta.url).then(({createLexicalTools:lo})=>{Au.contribute(LoopFrontendTool,{id:"document-tools",tools:$u=>lo($u.surfaceId)},{id:"document-tools"})},lo=>{console.warn("The document tools could not be loaded",lo)}),{})},DOCUMENT_TOOLBAR_PLUGIN_NAME="@datalayer/loop-plugin-document-toolbar",DocumentToolbarPlugin=defineLazyPlugin({name:DOCUMENT_TOOLBAR_PLUGIN_NAME,displayName:"Document toolbar",description:"Shows what the document’s code blocks run on.",octicon:"circle",emoji:"🔵",activationEvents:[onContributionPoint(LoopDocumentToolbar)],contributionPoints:[LoopDocumentToolbarItem],load:()=>__vitePreload(()=>import("./chunks/plugin-BMH63P5M.js"),[],import.meta.url)}),NOTEBOOK_PLUGIN_NAME="@datalayer/loop-plugin-notebook",NotebookPlugin={name:NOTEBOOK_PLUGIN_NAME,displayName:"Notebook editor",description:"A notebook beside the chat, on the session’s kernel.",octicon:"rows",emoji:"📓",dependencies:[AgentsPlugin],contributionPoints:[LoopNotebookToolbar,LoopOpeningNotebook],contributes:[contribution(LoopEditorView,{surfaceId:"notebook",title:"Notebook",icon:RowsIcon,order:10,canOpen:Au=>Au.sandbox.state==="running",unavailableReason:()=>"Needs a running sandbox",load:()=>__vitePreload(()=>import("./chunks/NotebookView-Dl-icjhk.js"),[],import.meta.url)},{id:"notebook",order:10}),contribution(LoopCommand,{name:"notebook",description:"Open the notebook beside the chat",group:"Open",keybinding:"Mod+Alt+N",run:async({workspace:Au})=>{if(Au.setActiveViewType("chat"),!requestSurface("notebook"))throw new Error("No chat is on screen to open the notebook beside.")}},{id:"notebook"})],build:Au=>(__vitePreload(async()=>{const{createNotebookTools:lo}=await Promise.resolve().then(()=>notebookHooks);return{createNotebookTools:lo}},void 0,import.meta.url).then(({createNotebookTools:lo})=>{Au.contribute(LoopFrontendTool,{id:"notebook-tools",tools:$u=>lo($u.surfaceId)},{id:"notebook-tools"})},lo=>{console.warn("The notebook tools could not be loaded",lo)}),{})},NOTEBOOK_TOOLBAR_PLUGIN_NAME="@datalayer/loop-plugin-notebook-toolbar",NotebookToolbarPlugin=defineLazyPlugin({name:NOTEBOOK_TOOLBAR_PLUGIN_NAME,displayName:"Notebook toolbar",description:"Shows what the notebook is running on, on its toolbar.",octicon:"circle",emoji:"🟢",activationEvents:[onContributionPoint(LoopNotebookToolbar)],contributionPoints:[LoopNotebookToolbarItem],load:()=>__vitePreload(()=>import("./chunks/plugin-Ba5UScsV.js"),[],import.meta.url)}),NotebookExtension=defineExtension({name:"@datalayer/loop-extension-notebook",displayName:"Notebooks",description:"A notebook beside the chat, and the toolbar that reports on it.",octicon:"rows",emoji:"📓",plugins:[NotebookPlugin,NotebookToolbarPlugin]}),DocumentExtension=defineExtension({name:"@datalayer/loop-extension-document",displayName:"Documents",description:"A rich-text document beside the chat, and the toolbar that reports on it.",octicon:"file",emoji:"📄",plugins:[DocumentPlugin,DocumentToolbarPlugin]}),NO_TURN$5=signal$2({id:0,status:"idle"}),MAX_HEIGHT=168;function Thinking(){return jsxRuntimeExports.jsxs(Box,{as:"span","aria-label":"The agent is thinking",display:"inline-flex",gap:"4px",alignItems:"center",sx:{height:"1.5em","& > i":{width:5,height:5,borderRadius:"50%",bg:"fg.muted",animation:"loop-turn-dot 1.2s ease-in-out infinite"},"& > i:nth-of-type(2)":{animationDelay:"0.15s"},"& > i:nth-of-type(3)":{animationDelay:"0.3s"},"@keyframes loop-turn-dot":{"0%, 80%, 100%":{opacity:.25},"40%":{opacity:1}}},children:[jsxRuntimeExports.jsx("i",{}),jsxRuntimeExports.jsx("i",{}),jsxRuntimeExports.jsx("i",{})]})}function TurnPanel({footer:Au="full"}){const lo=useContributions(LoopChatTurn),$u=useSignalValue$1(lo[0]?.value.turn??NO_TURN$5),Ru=useSignalValue$1(pageLayoutSheet),Iu=reactExports.useRef(null),[Ou,Pu]=reactExports.useState(null),[Du,Lu]=reactExports.useState(!1);reactExports.useEffect(()=>{const Fu=Iu.current;Fu&&(Fu.scrollTop=Fu.scrollHeight)},[$u.assistant]),reactExports.useEffect(()=>{if(!Du)return;const Fu=window.setTimeout(()=>Lu(!1),1400);return()=>window.clearTimeout(Fu)},[Du]);const ju=reactExports.useCallback(async()=>{const Fu=[$u.user,$u.assistant].filter(Boolean).join(`
3761
3761
 
3762
- `);await navigator.clipboard?.writeText(Fu),Lu(!0)},[$u.user,$u.assistant]);if(Ru==="panel"||$u.status==="idle"||!$u.user||Ou===$u.id)return null;const Bu=$u.status==="thinking"||$u.status==="streaming";return jsxRuntimeExports.jsxs(Box,{"data-turn-panel":"",borderTop:"1px solid",borderColor:"border.muted",px:3,pt:2,pb:Au==="none"?2:1,display:"flex",flexDirection:"column",gap:2,bg:"canvas.default",children:[jsxRuntimeExports.jsx(Box,{display:"flex",justifyContent:"flex-end",children:jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,lineHeight:1.45,px:2,py:1,borderRadius:"10px",bg:"accent.subtle",color:"fg.default",maxWidth:"85%",overflow:"hidden",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical"},children:$u.user})}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,alignItems:"flex-start",children:[jsxRuntimeExports.jsx(Box,{ref:Iu,flex:"1 1 auto",minWidth:0,maxHeight:MAX_HEIGHT,overflowY:"auto",fontSize:0,lineHeight:1.5,color:$u.assistant?"fg.default":"fg.muted",whiteSpace:$u.assistant?"normal":"pre-wrap",overflowWrap:"anywhere",children:$u.assistant?jsxRuntimeExports.jsx(Box,{sx:{...streamdownMarkdownStyles,fontSize:0},children:jsxRuntimeExports.jsx(_o$1,{rehypePlugins:REHYPE_PLUGINS_WITHOUT_HTML,children:normalizeAssistantMarkdown($u.assistant)})}):$u.activity?jsxRuntimeExports.jsx(Text$5,{sx:{color:"fg.muted",fontStyle:"italic"},children:$u.activity}):Bu?jsxRuntimeExports.jsx(Thinking,{}):$u.status==="error"?"The agent could not answer.":"Done — the result is in the page."}),jsxRuntimeExports.jsx(IconButton,{icon:CommentDiscussionIcon,size:"small",variant:"invisible","aria-label":"Open the conversation",onClick:openPagePanel,sx:{color:"fg.muted",flexShrink:0}})]}),$u.assistant&&$u.activity?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted",fontStyle:"italic"},children:$u.activity}):null,Au==="full"?jsxRuntimeExports.jsx(TurnFooter,{usage:$u.usage,live:Bu,latest:!0,padding:0,onCopy:ju,onRemove:()=>Pu($u.id)}):Au==="actions"?jsxRuntimeExports.jsxs(Box,{display:"flex",justifyContent:"flex-end",gap:1,mt:-1,children:[jsxRuntimeExports.jsx(IconButton,{icon:Du?CheckIcon:CopyIcon,size:"small",variant:"invisible","aria-label":Du?"Copied":"Copy this turn",onClick:()=>{ju()},sx:{color:"fg.muted"}}),jsxRuntimeExports.jsx(IconButton,{icon:XIcon,size:"small",variant:"invisible","aria-label":"Dismiss until the next turn",onClick:()=>Pu($u.id),sx:{color:"fg.muted"}})]}):null]})}const SPLIT_DEFAULT_SHARE=.4,SPLIT_MIN_SHARE=.2,SPLIT_MAX_SHARE=.8,SPLIT_KEY_STEP=.05;function clampSplitShare(Au){return Number.isFinite(Au)?Math.min(SPLIT_MAX_SHARE,Math.max(SPLIT_MIN_SHARE,Au)):SPLIT_DEFAULT_SHARE}function splitShareForKey(Au,lo){switch(lo){case"ArrowLeft":return clampSplitShare(Au-SPLIT_KEY_STEP);case"ArrowRight":return clampSplitShare(Au+SPLIT_KEY_STEP);case"Home":return SPLIT_MIN_SHARE;case"End":return SPLIT_MAX_SHARE;default:return null}}function SplitLayout({editors:Au,hasEditor:lo,transcript:$u,prompt:Ru,chips:Iu,picker:Ou,transient:Pu}){const[Du,Lu]=reactExports.useState(SPLIT_DEFAULT_SHARE),ju=reactExports.useRef(null),Bu=reactExports.useRef(!1),Fu=reactExports.useCallback(Gu=>{const Ku=ju.current?.getBoundingClientRect();return!Ku||Ku.width<=0?null:clampSplitShare((Gu-Ku.left)/Ku.width)},[]),zu=Gu=>{Bu.current=!0,Gu.currentTarget.setPointerCapture?.(Gu.pointerId),Gu.preventDefault()},qu=Gu=>{if(!Bu.current)return;const Ku=Fu(Gu.clientX);Ku!==null&&Lu(Ku)},Uu=Gu=>{Bu.current=!1,Gu.currentTarget.releasePointerCapture?.(Gu.pointerId)},Hu=Gu=>{const Ku=splitShareForKey(Du,Gu.key);Ku!==null&&(Gu.preventDefault(),Lu(Ku))},Vu=Math.round(Du*100);return jsxRuntimeExports.jsxs(Box,{"data-testid":"loop-split-layout",flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",children:[Ou,jsxRuntimeExports.jsxs(Box,{ref:ju,flex:"1 1 auto",minHeight:0,display:"flex",position:"relative",overflow:"hidden",children:[jsxRuntimeExports.jsxs(Box,{"data-testid":"loop-split-conversation",flex:lo?`0 0 ${Vu}%`:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column",ml:lo?"-1px":0,children:[$u,Iu,Ru]}),lo?jsxRuntimeExports.jsx(Box,{role:"separator","aria-orientation":"vertical","aria-label":"Resize the conversation and the page","aria-valuemin":Math.round(SPLIT_MIN_SHARE*100),"aria-valuemax":Math.round(SPLIT_MAX_SHARE*100),"aria-valuenow":Vu,tabIndex:0,onPointerDown:zu,onPointerMove:qu,onPointerUp:Uu,onPointerCancel:Uu,onKeyDown:Hu,flex:"0 0 7px",mx:"-3px",zIndex:1,cursor:"col-resize",display:"flex",justifyContent:"center",outline:"none",touchAction:"none",sx:{"&::before":{content:'""',width:"1px",height:"100%",bg:"border.default"},"&:hover::before, &:focus-visible::before":{width:"3px",bg:"accent.emphasis"}}}):null,jsxRuntimeExports.jsx(Box,{"data-testid":"loop-split-page",sx:lo?{flex:"1 1 0",minWidth:0,minHeight:0,display:"flex",...paneOpening("right")}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",zIndex:-1},children:Au})]}),Pu]})}const LOOP_PAGE_LAYOUT_PLUGIN_NAME="@datalayer/loop-plugin-page-layout",NO_TURN$4=signal$2({id:0,status:"idle"}),pageLayoutChatMode=signal$2("floating-draggable"),promptStance=signal$2("floating-top");let floatingStance="floating-top";const PAGE_LAYOUT_DISABLED_MODES=["assistant"];function pageLayoutForChatMode(Au){switch(Au){case"sidebar":return{bandMode:"panel",panelMode:"docked"};case"floating":return{bandMode:"panel",panelMode:"overlay"};case"floating-small":return{bandMode:"panel",panelMode:"popup"};default:return{bandMode:"floating",panelMode:"docked"}}}function setPageLayoutChatMode(Au){pageLayoutChatMode.value=Au;const{bandMode:lo}=pageLayoutForChatMode(Au);promptStance.value=lo==="floating"?floatingStance:"docked-top",lo==="panel"&&openPagePanel()}function ChatModeAction(){const Au=useSignalValue$1(pageLayoutChatMode);return jsxRuntimeExports.jsx(ChatViewModeToggle,{value:Au,onChange:setPageLayoutChatMode,disabledModes:PAGE_LAYOUT_DISABLED_MODES})}function LoopPageLayout({parts:Au,promptMode:lo,pageSize:$u}){const Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$4),Ou=useSignalValue$1(pageLayoutChatMode),Pu=lo==="floating"?pageLayoutForChatMode(Ou):{bandMode:"docked",panelMode:"docked"};return jsxRuntimeExports.jsx(PageLayout,{page:Au.editors,hasPage:Au.hasEditor,panel:Au.transcript,band:Au.prompt,chips:Au.chips,picker:Au.picker,transient:Au.transient,activity:Iu.activity,bandMode:Pu.bandMode,panelMode:Pu.panelMode,pageSize:$u})}function ConversationToggle(){return jsxRuntimeExports.jsx(PagePanelToggle,{panelName:"conversation",icon:CommentDiscussionIcon,sx:{order:2}})}const LoopPageLayoutPlugin={name:LOOP_PAGE_LAYOUT_PLUGIN_NAME,config:{arrangement:"page",turnPanel:"below",turnPanelFooter:"full",prompt:"docked",promptAnchor:"top",pageSize:void 0},displayName:"Page layout",description:"The editor — or, in the chat view, the conversation — on a centred sheet, the prompt docked above it at the same width or floating over it as a draggable card, the current turn under the prompt, the conversation in a side panel; or, split, the conversation and the work side by side with a hairline to drag.",octicon:"file",emoji:"📄",build:({config:Au,...lo})=>{if(Au.arrangement==="split")return lo.contribute(LoopChatLayout,{id:"split-layout",prompt:"docked",Component:SplitLayout},{id:"split-layout"}),{components:[]};const $u=Au.prompt,Ru=Au.pageSize;floatingStance=Au.promptAnchor==="bottom"?"floating-bottom":"floating-top",$u==="floating"&&(promptStance.value=floatingStance);const Iu=Ou=>jsxRuntimeExports.jsx(LoopPageLayout,{parts:Ou,promptMode:$u,pageSize:Ru});if(lo.contribute(LoopChatLayout,{id:"page-layout",prompt:$u==="floating"?floatingStance:"docked-top",promptStance:$u==="floating"?promptStance:void 0,Component:Iu},{id:"page-layout"}),Au.turnPanel!=="none"){const Ou=Au.turnPanelFooter,Pu=()=>jsxRuntimeExports.jsx(TurnPanel,{footer:Ou});lo.contribute(LoopPromptPanel,{id:"page-layout-turn",placement:Au.turnPanel,order:0,Component:Pu},{id:"page-layout-turn"})}return{components:[{id:"page-layout-conversation-toggle",slot:LoopSlots.header,Component:ConversationToggle},...$u==="floating"?[{id:"page-layout-chat-mode",slot:LoopSlots.promptAction,Component:ChatModeAction}]:[]]}}};function loopPlugins(Au={}){const{serverUrl:lo,target:$u="browser",defaultEditor:Ru,showViewSelector:Iu=!0,hideChatHeader:Ou=!1,chatHeaderButtons:Pu=!1,promptPlacement:Du,autoFocusPrompt:Lu=!0,suggestionLabels:ju=!0,fullScreenTopOffset:Bu=0,showAgentVariants:Fu=!1,agentSummary:zu=!0,teamId:qu,teamPicker:Uu=!0,pageLayout:Hu=!1,pageLayoutArrangement:Vu="page",pageLayoutTurnPanel:Gu="below",pageLayoutPrompt:Ku="docked",pageLayoutPromptAnchor:Zu="top",pageLayoutSize:Qu,pageLayoutTurnPanelFooter:Yu="full",localAgent:ed,localAgentSpec:Xu,datalayerAgentSpecId:rd,datalayerCreatePayload:nd,datalayerVisitors:od,datalayerKept:ad,embedToken:ld,targetFixed:fd,themeVariant:pd,themeOverrides:Sd,colorMode:wd,presence:bd,showTokenUsage:Td,thread:Pd,floatingPrompt:ud=!1,editorSelector:md=!1,editors:_d=!0,conversation:hd=!0,commandPalette:gd=!1,pluginsPanel:Ed=!1,windowFrame:xd=!1,firstPromptHook:Od}=Au,Bd=Ru??(_d?"notebook":"none");return hd?[configurePlugin(ChatPlugin,{defaultSurface:Bd,showSurfaceSelector:_d&&Iu&&!md,hideHeader:Ou,headerButtons:{newChat:Pu,clear:Pu},promptPlacement:ud?"floating":Du,autoFocusPrompt:Lu,suggestionLabels:ju,fullScreenTopOffset:Bu,themeVariant:pd,themeOverrides:Sd,colorMode:wd,presence:bd,showTokenUsage:Td,...Pd?{thread:Pd}:{}}),configurePlugin(InputPromptPlugin,{firstPromptHook:Od}),ChatHeaderPlugin,A2uiSurfacePlugin,ChatViewPlugin,..._d?[NotebookViewPlugin,DocumentViewPlugin]:[],configurePlugin(AgentsPlugin,{serverUrl:lo,target:$u,datalayerAgentSpecId:rd,datalayerCreatePayload:nd,datalayerVisitors:od,datalayerKept:ad,embedToken:ld,targetFixed:fd,showAgentVariants:Fu,showAgentSummary:zu,teamId:qu,showTeamPicker:Uu,localAgent:ed??(Xu?{createPayload:{description:`Local agent from the ${Xu} spec`,agent_library:"pydantic-ai",agent_spec_id:Xu,enable_codemode:!1}}:void 0)}),..._d?[NotebookExtension,DocumentExtension]:[],A2uiPlugin,AgentspecsPlugin,ModelsPlugin,ThemePlugin,SubagentActivityPlugin,configurePlugin(ShellPlugin,{defaultEditor:Bd,showSelector:_d&&md}),...ud?[PromptPlugin]:[],...Hu?[configurePlugin(LoopPageLayoutPlugin,{arrangement:Vu,turnPanel:Gu,turnPanelFooter:Yu,prompt:Ku,promptAnchor:Zu,pageSize:Qu})]:[],...gd?[LoopCommandsPlugin]:[],...Ed?[PluginsPanelPlugin]:[],...xd?[WindowFramePlugin]:[]]:[ThemePlugin,configurePlugin(ShellPlugin,{defaultEditor:"none",showSelector:!1}),...gd?[LoopCommandsPlugin]:[],...Ed?[PluginsPanelPlugin]:[],...xd?[WindowFramePlugin]:[]]}function LoopEmbed({agentId:Au="",showHeader:lo=!1,chatHeaderActions:$u,headerActions:Ru,headerContainer:Iu,frameTitle:Ou,frameHeight:Pu,sidebarRail:Du=!1,plugins:Lu=[],...ju}){const Bu=reactExports.useRef(ju.firstPromptHook);Bu.current=ju.firstPromptHook;const Fu=reactExports.useMemo(()=>buildLoopReactor([...loopPlugins({...ju,windowFrame:ju.windowFrame||Ou!==void 0,firstPromptHook:()=>Bu.current?.()}),...Lu]),[ju.serverUrl,ju.target,ju.datalayerAgentSpecId,ju.targetFixed,ju.themeVariant,JSON.stringify(ju.themeOverrides??null),ju.colorMode,ju.presence?.name,ju.presence?.face,ju.presence?.welcome,ju.presence?.paused,ju.showTokenUsage,ju.thread?.id,JSON.stringify(ju.datalayerCreatePayload??null),JSON.stringify(ju.datalayerVisitors??null),ju.datalayerKept?.url,ju.embedToken,ju.defaultEditor,ju.showViewSelector,ju.hideChatHeader,ju.chatHeaderButtons,ju.promptPlacement,ju.autoFocusPrompt,ju.suggestionLabels,ju.fullScreenTopOffset,ju.showAgentVariants,ju.agentSummary,ju.teamId,ju.teamPicker,ju.pageLayout,ju.pageLayoutTurnPanel,ju.pageLayoutTurnPanelFooter,ju.pageLayoutPrompt,ju.pageLayoutPromptAnchor,ju.pageLayoutSize?.format,ju.pageLayoutSize?.width,ju.pageLayoutSize?.height,ju.localAgentSpec,ju.floatingPrompt,ju.editorSelector,ju.editors,ju.conversation,ju.commandPalette,ju.pluginsPanel,ju.windowFrame,Ou!==void 0,Lu]);useReactor(Fu);const zu=jsxRuntimeExports.jsx(LoopWorkspace,{serverUrl:ju.serverUrl??"",agentId:Au,reactor:Fu,manageReactor:!1,showViewSelector:ju.showViewSelector,showHeader:lo,chatHeaderActions:$u,headerActions:Ru,headerContainer:Iu,sidebarRail:Du});return jsxRuntimeExports.jsx(QueryClientProvider,{client:internalQueryClient,children:Ou!==void 0?jsxRuntimeExports.jsx(WindowFrame,{title:Ou,height:Pu,children:zu}):jsxRuntimeExports.jsx(Box,{height:"100%",minHeight:0,width:"100%",flex:"1 1 auto",minWidth:0,children:zu})})}const RECORD_KIND_WORDS={session:"Session",tool_call:"Tool call",decision:"Rule",check:"Check",approval:"Approval",output:"Answer",feedback:"Feedback",turn:"Turn",run:"Working",notification:"Notification"};function entryOf(Au){return{uid:String(Au.uid??""),sessionUid:String(Au.session_uid??""),deploymentUid:String(Au.deployment_uid??""),version:Number(Au.version)||0,kind:String(Au.kind??"output"),summary:String(Au.summary??""),payload:Au.payload&&typeof Au.payload=="object"?Au.payload:{},createdAt:String(Au.created_at??"")}}function sessionSentence(Au){const lo=Au.filter(Pu=>Pu.kind==="tool_call").length,$u=Au.filter(Pu=>Pu.kind==="check"),Ru=Au.filter(Pu=>Pu.kind==="output"),Iu=Ru[Ru.length-1],Ou=[lo===0?"No tool called":`${lo} tool call${lo===1?"":"s"}`];return $u.length&&Ou.push(`${$u.length} step${$u.length===1?"":"s"} a check did not let pass`),Iu?.summary.startsWith("Stopped:")?Ou.push("stopped"):Ru.length&&Ou.push(`${Ru.length} answer${Ru.length===1?"":"s"}`),`${Ou.join(", ")}.`}async function read(Au,lo,$u){if(!Au.aiAgentsUrl)throw new Error("The record service is not configured.");const Ru=await fetch(`${Au.aiAgentsUrl.replace(/\/+$/,"")}/api/ai-agents/v1/apps${lo}`,{headers:Au.token?{Authorization:`Bearer ${Au.token}`}:{}}),Iu=await Ru.json().catch(()=>({}));if(!Ru.ok||Iu.success===!1)throw new Error(`${$u}: ${String(Iu.detail??Ru.status)}`);return Iu}async function listSessions(Au,lo,$u=20,Ru=!1){const Iu=await read(Au,`/sessions?app_uid=${encodeURIComponent(lo)}&limit=${$u}${Ru===null?"":`&tests=${Ru}`}`,"The sessions could not be read");return Array.isArray(Iu.sessions)?Iu.sessions.map(entryOf):[]}async function readSession(Au,lo){const $u=await read(Au,`/records?session_uid=${encodeURIComponent(lo)}&limit=500`,"The session could not be read");return Array.isArray($u.entries)?$u.entries.map(entryOf).filter(Ru=>Ru.kind!=="run"):[]}const APP_ACTIVITY_WORDS={title:"Activity",unsaved:"Recorded once it is saved on Datalayer: each session there — its address, or its Preview on Datalayer — is listed here.",signedOut:"Its activity is its owner’s: sign in to Datalayer to read it.",none:"Nothing yet: a session on Datalayer — its address, or the Preview on Datalayer — is recorded here."},NO_TURN$3=signal$2({id:0,status:"idle"});function useRead(Au,lo,$u=!0){const[Ru,Iu]=reactExports.useState({loading:$u});return reactExports.useEffect(()=>{if(!$u)return;let Ou=!1;return Iu(Pu=>({...Pu,loading:!0})),Au().then(Pu=>!Ou&&Iu({value:Pu,loading:!1}),Pu=>!Ou&&Iu({error:Pu instanceof Error?Pu.message:String(Pu),loading:!1})),()=>{Ou=!0}},[lo,$u]),Ru}function Session({context:Au,session:lo}){const[$u,Ru]=reactExports.useState(!1),Iu=useRead(()=>readSession(Au,lo.sessionUid),`${lo.sessionUid}:${Au.token}`,$u);return jsxRuntimeExports.jsxs(Box,{as:"details",onToggle:Ou=>Ru(Ou.currentTarget.open),borderTop:"1px solid",borderColor:"border.muted",py:2,children:[jsxRuntimeExports.jsxs(Box,{as:"summary",cursor:"pointer",fontSize:1,children:[lo.createdAt?jsxRuntimeExports.jsx(RelativeTime,{datetime:lo.createdAt}):"A session",lo.version?` · version ${lo.version}`:"",Iu.value?` · ${sessionSentence(Iu.value)}`:""]}),$u?Iu.loading?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):Iu.error?jsxRuntimeExports.jsx(Text$5,{role:"alert",sx:{fontSize:1},children:Iu.error}):jsxRuntimeExports.jsx(Box,{as:"ol",pl:3,mt:2,mb:0,fontSize:1,children:(Iu.value??[]).map(Ou=>jsxRuntimeExports.jsxs(Box,{as:"li",mb:1,children:[jsxRuntimeExports.jsx(Label,{sx:{mr:2},children:RECORD_KIND_WORDS[Ou.kind]??Ou.kind}),Ou.summary]},Ou.uid))}):null]})}function AppActivity({appUid:Au}){const lo=useIAMStore(Fu=>Fu.token)??"",$u=useCoreStore(Fu=>Fu.configuration)?.aiAgentsUrl??"",Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$3),Ou=Iu.status!=="thinking"&&Iu.status!=="streaming",[Pu,Du]=reactExports.useState(0);reactExports.useEffect(()=>{Ou&&Du(Iu.id)},[Ou,Iu.id]);const Lu={aiAgentsUrl:$u,token:lo},ju=!!(Au&&lo),Bu=useRead(()=>listSessions(Lu,Au??""),`${Au}:${lo}:${$u}:${Pu}`,ju);return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-activity",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,mb:2},children:APP_ACTIVITY_WORDS.title}),Au?lo?Bu.loading&&!Bu.value?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):Bu.error?jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:Bu.error}):(Bu.value??[]).length===0?jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.none}):(Bu.value??[]).map(Fu=>jsxRuntimeExports.jsx(Session,{context:Lu,session:Fu},Fu.uid)):jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.signedOut}):jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.unsaved})]})}const APP_ACTIVITY_PLUGIN_NAME="@datalayer/loop-plugin-app-activity";function defineAppActivityPlugin(Au,lo){function $u(){return jsxRuntimeExports.jsx(AppActivity,{appUid:lo})}return{name:`${APP_ACTIVITY_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: activity`,description:`What ${Au.name} did, session by session, from its record.`,octicon:"pulse",build:()=>({components:[{id:"app-activity",slot:LoopSlots.sidebar,order:20,Component:$u,rail:{label:"Activity",icon:PulseIcon}}]})}}const APP_PANEL_WIDTH=380;function elementsByPlace(Au){const lo=Au.filter($u=>$u.where==="page");return{panels:Au.filter($u=>$u.where==="panel"),page:lo.length>0?lo[lo.length-1]:null}}function ElementBody({element:Au,send:lo}){const $u=reactExports.useMemo(()=>readA2uiToolResult(Au.shows,SURFACE_CATALOG_ID),[Au.shows]),Ru=useOwnCatalog(),Iu=Ou=>{const Pu=answerAction(Ou);Pu&&lo?.(Pu.message,Pu.forwardedProps)};return!$u?.messages||$u.messages.length===0?jsxRuntimeExports.jsx(Text$5,{sx:{color:"fg.muted"},children:"Nothing to show."}):jsxRuntimeExports.jsx(InlineSurface,{messages:$u.messages,onAction:Iu,catalog:Ru},JSON.stringify(Au.shows))}function ElementHeader({element:Au}){return jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",justifyContent:"space-between",gap:2,mb:2,children:[jsxRuntimeExports.jsx(Text$5,{as:"h2",sx:{fontSize:2,fontWeight:"bold",m:0},children:Au.title}),jsxRuntimeExports.jsx(IconButton,{icon:XIcon,variant:"invisible",size:"small","aria-label":`Close ${Au.title}`,onClick:()=>closeLoopElement(Au.id)})]})}function AppElements({workspace:Au}){const lo=reactExports.useSyncExternalStore(onLoopElements,openLoopElements,openLoopElements),{panels:$u,page:Ru}=elementsByPlace(lo),Iu=Au?.viewControls.send;return $u.length===0&&Ru===null?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[$u.length>0?jsxRuntimeExports.jsx(Box,{as:"aside","aria-label":"Side panel",position:"absolute",top:0,right:0,bottom:0,width:`min(${APP_PANEL_WIDTH}px, 100%)`,zIndex:1,overflowY:"auto",borderLeft:"1px solid",borderColor:"border.default",bg:"canvas.subtle",boxShadow:"shadow.medium",p:3,display:"flex",flexDirection:"column",gap:3,children:$u.map(Ou=>jsxRuntimeExports.jsxs(Box,{as:"section","aria-label":Ou.title,children:[jsxRuntimeExports.jsx(ElementHeader,{element:Ou}),jsxRuntimeExports.jsx(ElementBody,{element:Ou,send:Iu})]},Ou.id))}):null,Ru!==null?jsxRuntimeExports.jsxs(Box,{role:"dialog","aria-label":Ru.title,position:"absolute",inset:0,zIndex:2,overflowY:"auto",bg:"canvas.default",p:[3,4],children:[jsxRuntimeExports.jsx(ElementHeader,{element:Ru}),jsxRuntimeExports.jsx(ElementBody,{element:Ru,send:Iu})]}):null]})}const APP_ELEMENTS_PLUGIN_NAME="@datalayer/loop-plugin-app-elements",AppElementsPlugin={name:APP_ELEMENTS_PLUGIN_NAME,displayName:"Side panel and pages",description:"What an application opens beside the conversation: a side panel, or a page of its own.",octicon:"sidebar-expand",build:()=>({components:[{id:"app-elements",slot:LoopSlots.root,Component:AppElements}]}),register:()=>clearLoopElements},appComponentsPluginName=Au=>`@datalayer/loop-plugin-app-components-${Au}`,hasCustomComponents=Au=>(Au.interface.customComponents??[]).length>0;function defineAppComponentsPlugin(Au,lo){const $u=Au.interface.customComponents??[];if($u.length===0)throw new Error(`“${Au.name}” has no component of its own to contribute.`);return{name:appComponentsPluginName(Au.id),displayName:`${Au.name}'s components`,description:`The components ${Au.name}'s developer wrote: ${$u.map(Ru=>Ru.name).join(", ")}.`,octicon:"apps",contributes:$u.flatMap(Ru=>[contribution(LoopCanvasBlock,{id:Ru.name,uiPlugin:`app:${Au.id}`,component:customComponentEntry(Ru,Au.version)},{id:Ru.name}),contribution(LoopA2uiComponent,{id:Ru.name,app:Au.id,implementation:customImplementation(Ru,Au.version,lo)},{id:Ru.name})])}}const COMPUTER_PARTS=["browse","files","shell"],COMPUTER_PART_TOOLS={browse:[],files:["list_computer_files","read_computer_file","write_computer_file"],shell:["execute_code","run_skill_script"]},COMPUTER_WORDS={title:"Computer",part:{browse:"Browse",files:"Files",shell:"Shell"},on:"on",off:"off",none:"It has no computer: browse, files and shell are all off. Turn one on in its permissions to give it one.",offSaid:Au=>`Off, so its agent is given no tool for it: ${Au.join(", ")}.`,noBrowser:"Browser: no browser runs on its computer yet, so there is nothing to show.",agentHas:"Its agent has the computer.",youHave:"You have the computer: its agent waits for it until you hand it back.",someoneHas:"Somebody else has taken this computer over.",takeOver:"Take over",handBack:"Hand back",run:"Run",yourCode:"Python to run on its computer",terminal:"What ran on it",nothingRan:"Nothing has run on it yet in this conversation.",files:"Files",notStarted:"Its computer starts when its agent first uses it: no file yet.",emptyDirectory:"Empty.",up:"Up",download:"Download",signedOut:"Its computer is shown once you are signed in to Datalayer."};function computerParts(Au){const lo=Au.permissions?.computer;return{browse:!!lo?.browse,files:!!lo?.files,shell:!!lo?.shell}}const hasComputer=Au=>COMPUTER_PARTS.some(lo=>Au[lo]),partsOff=Au=>COMPUTER_PARTS.filter(lo=>!Au[lo]).map(lo=>COMPUTER_WORDS.part[lo].toLowerCase());function partOf(Au){return COMPUTER_PARTS.find(lo=>COMPUTER_PART_TOOLS[lo].includes(Au))}const OUTPUT_LIMIT=4e3;function outputOf(Au){let lo=Au;if(typeof lo=="string")try{const Ru=JSON.parse(lo);Ru&&typeof Ru=="object"&&!Array.isArray(Ru)&&(lo=Ru)}catch{}let $u;if(lo&&typeof lo=="object"&&!Array.isArray(lo)){const Ru=lo,Iu=[typeof Ru.stdout=="string"?Ru.stdout:Ru.output,Ru.stderr,Ru.error??Ru.execution_error??Ru.code_error].filter(Ou=>typeof Ou=="string"&&Ou.trim()!=="");$u=Iu.length>0?Iu.join(`
3762
+ `);await navigator.clipboard?.writeText(Fu),Lu(!0)},[$u.user,$u.assistant]);if(Ru==="panel"||$u.status==="idle"||!$u.user||Ou===$u.id)return null;const Bu=$u.status==="thinking"||$u.status==="streaming";return jsxRuntimeExports.jsxs(Box,{"data-turn-panel":"",borderTop:"1px solid",borderColor:"border.muted",px:3,pt:2,pb:Au==="none"?2:1,display:"flex",flexDirection:"column",gap:2,bg:"canvas.default",children:[jsxRuntimeExports.jsx(Box,{display:"flex",justifyContent:"flex-end",children:jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,lineHeight:1.45,px:2,py:1,borderRadius:"10px",bg:"accent.subtle",color:"fg.default",maxWidth:"85%",overflow:"hidden",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical"},children:$u.user})}),jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,alignItems:"flex-start",children:[jsxRuntimeExports.jsx(Box,{ref:Iu,flex:"1 1 auto",minWidth:0,maxHeight:MAX_HEIGHT,overflowY:"auto",fontSize:0,lineHeight:1.5,color:$u.assistant?"fg.default":"fg.muted",whiteSpace:$u.assistant?"normal":"pre-wrap",overflowWrap:"anywhere",children:$u.assistant?jsxRuntimeExports.jsx(Box,{sx:{...streamdownMarkdownStyles,fontSize:0},children:jsxRuntimeExports.jsx(_o$1,{rehypePlugins:REHYPE_PLUGINS_WITHOUT_HTML,children:normalizeAssistantMarkdown($u.assistant)})}):$u.activity?jsxRuntimeExports.jsx(Text$5,{sx:{color:"fg.muted",fontStyle:"italic"},children:$u.activity}):Bu?jsxRuntimeExports.jsx(Thinking,{}):$u.status==="error"?"The agent could not answer.":"Done — the result is in the page."}),jsxRuntimeExports.jsx(IconButton,{icon:CommentDiscussionIcon,size:"small",variant:"invisible","aria-label":"Open the conversation",onClick:openPagePanel,sx:{color:"fg.muted",flexShrink:0}})]}),$u.assistant&&$u.activity?jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted",fontStyle:"italic"},children:$u.activity}):null,Au==="full"?jsxRuntimeExports.jsx(TurnFooter,{usage:$u.usage,live:Bu,latest:!0,padding:0,onCopy:ju,onRemove:()=>Pu($u.id)}):Au==="actions"?jsxRuntimeExports.jsxs(Box,{display:"flex",justifyContent:"flex-end",gap:1,mt:-1,children:[jsxRuntimeExports.jsx(IconButton,{icon:Du?CheckIcon:CopyIcon,size:"small",variant:"invisible","aria-label":Du?"Copied":"Copy this turn",onClick:()=>{ju()},sx:{color:"fg.muted"}}),jsxRuntimeExports.jsx(IconButton,{icon:XIcon,size:"small",variant:"invisible","aria-label":"Dismiss until the next turn",onClick:()=>Pu($u.id),sx:{color:"fg.muted"}})]}):null]})}const SPLIT_DEFAULT_SHARE=.4,SPLIT_MIN_SHARE=.2,SPLIT_MAX_SHARE=.8,SPLIT_KEY_STEP=.05;function clampSplitShare(Au){return Number.isFinite(Au)?Math.min(SPLIT_MAX_SHARE,Math.max(SPLIT_MIN_SHARE,Au)):SPLIT_DEFAULT_SHARE}function splitShareForKey(Au,lo){switch(lo){case"ArrowLeft":return clampSplitShare(Au-SPLIT_KEY_STEP);case"ArrowRight":return clampSplitShare(Au+SPLIT_KEY_STEP);case"Home":return SPLIT_MIN_SHARE;case"End":return SPLIT_MAX_SHARE;default:return null}}function SplitLayout({editors:Au,hasEditor:lo,transcript:$u,prompt:Ru,chips:Iu,picker:Ou,transient:Pu}){const[Du,Lu]=reactExports.useState(SPLIT_DEFAULT_SHARE),ju=reactExports.useRef(null),Bu=reactExports.useRef(!1),Fu=reactExports.useCallback(Gu=>{const Ku=ju.current?.getBoundingClientRect();return!Ku||Ku.width<=0?null:clampSplitShare((Gu-Ku.left)/Ku.width)},[]),zu=Gu=>{Bu.current=!0,Gu.currentTarget.setPointerCapture?.(Gu.pointerId),Gu.preventDefault()},qu=Gu=>{if(!Bu.current)return;const Ku=Fu(Gu.clientX);Ku!==null&&Lu(Ku)},Uu=Gu=>{Bu.current=!1,Gu.currentTarget.releasePointerCapture?.(Gu.pointerId)},Hu=Gu=>{const Ku=splitShareForKey(Du,Gu.key);Ku!==null&&(Gu.preventDefault(),Lu(Ku))},Vu=Math.round(Du*100);return jsxRuntimeExports.jsxs(Box,{"data-testid":"loop-split-layout",flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",children:[Ou,jsxRuntimeExports.jsxs(Box,{ref:ju,flex:"1 1 auto",minHeight:0,display:"flex",position:"relative",overflow:"hidden",children:[jsxRuntimeExports.jsxs(Box,{"data-testid":"loop-split-conversation",flex:lo?`0 0 ${Vu}%`:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column",ml:lo?"-1px":0,children:[$u,Iu,Ru]}),lo?jsxRuntimeExports.jsx(Box,{role:"separator","aria-orientation":"vertical","aria-label":"Resize the conversation and the page","aria-valuemin":Math.round(SPLIT_MIN_SHARE*100),"aria-valuemax":Math.round(SPLIT_MAX_SHARE*100),"aria-valuenow":Vu,tabIndex:0,onPointerDown:zu,onPointerMove:qu,onPointerUp:Uu,onPointerCancel:Uu,onKeyDown:Hu,flex:"0 0 7px",mx:"-3px",zIndex:1,cursor:"col-resize",display:"flex",justifyContent:"center",outline:"none",touchAction:"none",sx:{"&::before":{content:'""',width:"1px",height:"100%",bg:"border.default"},"&:hover::before, &:focus-visible::before":{width:"3px",bg:"accent.emphasis"}}}):null,jsxRuntimeExports.jsx(Box,{"data-testid":"loop-split-page",sx:lo?{flex:"1 1 0",minWidth:0,minHeight:0,display:"flex",...paneOpening("right")}:{position:"absolute",inset:0,visibility:"hidden",pointerEvents:"none",zIndex:-1},children:Au})]}),Pu]})}const LOOP_PAGE_LAYOUT_PLUGIN_NAME="@datalayer/loop-plugin-page-layout",NO_TURN$4=signal$2({id:0,status:"idle"}),pageLayoutChatMode=signal$2("floating-draggable"),promptStance=signal$2("floating-top");let floatingStance="floating-top";const PAGE_LAYOUT_DISABLED_MODES=["assistant"];function pageLayoutForChatMode(Au){switch(Au){case"sidebar":return{bandMode:"panel",panelMode:"docked"};case"floating":return{bandMode:"panel",panelMode:"overlay"};case"floating-small":return{bandMode:"panel",panelMode:"popup"};default:return{bandMode:"floating",panelMode:"docked"}}}function setPageLayoutChatMode(Au){pageLayoutChatMode.value=Au;const{bandMode:lo}=pageLayoutForChatMode(Au);promptStance.value=lo==="floating"?floatingStance:"docked-top",lo==="panel"&&openPagePanel()}function ChatModeAction(){const Au=useSignalValue$1(pageLayoutChatMode);return jsxRuntimeExports.jsx(ChatViewModeToggle,{value:Au,onChange:setPageLayoutChatMode,disabledModes:PAGE_LAYOUT_DISABLED_MODES})}function LoopPageLayout({parts:Au,promptMode:lo,pageSize:$u}){const Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$4),Ou=useSignalValue$1(pageLayoutChatMode),Pu=lo==="floating"?pageLayoutForChatMode(Ou):{bandMode:"docked",panelMode:"docked"};return jsxRuntimeExports.jsx(PageLayout,{page:Au.editors,hasPage:Au.hasEditor,panel:Au.transcript,band:Au.prompt,chips:Au.chips,picker:Au.picker,transient:Au.transient,activity:Iu.activity,bandMode:Pu.bandMode,panelMode:Pu.panelMode,pageSize:$u})}function ConversationToggle(){return jsxRuntimeExports.jsx(PagePanelToggle,{panelName:"conversation",icon:CommentDiscussionIcon,sx:{order:2}})}const LoopPageLayoutPlugin={name:LOOP_PAGE_LAYOUT_PLUGIN_NAME,config:{arrangement:"page",turnPanel:"below",turnPanelFooter:"full",prompt:"docked",promptAnchor:"top",pageSize:void 0},displayName:"Page layout",description:"The editor — or, in the chat view, the conversation — on a centred sheet, the prompt docked above it at the same width or floating over it as a draggable card, the current turn under the prompt, the conversation in a side panel; or, split, the conversation and the work side by side with a hairline to drag.",octicon:"file",emoji:"📄",build:({config:Au,...lo})=>{if(Au.arrangement==="split")return lo.contribute(LoopChatLayout,{id:"split-layout",prompt:"docked",Component:SplitLayout},{id:"split-layout"}),{components:[]};const $u=Au.prompt,Ru=Au.pageSize;floatingStance=Au.promptAnchor==="bottom"?"floating-bottom":"floating-top",$u==="floating"&&(promptStance.value=floatingStance);const Iu=Ou=>jsxRuntimeExports.jsx(LoopPageLayout,{parts:Ou,promptMode:$u,pageSize:Ru});if(lo.contribute(LoopChatLayout,{id:"page-layout",prompt:$u==="floating"?floatingStance:"docked-top",promptStance:$u==="floating"?promptStance:void 0,Component:Iu},{id:"page-layout"}),Au.turnPanel!=="none"){const Ou=Au.turnPanelFooter,Pu=()=>jsxRuntimeExports.jsx(TurnPanel,{footer:Ou});lo.contribute(LoopPromptPanel,{id:"page-layout-turn",placement:Au.turnPanel,order:0,Component:Pu},{id:"page-layout-turn"})}return{components:[{id:"page-layout-conversation-toggle",slot:LoopSlots.header,Component:ConversationToggle},...$u==="floating"?[{id:"page-layout-chat-mode",slot:LoopSlots.promptAction,Component:ChatModeAction}]:[]]}}};function loopPlugins(Au={}){const{serverUrl:lo,target:$u="browser",defaultEditor:Ru,showViewSelector:Iu=!0,hideChatHeader:Ou=!1,chatHeaderButtons:Pu=!1,promptPlacement:Du,autoFocusPrompt:Lu=!0,suggestionLabels:ju=!0,fullScreenTopOffset:Bu=0,showAgentVariants:Fu=!1,agentSummary:zu=!0,teamId:qu,teamPicker:Uu=!0,pageLayout:Hu=!1,pageLayoutArrangement:Vu="page",pageLayoutTurnPanel:Gu="below",pageLayoutPrompt:Ku="docked",pageLayoutPromptAnchor:Zu="top",pageLayoutSize:Qu,pageLayoutTurnPanelFooter:Yu="full",localAgent:ed,localAgentSpec:Xu,datalayerAgentSpecId:rd,datalayerCreatePayload:nd,datalayerVisitors:od,datalayerKept:ad,embedToken:ld,targetFixed:fd,themeVariant:pd,themeOverrides:Sd,colorMode:wd,presence:bd,showTokenUsage:Td,thread:Pd,floatingPrompt:ud=!1,editorSelector:md=!1,editors:_d=!0,conversation:hd=!0,commandPalette:gd=!1,pluginsPanel:Ed=!1,windowFrame:xd=!1,firstPromptHook:Od}=Au,Bd=Ru??(_d?"notebook":"none");return hd?[configurePlugin(ChatPlugin,{defaultSurface:Bd,showSurfaceSelector:_d&&Iu&&!md,hideHeader:Ou,headerButtons:{newChat:Pu,clear:Pu},promptPlacement:ud?"floating":Du,autoFocusPrompt:Lu,suggestionLabels:ju,fullScreenTopOffset:Bu,themeVariant:pd,themeOverrides:Sd,colorMode:wd,presence:bd,showTokenUsage:Td,...Pd?{thread:Pd}:{}}),configurePlugin(InputPromptPlugin,{firstPromptHook:Od}),ChatHeaderPlugin,A2uiSurfacePlugin,ChatViewPlugin,..._d?[NotebookViewPlugin,DocumentViewPlugin]:[],configurePlugin(AgentsPlugin,{serverUrl:lo,target:$u,datalayerAgentSpecId:rd,datalayerCreatePayload:nd,datalayerVisitors:od,datalayerKept:ad,embedToken:ld,targetFixed:fd,showAgentVariants:Fu,showAgentSummary:zu,teamId:qu,showTeamPicker:Uu,localAgent:ed??(Xu?{createPayload:{description:`Local agent from the ${Xu} spec`,agent_library:"pydantic-ai",agent_spec_id:Xu,enable_codemode:!1}}:void 0)}),..._d?[NotebookExtension,DocumentExtension]:[],A2uiPlugin,AgentspecsPlugin,ModelsPlugin,ThemePlugin,SubagentActivityPlugin,configurePlugin(ShellPlugin,{defaultEditor:Bd,showSelector:_d&&md}),...ud?[PromptPlugin]:[],...Hu?[configurePlugin(LoopPageLayoutPlugin,{arrangement:Vu,turnPanel:Gu,turnPanelFooter:Yu,prompt:Ku,promptAnchor:Zu,pageSize:Qu})]:[],...gd?[LoopCommandsPlugin]:[],...Ed?[PluginsPanelPlugin]:[],...xd?[WindowFramePlugin]:[]]:[ThemePlugin,configurePlugin(ShellPlugin,{defaultEditor:"none",showSelector:!1}),...gd?[LoopCommandsPlugin]:[],...Ed?[PluginsPanelPlugin]:[],...xd?[WindowFramePlugin]:[]]}function LoopEmbed({agentId:Au="",showHeader:lo=!1,chatHeaderActions:$u,headerActions:Ru,headerContainer:Iu,frameTitle:Ou,frameHeight:Pu,sidebarRail:Du=!1,plugins:Lu=[],...ju}){const Bu=reactExports.useRef(ju.firstPromptHook);Bu.current=ju.firstPromptHook;const Fu=reactExports.useMemo(()=>buildLoopReactor([...loopPlugins({...ju,windowFrame:ju.windowFrame||Ou!==void 0,firstPromptHook:()=>Bu.current?.()}),...Lu]),[ju.serverUrl,ju.target,ju.datalayerAgentSpecId,ju.targetFixed,ju.themeVariant,JSON.stringify(ju.themeOverrides??null),ju.colorMode,ju.presence?.name,ju.presence?.face,ju.presence?.welcome,ju.presence?.paused,ju.showTokenUsage,ju.thread?.id,JSON.stringify(ju.datalayerCreatePayload??null),JSON.stringify(ju.datalayerVisitors??null),ju.datalayerKept?.url,ju.embedToken,ju.defaultEditor,ju.showViewSelector,ju.hideChatHeader,ju.chatHeaderButtons,ju.promptPlacement,ju.autoFocusPrompt,ju.suggestionLabels,ju.fullScreenTopOffset,ju.showAgentVariants,ju.agentSummary,ju.teamId,ju.teamPicker,ju.pageLayout,ju.pageLayoutTurnPanel,ju.pageLayoutTurnPanelFooter,ju.pageLayoutPrompt,ju.pageLayoutPromptAnchor,ju.pageLayoutSize?.format,ju.pageLayoutSize?.width,ju.pageLayoutSize?.height,ju.localAgentSpec,ju.floatingPrompt,ju.editorSelector,ju.editors,ju.conversation,ju.commandPalette,ju.pluginsPanel,ju.windowFrame,Ou!==void 0,Lu]);useReactor(Fu);const zu=jsxRuntimeExports.jsx(LoopWorkspace,{serverUrl:ju.serverUrl??"",agentId:Au,reactor:Fu,manageReactor:!1,showViewSelector:ju.showViewSelector,showHeader:lo,chatHeaderActions:$u,headerActions:Ru,headerContainer:Iu,sidebarRail:Du});return jsxRuntimeExports.jsx(QueryClientProvider,{client:internalQueryClient,children:Ou!==void 0?jsxRuntimeExports.jsx(WindowFrame,{title:Ou,height:Pu,children:zu}):jsxRuntimeExports.jsx(Box,{height:"100%",minHeight:0,width:"100%",flex:"1 1 auto",minWidth:0,children:zu})})}const RECORD_KIND_WORDS={session:"Session",tool_call:"Tool call",decision:"Rule",check:"Check",approval:"Approval",output:"Answer",feedback:"Feedback",turn:"Turn",run:"Working",notification:"Notification"};function entryOf(Au){return{uid:String(Au.uid??""),sessionUid:String(Au.session_uid??""),deploymentUid:String(Au.deployment_uid??""),version:Number(Au.version)||0,kind:String(Au.kind??"output"),summary:String(Au.summary??""),payload:Au.payload&&typeof Au.payload=="object"?Au.payload:{},createdAt:String(Au.created_at??"")}}function sessionSentence(Au){const lo=Au.filter(Pu=>Pu.kind==="tool_call").length,$u=Au.filter(Pu=>Pu.kind==="check"),Ru=Au.filter(Pu=>Pu.kind==="output"),Iu=Ru[Ru.length-1],Ou=[lo===0?"No tool called":`${lo} tool call${lo===1?"":"s"}`];return $u.length&&Ou.push(`${$u.length} step${$u.length===1?"":"s"} a check did not let pass`),Iu?.summary.startsWith("Stopped:")?Ou.push("stopped"):Ru.length&&Ou.push(`${Ru.length} answer${Ru.length===1?"":"s"}`),`${Ou.join(", ")}.`}async function read(Au,lo,$u){if(!Au.aiAgentsUrl)throw new Error("The record service is not configured.");const Ru=await fetch(`${Au.aiAgentsUrl.replace(/\/+$/,"")}/api/ai-agents/v1/apps${lo}`,{headers:Au.token?{Authorization:`Bearer ${Au.token}`}:{}}),Iu=await Ru.json().catch(()=>({}));if(!Ru.ok||Iu.success===!1)throw new Error(`${$u}: ${String(Iu.detail??Ru.status)}`);return Iu}async function listSessions(Au,lo,$u=20,Ru=!1){const Iu=await read(Au,`/sessions?app_uid=${encodeURIComponent(lo)}&limit=${$u}${Ru===null?"":`&tests=${Ru}`}`,"The sessions could not be read");return Array.isArray(Iu.sessions)?Iu.sessions.map(entryOf):[]}async function readSession(Au,lo){const $u=await read(Au,`/records?session_uid=${encodeURIComponent(lo)}&limit=500`,"The session could not be read");return Array.isArray($u.entries)?$u.entries.map(entryOf).filter(Ru=>Ru.kind!=="run"):[]}const APP_ACTIVITY_WORDS={title:"Activity",unsaved:"Recorded once it is saved on Datalayer: each session there — its address, or its Preview on Datalayer — is listed here.",signedOut:"Its activity is its owner’s: sign in to Datalayer to read it.",none:"Nothing yet: a session on Datalayer — its address, or the Preview on Datalayer — is recorded here."},NO_TURN$3=signal$2({id:0,status:"idle"});function useRead(Au,lo,$u=!0){const[Ru,Iu]=reactExports.useState({loading:$u});return reactExports.useEffect(()=>{if(!$u)return;let Ou=!1;return Iu(Pu=>({...Pu,loading:!0})),Au().then(Pu=>!Ou&&Iu({value:Pu,loading:!1}),Pu=>!Ou&&Iu({error:Pu instanceof Error?Pu.message:String(Pu),loading:!1})),()=>{Ou=!0}},[lo,$u]),Ru}function Session({context:Au,session:lo}){const[$u,Ru]=reactExports.useState(!1),Iu=useRead(()=>readSession(Au,lo.sessionUid),`${lo.sessionUid}:${Au.token}`,$u);return jsxRuntimeExports.jsxs(Box,{as:"details",onToggle:Ou=>Ru(Ou.currentTarget.open),borderTop:"1px solid",borderColor:"border.muted",py:2,children:[jsxRuntimeExports.jsxs(Box,{as:"summary",cursor:"pointer",fontSize:1,children:[lo.createdAt?jsxRuntimeExports.jsx(RelativeTime,{datetime:lo.createdAt}):"A session",lo.version?` · version ${lo.version}`:"",Iu.value?` · ${sessionSentence(Iu.value)}`:""]}),$u?Iu.loading?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):Iu.error?jsxRuntimeExports.jsx(Text$5,{role:"alert",sx:{fontSize:1},children:Iu.error}):jsxRuntimeExports.jsx(Box,{as:"ol",pl:3,mt:2,mb:0,fontSize:1,children:(Iu.value??[]).map(Ou=>jsxRuntimeExports.jsxs(Box,{as:"li",mb:1,children:[jsxRuntimeExports.jsx(Label,{sx:{mr:2},children:RECORD_KIND_WORDS[Ou.kind]??Ou.kind}),Ou.summary]},Ou.uid))}):null]})}function AppActivity({appUid:Au}){const lo=useIAMStore(Fu=>Fu.token)??"",$u=useCoreStore(Fu=>Fu.configuration)?.aiAgentsUrl??"",Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$3),Ou=Iu.status!=="thinking"&&Iu.status!=="streaming",[Pu,Du]=reactExports.useState(0);reactExports.useEffect(()=>{Ou&&Du(Iu.id)},[Ou,Iu.id]);const Lu={aiAgentsUrl:$u,token:lo},ju=!!(Au&&lo),Bu=useRead(()=>listSessions(Lu,Au??""),`${Au}:${lo}:${$u}:${Pu}`,ju);return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-activity",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,mb:2},children:APP_ACTIVITY_WORDS.title}),Au?lo?Bu.loading&&!Bu.value?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):Bu.error?jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:Bu.error}):(Bu.value??[]).length===0?jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.none}):(Bu.value??[]).map(Fu=>jsxRuntimeExports.jsx(Session,{context:Lu,session:Fu},Fu.uid)):jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.signedOut}):jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_ACTIVITY_WORDS.unsaved})]})}const APP_ACTIVITY_PLUGIN_NAME="@datalayer/loop-plugin-app-activity";function defineAppActivityPlugin(Au,lo){function $u(){return jsxRuntimeExports.jsx(AppActivity,{appUid:lo})}return{name:`${APP_ACTIVITY_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: activity`,description:`What ${Au.name} did, session by session, from its record.`,octicon:"pulse",build:()=>({components:[{id:"app-activity",slot:LoopSlots.sidebar,order:20,Component:$u,rail:{label:"Activity",icon:PulseIcon}}]})}}const APP_PANEL_WIDTH=380;function elementsByPlace(Au){const lo=Au.filter($u=>$u.where==="page");return{panels:Au.filter($u=>$u.where==="panel"),page:lo.length>0?lo[lo.length-1]:null}}function ElementBody({element:Au,send:lo}){const $u=reactExports.useMemo(()=>readA2uiToolResult(Au.shows,SURFACE_CATALOG_ID),[Au.shows]),Ru=useOwnCatalog(),Iu=Ou=>{const Pu=answerAction(Ou);Pu&&lo?.(Pu.message,Pu.forwardedProps)};return!$u?.messages||$u.messages.length===0?jsxRuntimeExports.jsx(Text$5,{sx:{color:"fg.muted"},children:"Nothing to show."}):jsxRuntimeExports.jsx(InlineSurface,{messages:$u.messages,onAction:Iu,catalog:Ru},JSON.stringify(Au.shows))}function ElementHeader({element:Au}){return jsxRuntimeExports.jsxs(Box,{display:"flex",alignItems:"center",justifyContent:"space-between",gap:2,mb:2,children:[jsxRuntimeExports.jsx(Text$5,{as:"h2",sx:{fontSize:2,fontWeight:"bold",m:0},children:Au.title}),jsxRuntimeExports.jsx(IconButton,{icon:XIcon,variant:"invisible",size:"small","aria-label":`Close ${Au.title}`,onClick:()=>closeLoopElement(Au.id)})]})}function AppElements({workspace:Au}){const lo=reactExports.useSyncExternalStore(onLoopElements,openLoopElements,openLoopElements),{panels:$u,page:Ru}=elementsByPlace(lo),Iu=Au?.viewControls.send;return $u.length===0&&Ru===null?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[$u.length>0?jsxRuntimeExports.jsx(Box,{as:"aside","aria-label":"Side panel",position:"absolute",top:0,right:0,bottom:0,width:`min(${APP_PANEL_WIDTH}px, 100%)`,zIndex:1,overflowY:"auto",borderLeft:"1px solid",borderColor:"border.default",bg:"canvas.subtle",boxShadow:"shadow.medium",p:3,display:"flex",flexDirection:"column",gap:3,children:$u.map(Ou=>jsxRuntimeExports.jsxs(Box,{as:"section","aria-label":Ou.title,children:[jsxRuntimeExports.jsx(ElementHeader,{element:Ou}),jsxRuntimeExports.jsx(ElementBody,{element:Ou,send:Iu})]},Ou.id))}):null,Ru!==null?jsxRuntimeExports.jsxs(Box,{role:"dialog","aria-label":Ru.title,position:"absolute",inset:0,zIndex:2,overflowY:"auto",bg:"canvas.default",p:[3,4],children:[jsxRuntimeExports.jsx(ElementHeader,{element:Ru}),jsxRuntimeExports.jsx(ElementBody,{element:Ru,send:Iu})]}):null]})}const APP_ELEMENTS_PLUGIN_NAME="@datalayer/loop-plugin-app-elements",AppElementsPlugin={name:APP_ELEMENTS_PLUGIN_NAME,displayName:"Side panel and pages",description:"What an application opens beside the conversation: a side panel, or a page of its own.",octicon:"sidebar-expand",build:()=>({components:[{id:"app-elements",slot:LoopSlots.root,Component:AppElements}]}),register:()=>clearLoopElements},appComponentsPluginName=Au=>`@datalayer/loop-plugin-app-components-${Au}`,hasCustomComponents=Au=>(Au.interface.customComponents??[]).length>0;function defineAppComponentsPlugin(Au,lo){const $u=Au.interface.customComponents??[];if($u.length===0)throw new Error(`“${Au.name}” has no component of its own to contribute.`);return{name:appComponentsPluginName(Au.id),displayName:`${Au.name}'s components`,description:`The components ${Au.name}'s developer wrote: ${$u.map(Ru=>Ru.name).join(", ")}.`,octicon:"apps",contributes:$u.flatMap(Ru=>[contribution(LoopCanvasBlock,{id:Ru.name,uiPlugin:`app:${Au.id}`,component:customComponentEntry(Ru,Au.version)},{id:Ru.name}),contribution(LoopA2uiComponent,{id:Ru.name,app:Au.id,implementation:customImplementation(Ru,Au.version,lo,Au.id)},{id:Ru.name})])}}const COMPUTER_PARTS=["browse","files","shell"],COMPUTER_PART_TOOLS={browse:[],files:["list_computer_files","read_computer_file","write_computer_file"],shell:["execute_code","run_skill_script"]},COMPUTER_WORDS={title:"Computer",part:{browse:"Browse",files:"Files",shell:"Shell"},on:"on",off:"off",none:"It has no computer: browse, files and shell are all off. Turn one on in its permissions to give it one.",offSaid:Au=>`Off, so its agent is given no tool for it: ${Au.join(", ")}.`,noBrowser:"Browser: no browser runs on its computer yet, so there is nothing to show.",agentHas:"Its agent has the computer.",youHave:"You have the computer: its agent waits for it until you hand it back.",someoneHas:"Somebody else has taken this computer over.",takeOver:"Take over",handBack:"Hand back",run:"Run",yourCode:"Python to run on its computer",terminal:"What ran on it",nothingRan:"Nothing has run on it yet in this conversation.",files:"Files",notStarted:"Its computer starts when its agent first uses it: no file yet.",emptyDirectory:"Empty.",up:"Up",download:"Download",signedOut:"Its computer is shown once you are signed in to Datalayer."};function computerParts(Au){const lo=Au.permissions?.computer;return{browse:!!lo?.browse,files:!!lo?.files,shell:!!lo?.shell}}const hasComputer=Au=>COMPUTER_PARTS.some(lo=>Au[lo]),partsOff=Au=>COMPUTER_PARTS.filter(lo=>!Au[lo]).map(lo=>COMPUTER_WORDS.part[lo].toLowerCase());function partOf(Au){return COMPUTER_PARTS.find(lo=>COMPUTER_PART_TOOLS[lo].includes(Au))}const OUTPUT_LIMIT=4e3;function outputOf(Au){let lo=Au;if(typeof lo=="string")try{const Ru=JSON.parse(lo);Ru&&typeof Ru=="object"&&!Array.isArray(Ru)&&(lo=Ru)}catch{}let $u;if(lo&&typeof lo=="object"&&!Array.isArray(lo)){const Ru=lo,Iu=[typeof Ru.stdout=="string"?Ru.stdout:Ru.output,Ru.stderr,Ru.error??Ru.execution_error??Ru.code_error].filter(Ou=>typeof Ou=="string"&&Ou.trim()!=="");$u=Iu.length>0?Iu.join(`
3763
3763
  `):"stdout"in Ru||"output"in Ru?"":JSON.stringify(lo,null,2)}else $u=typeof lo=="string"?lo:lo==null?"":JSON.stringify(lo,null,2);return $u.length>OUTPUT_LIMIT?`${$u.slice(0,OUTPUT_LIMIT)}
3764
3764
  … (${($u.length-OUTPUT_LIMIT).toLocaleString("en")} characters more)`:$u}function commandOf(Au){for(const lo of["code","path","script_name"]){const $u=Au[lo];if(typeof $u=="string"&&$u.trim())return $u}return Object.keys(Au).length?JSON.stringify(Au):""}function terminalEntries(Au){const lo=[];for(const $u of Au){if($u.role!=="tool")continue;const Ru=partOf($u.name);Ru&&lo.push({tool:$u.name,part:Ru,command:commandOf($u.args??{}),output:$u.result===void 0?void 0:outputOf($u.result)})}return lo}const computerUrl=(Au,lo="")=>`${Au.serverUrl.replace(/\/+$/,"")}/api/v1/apps/agents/${encodeURIComponent(Au.agentId)}/computer${lo}`;function computerFileUrl(Au,lo){const $u=computerUrl(Au,`/file?path=${encodeURIComponent(lo)}`),Ru=(Au.userAppsUrl||"").trim();if(!Ru)return $u;try{const Iu=new URL($u),Ou=new URL(Ru);return Iu.protocol=Ou.protocol,Iu.host=Ou.host,Iu.toString()}catch{return $u}}async function asked(Au,lo,$u={}){const Ru=await fetch(computerUrl(Au,lo),{...$u,headers:{...$u.body?{"Content-Type":"application/json"}:{},...Au.token?{Authorization:`Bearer ${Au.token}`}:{}}});if(!Ru.ok){let Iu=`${Ru.status}`;try{const Ou=await Ru.json();Iu=typeof Ou.detail=="string"?Ou.detail:Iu}catch{}throw new Error(Iu)}return Ru}const readComputer=async Au=>(await asked(Au,"")).json(),listComputerFiles=async(Au,lo=".")=>(await(await asked(Au,`/files?path=${encodeURIComponent(lo)}`)).json()).entries,downloadComputerFile=async(Au,lo)=>{const $u=await fetch(computerFileUrl(Au,lo),{headers:Au.token?{Authorization:`Bearer ${Au.token}`}:{}});if(!$u.ok){let Ru=`${$u.status}`;try{const Iu=await $u.json();Ru=typeof Iu.detail=="string"?Iu.detail:Ru}catch{}throw new Error(Ru)}return $u.blob()},takeOverComputer=async Au=>(await asked(Au,"/take-over",{method:"POST"})).json(),handBackComputer=async Au=>{await asked(Au,"/hand-back",{method:"POST"})},runOnComputer=async(Au,lo)=>(await asked(Au,"/run",{method:"POST",body:JSON.stringify({code:lo})})).json();function parentOf(Au){const lo=Au.split("/").filter($u=>$u&&$u!==".");return lo.pop(),lo.length?lo.join("/"):"."}const NO_TURN$2=signal$2({id:0,status:"idle"}),NO_CONVERSATION$1=signal$2([]),MONO_FACE='ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',MONO={fontFamily:MONO_FACE,fontSize:0,whiteSpace:"pre-wrap",wordBreak:"break-word",m:0};function Parts({app:Au}){const lo=computerParts(Au),$u=partsOff(lo);return jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-parts",children:[jsxRuntimeExports.jsx(Box,{display:"flex",gap:1,flexWrap:"wrap",mb:1,children:COMPUTER_PARTS.map(Ru=>jsxRuntimeExports.jsxs(Label,{variant:lo[Ru]?"success":"secondary","data-part":Ru,"data-on":lo[Ru]?"true":"false",children:[COMPUTER_WORDS.part[Ru],":"," ",lo[Ru]?COMPUTER_WORDS.on:COMPUTER_WORDS.off]},Ru))}),$u.length>0&&$u.length<COMPUTER_PARTS.length?jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:0,color:"fg.muted",m:0},children:COMPUTER_WORDS.offSaid($u)}):null]})}function Terminal({conversation:Au}){const lo=terminalEntries(Au);return jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-terminal",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:1,mt:3,mb:1},children:COMPUTER_WORDS.terminal}),lo.length===0?jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:COMPUTER_WORDS.nothingRan}):jsxRuntimeExports.jsx(Box,{bg:"canvas.inset",border:"1px solid",borderColor:"border.muted",borderRadius:2,p:2,maxHeight:320,overflow:"auto",children:lo.map(($u,Ru)=>jsxRuntimeExports.jsxs(Box,{mb:2,children:[jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{...MONO,fontWeight:"semibold"},children:`$ ${$u.tool}${$u.command?`: ${$u.command}`:""}`}),$u.output===void 0?jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):jsxRuntimeExports.jsx(Text$5,{as:"pre",sx:{...MONO,color:"fg.muted"},children:$u.output})]},Ru))})]})}function save(Au,lo){const $u=URL.createObjectURL(new Blob([Au],{type:"application/octet-stream"})),Ru=document.createElement("a");Ru.href=$u,Ru.download=lo,Ru.click(),URL.revokeObjectURL($u)}function Files({context:Au,state:lo,ended:$u}){const[Ru,Iu]=reactExports.useState("."),[Ou,Pu]=reactExports.useState(),[Du,Lu]=reactExports.useState("");return reactExports.useEffect(()=>{if(!lo.started)return;let ju=!1;return listComputerFiles(Au,Ru).then(Bu=>{ju||(Pu(Bu),Lu(""))},Bu=>!ju&&Lu(Bu instanceof Error?Bu.message:String(Bu))),()=>{ju=!0}},[Au.serverUrl,Au.agentId,Au.token,Ru,lo.started,$u]),jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-files",children:[jsxRuntimeExports.jsxs(Heading$2,{as:"h4",sx:{fontSize:1,mt:3,mb:1},children:[COMPUTER_WORDS.files,Ru!=="."?jsxRuntimeExports.jsx(Text$5,{sx:{fontWeight:"normal",color:"fg.muted"},children:` · ${Ru}`}):null]}),lo.started?Du?jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:1,color:"danger.fg",m:0},children:Du}):Ou?jsxRuntimeExports.jsxs(Box,{as:"ul",listStyle:"none",p:0,m:0,children:[Ru!=="."?jsxRuntimeExports.jsx(Box,{as:"li",children:jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",onClick:()=>Iu(parentOf(Ru)),children:COMPUTER_WORDS.up})}):null,Ou.length===0?jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:COMPUTER_WORDS.emptyDirectory}):null,Ou.map(ju=>jsxRuntimeExports.jsx(Box,{as:"li","data-path":ju.path,display:"flex",alignItems:"center",gap:2,fontSize:1,py:1,borderTop:"1px solid",borderColor:"border.muted",children:ju.type==="directory"?jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"invisible",onClick:()=>Iu(ju.path),children:`${ju.name}/`}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Text$5,{sx:{flex:1,fontFamily:MONO_FACE,fontSize:0},children:ju.name}),jsxRuntimeExports.jsx(Text$5,{sx:{color:"fg.muted",fontSize:0},children:`${ju.size.toLocaleString("en")} bytes`}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small","aria-label":`${COMPUTER_WORDS.download} ${ju.name}`,onClick:()=>{downloadComputerFile(Au,ju.path).then(Bu=>save(Bu,ju.name),Bu=>Lu(Bu instanceof Error?Bu.message:String(Bu)))},children:COMPUTER_WORDS.download})]})},ju.path))]}):jsxRuntimeExports.jsx(StyledSpinner,{size:"small"}):jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:COMPUTER_WORDS.notStarted})]})}function YourTerminal({context:Au}){const[lo,$u]=reactExports.useState(""),[Ru,Iu]=reactExports.useState(!1),[Ou,Pu]=reactExports.useState([]),Du=()=>{Iu(!0),runOnComputer(Au,lo).then(Lu=>{Pu(ju=>[...ju,{code:lo,output:Lu}]),$u(""),Iu(!1)},Lu=>{Pu(ju=>[...ju,{code:lo,output:{stdout:"",stderr:"",error:Lu instanceof Error?Lu.message:String(Lu)}}]),Iu(!1)})};return jsxRuntimeExports.jsxs(Box,{"data-testid":"computer-your-terminal",mt:2,children:[Ou.map((Lu,ju)=>jsxRuntimeExports.jsxs(Box,{mb:2,children:[jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{...MONO,fontWeight:"semibold"},children:`>>> ${Lu.code}`}),jsxRuntimeExports.jsx(Text$5,{as:"pre",sx:{...MONO,color:"fg.muted"},children:[Lu.output.stdout,Lu.output.stderr,Lu.output.error].filter(Boolean).join(`
3765
3765
  `)})]},ju)),jsxRuntimeExports.jsx(Textarea,{"aria-label":COMPUTER_WORDS.yourCode,placeholder:COMPUTER_WORDS.yourCode,value:lo,onChange:Lu=>$u(Lu.target.value),sx:{width:"100%",fontFamily:MONO_FACE},rows:3}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",sx:{mt:1},disabled:Ru||!lo.trim(),onClick:Du,children:COMPUTER_WORDS.run})]})}function AppComputer({app:Au,workspace:lo}){const $u=useIAMStore(ad=>ad.token)??"",Ru=useContributions(LoopChatTurn),Iu=useSignalValue$1(Ru[0]?.value.turn??NO_TURN$2),Ou=useSignalValue$1(Ru[0]?.value.conversation??NO_CONVERSATION$1),Pu=Iu.status!=="thinking"&&Iu.status!=="streaming",[Du,Lu]=reactExports.useState(0);reactExports.useEffect(()=>{Pu&&Lu(Iu.id)},[Pu,Iu.id]);const ju=useChatWords(),Bu=lo?agentServerOf(lo.sandbox,lo.serverUrl):void 0,Fu=Bu===void 0?noRuntimeSaid(lo?.sandbox??IDLE_SANDBOX_SNAPSHOT,ju):void 0,zu=lo?.agentId||Au.id,[qu,Uu]=reactExports.useState(),Hu=qu?.servedFrom??"",Vu=reactExports.useMemo(()=>Bu===void 0?void 0:{serverUrl:Bu,agentId:zu,token:$u||void 0,userAppsUrl:Hu||void 0},[Bu,zu,$u,Hu]),Gu=computerParts(Au),[Ku,Zu]=reactExports.useState(""),[Qu,Yu]=reactExports.useState(!1),ed=reactExports.useRef(!0);reactExports.useEffect(()=>(ed.current=!0,()=>{ed.current=!1}),[]);const Xu=reactExports.useCallback(()=>{Vu&&readComputer(Vu).then(ad=>{ed.current&&(Uu(ad),Zu(""))},ad=>ed.current&&Zu(ad instanceof Error?ad.message:String(ad)))},[Vu]),rd=hasComputer(Gu);reactExports.useEffect(()=>{rd&&Vu&&Xu()},[rd,Vu,Xu,Du]);const nd=ad=>{Vu&&(Yu(!0),ad(Vu).then(()=>{ed.current&&(Yu(!1),Xu())},ld=>{ed.current&&(Yu(!1),Zu(ld instanceof Error?ld.message:String(ld)))}))},od=!!qu?.yours;return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-computer",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,mb:2},children:COMPUTER_WORDS.title}),jsxRuntimeExports.jsx(Parts,{app:Au}),rd?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:0,color:"fg.muted",m:0,mt:1},children:COMPUTER_WORDS.noBrowser}),Fu?jsxRuntimeExports.jsx(Text$5,{as:"p",role:"status",sx:{fontSize:1,color:"fg.default",m:0,mt:2},children:Fu}):null,Ku?jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:1,color:"danger.fg",m:0,mt:2},children:Ku}):null,qu&&Vu?jsxRuntimeExports.jsxs(Box,{mt:2,"data-testid":"computer-holder",children:[jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:1,m:0,mb:1},children:qu.held?od?COMPUTER_WORDS.youHave:COMPUTER_WORDS.someoneHas:COMPUTER_WORDS.agentHas}),qu.held?od?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",disabled:Qu,onClick:()=>nd(handBackComputer),children:COMPUTER_WORDS.handBack}),jsxRuntimeExports.jsx(YourTerminal,{context:Vu})]}):null:jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Qu,onClick:()=>nd(takeOverComputer),children:COMPUTER_WORDS.takeOver})]}):null,jsxRuntimeExports.jsx(Terminal,{conversation:Ou}),qu&&Vu?jsxRuntimeExports.jsx(Files,{context:Vu,state:qu,ended:Du}):null]}):jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0,mt:1},children:COMPUTER_WORDS.none})]})}const APP_COMPUTER_PLUGIN_NAME="@datalayer/loop-plugin-app-computer";function defineAppComputerPlugin(Au){function lo({workspace:Ru}){return jsxRuntimeExports.jsx(AppComputer,{app:Au,workspace:Ru})}return{name:`${APP_COMPUTER_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: computer`,description:`The computer ${Au.name} runs on: what ran on it, its files, and taking it over.`,octicon:"device-desktop",build:()=>({components:[{id:"app-computer",slot:LoopSlots.sidebar,order:30,Component:lo,rail:{label:"Computer",icon:DeviceDesktopIcon}}]})}}const SAVE_TOOL="save_to_space",SAVE_WORDS={approve:"Approve and save",decline:"Decline",where:Au=>Au?`To keep as a page of ${Au}:`:"To keep as a page of its Space:"};function draftOfApproval(Au){if(Au.tool_name!==SAVE_TOOL)return null;const lo=$u=>{const Ru=Au.tool_args?.[$u];return typeof Ru=="string"?Ru:""};return{title:lo("title"),content:lo("content"),space:lo("space")}}const APP_RULES_WORDS={title:"Rules and approvals",byDefault:"With no rule of its own: reading is done, anything else waits for you.",none:"It has no rule of its own.",waiting:"Waiting for you",nothingWaiting:"Nothing is waiting for your yes.",signedOut:"Its approvals reach you here once you are signed in to Datalayer.",offline:"Approvals are not connected yet: what you approve or reject is not sent until they are.",approve:"Approve",reject:"Reject"};function ruleInWords(Au){const lo=BEHAVIOUR_WORDS[Au.behaviour];return{action:Au.action,covers:Au.appliesTo.map(coverOf).join(", "),says:lo.says,means:lo.means}}const ruleOfApproval=Au=>{const lo=Au.tool_args?._rule??Au.tool_args?._check;return typeof lo=="string"?lo:""};function approvalsOfApp(Au,lo){return Au.filter($u=>$u.agent_id===lo||$u.tool_args?._app===lo)}const PENDING={status:"pending"};function DraftShown({draft:Au}){return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-draft",mt:1,children:[jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{m:0,fontSize:0,color:"fg.muted"},children:SAVE_WORDS.where(Au.space)}),jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{m:0,fontWeight:"semibold"},children:Au.title}),jsxRuntimeExports.jsx(Box,{as:"pre",m:0,mt:1,p:2,maxHeight:240,overflow:"auto",whiteSpace:"pre-wrap",fontFamily:"inherit",fontSize:0,bg:"canvas.subtle",borderRadius:2,children:Au.content})]})}function Approvals({app:Au}){const lo=useToolApprovalsQuery(PENDING),$u=useApproveToolRequest(),Ru=useRejectToolRequest(),Iu=reactExports.useMemo(()=>approvalsOfApp(lo.data?.approvals??[],Au.id),[lo.data,Au.id]);return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-approvals",children:[jsxRuntimeExports.jsx(Heading$2,{as:"h4",sx:{fontSize:1,mt:3,mb:1},children:APP_RULES_WORDS.waiting}),$u.connectionState!=="connected"?jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:0,color:"fg.muted",m:0,mb:1},children:APP_RULES_WORDS.offline}):null,Iu.length===0?jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_RULES_WORDS.nothingWaiting}):jsxRuntimeExports.jsx(Box,{as:"ul",listStyle:"none",p:0,m:0,children:Iu.map(Ou=>{const Pu=draftOfApproval(Ou);return jsxRuntimeExports.jsxs(Box,{as:"li",py:2,borderTop:"1px solid",borderColor:"border.muted",fontSize:1,children:[jsxRuntimeExports.jsx(Text$5,{sx:{fontWeight:"semibold"},children:Ou.tool_name}),ruleOfApproval(Ou)?jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:ruleOfApproval(Ou)}):null,Pu?jsxRuntimeExports.jsx(DraftShown,{draft:Pu}):null,jsxRuntimeExports.jsxs(Box,{display:"flex",gap:2,mt:1,children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"primary",disabled:$u.isPending,onClick:()=>$u.mutate({id:Ou.id}),children:Pu?SAVE_WORDS.approve:APP_RULES_WORDS.approve}),jsxRuntimeExports.jsx(ButtonComponent,{size:"small",disabled:Ru.isPending,onClick:()=>Ru.mutate({id:Ou.id}),children:Pu?SAVE_WORDS.decline:APP_RULES_WORDS.reject})]})]},Ou.id)})})]})}function AppRulesCard({app:Au}){const lo=!!useIAMStore($u=>$u.token);return jsxRuntimeExports.jsxs(Box,{"data-testid":"app-rules",mb:4,children:[jsxRuntimeExports.jsx(Heading$2,{as:"h3",sx:{fontSize:2,mb:2},children:APP_RULES_WORDS.title}),Au.rules.length===0?jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:1,color:"fg.muted",m:0},children:APP_RULES_WORDS.none}):jsxRuntimeExports.jsx(Box,{as:"ul",listStyle:"none",p:0,m:0,children:Au.rules.map(ruleInWords).map(($u,Ru)=>jsxRuntimeExports.jsxs(Box,{as:"li",py:1,fontSize:1,children:[jsxRuntimeExports.jsx(Text$5,{children:$u.action})," ",jsxRuntimeExports.jsx(Label,{title:$u.means,children:$u.says}),jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{m:0,color:"fg.muted",fontSize:0},children:$u.covers})]},Ru))}),jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:0,color:"fg.muted",mt:1,mb:0},children:APP_RULES_WORDS.byDefault}),lo?jsxRuntimeExports.jsx(Approvals,{app:Au}):jsxRuntimeExports.jsx(Text$5,{as:"p",sx:{fontSize:1,color:"fg.muted",mt:3,mb:0},children:APP_RULES_WORDS.signedOut})]})}const APP_RULES_PLUGIN_NAME="@datalayer/loop-plugin-app-rules";function defineAppRulesPlugin(Au){function lo(){return jsxRuntimeExports.jsx(AppRulesCard,{app:Au})}return{name:`${APP_RULES_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: rules and approvals`,description:`When ${Au.name} acts alone, when it asks, and what waits for your yes.`,octicon:"shield-check",build:()=>({components:[{id:"app-rules",slot:LoopSlots.sidebar,order:10,Component:lo,rail:{label:"Rules",icon:ShieldCheckIcon}}]})}}const COMMAND_INPUT="{input}";function commandPrompt(Au,lo=""){const $u=lo.trim();return Au.prompt.includes(COMMAND_INPUT)?Au.prompt.split(COMMAND_INPUT).join($u).trim():$u?`${Au.prompt}
3766
3766
 
3767
3767
  ${$u}`:Au.prompt}function modeDefaults(Au){return Object.fromEntries((Au.interface.modes??[]).filter(lo=>lo.options.length>0).map(lo=>[lo.id,lo.default||lo.options[0].id]))}function modeChoice(Au,lo={}){const $u=Au.interface.modes??[];for(const[Ru,Iu]of Object.entries(lo)){const Ou=$u.find(Pu=>Pu.id===Ru);if(!Ou)throw new Error(`${Au.name} has no mode “${Ru}”.`);if(!Ou.options.some(Pu=>Pu.id===Iu))throw new Error(`The mode ${Ou.label} has no option “${Iu}”.`)}return{...modeDefaults(Au),...lo}}function profileChoice(Au,lo){const $u=Au.interface.profiles??[];if(lo){const Ru=$u.find(Iu=>Iu.id===lo);if(!Ru)throw new Error($u.length===0?`${Au.name} has no profiles: “${lo}” cannot be chosen.`:`${Au.name} has no profile “${lo}”.`);return Ru}return $u[0]}function startersFor(Au,lo){const $u=profileChoice(Au,lo);return $u&&$u.starters.length>0?$u.starters:Au.interface.starters}function modeEffect(Au,lo={},$u){const Ru=modeChoice(Au,lo),Iu=profileChoice(Au,$u),Ou=(Au.interface.modes??[]).flatMap(Lu=>Lu.options.filter(ju=>ju.id===Ru[Lu.id])),Pu=[Iu?.instructions??"",...Ou.map(Lu=>Lu.instructions??"")].map(Lu=>Lu.trim()).filter(Boolean).join(`
3768
3768
 
3769
- `),Du=Ou.find(Lu=>Lu.model)?.model??Iu?.model??void 0;return Du?{instructions:Pu,model:Du}:{instructions:Pu}}async function holdUploads(Au,lo,$u,Ru=readFile){const Iu=uploadsRefusal(Au,[...lo,...$u.map(Ou=>({name:Ou.name,type:Ou.type,size:Ou.size}))]);return Iu?{files:[...lo],refused:Iu}:{files:[...lo,...await Promise.all($u.map(Ru))],refused:null}}const APP_COMPOSER_PLUGIN_NAME="@datalayer/loop-plugin-app-composer";function startersAsOpeners(Au){return Au.map(lo=>({text:lo.label,message:lo.message,...lo.category?{group:lo.category}:{}}))}const needsAppComposer=Au=>(Au.interface.commands??[]).length>0||(Au.interface.modes??[]).length>0||(Au.interface.profiles??[]).length>0||!!Au.interface.uploads;function defineAppComposerPlugin(Au){const lo=Au.interface.profiles??[],$u=signal$2(profileChoice(Au)?.id),Ru=signal$2(!1),Iu=computed$1(()=>({openers:startersAsOpeners(startersFor(Au,$u.value))}));function Ou(){const zu=interfaceWords(useChatLanguage()),qu=profileChoice(Au,useSignalValue$1($u)),Uu=useSignalValue$1(Ru);if(!qu)return null;const Hu=`${zu.profile}: ${qu.label}`;return Uu?jsxRuntimeExports.jsx(Text$5,{title:`${Hu} (${zu.profileKept})`,sx:{fontSize:0,color:"fg.muted",px:2},children:Hu}):jsxRuntimeExports.jsxs(ActionMenu,{children:[jsxRuntimeExports.jsx(ActionMenu.Button,{size:"small",variant:"invisible","aria-label":Hu,children:Hu}),jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"medium",children:jsxRuntimeExports.jsx(ActionList,{selectionVariant:"single",children:jsxRuntimeExports.jsxs(ActionList.Group,{children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:zu.profile}),lo.map(Vu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Vu.id===qu.id,onSelect:()=>{$u.value=profileChoice(Au,Vu.id)?.id},children:[Vu.label,Vu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:Vu.description}):null]},Vu.id))]})})})]})}const Pu=Au.interface.modes??[],Du=signal$2(modeDefaults(Au));function Lu(){const zu=useSignalValue$1(Du);return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Pu.map(qu=>{const Uu=qu.options.find(Hu=>Hu.id===zu[qu.id])??qu.options[0];return jsxRuntimeExports.jsxs(ActionMenu,{children:[jsxRuntimeExports.jsxs(ActionMenu.Button,{size:"small",variant:"invisible","aria-label":`${qu.label}: ${Uu.label}`,children:[qu.label,": ",Uu.label]}),jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"medium",children:jsxRuntimeExports.jsx(ActionList,{selectionVariant:"single",children:jsxRuntimeExports.jsxs(ActionList.Group,{children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:qu.label}),qu.options.map(Hu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Hu.id===Uu.id,onSelect:()=>{Du.value=modeChoice(Au,{...Du.peek(),[qu.id]:Hu.id})},children:[Hu.label,Hu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:Hu.description}):null]},Hu.id))]})})})]},qu.id)})})}const ju=Au.interface.uploads,Bu=signal$2({files:[],refused:null});function Fu(){const zu=interfaceWords(useChatLanguage()),qu=useSignalValue$1(Bu),Uu=reactExports.useRef(null);return ju?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(IconButton,{icon:PaperclipIcon,size:"small",variant:"invisible","aria-label":`${zu.attach}. ${uploadsInWords(ju)}`,onClick:()=>Uu.current?.click()}),jsxRuntimeExports.jsx("input",{ref:Uu,type:"file",hidden:!0,multiple:ju.maxFiles>1,accept:uploadsAccept(ju),"aria-label":zu.attach,onChange:Hu=>{const Vu=Array.from(Hu.target.files??[]);Hu.target.value="",holdUploads(Au,Bu.peek().files,Vu).then(Gu=>{Bu.value=Gu})}}),qu.files.map(Hu=>jsxRuntimeExports.jsx(Token$3,{text:Hu.name,size:"small",onRemove:()=>{Bu.value={files:Bu.peek().files.filter(Vu=>Vu!==Hu),refused:null}}},Hu.name)),qu.refused?jsxRuntimeExports.jsx(Text$5,{role:"alert",sx:{fontSize:0,color:"danger.fg"},children:qu.refused}):null]}):null}return{name:`${APP_COMPOSER_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: commands, modes, profiles and uploads`,description:`The commands, modes, profiles and files ${Au.name} takes in its composer.`,octicon:"command-palette",emoji:"⌘",contributes:[...lo.length>0?[contribution(LoopRunProps,{id:"app-profile",props:()=>(Ru.value=!0,{loop:{profile:$u.peek()}})},{id:"app-profile"}),contribution(LoopChatExtras,{id:"app-profile-starters",extras:Iu},{id:"app-profile-starters"})]:[],...(Au.interface.commands??[]).map(zu=>contribution(LoopCommand,{name:zu.name,description:zu.description,group:Au.name,composer:!0,run:async({argv:qu})=>({prompt:commandPrompt(zu,qu)})},{id:`app-command-${zu.name}`})),...Pu.length>0?[contribution(LoopRunProps,{id:"app-modes",props:()=>({loop:{modes:{...Du.peek()}}})},{id:"app-modes"})]:[],...ju?[contribution(LoopRunProps,{id:"app-uploads",props:()=>{const zu=Bu.peek().files;return zu.length===0?{}:(Bu.value={files:[],refused:null},{loop:{files:zu}})}},{id:"app-uploads"})]:[]],build:()=>({components:[...lo.length>0?[{id:"app-profile",slot:LoopSlots.promptAction,order:3,Component:Ou}]:[],...Pu.length>0?[{id:"app-modes",slot:LoopSlots.promptAction,order:5,Component:Lu}]:[],...ju?[{id:"app-uploads",slot:LoopSlots.promptAction,order:4,Component:Fu}]:[]]})}}const FEEDBACK_COMMENT_LIMIT=2e3,answerIdOf=Au=>Au>0?`answer-${Au}`:void 0,FEEDBACK_WORDS={ask:"Was this answer useful?",liked:"This answer was useful",disliked:"This answer was not useful",comment:"Anything to add? (optional)",send:"Send",kept:Au=>`Thank you. Kept in ${Au}’s record.`,where:Au=>`What you say is kept with this conversation in ${Au}’s record, for its builder to read.`,tooLong:`A comment is at most ${FEEDBACK_COMMENT_LIMIT} characters.`,noRuntime:"No runtime is assigned to this conversation, so nothing can be sent.",noSession:"This conversation has no name the application knows yet: send a message first."},keepsFeedback=Au=>(Au.record?.include??[]).includes("feedback"),feedbackEndpoint=Au=>`${Au.replace(/\/+$/,"")}/api/v1/apps/feedback`;function feedbackProblems(Au){const lo=[];return Au.session.trim()||lo.push(FEEDBACK_WORDS.noSession),Au.comment.trim().length>FEEDBACK_COMMENT_LIMIT&&lo.push(FEEDBACK_WORDS.tooLong),lo}async function sendFeedback(Au,{agentBaseUrl:lo,token:$u,fetcher:Ru=fetch}){const Iu=feedbackProblems(Au);if(Iu.length)throw new Error(Iu.join(" "));const Ou=await Ru(feedbackEndpoint(lo),{method:"POST",headers:{"Content-Type":"application/json",...$u?{Authorization:`Bearer ${$u}`}:{}},body:JSON.stringify({session:Au.session,liked:Au.liked,comment:Au.comment.trim(),...Au.message?{message:Au.message}:{}})}),Pu=await Ou.json().catch(()=>({}));if(!Ou.ok){const Du=typeof Pu.detail=="string"?Pu.detail:`${Ou.status}`;throw new Error(`The feedback was not kept: ${Du}`)}return String(Pu.summary??"")}const APP_FEEDBACK_PLUGIN_NAME="@datalayer/loop-plugin-app-feedback",NO_TURN$1=signal$2({id:0,status:"idle"}),NO_CONVERSATION=signal$2([]);function AppFeedback({app:Au,workspace:lo}){const $u=useContributions(LoopChatTurn),Ru=useSignalValue$1($u[0]?.value.turn??NO_TURN$1),Ou=useSignalValue$1($u[0]?.value.conversation??NO_CONVERSATION).filter(Ku=>Ku.role==="assistant").length,Pu=useIAMStore(Ku=>Ku.token),[Du,Lu]=reactExports.useState(null),[ju,Bu]=reactExports.useState(""),[Fu,zu]=reactExports.useState(null);if(Ru.status!=="done"||!Ru.assistant||!Ru.thread)return null;const qu=Ru.thread,Uu=Du?.turn===Ru.id?Du.liked:null,Hu=Fu?.turn===Ru.id?Fu:null,Vu=agentServerOf(lo.sandbox,lo.serverUrl),Gu=async()=>{if(Uu!==null){if(Vu===void 0){zu({turn:Ru.id,state:"refused",says:FEEDBACK_WORDS.noRuntime});return}zu({turn:Ru.id,state:"sending",says:""});try{await sendFeedback({session:qu,liked:Uu,comment:ju,message:answerIdOf(Ou)},{agentBaseUrl:Vu,token:Pu}),zu({turn:Ru.id,state:"kept",says:FEEDBACK_WORDS.kept(Au.name)}),Bu("")}catch(Ku){zu({turn:Ru.id,state:"refused",says:Ku instanceof Error?Ku.message:String(Ku)})}}};return Hu?.state==="kept"?jsxRuntimeExports.jsx("div",{style:{padding:"4px 8px"},children:jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:Hu.says})}):jsxRuntimeExports.jsxs("div",{role:"group","aria-label":FEEDBACK_WORDS.ask,style:{display:"flex",flexDirection:"column",gap:4,padding:"4px 8px"},children:[jsxRuntimeExports.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:FEEDBACK_WORDS.ask}),jsxRuntimeExports.jsx(IconButton,{size:"small",variant:Uu===!0?"default":"invisible",icon:ThumbsupIcon,"aria-label":FEEDBACK_WORDS.liked,"aria-pressed":Uu===!0,unsafeDisableTooltip:!0,onClick:()=>Lu({turn:Ru.id,liked:!0})}),jsxRuntimeExports.jsx(IconButton,{size:"small",variant:Uu===!1?"default":"invisible",icon:ThumbsdownIcon,"aria-label":FEEDBACK_WORDS.disliked,"aria-pressed":Uu===!1,unsafeDisableTooltip:!0,onClick:()=>Lu({turn:Ru.id,liked:!1})})]}),Uu!==null?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Textarea,{"aria-label":FEEDBACK_WORDS.comment,placeholder:FEEDBACK_WORDS.comment,value:ju,rows:2,resize:"vertical",block:!0,onChange:Ku=>Bu(Ku.target.value)}),jsxRuntimeExports.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"default",disabled:Hu?.state==="sending",onClick:()=>{Gu()},children:FEEDBACK_WORDS.send}),jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:FEEDBACK_WORDS.where(Au.name)})]})]}):null,Hu?.state==="refused"?jsxRuntimeExports.jsx(Text$5,{role:"alert",sx:{fontSize:0,color:"fg.default"},children:Hu.says}):null]})}function defineAppFeedbackPlugin(Au){function lo({workspace:$u}){return jsxRuntimeExports.jsx(AppFeedback,{app:Au,workspace:$u})}return{name:`${APP_FEEDBACK_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: feedback`,description:`A thumb and a comment on each answer of ${Au.name}, kept in its record.`,octicon:"thumbsup",emoji:"👍",contributes:[contribution(LoopPromptPanel,{id:"app-feedback",placement:"above",order:20,Component:lo},{id:"app-feedback"})]}}const KEPT_ITEMS={conversations:"this conversation",actions:"what it does",decisions:"how its rules decided",approvals:"what is approved",checks:"what its checks stopped",outputs:"its answers",feedback:"what you say of its answers"},RETENTION=/^([1-9]\d*)_(day|days|month|months|year|years)$/;function keptForWords(Au){const lo=RETENTION.exec(Au.trim());if(!lo)throw new Error(`Cannot read the retention \`${Au}\`: write 90_days, 18_months or 1_years.`);const $u=Number(lo[1]),Ru=lo[2].replace(/s$/,"");return $u===1?`a ${Ru}`:`${$u} ${Ru}s`}function inWords(Au){return Au.length<2?Au[0]??"":`${Au.slice(0,-1).join(", ")} and ${Au[Au.length-1]}`}function keptBeforeFirstMessage(Au,{visitor:lo=!1}={}){if(lo)return"Nothing of this conversation is kept: you are not signed in.";const $u=Au.name||"This application",Ru=keptForWords(Au.record.keepFor),Iu=Au.record.include.map(Ou=>KEPT_ITEMS[Ou]).filter(Ou=>!!Ou);return Iu.length?`${$u} keeps ${inWords(Iu)} for ${Ru}, then deletes it.`:`${$u} keeps only that this conversation took place, for ${Ru}.`}const beforeFirstMessage=Au=>Au.id===0&&!Au.user,APP_KEPT_PLUGIN_NAME="@datalayer/loop-plugin-app-kept",NO_TURN=signal$2({id:0,status:"idle"});function AppKept({says:Au}){const lo=useContributions(LoopChatTurn),$u=useSignalValue$1(lo[0]?.value.turn??NO_TURN);return beforeFirstMessage($u)?jsxRuntimeExports.jsx("div",{role:"note",style:{padding:"4px 8px"},children:jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:Au})}):null}function defineAppKeptPlugin(Au,lo){function $u(){return jsxRuntimeExports.jsx(AppKept,{says:lo})}return{name:`${APP_KEPT_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: what it keeps`,description:`What ${Au.name} keeps of a conversation, and for how long, said before the first message.`,octicon:"archive",emoji:"🗄",contributes:[contribution(LoopPromptPanel,{id:"app-kept",placement:"below",order:30,Component:$u},{id:"app-kept"})]}}const appPluginName=Au=>`loop-app-${Au}`;function appPluginPair(Au){const lo=appPluginName(Au);return{page:{name:lo,requiredBackendPlugins:[lo]},server:{name:lo,frontendDependencies:[lo]},extension:lo}}const appPluginsBase=(Au,lo)=>`${Au.replace(/\/+$/,"")}/api/v1/apps/${encodeURIComponent(lo)}`;function appRuntimeOf({target:Au,snapshot:lo,serverUrl:$u}){if(!(!Au||Au==="browser")){if(lo.agentBaseUrl)return lo.agentBaseUrl;if(Au!=="datalayer")return lo.state==="running"&&$u?$u:void 0}}const APP_RUNTIME_PLUGIN_NAME="@datalayer/loop-plugin-app-runtime",runningOf=Au=>lo=>Au.includes(lo);function AppRuntimePlugins({appId:Au}){const lo=useReactorPlatform(),$u=useOptionalSandboxService(),Ru=useSignalValue$1($u?.target??IDLE_SANDBOX_TARGET_SIGNAL),Iu=useSignalValue$1($u?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Ou=appRuntimeOf({target:Ru,snapshot:Iu,serverUrl:$u?.serverUrl}),Pu=appPluginName(Au);reactExports.useEffect(()=>{Ou||(registerReactor(lo,runningOf([Pu])),lo.setBackendPlugins([Pu]))},[lo,Ou,Pu]);const Du=reactExports.useCallback(Lu=>registerReactor(lo,runningOf(Lu.plugins.filter(ju=>ju.enabled).map(ju=>ju.name))),[lo]);return useBackendPluginStream(Ou?appPluginsBase(Ou,Au):void 0,{onState:Du}),null}function defineAppRuntimePlugin(Au){const lo=()=>jsxRuntimeExports.jsx(AppRuntimePlugins,{appId:Au});return{name:APP_RUNTIME_PLUGIN_NAME,displayName:"Its runtime",description:"Tells the application’s page which of its plugins its runtime holds.",octicon:"server",build:()=>({components:[{slot:LoopSlots.status,id:"app-runtime-plugins",Component:lo}]})}}const agentIdOf=Au=>{const lo=Au.agent||Au.team,$u=lo.lastIndexOf(":");return $u>0&&lo.slice($u+1).includes(".")?lo.slice(0,$u):lo};function defineAppPlugin(Au,lo=Au){if(!Au.agent)throw new Error(`“${Au.name}” is run by a team, which the workspace does not run as an application yet.`);const $u=appPluginPair(Au.id);return defineAgentCapacityPlugin({key:`app-${Au.id}`,name:$u.page.name,requiredBackendPlugins:$u.page.requiredBackendPlugins,displayName:lo.name,description:lo.description||`The ${lo.name} application`,specId:agentIdOf(Au),emoji:Au.emoji,createPayload:{name:Au.id,app_spec:dumpAppspec(Au),enable_codemode:!!Au.permissions?.computer?.shell,...Au.model?{model:Au.model}:{}},suggestions:startersAsOpeners(lo.interface.starters),instructions:Au.instructions,model:Au.model,...(Au.interface.modes??[]).length>0||(Au.interface.profiles??[]).length>0?{modeEffect:(Ru,Iu)=>modeEffect(Au,Ru,Iu)}:{}})}function appExtension(Au,lo,$u){return defineExtension({name:appPluginPair(Au.id).extension,displayName:lo.name,description:lo.description||`The ${lo.name} application`,emoji:Au.emoji,version:Au.version,plugins:$u})}function appLayoutOptions(Au){const lo=Au.interface.layout;if(lo==="chat")return{editors:!1,showViewSelector:!1};const $u=hasAppPage(Au);return{editors:!$u,showViewSelector:!$u,...$u?{defaultEditor:APP_PAGE_SURFACE}:{},pageLayout:!0,pageLayoutArrangement:lo==="split"?"split":"page",pageLayoutPrompt:"floating",pageLayoutPromptAnchor:"bottom",pageLayoutTurnPanelFooter:"actions"}}function appPreset(Au,lo={}){if(Au.kind==="decision"){if(!lo.page)throw new Error(`“${Au.name}” is a decision, whose page is drawn by where it runs: none was given here.`);return{plugins:[defineAppHostPagePlugin(Au,lo.page)],workspace:{conversation:!1,editors:!1,showViewSelector:!1}}}const $u=hasAppPage(Au),Ru=lo.shown??Au,Iu=new Set((lo.pluginsOff??[]).map(canvasBlocksPluginName)),Ou=CANVAS_BLOCK_PLUGINS.filter(Pu=>!Iu.has(Pu.name));return{plugins:[defineAppPlugin(Au,Ru),defineAppRuntimePlugin(Au.id),...$u?[defineAppPagePlugin(Ru),...Ou]:[],...hasCustomComponents(Au)?[defineAppComponentsPlugin(Au)]:[],...needsAppComposer(Au)?[defineAppComposerPlugin(Ru)]:[],...keepsFeedback(Au)?[defineAppFeedbackPlugin(Au)]:[],...lo.kept?[defineAppKeptPlugin(Au,keptBeforeFirstMessage(Au,lo.kept))]:[],...lo.sidebar?[defineAppRulesPlugin(Au),defineAppActivityPlugin(Au,lo.appUid),defineAppComputerPlugin(Au)]:lo.computer?[defineAppComputerPlugin(Au)]:[],AppElementsPlugin],workspace:appLayoutOptions(Au)}}function appDatalayerCreatePayload(Au,lo){return{name:Au.id,transport:"ag-ui",agent_spec_id:agentIdOf(Au),app_spec:dumpAppspec(Au),enable_codemode:!!Au.permissions?.computer?.shell,...lo?{app_instance:{app_uid:lo.appUid??"",deployment_uid:lo.deploymentUid??"",version:lo.version??0,...lo.organizationUid?{organization_uid:lo.organizationUid}:{}}}:{}}}const DATALAYER_BOOTSTRAP_AGENTSPEC="example-simple",NO_PLUGINS$1=[];function appThemeOverrides(Au){const lo=Au.interface?.accent;return lo?{light:themeAccentVars(lo,"light"),dark:themeAccentVars(lo,"dark")}:void 0}function AppRenderer({app:Au,plugins:lo=NO_PLUGINS$1,instance:$u,onPresence:Ru,onSaying:Iu,paused:Ou=!1,sidebar:Pu=!1,computer:Du=!1,frame:Lu=!1,page:ju,pluginsOff:Bu,language:Fu,...zu}){const qu=JSON.stringify(dumpAppspec(Au)),Uu=[...Bu??[]].sort().join(","),Hu=(Fu?[Fu]:preferredLanguages()).join(","),Vu=reactExports.useMemo(()=>translatedAppspec(Au,Hu.split(",").filter(Boolean)),[qu,Hu]),Gu=!!$u?.deploymentUid,Ku=!!zu.datalayerVisitors,Zu=reactExports.useMemo(()=>{try{return appPreset(Au,{page:ju,pluginsOff:Bu,sidebar:Pu,computer:Du,appUid:$u?.appUid,shown:Vu,...Gu?{kept:{visitor:Ku}}:{}})}catch(ld){return{problem:ld instanceof Error?ld.message:String(ld)}}},[qu,Vu,ju,Uu,Pu,Du,$u?.appUid,Gu,Ku]),Qu=reactExports.useMemo(()=>"problem"in Zu?lo:[appExtension(Au,Vu,Zu.plugins),...lo],[Zu,lo]),Yu=!("problem"in Zu)&&Zu.workspace.conversation!==!1,ed=reactExports.useMemo(()=>Yu?appDatalayerCreatePayload(Au,$u):void 0,[qu,Yu,$u?.appUid,$u?.deploymentUid,$u?.version]),Xu=useSystemColorMode(),rd=Au.interface?.theme,nd=rd?.mode==="auto"?Xu:rd?.mode==="light"||rd?.mode==="dark"?rd.mode:void 0,od=Au.interface?.accent,ad=reactExports.useMemo(()=>appThemeOverrides(Au),[od]);return"problem"in Zu?jsxRuntimeExports.jsx("div",{role:"status",style:{padding:16},children:Zu.problem}):jsxRuntimeExports.jsx(ChatLanguage,{language:Fu,children:jsxRuntimeExports.jsx(LoopEmbed,{agentId:Au.id,...Zu.workspace,...Lu?{frameTitle:[Au.emoji,Vu.name].filter(Boolean).join(" ")}:{},sidebarRail:Pu||Du,teamPicker:!1,showAgentVariants:!1,pluginsPanel:!1,datalayerAgentSpecId:DATALAYER_BOOTSTRAP_AGENTSPEC,targetFixed:!0,...rd?{themeVariant:rd.variant}:{},...nd?{colorMode:nd}:{},themeOverrides:ad,presence:{name:Vu.name,face:Au.emoji,welcome:Vu.interface.welcome||Vu.description,paused:Ou,onPresence:Ru,onSaying:Iu},showTokenUsage:!1,datalayerCreatePayload:ed,...zu,plugins:Qu})})}const ASSISTANT_CHARACTERS_PLUGIN_NAME="@datalayer/loop-plugin-assistant-characters",AssistantCharactersPlugin={name:ASSISTANT_CHARACTERS_PLUGIN_NAME,displayName:"Assistant characters",description:"Datalayer's own characters for the floating assistant: a paper clip, a wizard, a cat and the L👀P eyes.",octicon:"paperclip",contributes:ASSISTANT_CHARACTERS.map(Au=>contribution(LoopAssistantCharacter,{id:Au.id,character:Au},{id:Au.id}))};function assistantCharactersOf(Au){return Au.getContributions(LoopAssistantCharacter).map(lo=>lo.value)}function assistantCharactersFrom(Au){const lo=buildReactorFromPlugins(Au);lo.start();try{return assistantCharactersOf(lo)}finally{lo.stop()}}function assistantCharacterFor(Au,lo){const $u=lo.app?"app":lo.person?"person":"default",Ru=lo.app??lo.person??DEFAULT_ASSISTANT_CHARACTER,Iu=Au.find(Pu=>Pu.id===Ru);return Iu?{id:Ru,character:Iu.character,saidBy:$u}:{saidBy:$u,problem:`${$u==="app"?"This application names":$u==="person"?"Your settings name":"The default is"} the character “${Ru}”, which nothing enabled here draws; the characters are ${Au.map(Pu=>Pu.id).join(", ")||"none"}.`}}const EMBED_TAG="datalayer-app",EMBED_ATTRIBUTES={app:"The application’s id on Datalayer.",origin:"Where Datalayer is; the origin the script was loaded from by default.",token:"An embed token for an application that is not public, issued to your server for each visit.",spec:"The address of an Appspec (YAML or JSON) to run, in place of `app`.",mode:"inline, bubble, panel or assistant; the Appspec’s `deployment.embedded.mode` by default, then inline.",accent:"green, rose, sky, lime, sun or violet; the Appspec’s `interface.accent` by default, else the theme’s own colours.",theme:"light, dark or auto (the visitor’s system); auto by default.",font:"A CSS font family for the application’s text; Inter, then the system’s sans-serif, by default.",server:"An agent-runtimes server the application’s agent runs on; a Datalayer runtime by default.",api:"Datalayer’s API, where an application is read with its token; the platform’s by default.",height:"The height of an inline application, in pixels; 640 by default.",resume:"true or false: whether a visit’s conversation is picked up again after the page reloads, kept in the page’s storage; true by default.",language:"The language the visitor reads the application in, as BCP 47 tags it (fr, pt-BR): its translation into it, and the chat’s own words; the visitor’s browser’s by default.","user-token":"A token your server signed with the deployment’s secret, naming your user (HS256: sub, name, exp at most an hour away): what an application that says user: signed opens its session with."},EMBED_OBSERVED_ATTRIBUTES=Object.keys(EMBED_ATTRIBUTES),EMBED_HOST_VARIABLES={accent:"--datalayer-app-accent",font:"--datalayer-app-font",theme:"--datalayer-app-theme"},EMBED_COLOR_MODES=["light","dark","auto"],EMBED_FLOATING_VIEWS={bubble:"floating-small",panel:"panel",assistant:"assistant"};function floatingViewOf(Au){return Au==="inline"?void 0:EMBED_FLOATING_VIEWS[Au]}class EmbedAttributeError extends Error{constructor(lo){super(lo),this.name="EmbedAttributeError"}}function runnable({app:Au,problems:lo}){if(!Au.id)throw new EmbedAttributeError(`datalayer-app: the Appspec names no application${lo.length?` (${lo[0]})`:""}.`);if(Au.kind!=="decision"&&!Au.agent)throw new EmbedAttributeError(`datalayer-app: “${Au.name||Au.id}” names no agent to answer; an embedded application is run by an agent (a team is not supported yet).`);return Au}const listed=Au=>`${Au.slice(0,-1).join(", ")} or ${Au[Au.length-1]}`;function oneOf(Au,lo,$u){const Ru=Au?.trim();if(Ru){if(!lo.includes(Ru))throw new EmbedAttributeError(`datalayer-app: "${Ru}" is not ${$u}; it is ${listed(lo)}.`);return Ru}}function checkedFont(Au){const lo=Au?.trim()??"";if(!lo)return"";if(!/^[\w\s,"'.-]+$/u.test(lo))throw new EmbedAttributeError(`datalayer-app: the font "${lo}" is not a font family; write it as a CSS font-family is written, such as "Georgia, serif".`);return lo}function embedLookOf(Au,lo){const{attributes:$u,variables:Ru={}}=Au,Iu=oneOf($u.mode,APP_EMBED_MODES,"a mode")??lo?.deployment?.embedded?.mode??"inline",Ou=oneOf($u.accent,APP_ACCENTS,"an accent")??oneOf(Ru.accent,APP_ACCENTS,"an accent")??lo?.interface?.accent,Pu=oneOf($u.theme,EMBED_COLOR_MODES,"a theme")??oneOf(Ru.theme,EMBED_COLOR_MODES,"a theme")??lo?.interface?.theme?.mode??"auto",Du=checkedFont($u.font)||checkedFont(Ru.font),Lu=lo?.interface?.theme?.variant??"loop";return{mode:Iu,accent:Ou,colorMode:Pu,font:Du,variant:Lu}}function resumeOf(Au){return oneOf(Au,["true","false"],"a value of resume")!=="false"}function languageOf(Au){const lo=Au?.trim();if(lo){if(!LANGUAGE_TAG.test(lo))throw new EmbedAttributeError(`datalayer-app: "${lo}" is not a language as BCP 47 tags it, such as fr or pt-BR.`);return lo}}function inlineHeightOf(Au){const lo=Number.parseInt(Au??"",10);return Number.isFinite(lo)&&lo>=240?lo:640}const CHAT_EXTRAS_PLUGIN_NAME="@datalayer/loop-plugin-chat-extras";let counter=0;function createChatExtrasPlugin(){const Au=`chat-extras-${counter+=1}`,lo=signal$2({});return{plugin:{name:CHAT_EXTRAS_PLUGIN_NAME,displayName:"Chat Extras",description:"A host example’s live banner and footer status.",octicon:"megaphone",emoji:"📣",contributes:[contribution(LoopChatExtras,{id:Au,extras:lo},{id:Au})]},setExtras:Ru=>{lo.value=Ru}}}const HOST_CONTEXT_TOOL="host_context",hostTool=Au=>`host_${Au}`;function signedUser(Au){return Au?.user==="signed"}const hostRefused=Au=>`No rule of this application names ${Au}: it is left to the person, and the page was not called.`,hostNotAllowed=Au=>`The person did not allow ${Au}: the page was not called.`,confirmOnPage=Au=>typeof window<"u"&&typeof window.confirm=="function"?window.confirm(Au.sentence):!1,actionOf=(Au,lo)=>Au.rules.find($u=>$u.appliesTo.includes(lo))?.action;function hostFrontendTools(Au,lo){const $u=Au.deployment.embedded?.host;if(!$u)return[];const Ru=Pu=>behaviourFor(Au,Pu),Iu=Pu=>Ru(Pu)!=="leave_to_me",Ou=[];$u.context.length>0&&Ou.push({name:HOST_CONTEXT_TOOL,description:`What the page you are embedded in says of its visitor and of itself: ${$u.context.join(", ")}. Read it before answering what depends on them.`,parameters:{type:"object",properties:{}},location:"frontend",handler:async()=>{if(!Iu(HOST_CONTEXT_TOOL))return{error:hostRefused(HOST_CONTEXT_TOOL)};const Pu=lo().context?.()??{},Du={},Lu=[];for(const ju of $u.context)Pu[ju]===void 0?Lu.push(ju):Du[ju]=Pu[ju];return{values:Du,...Lu.length>0?{unsaid:Lu}:{}}}});for(const Pu of $u.functions){const Du=hostTool(Pu.name);Ou.push({name:Du,description:Pu.description,parameters:Pu.parameters,location:"frontend",handler:async Lu=>{const ju=Fu=>(lo().onEvent?.({type:"action",detail:{function:Pu.name,arguments:Lu,...Fu}}),Fu);if(!Iu(Du))return ju({error:hostRefused(Du)});if(Ru(Du)!=="do_it"){const Fu=actionOf(Au,Du)??Pu.description;if(!await(lo().ask??confirmOnPage)({function:Pu.name,arguments:Lu,sentence:`${Fu}? (${Pu.name} with ${JSON.stringify(Lu)})`}))return ju({error:hostNotAllowed(Du)})}const Bu=lo().functions?.[Pu.name];if(!Bu)return ju({error:`The page offers no function ${Pu.name}: it was not called.`});try{return ju({result:await Bu(Lu)})}catch(Fu){return ju({error:`The page's ${Pu.name} failed: ${Fu instanceof Error?Fu.message:String(Fu)}`})}}})}return Ou}function hostUserRunProps(Au,lo){if(signedUser(Au.deployment.embedded?.host))return{id:"host-user",props:()=>{const $u=lo().userToken?.()?.trim();return $u?{loop:{user_token:$u}}:{}}}}function withFace(Au,lo,$u){return!lo||!$u?Au:Object.fromEntries(Object.entries(Au).map(([Ru,Iu])=>[Ru,typeof Iu=="string"?Iu.split($u).join(lo):Iu]))}function faceOf(Au,lo){return Au==="loop"?loopFontFamily:typeof lo.fontFamily=="string"?lo.fontFamily:""}const accentOver=(Au,lo)=>Au?themeAccentVars(Au,lo):{};function embedThemeStyles({accent:Au,font:lo="",variant:$u="loop"}){const Ru=getThemeConfig($u).themeStyles,Iu=Ou=>{const Pu=Ru[Ou];return withFace({...Pu,...accentOver(Au,Ou)},lo,faceOf($u,Pu))};return{...Ru,light:Iu("light"),dark:Iu("dark")}}function embedThemeOverrides({accent:Au,font:lo="",variant:$u="loop"}){const Ru=getThemeConfig($u).themeStyles,Iu=Ou=>{const Pu=Ru[Ou];return{...Object.fromEntries(Object.entries(withFace(Pu,lo,faceOf($u,Pu))).filter(([Lu,ju])=>typeof ju=="string"&&ju!==Pu[Lu])),...accentOver(Au,Ou)}};return{light:Iu("light"),dark:Iu("dark")}}function embedShadowCss(Au){const lo=`
3769
+ `),Du=Ou.find(Lu=>Lu.model)?.model??Iu?.model??void 0;return Du?{instructions:Pu,model:Du}:{instructions:Pu}}async function holdUploads(Au,lo,$u,Ru=readFile){const Iu=uploadsRefusal(Au,[...lo,...$u.map(Ou=>({name:Ou.name,type:Ou.type,size:Ou.size}))]);return Iu?{files:[...lo],refused:Iu}:{files:[...lo,...await Promise.all($u.map(Ru))],refused:null}}const APP_COMPOSER_PLUGIN_NAME="@datalayer/loop-plugin-app-composer";function startersAsOpeners(Au){return Au.map(lo=>({text:lo.label,message:lo.message,...lo.category?{group:lo.category}:{}}))}const needsAppComposer=Au=>(Au.interface.commands??[]).length>0||(Au.interface.modes??[]).length>0||(Au.interface.profiles??[]).length>0||!!Au.interface.uploads;function defineAppComposerPlugin(Au){const lo=Au.interface.profiles??[],$u=signal$2(profileChoice(Au)?.id),Ru=signal$2(!1),Iu=computed$1(()=>({openers:startersAsOpeners(startersFor(Au,$u.value))}));function Ou(){const zu=interfaceWords(useChatLanguage()),qu=profileChoice(Au,useSignalValue$1($u)),Uu=useSignalValue$1(Ru);if(!qu)return null;const Hu=`${zu.profile}: ${qu.label}`;return Uu?jsxRuntimeExports.jsx(Text$5,{title:`${Hu} (${zu.profileKept})`,sx:{fontSize:0,color:"fg.muted",px:2},children:Hu}):jsxRuntimeExports.jsxs(ActionMenu,{children:[jsxRuntimeExports.jsx(ActionMenu.Button,{size:"small",variant:"invisible","aria-label":Hu,children:Hu}),jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"medium",children:jsxRuntimeExports.jsx(ActionList,{selectionVariant:"single",children:jsxRuntimeExports.jsxs(ActionList.Group,{children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:zu.profile}),lo.map(Vu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Vu.id===qu.id,onSelect:()=>{$u.value=profileChoice(Au,Vu.id)?.id},children:[Vu.label,Vu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:Vu.description}):null]},Vu.id))]})})})]})}const Pu=Au.interface.modes??[],Du=signal$2(modeDefaults(Au));function Lu(){const zu=useSignalValue$1(Du);return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Pu.map(qu=>{const Uu=qu.options.find(Hu=>Hu.id===zu[qu.id])??qu.options[0];return jsxRuntimeExports.jsxs(ActionMenu,{children:[jsxRuntimeExports.jsxs(ActionMenu.Button,{size:"small",variant:"invisible","aria-label":`${qu.label}: ${Uu.label}`,children:[qu.label,": ",Uu.label]}),jsxRuntimeExports.jsx(ActionMenu.Overlay,{width:"medium",children:jsxRuntimeExports.jsx(ActionList,{selectionVariant:"single",children:jsxRuntimeExports.jsxs(ActionList.Group,{children:[jsxRuntimeExports.jsx(ActionList.GroupHeading,{children:qu.label}),qu.options.map(Hu=>jsxRuntimeExports.jsxs(ActionList.Item,{selected:Hu.id===Uu.id,onSelect:()=>{Du.value=modeChoice(Au,{...Du.peek(),[qu.id]:Hu.id})},children:[Hu.label,Hu.description?jsxRuntimeExports.jsx(ActionList.Description,{variant:"block",children:Hu.description}):null]},Hu.id))]})})})]},qu.id)})})}const ju=Au.interface.uploads,Bu=signal$2({files:[],refused:null});function Fu(){const zu=interfaceWords(useChatLanguage()),qu=useSignalValue$1(Bu),Uu=reactExports.useRef(null);return ju?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(IconButton,{icon:PaperclipIcon,size:"small",variant:"invisible","aria-label":`${zu.attach}. ${uploadsInWords(ju)}`,onClick:()=>Uu.current?.click()}),jsxRuntimeExports.jsx("input",{ref:Uu,type:"file",hidden:!0,multiple:ju.maxFiles>1,accept:uploadsAccept(ju),"aria-label":zu.attach,onChange:Hu=>{const Vu=Array.from(Hu.target.files??[]);Hu.target.value="",holdUploads(Au,Bu.peek().files,Vu).then(Gu=>{Bu.value=Gu})}}),qu.files.map(Hu=>jsxRuntimeExports.jsx(Token$3,{text:Hu.name,size:"small",onRemove:()=>{Bu.value={files:Bu.peek().files.filter(Vu=>Vu!==Hu),refused:null}}},Hu.name)),qu.refused?jsxRuntimeExports.jsx(Text$5,{role:"alert",sx:{fontSize:0,color:"danger.fg"},children:qu.refused}):null]}):null}return{name:`${APP_COMPOSER_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: commands, modes, profiles and uploads`,description:`The commands, modes, profiles and files ${Au.name} takes in its composer.`,octicon:"command-palette",emoji:"⌘",contributes:[...lo.length>0?[contribution(LoopRunProps,{id:"app-profile",props:()=>(Ru.value=!0,{loop:{profile:$u.peek()}})},{id:"app-profile"}),contribution(LoopChatExtras,{id:"app-profile-starters",extras:Iu},{id:"app-profile-starters"})]:[],...(Au.interface.commands??[]).map(zu=>contribution(LoopCommand,{name:zu.name,description:zu.description,group:Au.name,composer:!0,run:async({argv:qu})=>({prompt:commandPrompt(zu,qu)})},{id:`app-command-${zu.name}`})),...Pu.length>0?[contribution(LoopRunProps,{id:"app-modes",props:()=>({loop:{modes:{...Du.peek()}}})},{id:"app-modes"})]:[],...ju?[contribution(LoopRunProps,{id:"app-uploads",props:()=>{const zu=Bu.peek().files;return zu.length===0?{}:(Bu.value={files:[],refused:null},{loop:{files:zu}})}},{id:"app-uploads"})]:[]],build:()=>({components:[...lo.length>0?[{id:"app-profile",slot:LoopSlots.promptAction,order:3,Component:Ou}]:[],...Pu.length>0?[{id:"app-modes",slot:LoopSlots.promptAction,order:5,Component:Lu}]:[],...ju?[{id:"app-uploads",slot:LoopSlots.promptAction,order:4,Component:Fu}]:[]]})}}const FEEDBACK_COMMENT_LIMIT=2e3,answerIdOf=Au=>Au>0?`answer-${Au}`:void 0,FEEDBACK_WORDS={ask:"Was this answer useful?",liked:"This answer was useful",disliked:"This answer was not useful",comment:"Anything to add? (optional)",send:"Send",kept:Au=>`Thank you. Kept in ${Au}’s record.`,where:Au=>`What you say is kept with this conversation in ${Au}’s record, for its builder to read.`,tooLong:`A comment is at most ${FEEDBACK_COMMENT_LIMIT} characters.`,noRuntime:"No runtime is assigned to this conversation, so nothing can be sent.",noSession:"This conversation has no name the application knows yet: send a message first."},keepsFeedback=Au=>(Au.record?.include??[]).includes("feedback"),feedbackEndpoint=Au=>`${Au.replace(/\/+$/,"")}/api/v1/apps/feedback`;function feedbackProblems(Au){const lo=[];return Au.session.trim()||lo.push(FEEDBACK_WORDS.noSession),Au.comment.trim().length>FEEDBACK_COMMENT_LIMIT&&lo.push(FEEDBACK_WORDS.tooLong),lo}async function sendFeedback(Au,{agentBaseUrl:lo,token:$u,fetcher:Ru=fetch}){const Iu=feedbackProblems(Au);if(Iu.length)throw new Error(Iu.join(" "));const Ou=await Ru(feedbackEndpoint(lo),{method:"POST",headers:{"Content-Type":"application/json",...$u?{Authorization:`Bearer ${$u}`}:{}},body:JSON.stringify({session:Au.session,liked:Au.liked,comment:Au.comment.trim(),...Au.message?{message:Au.message}:{}})}),Pu=await Ou.json().catch(()=>({}));if(!Ou.ok){const Du=typeof Pu.detail=="string"?Pu.detail:`${Ou.status}`;throw new Error(`The feedback was not kept: ${Du}`)}return String(Pu.summary??"")}const APP_FEEDBACK_PLUGIN_NAME="@datalayer/loop-plugin-app-feedback",NO_TURN$1=signal$2({id:0,status:"idle"}),NO_CONVERSATION=signal$2([]);function AppFeedback({app:Au,workspace:lo}){const $u=useContributions(LoopChatTurn),Ru=useSignalValue$1($u[0]?.value.turn??NO_TURN$1),Ou=useSignalValue$1($u[0]?.value.conversation??NO_CONVERSATION).filter(Ku=>Ku.role==="assistant").length,Pu=useIAMStore(Ku=>Ku.token),[Du,Lu]=reactExports.useState(null),[ju,Bu]=reactExports.useState(""),[Fu,zu]=reactExports.useState(null);if(Ru.status!=="done"||!Ru.assistant||!Ru.thread)return null;const qu=Ru.thread,Uu=Du?.turn===Ru.id?Du.liked:null,Hu=Fu?.turn===Ru.id?Fu:null,Vu=agentServerOf(lo.sandbox,lo.serverUrl),Gu=async()=>{if(Uu!==null){if(Vu===void 0){zu({turn:Ru.id,state:"refused",says:FEEDBACK_WORDS.noRuntime});return}zu({turn:Ru.id,state:"sending",says:""});try{await sendFeedback({session:qu,liked:Uu,comment:ju,message:answerIdOf(Ou)},{agentBaseUrl:Vu,token:Pu}),zu({turn:Ru.id,state:"kept",says:FEEDBACK_WORDS.kept(Au.name)}),Bu("")}catch(Ku){zu({turn:Ru.id,state:"refused",says:Ku instanceof Error?Ku.message:String(Ku)})}}};return Hu?.state==="kept"?jsxRuntimeExports.jsx("div",{style:{padding:"4px 8px"},children:jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:Hu.says})}):jsxRuntimeExports.jsxs("div",{role:"group","aria-label":FEEDBACK_WORDS.ask,style:{display:"flex",flexDirection:"column",gap:4,padding:"4px 8px"},children:[jsxRuntimeExports.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:FEEDBACK_WORDS.ask}),jsxRuntimeExports.jsx(IconButton,{size:"small",variant:Uu===!0?"default":"invisible",icon:ThumbsupIcon,"aria-label":FEEDBACK_WORDS.liked,"aria-pressed":Uu===!0,unsafeDisableTooltip:!0,onClick:()=>Lu({turn:Ru.id,liked:!0})}),jsxRuntimeExports.jsx(IconButton,{size:"small",variant:Uu===!1?"default":"invisible",icon:ThumbsdownIcon,"aria-label":FEEDBACK_WORDS.disliked,"aria-pressed":Uu===!1,unsafeDisableTooltip:!0,onClick:()=>Lu({turn:Ru.id,liked:!1})})]}),Uu!==null?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Textarea,{"aria-label":FEEDBACK_WORDS.comment,placeholder:FEEDBACK_WORDS.comment,value:ju,rows:2,resize:"vertical",block:!0,onChange:Ku=>Bu(Ku.target.value)}),jsxRuntimeExports.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[jsxRuntimeExports.jsx(ButtonComponent,{size:"small",variant:"default",disabled:Hu?.state==="sending",onClick:()=>{Gu()},children:FEEDBACK_WORDS.send}),jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:FEEDBACK_WORDS.where(Au.name)})]})]}):null,Hu?.state==="refused"?jsxRuntimeExports.jsx(Text$5,{role:"alert",sx:{fontSize:0,color:"fg.default"},children:Hu.says}):null]})}function defineAppFeedbackPlugin(Au){function lo({workspace:$u}){return jsxRuntimeExports.jsx(AppFeedback,{app:Au,workspace:$u})}return{name:`${APP_FEEDBACK_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: feedback`,description:`A thumb and a comment on each answer of ${Au.name}, kept in its record.`,octicon:"thumbsup",emoji:"👍",contributes:[contribution(LoopPromptPanel,{id:"app-feedback",placement:"above",order:20,Component:lo},{id:"app-feedback"})]}}const KEPT_ITEMS={conversations:"this conversation",actions:"what it does",decisions:"how its rules decided",approvals:"what is approved",checks:"what its checks stopped",outputs:"its answers",feedback:"what you say of its answers"},RETENTION=/^([1-9]\d*)_(day|days|month|months|year|years)$/;function keptForWords(Au){const lo=RETENTION.exec(Au.trim());if(!lo)throw new Error(`Cannot read the retention \`${Au}\`: write 90_days, 18_months or 1_years.`);const $u=Number(lo[1]),Ru=lo[2].replace(/s$/,"");return $u===1?`a ${Ru}`:`${$u} ${Ru}s`}function inWords(Au){return Au.length<2?Au[0]??"":`${Au.slice(0,-1).join(", ")} and ${Au[Au.length-1]}`}function keptBeforeFirstMessage(Au,{visitor:lo=!1}={}){if(lo)return"Nothing of this conversation is kept: you are not signed in.";const $u=Au.name||"This application",Ru=keptForWords(Au.record.keepFor),Iu=Au.record.include.map(Ou=>KEPT_ITEMS[Ou]).filter(Ou=>!!Ou);return Iu.length?`${$u} keeps ${inWords(Iu)} for ${Ru}, then deletes it.`:`${$u} keeps only that this conversation took place, for ${Ru}.`}const beforeFirstMessage=Au=>Au.id===0&&!Au.user,APP_KEPT_PLUGIN_NAME="@datalayer/loop-plugin-app-kept",NO_TURN=signal$2({id:0,status:"idle"});function AppKept({says:Au}){const lo=useContributions(LoopChatTurn),$u=useSignalValue$1(lo[0]?.value.turn??NO_TURN);return beforeFirstMessage($u)?jsxRuntimeExports.jsx("div",{role:"note",style:{padding:"4px 8px"},children:jsxRuntimeExports.jsx(Text$5,{sx:{fontSize:0,color:"fg.muted"},children:Au})}):null}function defineAppKeptPlugin(Au,lo){function $u(){return jsxRuntimeExports.jsx(AppKept,{says:lo})}return{name:`${APP_KEPT_PLUGIN_NAME}-${Au.id}`,displayName:`${Au.name}: what it keeps`,description:`What ${Au.name} keeps of a conversation, and for how long, said before the first message.`,octicon:"archive",emoji:"🗄",contributes:[contribution(LoopPromptPanel,{id:"app-kept",placement:"below",order:30,Component:$u},{id:"app-kept"})]}}const appPluginName=Au=>`loop-app-${Au}`;function appPluginPair(Au){const lo=appPluginName(Au);return{page:{name:lo,requiredBackendPlugins:[lo]},server:{name:lo,frontendDependencies:[lo]},extension:lo}}const appPluginsBase=(Au,lo)=>`${Au.replace(/\/+$/,"")}/api/v1/apps/${encodeURIComponent(lo)}`;function appRuntimeOf({target:Au,snapshot:lo,serverUrl:$u}){if(!(!Au||Au==="browser")){if(lo.agentBaseUrl)return lo.agentBaseUrl;if(Au!=="datalayer")return lo.state==="running"&&$u?$u:void 0}}const APP_RUNTIME_PLUGIN_NAME="@datalayer/loop-plugin-app-runtime",runningOf=Au=>lo=>Au.includes(lo);function AppRuntimePlugins({appId:Au,pageSide:lo=!1}){const $u=useReactorPlatform(),Ru=useOptionalSandboxService(),Iu=useSignalValue$1(Ru?.target??IDLE_SANDBOX_TARGET_SIGNAL),Ou=useSignalValue$1(Ru?.snapshot??IDLE_SANDBOX_SNAPSHOT_SIGNAL),Pu=appRuntimeOf({target:Iu,snapshot:Ou,serverUrl:Ru?.serverUrl}),Du=appPluginName(Au);reactExports.useEffect(()=>{Pu||(registerReactor($u,runningOf([Du])),$u.setBackendPlugins([Du]))},[$u,Pu,Du]);const Lu=reactExports.useCallback(ju=>registerReactor($u,runningOf(ju.plugins.filter(Bu=>Bu.enabled).map(Bu=>Bu.name))),[$u]);return useBackendPluginStream(Pu?appPluginsBase(Pu,Au):void 0,{onState:Lu}),reactExports.useEffect(()=>{if(!Pu||!lo)return;let ju=!0;return bootstrapExtensions(appPluginsBase(Pu,Au)).then(Bu=>{for(const Fu of Bu.filter(zu=>zu.name===Du))ju&&$u.install(Fu)}),()=>{ju=!1}},[$u,Pu,Au,Du,lo]),null}function defineAppRuntimePlugin(Au,{pageSide:lo=!1}={}){const $u=()=>jsxRuntimeExports.jsx(AppRuntimePlugins,{appId:Au,pageSide:lo});return{name:APP_RUNTIME_PLUGIN_NAME,displayName:"Its runtime",description:"Tells the application’s page which of its plugins its runtime holds.",octicon:"server",build:()=>({components:[{slot:LoopSlots.status,id:"app-runtime-plugins",Component:$u}]})}}const agentIdOf=Au=>{const lo=Au.agent||Au.team,$u=lo.lastIndexOf(":");return $u>0&&lo.slice($u+1).includes(".")?lo.slice(0,$u):lo};function defineAppPlugin(Au,lo=Au){if(!Au.agent)throw new Error(`“${Au.name}” is run by a team, which the workspace does not run as an application yet.`);const $u=appPluginPair(Au.id);return defineAgentCapacityPlugin({key:`app-${Au.id}`,name:$u.page.name,requiredBackendPlugins:$u.page.requiredBackendPlugins,displayName:lo.name,description:lo.description||`The ${lo.name} application`,specId:agentIdOf(Au),emoji:Au.emoji,createPayload:{name:Au.id,app_spec:dumpAppspec(Au),enable_codemode:!!Au.permissions?.computer?.shell,...Au.model?{model:Au.model}:{}},suggestions:startersAsOpeners(lo.interface.starters),instructions:Au.instructions,model:Au.model,...(Au.interface.modes??[]).length>0||(Au.interface.profiles??[]).length>0?{modeEffect:(Ru,Iu)=>modeEffect(Au,Ru,Iu)}:{}})}function appExtension(Au,lo,$u){return defineExtension({name:appPluginPair(Au.id).extension,displayName:lo.name,description:lo.description||`The ${lo.name} application`,emoji:Au.emoji,version:Au.version,plugins:$u})}function appLayoutOptions(Au){const lo=Au.interface.layout;if(lo==="chat")return{editors:!1,showViewSelector:!1};const $u=hasAppPage(Au);return{editors:!$u,showViewSelector:!$u,...$u?{defaultEditor:APP_PAGE_SURFACE}:{},pageLayout:!0,pageLayoutArrangement:lo==="split"?"split":"page",pageLayoutPrompt:"floating",pageLayoutPromptAnchor:"bottom",pageLayoutTurnPanelFooter:"actions"}}function appPreset(Au,lo={}){if(Au.kind==="decision"){if(!lo.page)throw new Error(`“${Au.name}” is a decision, whose page is drawn by where it runs: none was given here.`);return{plugins:[defineAppHostPagePlugin(Au,lo.page)],workspace:{conversation:!1,editors:!1,showViewSelector:!1}}}const $u=hasAppPage(Au),Ru=lo.shown??Au,Iu=new Set((lo.pluginsOff??[]).map(canvasBlocksPluginName)),Ou=CANVAS_BLOCK_PLUGINS.filter(Pu=>!Iu.has(Pu.name));return{plugins:[defineAppPlugin(Au,Ru),defineAppRuntimePlugin(Au.id,{pageSide:hasFolderModules(Au)}),...$u?[defineAppPagePlugin(Ru),...Ou]:[],...hasCustomComponents(Au)?[defineAppComponentsPlugin(Au)]:[],...needsAppComposer(Au)?[defineAppComposerPlugin(Ru)]:[],...keepsFeedback(Au)?[defineAppFeedbackPlugin(Au)]:[],...lo.kept?[defineAppKeptPlugin(Au,keptBeforeFirstMessage(Au,lo.kept))]:[],...lo.sidebar?[defineAppRulesPlugin(Au),defineAppActivityPlugin(Au,lo.appUid),defineAppComputerPlugin(Au)]:lo.computer?[defineAppComputerPlugin(Au)]:[],AppElementsPlugin],workspace:appLayoutOptions(Au)}}function appDatalayerCreatePayload(Au,lo){return{name:Au.id,transport:"ag-ui",agent_spec_id:agentIdOf(Au),app_spec:dumpAppspec(Au),enable_codemode:!!Au.permissions?.computer?.shell,...lo?{app_instance:{app_uid:lo.appUid??"",deployment_uid:lo.deploymentUid??"",version:lo.version??0,...lo.organizationUid?{organization_uid:lo.organizationUid}:{}}}:{}}}const DATALAYER_BOOTSTRAP_AGENTSPEC="example-simple",NO_PLUGINS$1=[];function appThemeOverrides(Au){const lo=Au.interface?.accent;return lo?{light:themeAccentVars(lo,"light"),dark:themeAccentVars(lo,"dark")}:void 0}function AppRenderer({app:Au,plugins:lo=NO_PLUGINS$1,instance:$u,onPresence:Ru,onSaying:Iu,paused:Ou=!1,sidebar:Pu=!1,computer:Du=!1,frame:Lu=!1,page:ju,pluginsOff:Bu,language:Fu,...zu}){const qu=JSON.stringify(dumpAppspec(Au)),Uu=[...Bu??[]].sort().join(","),Hu=(Fu?[Fu]:preferredLanguages()).join(","),Vu=reactExports.useMemo(()=>translatedAppspec(Au,Hu.split(",").filter(Boolean)),[qu,Hu]),Gu=!!$u?.deploymentUid,Ku=!!zu.datalayerVisitors,Zu=reactExports.useMemo(()=>{try{return appPreset(Au,{page:ju,pluginsOff:Bu,sidebar:Pu,computer:Du,appUid:$u?.appUid,shown:Vu,...Gu?{kept:{visitor:Ku}}:{}})}catch(ld){return{problem:ld instanceof Error?ld.message:String(ld)}}},[qu,Vu,ju,Uu,Pu,Du,$u?.appUid,Gu,Ku]),Qu=reactExports.useMemo(()=>"problem"in Zu?lo:[appExtension(Au,Vu,Zu.plugins),...lo],[Zu,lo]),Yu=!("problem"in Zu)&&Zu.workspace.conversation!==!1,ed=reactExports.useMemo(()=>Yu?appDatalayerCreatePayload(Au,$u):void 0,[qu,Yu,$u?.appUid,$u?.deploymentUid,$u?.version]),Xu=useSystemColorMode(),rd=Au.interface?.theme,nd=rd?.mode==="auto"?Xu:rd?.mode==="light"||rd?.mode==="dark"?rd.mode:void 0,od=Au.interface?.accent,ad=reactExports.useMemo(()=>appThemeOverrides(Au),[od]);return"problem"in Zu?jsxRuntimeExports.jsx("div",{role:"status",style:{padding:16},children:Zu.problem}):jsxRuntimeExports.jsx(ChatLanguage,{language:Fu,children:jsxRuntimeExports.jsx(LoopEmbed,{agentId:Au.id,...Zu.workspace,...Lu?{frameTitle:[Au.emoji,Vu.name].filter(Boolean).join(" ")}:{},sidebarRail:Pu||Du,teamPicker:!1,showAgentVariants:!1,pluginsPanel:!1,datalayerAgentSpecId:DATALAYER_BOOTSTRAP_AGENTSPEC,targetFixed:!0,...rd?{themeVariant:rd.variant}:{},...nd?{colorMode:nd}:{},themeOverrides:ad,presence:{name:Vu.name,face:Au.emoji,welcome:Vu.interface.welcome||Vu.description,paused:Ou,onPresence:Ru,onSaying:Iu},showTokenUsage:!1,datalayerCreatePayload:ed,...zu,plugins:Qu})})}const ASSISTANT_CHARACTERS_PLUGIN_NAME="@datalayer/loop-plugin-assistant-characters",AssistantCharactersPlugin={name:ASSISTANT_CHARACTERS_PLUGIN_NAME,displayName:"Assistant characters",description:"Datalayer's own characters for the floating assistant: a paper clip, a wizard, a cat and the L👀P eyes.",octicon:"paperclip",contributes:ASSISTANT_CHARACTERS.map(Au=>contribution(LoopAssistantCharacter,{id:Au.id,character:Au},{id:Au.id}))};function assistantCharactersOf(Au){return Au.getContributions(LoopAssistantCharacter).map(lo=>lo.value)}function assistantCharactersFrom(Au){const lo=buildReactorFromPlugins(Au);lo.start();try{return assistantCharactersOf(lo)}finally{lo.stop()}}function assistantCharacterFor(Au,lo){const $u=lo.app?"app":lo.person?"person":"default",Ru=lo.app??lo.person??DEFAULT_ASSISTANT_CHARACTER,Iu=Au.find(Pu=>Pu.id===Ru);return Iu?{id:Ru,character:Iu.character,saidBy:$u}:{saidBy:$u,problem:`${$u==="app"?"This application names":$u==="person"?"Your settings name":"The default is"} the character “${Ru}”, which nothing enabled here draws; the characters are ${Au.map(Pu=>Pu.id).join(", ")||"none"}.`}}const EMBED_TAG="datalayer-app",EMBED_ATTRIBUTES={app:"The application’s id on Datalayer.",origin:"Where Datalayer is; the origin the script was loaded from by default.",token:"An embed token for an application that is not public, issued to your server for each visit.",spec:"The address of an Appspec (YAML or JSON) to run, in place of `app`.",mode:"inline, bubble, panel or assistant; the Appspec’s `deployment.embedded.mode` by default, then inline.",accent:"green, rose, sky, lime, sun or violet; the Appspec’s `interface.accent` by default, else the theme’s own colours.",theme:"light, dark or auto (the visitor’s system); auto by default.",font:"A CSS font family for the application’s text; Inter, then the system’s sans-serif, by default.",server:"An agent-runtimes server the application’s agent runs on; a Datalayer runtime by default.",api:"Datalayer’s API, where an application is read with its token; the platform’s by default.",height:"The height of an inline application, in pixels; 640 by default.",resume:"true or false: whether a visit’s conversation is picked up again after the page reloads, kept in the page’s storage; true by default.",language:"The language the visitor reads the application in, as BCP 47 tags it (fr, pt-BR): its translation into it, and the chat’s own words; the visitor’s browser’s by default.","user-token":"A token your server signed with the deployment’s secret, naming your user (HS256: sub, name, exp at most an hour away): what an application that says user: signed opens its session with."},EMBED_OBSERVED_ATTRIBUTES=Object.keys(EMBED_ATTRIBUTES),EMBED_HOST_VARIABLES={accent:"--datalayer-app-accent",font:"--datalayer-app-font",theme:"--datalayer-app-theme"},EMBED_COLOR_MODES=["light","dark","auto"],EMBED_FLOATING_VIEWS={bubble:"floating-small",panel:"panel",assistant:"assistant"};function floatingViewOf(Au){return Au==="inline"?void 0:EMBED_FLOATING_VIEWS[Au]}class EmbedAttributeError extends Error{constructor(lo){super(lo),this.name="EmbedAttributeError"}}function runnable({app:Au,problems:lo}){if(!Au.id)throw new EmbedAttributeError(`datalayer-app: the Appspec names no application${lo.length?` (${lo[0]})`:""}.`);if(Au.kind!=="decision"&&!Au.agent)throw new EmbedAttributeError(`datalayer-app: “${Au.name||Au.id}” names no agent to answer; an embedded application is run by an agent (a team is not supported yet).`);return Au}const listed=Au=>`${Au.slice(0,-1).join(", ")} or ${Au[Au.length-1]}`;function oneOf(Au,lo,$u){const Ru=Au?.trim();if(Ru){if(!lo.includes(Ru))throw new EmbedAttributeError(`datalayer-app: "${Ru}" is not ${$u}; it is ${listed(lo)}.`);return Ru}}function checkedFont(Au){const lo=Au?.trim()??"";if(!lo)return"";if(!/^[\w\s,"'.-]+$/u.test(lo))throw new EmbedAttributeError(`datalayer-app: the font "${lo}" is not a font family; write it as a CSS font-family is written, such as "Georgia, serif".`);return lo}function embedLookOf(Au,lo){const{attributes:$u,variables:Ru={}}=Au,Iu=oneOf($u.mode,APP_EMBED_MODES,"a mode")??lo?.deployment?.embedded?.mode??"inline",Ou=oneOf($u.accent,APP_ACCENTS,"an accent")??oneOf(Ru.accent,APP_ACCENTS,"an accent")??lo?.interface?.accent,Pu=oneOf($u.theme,EMBED_COLOR_MODES,"a theme")??oneOf(Ru.theme,EMBED_COLOR_MODES,"a theme")??lo?.interface?.theme?.mode??"auto",Du=checkedFont($u.font)||checkedFont(Ru.font),Lu=lo?.interface?.theme?.variant??"loop";return{mode:Iu,accent:Ou,colorMode:Pu,font:Du,variant:Lu}}function resumeOf(Au){return oneOf(Au,["true","false"],"a value of resume")!=="false"}function languageOf(Au){const lo=Au?.trim();if(lo){if(!LANGUAGE_TAG.test(lo))throw new EmbedAttributeError(`datalayer-app: "${lo}" is not a language as BCP 47 tags it, such as fr or pt-BR.`);return lo}}function inlineHeightOf(Au){const lo=Number.parseInt(Au??"",10);return Number.isFinite(lo)&&lo>=240?lo:640}const EMBED_PROPERTIES=["context","functions","token"];function adoptPropertiesSetEarly(Au,lo=EMBED_PROPERTIES){const $u=[],Ru=Au;for(const Iu of lo)if(Object.prototype.hasOwnProperty.call(Au,Iu)){const Ou=Ru[Iu];delete Ru[Iu],Ru[Iu]=Ou,$u.push(Iu)}return $u}const CHAT_EXTRAS_PLUGIN_NAME="@datalayer/loop-plugin-chat-extras";let counter=0;function createChatExtrasPlugin(){const Au=`chat-extras-${counter+=1}`,lo=signal$2({});return{plugin:{name:CHAT_EXTRAS_PLUGIN_NAME,displayName:"Chat Extras",description:"A host example’s live banner and footer status.",octicon:"megaphone",emoji:"📣",contributes:[contribution(LoopChatExtras,{id:Au,extras:lo},{id:Au})]},setExtras:Ru=>{lo.value=Ru}}}const HOST_CONTEXT_TOOL="host_context",hostTool=Au=>`host_${Au}`;function signedUser(Au){return Au?.user==="signed"}const hostRefused=Au=>`No rule of this application names ${Au}: it is left to the person, and the page was not called.`,hostNotAllowed=Au=>`The person did not allow ${Au}: the page was not called.`,confirmOnPage=Au=>typeof window<"u"&&typeof window.confirm=="function"?window.confirm(Au.sentence):!1,actionOf=(Au,lo)=>Au.rules.find($u=>$u.appliesTo.includes(lo))?.action;function hostFrontendTools(Au,lo){const $u=Au.deployment.embedded?.host;if(!$u)return[];const Ru=Pu=>behaviourFor(Au,Pu),Iu=Pu=>Ru(Pu)!=="leave_to_me",Ou=[];$u.context.length>0&&Ou.push({name:HOST_CONTEXT_TOOL,description:`What the page you are embedded in says of its visitor and of itself: ${$u.context.join(", ")}. Read it before answering what depends on them.`,parameters:{type:"object",properties:{}},location:"frontend",handler:async()=>{if(!Iu(HOST_CONTEXT_TOOL))return{error:hostRefused(HOST_CONTEXT_TOOL)};const Pu=lo().context?.()??{},Du={},Lu=[];for(const ju of $u.context)Pu[ju]===void 0?Lu.push(ju):Du[ju]=Pu[ju];return{values:Du,...Lu.length>0?{unsaid:Lu}:{}}}});for(const Pu of $u.functions){const Du=hostTool(Pu.name);Ou.push({name:Du,description:Pu.description,parameters:Pu.parameters,location:"frontend",handler:async Lu=>{const ju=Fu=>(lo().onEvent?.({type:"action",detail:{function:Pu.name,arguments:Lu,...Fu}}),Fu);if(!Iu(Du))return ju({error:hostRefused(Du)});if(Ru(Du)!=="do_it"){const Fu=actionOf(Au,Du)??Pu.description;if(!await(lo().ask??confirmOnPage)({function:Pu.name,arguments:Lu,sentence:`${Fu}? (${Pu.name} with ${JSON.stringify(Lu)})`}))return ju({error:hostNotAllowed(Du)})}const Bu=lo().functions?.[Pu.name];if(!Bu)return ju({error:`The page offers no function ${Pu.name}: it was not called.`});try{return ju({result:await Bu(Lu)})}catch(Fu){return ju({error:`The page's ${Pu.name} failed: ${Fu instanceof Error?Fu.message:String(Fu)}`})}}})}return Ou}function hostUserRunProps(Au,lo){if(signedUser(Au.deployment.embedded?.host))return{id:"host-user",props:()=>{const $u=lo().userToken?.()?.trim();return $u?{loop:{user_token:$u}}:{}}}}function withFace(Au,lo,$u){return!lo||!$u?Au:Object.fromEntries(Object.entries(Au).map(([Ru,Iu])=>[Ru,typeof Iu=="string"?Iu.split($u).join(lo):Iu]))}function faceOf(Au,lo){return Au==="loop"?loopFontFamily:typeof lo.fontFamily=="string"?lo.fontFamily:""}const accentOver=(Au,lo)=>Au?themeAccentVars(Au,lo):{};function embedThemeStyles({accent:Au,font:lo="",variant:$u="loop"}){const Ru=getThemeConfig($u).themeStyles,Iu=Ou=>{const Pu=Ru[Ou];return withFace({...Pu,...accentOver(Au,Ou)},lo,faceOf($u,Pu))};return{...Ru,light:Iu("light"),dark:Iu("dark")}}function embedThemeOverrides({accent:Au,font:lo="",variant:$u="loop"}){const Ru=getThemeConfig($u).themeStyles,Iu=Ou=>{const Pu=Ru[Ou];return{...Object.fromEntries(Object.entries(withFace(Pu,lo,faceOf($u,Pu))).filter(([Lu,ju])=>typeof ju=="string"&&ju!==Pu[Lu])),...accentOver(Au,Ou)}};return{light:Iu("light"),dark:Iu("dark")}}function embedShadowCss(Au){const lo=`
3770
3770
  :host {
3771
3771
  all: initial;
3772
3772
  display: block;
@@ -3799,6 +3799,6 @@ iframe.datalayer-app-frame {
3799
3799
  min-height: 240px;
3800
3800
  }
3801
3801
  `;return Au?`${lo}
3802
- ${scopeThemeCss(Au,[`[${THEME_SCOPE_ATTRIBUTE}]`])}`:lo}const EMBED_SESSION_KEY_PREFIX="datalayer-app:session";function visitOfToken(Au){const lo=Au?.split(".")[1];if(lo)try{const $u=lo.replace(/-/g,"+").replace(/_/g,"/"),Ru=$u+"=".repeat((4-$u.length%4)%4),Iu=JSON.parse(atob(Ru));return typeof Iu.visit=="string"&&Iu.visit?Iu.visit:void 0}catch{return}}function embedSessionKey(Au,lo){return`${EMBED_SESSION_KEY_PREFIX}:${Au}:${lo}`}const IN_MEMORY=new Map;function hostStorage(){try{return typeof window<"u"?window.localStorage:void 0}catch{return}}function sessionKeeper({persist:Au,storage:lo=hostStorage}){return{read:$u=>{if(Au)try{const Ru=lo()?.getItem($u);if(Ru)return Ru}catch{}return IN_MEMORY.get($u)},keep:($u,Ru)=>{if(IN_MEMORY.set($u,Ru),Au)try{lo()?.setItem($u,Ru)}catch{}},forget:$u=>{IN_MEMORY.delete($u);try{lo()?.removeItem($u)}catch{}}}}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:Ou}=$u;(Iu==="user"||Iu==="assistant")&&typeof Ru=="string"&&typeof Ou=="string"&&Ou.trim()&&lo.push({id:Ru,role:Iu,content:Ou,createdAt:new Date})}return lo}async function reattachSession({serverUrl:Au,uid:lo,token:$u,fetcher:Ru=fetch}){try{const Iu=await Ru(`${Au.replace(/\/+$/,"")}/api/v1/apps/sessions/${encodeURIComponent(lo)}/messages`,{headers:{Authorization:`Bearer ${$u}`}});if(!Iu.ok)return{kind:"gone",uid:lo};const Ou=await Iu.json();return{kind:"resumed",uid:lo,messages:messagesOfThread(Ou.messages)}}catch{return{kind:"gone",uid:lo}}}const WINDOW_NOT_YET='The application takes a window message once its conversation has started, on its own server (the "server" attribute).';async function postWindowMessage({serverUrl:Au,uid:lo,token:$u,data:Ru,fetcher:Iu=fetch}){const Ou=await Iu(`${Au.replace(/\/+$/,"")}/api/v1/apps/sessions/${encodeURIComponent(lo)}/window`,{method:"POST",headers:{"content-type":"application/json",...$u?{Authorization:`Bearer ${$u}`}:{}},body:JSON.stringify({data:Ru})});if(!Ou.ok){let Du="";try{const Lu=await Ou.json();Du=typeof Lu.detail=="string"?Lu.detail:""}catch{}throw new Error(Du||`The window message was refused (${Ou.status}).`)}const Pu=windowTurnOf(await Ou.text());if(Pu.error)throw new Error(Pu.error);return Pu.said}const sessionGoneSentence=Au=>`Your earlier conversation with ${Au} has ended, so this is a new one.`;function useEmbedSession({app:Au,serverUrl:lo,embedToken:$u,resume:Ru=!0}){const Iu=lo&&$u?visitOfToken($u):void 0,Ou=Iu?embedSessionKey(Au.id,Iu):void 0,Pu=reactExports.useMemo(()=>sessionKeeper({persist:Ru}),[Ru]),[Du,Lu]=reactExports.useState();return reactExports.useEffect(()=>{if(!Ou||!lo||!$u)return;let ju=!1;const Bu=qu=>{Pu.keep(Ou,qu),Lu(Uu=>Uu?.said?{...Uu,said:void 0}:Uu)},Fu=qu=>Lu({token:$u,thread:{id:generateMessageId(),messages:[],onStarted:Bu},...qu?{said:qu}:{}}),zu=Pu.read(Ou);if(!zu){Fu();return}return reattachSession({serverUrl:lo,uid:zu,token:$u}).then(qu=>{if(!ju){if(qu.kind==="resumed"){Lu({token:$u,thread:{id:zu,messages:qu.messages,onStarted:Bu}});return}Pu.forget(Ou),Fu(sessionGoneSentence(Au.name))}}),()=>{ju=!0}},[Ou,lo,$u,Pu]),Ou?!Du||Du.token!==$u?{ready:!1}:{ready:!0,thread:Du.thread,...Du.said?{said:Du.said}:{}}:{ready:!0}}function useWindowPort({serverUrl:Au,embedToken:lo,session:$u,host:Ru}){const Iu=reactExports.useRef(Ru);Iu.current=Ru;const Ou=$u.thread,Pu=reactExports.useRef(Ou?.messages.length?Ou.id:void 0),Du=reactExports.useMemo(()=>({id:generateMessageId(),messages:[]}),[]),Lu=Ou??(Au&&$u.ready?Du:void 0),ju=reactExports.useMemo(()=>Lu&&{...Lu,onStarted:Bu=>{Pu.current=Bu,Lu.onStarted?.(Bu)}},[Lu]);return reactExports.useEffect(()=>{const Bu=Ru?.onWindowPort;if(!(!Au||!Bu))return Bu(async Fu=>{if(!Pu.current)throw new Error(WINDOW_NOT_YET);const zu=await postWindowMessage({serverUrl:Au,uid:Pu.current,...lo?{token:lo}:{},data:Fu});for(const qu of zu)Iu.current?.onEvent?.({type:"window-message",detail:{data:qu}})}),()=>Bu(null)},[Au,lo,Ru]),ju?{...$u,thread:ju}:$u}function SessionSaid({said:Au}){return Au?jsxRuntimeExports.jsx(Text$5,{as:"p",role:"status",sx:{px:3,py:2,m:0,fontSize:1},children:Au}):null}const NO_HOST_PLUGINS=[];function useHostBridge(Au,lo){const $u=reactExports.useRef(lo);$u.current=lo;const Ru=reactExports.useMemo(()=>createChatExtrasPlugin(),[]),Iu=Au.deployment.embedded?.host,Ou=JSON.stringify([Iu??null,Au.rules,Au.connections]);reactExports.useEffect(()=>{Ru.setExtras({frontendTools:hostFrontendTools(Au,()=>$u.current??{})})},[Ru,Ou]);const Pu=Iu?.user==="signed",Du=reactExports.useMemo(()=>{const Uu=hostUserRunProps(Au,()=>$u.current??{});return Uu?{name:`loop-host-user-${Au.id}`,displayName:`${Au.name}: who its user is`,description:`The token naming its user that the host's server signed, sent with every run of ${Au.name}.`,octicon:"person",emoji:"👤",contributes:[contribution(LoopRunProps,Uu,{id:"host-user"})]}:void 0},[Au.id,Pu]),Lu=reactExports.useMemo(()=>Iu?[Ru.plugin,...Du?[Du]:[]]:NO_HOST_PLUGINS,[Iu,Ru,Du]);reactExports.useEffect(()=>onLoopWindowMessage(Uu=>$u.current?.onEvent?.({type:"window-message",detail:{data:Uu}})),[]);const ju=reactExports.useRef({answering:!1}),Bu=reactExports.useRef("idle"),Fu=reactExports.useRef(""),zu=reactExports.useCallback(Uu=>{ju.current=Uu},[]),qu=reactExports.useCallback(Uu=>{const Hu=Bu.current;Bu.current=Uu;const Vu=Uu==="idle"||Uu==="waiting",Gu=ju.current.saying;Vu&&Hu!=="idle"&&Hu!=="waiting"&&ju.current.answering&&Gu&&Gu.id!==Fu.current&&(Fu.current=Gu.id,$u.current?.onEvent?.({type:"message",detail:{id:Gu.id,text:Gu.markdown||Gu.text}}))},[]);return{plugins:Lu,onPresence:qu,onSaying:zu}}const NO_PLUGINS=[];function embedAssistantCharacter(Au,lo=NO_PLUGINS){return assistantCharacterFor(assistantCharactersFrom([AssistantCharactersPlugin,...lo]),{app:Au.interface.assistant})}const signedOutSentence=Au=>`${Au.name} runs on Datalayer, which needs you signed in. An application embedded for visitors who are not needs its embed token (LOOP D-14), or an agent-runtimes server of the host's own (the "server" attribute).`;function Face({emoji:Au}){return jsxRuntimeExports.jsx(FluentEmoji,{emoji:Au,size:20,label:""})}function AppFloating({app:Au,view:lo,colorMode:$u,themeVariant:Ru,themeOverrides:Iu,character:Ou,serverUrl:Pu,instance:Du,embedToken:Lu,renderer:ju,host:Bu,session:Fu,language:zu}){const qu=useChatWords(),[Uu,Hu]=reactExports.useState("idle"),[Vu,Gu]=reactExports.useState({answering:!1}),Ku=useHostBridge(Au,Bu),Zu=reactExports.useCallback(rd=>{Hu(rd),Ku.onPresence(rd)},[Ku.onPresence]),Qu=reactExports.useCallback(rd=>{Gu(rd),Ku.onSaying(rd)},[Ku.onSaying]),Yu=Au.interface.welcome||Au.description,ed=useIAMStore(rd=>rd.token),Xu=!Pu&&!ed&&!ju?.datalayerVisitors;return jsxRuntimeExports.jsx(ChatFloating,{defaultViewMode:lo,...Ou?{assistantCharacter:Ou}:{},...Au.interface.balloon?{balloonDisplay:Au.interface.balloon}:{},title:Au.name,description:Yu,brandIcon:jsxRuntimeExports.jsx(Face,{emoji:Au.emoji}),buttonIcon:jsxRuntimeExports.jsx(Face,{emoji:Au.emoji}),buttonTooltip:qu.talkTo(Au.name),colorMode:$u,useStore:!1,conversation:{body:Xu?jsxRuntimeExports.jsx(Text$5,{as:"p",role:"status",sx:{p:3,m:0,fontSize:1},children:signedOutSentence(Au)}):Fu&&!Fu.ready?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(SessionSaid,{said:Fu?.said}),jsxRuntimeExports.jsx(AppRenderer,{app:Au,target:Pu?"local":"datalayer",...Pu?{serverUrl:Pu}:{},...Pu&&Lu?{embedToken:Lu}:{},instance:Du,themeOverrides:Iu,colorMode:$u,...Ru?{themeVariant:Ru}:{},hideChatHeader:!0,autoFocusPrompt:!1,onPresence:Zu,onSaying:Qu,plugins:Ku.plugins,...Fu?.thread?{thread:Fu.thread}:{},...zu?{language:zu}:{},...ju})]}),presence:Uu,saying:Vu.saying,answering:Vu.answering}})}function OwnPortalRoot(){const Au=reactExports.useRef(null);return reactExports.useLayoutEffect(()=>{Au.current&&registerPortalRoot(Au.current)},[]),jsxRuntimeExports.jsx("div",{ref:Au,className:"datalayer-app-portal"})}function useSystemMode(){const Au=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-color-scheme: dark)"):null,[lo,$u]=reactExports.useState(!!Au?.matches);return reactExports.useEffect(()=>{if(!Au)return;const Ru=()=>$u(Au.matches);return Au.addEventListener?.("change",Ru),()=>Au.removeEventListener?.("change",Ru)},[Au]),lo?"dark":"light"}function EmbedThemed({accent:Au,colorMode:lo,font:$u,variant:Ru,children:Iu,style:Ou}){const Pu=reactExports.useMemo(()=>embedThemeStyles({accent:Au,font:$u,variant:Ru}),[Au,$u,Ru]);return jsxRuntimeExports.jsx("div",{"data-color-mode":lo,style:{display:"contents"},children:jsxRuntimeExports.jsx(DatalayerThemeProvider,{colorMode:lo,theme:getThemeConfig(Ru).primerTheme,themeStyles:Pu,baseStyles:Ou,children:Iu})})}function AppEmbed({app:Au,mode:lo,accent:$u,colorMode:Ru,font:Iu,language:Ou,serverUrl:Pu,instance:Du,embedToken:Lu,visitors:ju,height:Bu=640,ownPortal:Fu=!1,plugins:zu=NO_PLUGINS,host:qu,resume:Uu=!0}){const Hu=useHostBridge(Au,qu),Vu=reactExports.useMemo(()=>ju?{datalayerVisitors:ju}:void 0,[ju]),Gu=useEmbedSession({app:Au,serverUrl:Pu,embedToken:Lu,resume:Uu}),Ku=useWindowPort({serverUrl:Pu,embedToken:Lu,session:Gu,host:qu}),Zu=useSystemMode(),Qu=Au.interface.theme?.variant??"loop",Yu=Ru??Au.interface.theme?.mode??"auto",ed=Yu==="auto"?Zu:Yu,Xu=lo??Au.deployment.embedded?.mode??"inline",rd=floatingViewOf(Xu),nd=$u??Au.interface.accent,od=reactExports.useMemo(()=>embedThemeOverrides({accent:nd,font:Iu,variant:Qu}),[nd,Iu,Qu]),ad=Au.interface.assistant,ld=reactExports.useMemo(()=>rd==="assistant"?embedAssistantCharacter(Au,zu):void 0,[rd,ad,zu]);if(ld&&"problem"in ld)return jsxRuntimeExports.jsx("p",{role:"status",className:"datalayer-app-said",children:ld.problem});const fd=ld?.character;return jsxRuntimeExports.jsx(ChatLanguage,{language:Ou,children:jsxRuntimeExports.jsxs(EmbedThemed,{accent:nd,colorMode:ed,font:Iu,variant:Qu,style:rd?{backgroundColor:"transparent"}:{height:Bu,display:"flex",flexDirection:"column"},children:[Fu?jsxRuntimeExports.jsx(OwnPortalRoot,{}):null,rd?jsxRuntimeExports.jsx(AppFloating,{app:Au,view:rd,serverUrl:Pu,instance:Du,embedToken:Lu,colorMode:ed,themeVariant:Qu,themeOverrides:od,character:fd,host:qu,session:Ku,...Vu?{renderer:Vu}:{},...Ou?{language:Ou}:{}}):Ku.ready?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(SessionSaid,{said:Ku.said}),jsxRuntimeExports.jsx(AppRenderer,{app:Au,target:Pu?"local":"datalayer",...Pu?{serverUrl:Pu}:{},...Pu&&Lu?{embedToken:Lu}:{},...Vu??{},instance:Du,themeOverrides:od,colorMode:ed,themeVariant:Qu,plugins:Hu.plugins,onPresence:Hu.onPresence,onSaying:Hu.onSaying,...Ku.thread?{thread:Ku.thread}:{},...Ou?{language:Ou}:{}})]}):null]})})}const VISITORS_PATH="/api/loop-visitors",VISITOR_EXAMPLES=["web-research","customer-interview"],AT_PREFIX="at:",DEFAULT_API="https://prod1.datalayer.run",isAppUid=Au=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(Au),SLUG=/^[a-z0-9][a-z0-9-]{0,62}$/;function visitorsAt(Au,lo){const $u=Au.replace(/\/+$/,"");return{url:`${$u}${VISITORS_PATH}`,app:lo,inferenceUrl:$u}}const TOKEN_HINT='Embedded for a visitor it refuses, it takes its embed token (the "token" attribute).',notKeptSentence=Au=>`datalayer-app: "${Au}" is an example Datalayer does not keep ready for visitors (${VISITOR_EXAMPLES.join(", ")} are); embed it at its address once it is deployed. ${TOKEN_HINT}`,refusedSentence=Au=>`datalayer-app: ${Au.trim().replace(/\.?\s*Sign in to use it\.?$/,".")} ${TOKEN_HINT}`;async function readVisitorApp({api:Au=DEFAULT_API,app:lo,fetcher:$u=fetch,catalogue:Ru=getApp}){const Iu=lo.trim();if(isAppUid(Iu))return{kind:"decision",app:Iu};const Ou=Ru(Iu);if(Ou)return Ou.kind==="decision"?{kind:"decision",app:Iu}:VISITOR_EXAMPLES.includes(Ou.id)?{kind:"visitors",app:runnable({app:Ou,problems:[]}),visitors:visitorsAt(Au,Ou.id)}:{kind:"said",text:notKeptSentence(Iu)};if(!SLUG.test(Iu))return{kind:"said",text:`datalayer-app: "${Iu}" is neither an application's id, an example's, nor an address.`};let Pu;try{Pu=await $u(`${Au.replace(/\/+$/,"")}/api/ai-agents/v1/apps/deployments/at/${encodeURIComponent(Iu)}`)}catch(zu){return{kind:"said",text:`datalayer-app: Datalayer could not be reached to read "${Iu}" (${zu instanceof Error?zu.message:String(zu)}).`}}const Du=await Pu.json().catch(()=>({}));if(!Pu.ok||Du.success===!1){const zu=String(Du.detail??Du.message??`No application is at "${Iu}".`);return{kind:"said",text:refusedSentence(zu)}}const Lu=Du.session??{};if(!Lu.opens)return{kind:"said",text:refusedSentence(String(Lu.reason||`"${Iu}" is not run without an account.`))};const ju=Du.deployment??{},Bu=parseAppspec(Du.spec);if(Bu.app.kind==="decision")return{kind:"decision",app:Iu};const Fu=typeof ju.app_name=="string"&&ju.app_name?ju.app_name:Bu.app.name;return{kind:"visitors",app:runnable({app:{...Bu.app,name:Fu},problems:Bu.problems}),visitors:visitorsAt(Au,`${AT_PREFIX}${Iu}`)}}const EMBED_MESSAGES={size:"datalayer-app:size",decision:"datalayer-app:decision",token:"datalayer-app:token",tokenExpired:"datalayer-app:token-expired"};function appspecOfText(Au){const lo=Au.replace(/\t/g," ").split(`
3802
+ ${scopeThemeCss(Au,[`[${THEME_SCOPE_ATTRIBUTE}]`])}`:lo}const EMBED_SESSION_KEY_PREFIX="datalayer-app:session";function visitOfToken(Au){const lo=Au?.split(".")[1];if(lo)try{const $u=lo.replace(/-/g,"+").replace(/_/g,"/"),Ru=$u+"=".repeat((4-$u.length%4)%4),Iu=JSON.parse(atob(Ru));return typeof Iu.visit=="string"&&Iu.visit?Iu.visit:void 0}catch{return}}function embedSessionKey(Au,lo){return`${EMBED_SESSION_KEY_PREFIX}:${Au}:${lo}`}const IN_MEMORY=new Map;function hostStorage(){try{return typeof window<"u"?window.localStorage:void 0}catch{return}}function sessionKeeper({persist:Au,storage:lo=hostStorage}){return{read:$u=>{if(Au)try{const Ru=lo()?.getItem($u);if(Ru)return Ru}catch{}return IN_MEMORY.get($u)},keep:($u,Ru)=>{if(IN_MEMORY.set($u,Ru),Au)try{lo()?.setItem($u,Ru)}catch{}},forget:$u=>{IN_MEMORY.delete($u);try{lo()?.removeItem($u)}catch{}}}}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:Ou}=$u;(Iu==="user"||Iu==="assistant")&&typeof Ru=="string"&&typeof Ou=="string"&&Ou.trim()&&lo.push({id:Ru,role:Iu,content:Ou,createdAt:new Date})}return lo}async function reattachSession({serverUrl:Au,uid:lo,token:$u,fetcher:Ru=fetch}){try{const Iu=await Ru(`${Au.replace(/\/+$/,"")}/api/v1/apps/sessions/${encodeURIComponent(lo)}/messages`,{headers:{Authorization:`Bearer ${$u}`}});if(!Iu.ok)return{kind:"gone",uid:lo};const Ou=await Iu.json();return{kind:"resumed",uid:lo,messages:messagesOfThread(Ou.messages)}}catch{return{kind:"gone",uid:lo}}}const WINDOW_NOT_YET='The application takes a window message once its conversation has started, on its own server (the "server" attribute).';async function postWindowMessage({serverUrl:Au,uid:lo,token:$u,data:Ru,fetcher:Iu=fetch}){const Ou=await Iu(`${Au.replace(/\/+$/,"")}/api/v1/apps/sessions/${encodeURIComponent(lo)}/window`,{method:"POST",headers:{"content-type":"application/json",...$u?{Authorization:`Bearer ${$u}`}:{}},body:JSON.stringify({data:Ru})});if(!Ou.ok){let Du="";try{const Lu=await Ou.json();Du=typeof Lu.detail=="string"?Lu.detail:""}catch{}throw new Error(Du||`The window message was refused (${Ou.status}).`)}const Pu=windowTurnOf(await Ou.text());if(Pu.error)throw new Error(Pu.error);return Pu.said}const sessionGoneSentence=Au=>`Your earlier conversation with ${Au} has ended, so this is a new one.`;function useEmbedSession({app:Au,serverUrl:lo,embedToken:$u,resume:Ru=!0}){const Iu=lo&&$u?visitOfToken($u):void 0,Ou=Iu?embedSessionKey(Au.id,Iu):void 0,Pu=reactExports.useMemo(()=>sessionKeeper({persist:Ru}),[Ru]),[Du,Lu]=reactExports.useState();return reactExports.useEffect(()=>{if(!Ou||!lo||!$u)return;let ju=!1;const Bu=qu=>{Pu.keep(Ou,qu),Lu(Uu=>Uu?.said?{...Uu,said:void 0}:Uu)},Fu=qu=>Lu({token:$u,thread:{id:generateMessageId(),messages:[],onStarted:Bu},...qu?{said:qu}:{}}),zu=Pu.read(Ou);if(!zu){Fu();return}return reattachSession({serverUrl:lo,uid:zu,token:$u}).then(qu=>{if(!ju){if(qu.kind==="resumed"){Lu({token:$u,thread:{id:zu,messages:qu.messages,onStarted:Bu}});return}Pu.forget(Ou),Fu(sessionGoneSentence(Au.name))}}),()=>{ju=!0}},[Ou,lo,$u,Pu]),Ou?!Du||Du.token!==$u?{ready:!1}:{ready:!0,thread:Du.thread,...Du.said?{said:Du.said}:{}}:{ready:!0}}function useWindowPort({serverUrl:Au,embedToken:lo,session:$u,host:Ru}){const Iu=reactExports.useRef(Ru);Iu.current=Ru;const Ou=$u.thread,Pu=reactExports.useRef(Ou?.messages.length?Ou.id:void 0),Du=reactExports.useMemo(()=>({id:generateMessageId(),messages:[]}),[]),Lu=Ou??(Au&&$u.ready?Du:void 0),ju=reactExports.useMemo(()=>Lu&&{...Lu,onStarted:Bu=>{Pu.current=Bu,Lu.onStarted?.(Bu)}},[Lu]);return reactExports.useEffect(()=>{const Bu=Ru?.onWindowPort;if(!(!Au||!Bu))return Bu(async Fu=>{if(!Pu.current)throw new Error(WINDOW_NOT_YET);const zu=await postWindowMessage({serverUrl:Au,uid:Pu.current,...lo?{token:lo}:{},data:Fu});for(const qu of zu)Iu.current?.onEvent?.({type:"window-message",detail:{data:qu}})}),()=>Bu(null)},[Au,lo,Ru]),ju?{...$u,thread:ju}:$u}function SessionSaid({said:Au}){return Au?jsxRuntimeExports.jsx(Text$5,{as:"p",role:"status",sx:{px:3,py:2,m:0,fontSize:1},children:Au}):null}const NO_HOST_PLUGINS=[];function useHostBridge(Au,lo){const $u=reactExports.useRef(lo);$u.current=lo;const Ru=reactExports.useMemo(()=>createChatExtrasPlugin(),[]),Iu=Au.deployment.embedded?.host,Ou=JSON.stringify([Iu??null,Au.rules,Au.connections]);reactExports.useEffect(()=>{Ru.setExtras({frontendTools:hostFrontendTools(Au,()=>$u.current??{})})},[Ru,Ou]);const Pu=Iu?.user==="signed",Du=reactExports.useMemo(()=>{const Uu=hostUserRunProps(Au,()=>$u.current??{});return Uu?{name:`loop-host-user-${Au.id}`,displayName:`${Au.name}: who its user is`,description:`The token naming its user that the host's server signed, sent with every run of ${Au.name}.`,octicon:"person",emoji:"👤",contributes:[contribution(LoopRunProps,Uu,{id:"host-user"})]}:void 0},[Au.id,Pu]),Lu=reactExports.useMemo(()=>Iu?[Ru.plugin,...Du?[Du]:[]]:NO_HOST_PLUGINS,[Iu,Ru,Du]);reactExports.useEffect(()=>onLoopWindowMessage(Uu=>$u.current?.onEvent?.({type:"window-message",detail:{data:Uu}})),[]);const ju=reactExports.useRef({answering:!1}),Bu=reactExports.useRef("idle"),Fu=reactExports.useRef(""),zu=reactExports.useCallback(Uu=>{ju.current=Uu},[]),qu=reactExports.useCallback(Uu=>{const Hu=Bu.current;Bu.current=Uu;const Vu=Uu==="idle"||Uu==="waiting",Gu=ju.current.saying;Vu&&Hu!=="idle"&&Hu!=="waiting"&&ju.current.answering&&Gu&&Gu.id!==Fu.current&&(Fu.current=Gu.id,$u.current?.onEvent?.({type:"message",detail:{id:Gu.id,text:Gu.markdown||Gu.text}}))},[]);return{plugins:Lu,onPresence:qu,onSaying:zu}}const NO_PLUGINS=[];function embedAssistantCharacter(Au,lo=NO_PLUGINS){return assistantCharacterFor(assistantCharactersFrom([AssistantCharactersPlugin,...lo]),{app:Au.interface.assistant})}const signedOutSentence=Au=>`${Au.name} runs on Datalayer, which needs you signed in. An application embedded for visitors who are not needs its embed token (LOOP D-14), or an agent-runtimes server of the host's own (the "server" attribute).`;function Face({emoji:Au}){return jsxRuntimeExports.jsx(FluentEmoji,{emoji:Au,size:20,label:""})}function AppFloating({app:Au,view:lo,colorMode:$u,themeVariant:Ru,themeOverrides:Iu,character:Ou,serverUrl:Pu,instance:Du,embedToken:Lu,renderer:ju,host:Bu,session:Fu,language:zu}){const qu=useChatWords(),[Uu,Hu]=reactExports.useState("idle"),[Vu,Gu]=reactExports.useState({answering:!1}),Ku=useHostBridge(Au,Bu),Zu=reactExports.useCallback(rd=>{Hu(rd),Ku.onPresence(rd)},[Ku.onPresence]),Qu=reactExports.useCallback(rd=>{Gu(rd),Ku.onSaying(rd)},[Ku.onSaying]),Yu=Au.interface.welcome||Au.description,ed=useIAMStore(rd=>rd.token),Xu=!Pu&&!ed&&!ju?.datalayerVisitors;return jsxRuntimeExports.jsx(ChatFloating,{defaultViewMode:lo,...Ou?{assistantCharacter:Ou}:{},...Au.interface.balloon?{balloonDisplay:Au.interface.balloon}:{},title:Au.name,description:Yu,brandIcon:jsxRuntimeExports.jsx(Face,{emoji:Au.emoji}),buttonIcon:jsxRuntimeExports.jsx(Face,{emoji:Au.emoji}),buttonTooltip:qu.talkTo(Au.name),colorMode:$u,useStore:!1,conversation:{body:Xu?jsxRuntimeExports.jsx(Text$5,{as:"p",role:"status",sx:{p:3,m:0,fontSize:1},children:signedOutSentence(Au)}):Fu&&!Fu.ready?null:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(SessionSaid,{said:Fu?.said}),jsxRuntimeExports.jsx(AppRenderer,{app:Au,target:Pu?"local":"datalayer",...Pu?{serverUrl:Pu}:{},...Pu&&Lu?{embedToken:Lu}:{},instance:Du,themeOverrides:Iu,colorMode:$u,...Ru?{themeVariant:Ru}:{},hideChatHeader:!0,autoFocusPrompt:!1,onPresence:Zu,onSaying:Qu,plugins:Ku.plugins,...Fu?.thread?{thread:Fu.thread}:{},...zu?{language:zu}:{},...ju})]}),presence:Uu,saying:Vu.saying,answering:Vu.answering}})}function OwnPortalRoot(){const Au=reactExports.useRef(null);return reactExports.useLayoutEffect(()=>{Au.current&&registerPortalRoot(Au.current)},[]),jsxRuntimeExports.jsx("div",{ref:Au,className:"datalayer-app-portal"})}function useSystemMode(){const Au=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-color-scheme: dark)"):null,[lo,$u]=reactExports.useState(!!Au?.matches);return reactExports.useEffect(()=>{if(!Au)return;const Ru=()=>$u(Au.matches);return Au.addEventListener?.("change",Ru),()=>Au.removeEventListener?.("change",Ru)},[Au]),lo?"dark":"light"}function EmbedThemed({accent:Au,colorMode:lo,font:$u,variant:Ru,children:Iu,style:Ou}){const Pu=reactExports.useMemo(()=>embedThemeStyles({accent:Au,font:$u,variant:Ru}),[Au,$u,Ru]);return jsxRuntimeExports.jsx("div",{"data-color-mode":lo,style:{display:"contents"},children:jsxRuntimeExports.jsx(DatalayerThemeProvider,{colorMode:lo,theme:getThemeConfig(Ru).primerTheme,themeStyles:Pu,baseStyles:Ou,children:Iu})})}function AppEmbed({app:Au,mode:lo,accent:$u,colorMode:Ru,font:Iu,language:Ou,serverUrl:Pu,instance:Du,embedToken:Lu,visitors:ju,height:Bu=640,ownPortal:Fu=!1,plugins:zu=NO_PLUGINS,host:qu,resume:Uu=!0}){const Hu=lo??Au.deployment.embedded?.mode??"inline",Vu=useHostBridge(Au,Hu==="inline"?qu:void 0),Gu=reactExports.useMemo(()=>ju?{datalayerVisitors:ju}:void 0,[ju]),Ku=useEmbedSession({app:Au,serverUrl:Pu,embedToken:Lu,resume:Uu}),Zu=useWindowPort({serverUrl:Pu,embedToken:Lu,session:Ku,host:qu}),Qu=useSystemMode(),Yu=Au.interface.theme?.variant??"loop",ed=Ru??Au.interface.theme?.mode??"auto",Xu=ed==="auto"?Qu:ed,rd=floatingViewOf(Hu),nd=$u??Au.interface.accent,od=reactExports.useMemo(()=>embedThemeOverrides({accent:nd,font:Iu,variant:Yu}),[nd,Iu,Yu]),ad=Au.interface.assistant,ld=reactExports.useMemo(()=>rd==="assistant"?embedAssistantCharacter(Au,zu):void 0,[rd,ad,zu]);if(ld&&"problem"in ld)return jsxRuntimeExports.jsx("p",{role:"status",className:"datalayer-app-said",children:ld.problem});const fd=ld?.character;return jsxRuntimeExports.jsx(ChatLanguage,{language:Ou,children:jsxRuntimeExports.jsxs(EmbedThemed,{accent:nd,colorMode:Xu,font:Iu,variant:Yu,style:rd?{backgroundColor:"transparent"}:{height:Bu,display:"flex",flexDirection:"column"},children:[Fu?jsxRuntimeExports.jsx(OwnPortalRoot,{}):null,rd?jsxRuntimeExports.jsx(AppFloating,{app:Au,view:rd,serverUrl:Pu,instance:Du,embedToken:Lu,colorMode:Xu,themeVariant:Yu,themeOverrides:od,character:fd,host:qu,session:Zu,...Gu?{renderer:Gu}:{},...Ou?{language:Ou}:{}}):Zu.ready?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(SessionSaid,{said:Zu.said}),jsxRuntimeExports.jsx(AppRenderer,{app:Au,target:Pu?"local":"datalayer",...Pu?{serverUrl:Pu}:{},...Pu&&Lu?{embedToken:Lu}:{},...Gu??{},instance:Du,themeOverrides:od,colorMode:Xu,themeVariant:Yu,plugins:Vu.plugins,onPresence:Vu.onPresence,onSaying:Vu.onSaying,...Zu.thread?{thread:Zu.thread}:{},...Ou?{language:Ou}:{}})]}):null]})})}const VISITORS_PATH="/api/loop-visitors",VISITOR_EXAMPLES=["web-research","customer-interview"],AT_PREFIX="at:",DEFAULT_API="https://prod1.datalayer.run",isAppUid=Au=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(Au),SLUG=/^[a-z0-9][a-z0-9-]{0,62}$/;function visitorsAt(Au,lo){const $u=Au.replace(/\/+$/,"");return{url:`${$u}${VISITORS_PATH}`,app:lo,inferenceUrl:$u}}const TOKEN_HINT='Embedded for a visitor it refuses, it takes its embed token (the "token" attribute).',notKeptSentence=Au=>`datalayer-app: "${Au}" is an example Datalayer does not keep ready for visitors (${VISITOR_EXAMPLES.join(", ")} are); embed it at its address once it is deployed. ${TOKEN_HINT}`,refusedSentence=Au=>`datalayer-app: ${Au.trim().replace(/\.?\s*Sign in to use it\.?$/,".")} ${TOKEN_HINT}`;async function readVisitorApp({api:Au=DEFAULT_API,app:lo,fetcher:$u=fetch,catalogue:Ru=getApp}){const Iu=lo.trim();if(isAppUid(Iu))return{kind:"decision",app:Iu};const Ou=Ru(Iu);if(Ou)return Ou.kind==="decision"?{kind:"decision",app:Iu}:VISITOR_EXAMPLES.includes(Ou.id)?{kind:"visitors",app:runnable({app:Ou,problems:[]}),visitors:visitorsAt(Au,Ou.id)}:{kind:"said",text:notKeptSentence(Iu)};if(!SLUG.test(Iu))return{kind:"said",text:`datalayer-app: "${Iu}" is neither an application's id, an example's, nor an address.`};let Pu;try{Pu=await $u(`${Au.replace(/\/+$/,"")}/api/ai-agents/v1/apps/deployments/at/${encodeURIComponent(Iu)}`)}catch(zu){return{kind:"said",text:`datalayer-app: Datalayer could not be reached to read "${Iu}" (${zu instanceof Error?zu.message:String(zu)}).`}}const Du=await Pu.json().catch(()=>({}));if(!Pu.ok||Du.success===!1){const zu=String(Du.detail??Du.message??`No application is at "${Iu}".`);return{kind:"said",text:refusedSentence(zu)}}const Lu=Du.session??{};if(!Lu.opens)return{kind:"said",text:refusedSentence(String(Lu.reason||`"${Iu}" is not run without an account.`))};const ju=Du.deployment??{},Bu=parseAppspec(Du.spec);if(Bu.app.kind==="decision")return{kind:"decision",app:Iu};const Fu=typeof ju.app_name=="string"&&ju.app_name?ju.app_name:Bu.app.name;return{kind:"visitors",app:runnable({app:{...Bu.app,name:Fu},problems:Bu.problems}),visitors:visitorsAt(Au,`${AT_PREFIX}${Iu}`)}}const EMBED_MESSAGES={size:"datalayer-app:size",decision:"datalayer-app:decision",token:"datalayer-app:token",tokenExpired:"datalayer-app:token-expired"};function appspecOfText(Au){const lo=Au.replace(/\t/g," ").split(`
3803
3803
  `),$u=Math.min(...lo.filter(Ou=>Ou.trim()).map(Ou=>Ou.length-Ou.trimStart().length)),Ru=lo.map(Ou=>Ou.slice(Number.isFinite($u)?$u:0)).join(`
3804
- `).trim();if(!Ru)throw new EmbedAttributeError("datalayer-app: the Appspec is empty.");let Iu;if(Ru.startsWith("{")){let Ou;try{Ou=JSON.parse(Ru)}catch(Pu){throw new EmbedAttributeError(`datalayer-app: the Appspec is not JSON (${Pu.message}).`)}Iu=parseAppspec(Ou)}else Iu=readAppspecYaml(Ru);return runnable(Iu)}function frameSrcOf(Au,lo,$u=""){return`${Au.replace(/\/+$/,"")}/public/apps/${encodeURIComponent(lo)}/run?embed=1${$u?`#token=${encodeURIComponent($u)}`:""}`}function frameInLanguage(Au,lo){if(!lo)return Au;const $u=Au.indexOf("#"),[Ru,Iu]=$u<0?[Au,""]:[Au.slice(0,$u),Au.slice($u)];return`${Ru}${Ru.includes("?")?"&":"?"}language=${encodeURIComponent(lo)}${Iu}`}async function readEmbeddedApp({api:Au,origin:lo,app:$u,token:Ru,fetcher:Iu=fetch}){const Ou=await Iu(`${Au.replace(/\/+$/,"")}/api/spacer/v1/apps/${encodeURIComponent($u)}/embedded`,{headers:{Authorization:`Bearer ${Ru}`}});if(Ou.status===401)return{kind:"said",text:"datalayer-app: the embed token expired or is not for this application.",expired:!0};if(!Ou.ok)return{kind:"said",text:`datalayer-app: the application could not be read (${Ou.status}).`};const Pu=await Ou.json();let Du;try{Du=JSON.parse(String(Pu.app?.model_s??"{}"))}catch{Du={}}if(!Du.spec)return{kind:"frame",src:frameSrcOf(lo,$u,Ru)};const Lu=runnable(parseAppspec(Du.spec));return Lu.kind==="decision"?{kind:"frame",src:frameSrcOf(lo,$u,Ru)}:{kind:"spec",app:Lu}}function currentScriptUrl(){try{const Au=document.currentScript;return Au?.src?new URL(Au.src,location.href).href:""}catch{return""}}function defineDatalayerAppElement(Au={}){if(typeof window>"u"||!("customElements"in window))return;const lo=Au.tag??EMBED_TAG,$u=customElements.get(lo);if($u)return $u;const Ru=Au.scriptUrl??currentScriptUrl(),Iu=Ru?new URL(Ru).origin:"",Ou=Ru?Ru.replace(/\.js(\?.*)?$/,".css"):"";class Pu extends HTMLElement{static get observedAttributes(){return EMBED_OBSERVED_ATTRIBUTES}root=null;frame=null;source=null;loading=0;passed={};offered={};windowPort=null;host={context:()=>this.passed,userToken:()=>this.getAttribute("user-token")||void 0,functions:this.offered,onWindowPort:Lu=>{this.windowPort=Lu},onEvent:Lu=>this.dispatchEvent(new CustomEvent(Lu.type,{detail:Lu.detail,bubbles:!0,composed:!0}))};get context(){return this.passed}set context(Lu){this.passed={...Lu??{}}}postWindowMessage(Lu){const ju=this.windowPort;return ju?ju(Lu):Promise.reject(new Error(`datalayer-app: ${WINDOW_NOT_YET}`))}get functions(){return this.offered}set functions(Lu){for(const ju of Object.keys(this.offered))delete this.offered[ju];Object.assign(this.offered,Lu??{})}constructor(){super(),this.attachShadow({mode:"open"}),this.onMessage=this.onMessage.bind(this)}get token(){return this.getAttribute("token")??""}set token(Lu){Lu?this.setAttribute("token",String(Lu)):this.removeAttribute("token")}get userToken(){return this.getAttribute("user-token")??""}set userToken(Lu){Lu?this.setAttribute("user-token",String(Lu)):this.removeAttribute("user-token")}connectedCallback(){window.addEventListener("message",this.onMessage),this.load()}disconnectedCallback(){window.removeEventListener("message",this.onMessage),this.unmount()}attributeChangedCallback(Lu,ju,Bu){if(!(!this.isConnected||ju===Bu)&&Lu!=="user-token"){if(Lu==="token"&&this.frame?.contentWindow&&Bu){this.frame.contentWindow.postMessage({type:EMBED_MESSAGES.token,token:Bu},this.origin());return}if(["mode","accent","theme","font","height","resume","language"].includes(Lu)){this.draw();return}this.load()}}origin(){return(this.getAttribute("origin")||Iu||location.origin).replace(/\/+$/,"")}inputs(){const Lu={};for(const Fu of EMBED_OBSERVED_ATTRIBUTES)Lu[Fu]=this.getAttribute(Fu);const ju=getComputedStyle(this),Bu={};for(const[Fu,zu]of Object.entries(EMBED_HOST_VARIABLES)){const qu=ju.getPropertyValue(zu).trim();qu&&(Bu[Fu]=qu.replace(/^["']|["']$/g,""))}return{attributes:Lu,variables:Bu}}async read(){const Lu=this.querySelector('script[type="application/yaml"], script[type="application/json"], script[type="text/yaml"]');if(Lu?.textContent?.trim())return{kind:"spec",app:appspecOfText(Lu.textContent)};const ju=this.getAttribute("spec");if(ju){const zu=await fetch(new URL(ju,location.href).href);return zu.ok?{kind:"spec",app:appspecOfText(await zu.text())}:{kind:"said",text:`datalayer-app: the Appspec at ${ju} could not be read (${zu.status}).`}}const Bu=this.getAttribute("app");if(!Bu)return{kind:"said",text:'datalayer-app: the "app" attribute names the application to show, or "spec" the address of its Appspec.'};const Fu=this.token;if(!Fu){const zu=await readVisitorApp({api:this.api(),app:Bu});return zu.kind==="decision"?{kind:"frame",src:frameSrcOf(this.origin(),zu.app)}:zu.kind==="said"?{kind:"said",text:zu.text}:{kind:"spec",app:zu.app,visitors:zu.visitors}}return readEmbeddedApp({api:this.api(),origin:this.origin(),app:Bu,token:Fu})}api(){return(this.getAttribute("api")||coreStore.getState().configuration?.spacerUrl||DEFAULT_API).replace(/\/+$/,"")}async load(){const Lu=++this.loading;let ju;try{ju=await this.read()}catch(Bu){ju={kind:"said",text:Bu instanceof Error?Bu.message:`datalayer-app: ${String(Bu)}`}}Lu!==this.loading||!this.isConnected||(this.source=ju,this.draw(),ju.kind==="said"&&ju.expired&&this.dispatchEvent(new CustomEvent("token-expired",{detail:{app:this.getAttribute("app")??""},bubbles:!0,composed:!0})))}unmount(){this.root?.unmount(),this.root=null,this.frame=null}skeleton(Lu){const ju=this.shadowRoot;if(this.unmount(),ju.replaceChildren(),Ou){const Fu=document.createElement("link");Fu.rel="stylesheet",Fu.href=Ou,ju.appendChild(Fu)}const Bu=document.createElement("style");return Bu.textContent=embedShadowCss(Lu),ju.appendChild(Bu),ju}say(Lu){this.setAttribute("data-embed-mode","inline");const ju=this.skeleton(),Bu=document.createElement("p");Bu.className="datalayer-app-said",Bu.setAttribute("role","status"),Bu.textContent=Lu,ju.appendChild(Bu)}draw(){const Lu=this.source;if(!Lu)return;if(Lu.kind==="said"){this.say(Lu.text);return}if(Lu.kind==="frame"){let Hu;try{Hu=languageOf(this.getAttribute("language"))}catch(Ku){this.say(Ku.message);return}this.setAttribute("data-embed-mode","inline");const Vu=this.skeleton(),Gu=document.createElement("iframe");Gu.className="datalayer-app-frame",Gu.src=frameInLanguage(Lu.src,Hu),Gu.title="Datalayer app",Gu.style.height=`${inlineHeightOf(this.getAttribute("height"))}px`,Gu.setAttribute("allow","clipboard-write"),Vu.appendChild(Gu),this.frame=Gu;return}let ju,Bu,Fu;try{ju=embedLookOf(this.inputs(),Lu.app),Bu=resumeOf(this.getAttribute("resume")),Fu=languageOf(this.getAttribute("language"))}catch(Hu){this.say(Hu.message);return}if(ju.mode==="assistant"){const Hu=embedAssistantCharacter(Lu.app);if("problem"in Hu){this.say(Hu.problem);return}}this.setAttribute("data-embed-mode",ju.mode);const zu=this.skeleton(getThemeConfig(ju.variant).themeStyles.css),qu=document.createElement("div");qu.className="datalayer-app-root",zu.appendChild(qu),this.root=clientExports.createRoot(qu);const Uu=this.getAttribute("server")||void 0;this.root.render(jsxRuntimeExports.jsx(me$3,{target:zu,children:jsxRuntimeExports.jsx(AppEmbed,{app:Lu.app,mode:ju.mode,accent:ju.accent,colorMode:ju.colorMode,font:ju.font,serverUrl:Uu,...Uu&&this.token?{embedToken:this.token}:{},...Lu.visitors?{visitors:Lu.visitors}:{},height:inlineHeightOf(this.getAttribute("height")),ownPortal:!0,host:this.host,resume:Bu,...Fu?{language:Fu}:{}})}))}onMessage(Lu){if(!this.frame||Lu.source!==this.frame.contentWindow||Lu.origin!==this.origin())return;const ju=Lu.data??{};ju.type===EMBED_MESSAGES.size&&typeof ju.height=="number"&&ju.height>0?this.frame.style.height=`${Math.ceil(ju.height)}px`:ju.type===EMBED_MESSAGES.decision?this.dispatchEvent(new CustomEvent("decision",{detail:ju.record,bubbles:!0,composed:!0})):ju.type===EMBED_MESSAGES.tokenExpired&&this.dispatchEvent(new CustomEvent("token-expired",{detail:{app:this.getAttribute("app")??""},bubbles:!0,composed:!0}))}}return customElements.define(lo,Pu),Pu}const SCRIPT_FILE="datalayer-app.js";defineDatalayerAppElement({scriptUrl:new URL(SCRIPT_FILE,import.meta.url).href});const mermaidVLURNSYL=Object.freeze(Object.defineProperty({__proto__:null,Mermaid:Ee$2},Symbol.toStringTag,{value:"Module"}));export{ExternalTokenizer as $,A2uiSurfaceComposed as A,Box as B,CheckIcon as C,Dialog$1 as D,InputPrompt as E,Signal as F,o$1 as G,Heading$2 as H,IconButton as I,LoopOpeningNotebook as J,LoopNotebookToolbarItem as K,Label as L,MessageProcessor as M,NO_SANDBOX_YET as N,LoopNotebookToolbar as O,PlayIcon as P,QueryClient as Q,LRLanguage as R,SANDBOX_KIND_LABELS as S,Text$5 as T,LanguageSupport as U,indentNodeProp as V,continuedIndent as W,foldNodeProp as X,styleTags as Y,tags as Z,__vitePreload as _,QueryClientProvider as a,base$2 as a$,ifNotIn as a0,completeFromList as a1,LRParser as a2,syntaxTree as a3,delimitedIndent as a4,foldInside as a5,getDefaultExportFromCjs as a6,WIDGET_VIEW_MIMETYPE as a7,MimeModel as a8,Lumino as a9,useSystemColorMode as aA,getThemeConfig as aB,JupyterReactTheme$1 as aC,l$1 as aD,v$1 as aE,a$1 as aF,Kernel as aG,registerSandboxServiceManager as aH,DatalayerThemeProvider as aI,de$1 as aJ,on$1 as aK,nl as aL,es as aM,H as aN,disposeServiceManager as aO,create$i as aP,setIfUndefined as aQ,create$8 as aR,fromBase64 as aS,onChange as aT,varStorage as aU,toBase64 as aV,offChange as aW,createUint8ArrayFromArrayBuffer as aX,map$6 as aY,WIDGET_STATE_MIMETYPE as aZ,ManagerBase as a_,RenderMimeRegistry as aa,standardRendererFactories as ab,purify$1 as ac,format$2 as ad,Token$2 as ae,Menu as af,DisposableDelegate as ag,ArrayExt as ah,Widget as ai,PanelLayout as aj,HoverBox as ak,IToolbarWidgetRegistry as al,ITranslator as am,createToolbarFactory as an,nullTranslator as ao,createDefaultFactory as ap,ObservableList as aq,Toolbar$2 as ar,ReactWidget as as,some$2 as at,ISanitizer as au,ICommandPalette as av,StatusBar as aw,useAgentsRuntimes as ax,xu as ay,useThemeStore as az,sandboxExecuteOverHttp as b,contribution as b$,controls as b0,SemVerCache as b1,JUPYTER_WIDGETS_VERSION as b2,JUPYTER_CONTROLS_VERSION as b3,shims as b4,semverExports as b5,requireLoader as b6,serialize_state as b7,Panel as b8,PromiseDelegate as b9,Prec as bA,keymap as bB,EditorView as bC,Language as bD,indentUnit as bE,foldService as bF,defineLanguageFacet as bG,CompletionContext as bH,EditorState as bI,languageDataProp as bJ,LanguageDescription as bK,ParseContext as bL,ContextTracker as bM,bracketMatchingHandle as bN,LocalTokenGroup as bO,NodeWeakMap as bP,IterMode as bQ,sublanguageProp as bR,flatIndent as bS,snippetCompletion as bT,LoopDocumentToolbarItem as bU,LoopDocumentToolbar as bV,LoopOpeningDocument as bW,useOptionalSandboxService as bX,IDLE_SANDBOX_SNAPSHOT_SIGNAL as bY,definePlugin as bZ,DOCUMENT_TOOLBAR_PLUGIN_NAME as b_,DEFAULT_SERVICE_URLS as ba,requestDatalayerAPI as bb,API_BASE_PATHS as bc,ActionList as bd,distExports as be,ActionListContainerContext as bf,BoxWithFallback as bg,merge$5 as bh,defaultSxProp as bi,useId as bj,reactDomExports as bk,useIsomorphicLayoutEffect$2 as bl,ChevronDownIcon as bm,classes$t as bn,SubItem as bo,Box$1 as bp,themeConfigs as bq,Parser$4 as br,NodeType as bs,NodeProp as bt,Tag$1 as bu,NodeSet as bv,Tree as bw,parseMixed as bx,EditorSelection as by,countColumn as bz,ButtonComponent as c,setToolbar as c$,KernelIndicator as c0,NOTEBOOK_TOOLBAR_PLUGIN_NAME as c1,useReactorPlatform as c2,AGENTS_PLUGIN_NAME as c3,IDLE_SANDBOX_TARGET_SIGNAL as c4,AGENTSPECS$1 as c5,useAgentRuntimes as c6,Eu as c7,Ke$2 as c8,_c as c9,SearchDocumentModel as cA,SearchDocumentView as cB,isResponsiveValue as cC,clsx as cD,Rgb as cE,rgbConvert as cF,define as cG,extend$3 as cH,Color as cI,commonjsRequire as cJ,TextInput$1 as cK,SearchIcon as cL,SyncIcon as cM,ToggleSwitch as cN,ChevronRightIcon as cO,StyledSpinner as cP,ToolbarButton as cQ,fileUploadIcon as cR,TextItem as cS,GroupItem as cT,libExports$2 as cU,WidgetTracker as cV,folderIcon as cW,linkIcon as cX,Clipboard as cY,downloadIcon as cZ,copyIcon as c_,is as ca,Ys as cb,PencilIcon as cc,SingletonLayout as cd,FocusTracker as ce,libExports$5 as cf,VDomModel as cg,TableOfContents as ch,JSONExt as ci,VDomRenderer as cj,LabIcon as ck,classes as cl,map$8 as cm,showErrorMessage as cn,AttachedProperty as co,addIcon as cp,launcherIcon as cq,MainAreaWidget as cr,find$5 as cs,TranslatorConnector as ct,Gettext as cu,DEFAULT_LANGUAGE_CODE as cv,normalizeDomain as cw,ITranslatorConnector as cx,Dialog as cy,showDialog$1 as cz,displayUrl as d,EditorThemeRegistry as d$,InputDialog as d0,Notification as d1,CommandRegistry as d2,closeIcon as d3,cutIcon as d4,pasteIcon as d5,newFolderIcon as d6,textEditorIcon as d7,markdownIcon as d8,refreshIcon as d9,jupyterIcon as dA,SettingRegistry as dB,MenuFactory as dC,moveUpIcon as dD,moveDownIcon as dE,Button$1 as dF,deleteIcon as dG,DOMUtils as dH,lineFormIcon as dI,deleteLine as dJ,toggleBlockComment as dK,toggleComment as dL,toggleTabFocusMode as dM,selectNextOccurrence as dN,foldable as dO,foldCode as dP,unfoldCode as dQ,foldState as dR,foldEffect as dS,unfoldEffect as dT,foldAll as dU,unfoldAll as dV,IEditorServices as dW,EditorLanguageRegistry as dX,parseMathIPython as dY,StreamLanguage as dZ,pythonBuiltin as d_,editIcon as da,fileIcon as db,stopIcon as dc,filterIcon as dd,DisposableSet as de,clearNumbering as df,getHeadingId as dg,addPrefix as dh,parseHeadings as di,filterHeadings as dj,StackedLayout as dk,ABCWidgetFactory as dl,DocumentWidget as dm,ITableOfContentsRegistry as dn,markdownRendererFactory as dp,CommandLinker as dq,SkeletonBox as dr,getBrightPalette as ds,useColorPalette as dt,SkeletonText as du,Tooltip as dv,ActionMenu as dw,KebabHorizontalIcon as dx,IWindowResolver as dy,buildIcon as dz,Link$1 as e,ListUnorderedIcon as e$,EditorExtensionRegistry as e0,ybinding as e1,CodeMirrorEditorFactory as e2,CodeMirrorMimeTypeService as e3,IPositionModel as e4,KERNEL_PROVIDER_ID as e5,Completer as e6,CompleterModel as e7,ProviderReconciliator as e8,CompletionHandler as e9,useLayoutStore as eA,useRuntimesStore as eB,color$1 as eC,OutputPrompt as eD,Stdin as eE,CodeCell as eF,notebookStore as eG,useJupyterLabCssLoaded as eH,TelescopeIcon as eI,XIcon as eJ,CounterLabel as eK,PauseIcon as eL,DownloadIcon as eM,SPAN_SOURCE_LABELS as eN,sourceOfSpan as eO,AGENT_SPAN_ATTRIBUTES as eP,describeAgentSpan as eQ,SpecMark as eR,rgb as eS,parse$4 as eT,UUID as eU,EN_US as eV,errorIcon as eW,Platform as eX,caretDownEmptyThinIcon as eY,StringExt as eZ,SegmentedControl as e_,historyIcon as ea,ICompletionProviderManager as eb,IInlineCompleterFactory as ec,KernelCompleterProvider as ed,CommandToolbarButton as ee,caretLeftIcon as ef,caretRightIcon as eg,checkIcon as eh,COMPLETER_ACTIVE_CLASS as ei,Debouncer as ej,ISessionContextDialogs as ek,SessionContextDialogs as el,saveIcon as em,addCommandToolbarButtonClass as en,UseSignal as eo,CommandToolbarButtonComponent as ep,createStore$1 as eq,useStore$1 as er,runtimesStore as es,DATALAYER_IAM_TOKEN_KEY as et,DATALAYER_IAM_USER_KEY as eu,coreStore as ev,iamStore as ew,layoutStore as ex,useCoreStore as ey,useIAMStore as ez,CopyIcon as f,AgentTools as f$,GraphIcon as f0,ProgressBar as f1,ClockIcon as f2,DatabaseIcon as f3,FileIcon as f4,ToolsIcon as f5,CommentDiscussionIcon as f6,AiModelIcon as f7,InfoIcon as f8,KeyIcon as f9,useOnOutsideClick as fA,useResizeObserver as fB,VisuallyHidden as fC,TriangleDownIcon as fD,qe$4 as fE,sx as fF,requireSerialize as fG,requireMessages as fH,mockSocketExports as fI,ObservableMap as fJ,exponent as fK,formatSpecifier as fL,formatPrefix as fM,CodeEditorWrapper as fN,CodeEditor as fO,IEditorMimeTypeService as fP,EditorSearchProvider as fQ,CodeMirrorEditor$1 as fR,getPrefix as fS,isMarkdown as fT,findNext as fU,gotoLine as fV,consoleIcon as fW,undoIcon as fX,redoIcon as fY,selectAll as fZ,Sanitizer as f_,devtools as fa,subscribeWithSelector as fb,persist as fc,CheckCircleFillIcon as fd,AlertIcon as fe,useAgentRuntimeMcpStatus as ff,useAgentRuntimeCodemodeStatus as fg,useAgentRuntimeContextSnapshot as fh,useAgentRuntimeFullContext as fi,useAgentRuntimeWsState as fj,useMutation as fk,useQuery as fl,ForwardRef$3 as fm,NoteIcon as fn,ServerIcon as fo,CheckCircleIcon as fp,XCircleIcon as fq,BriefcaseIcon as fr,SemanticCommand as fs,MenuBar as ft,runIcon as fu,fastForwardIcon as fv,getAnchoredPosition as fw,reactIsExports as fx,useTheme as fy,useOnEscapePress as fz,createAllAgentRuntimesTools as g,readServerCatalogue as g$,useToast as g0,isInsideJupyterLab as g1,FormControl$1 as g2,MailIcon as g3,Textarea as g4,$e$5 as g5,JUPYTER_NOTEBOOK_FRONTEND_TOOL_SPEC_0_0_1 as g6,LEXICAL_DOCUMENT_FRONTEND_TOOL_SPEC_0_0_1 as g7,RUNTIME_ECHO_BACKEND_TOOL_SPEC_0_0_1 as g8,TAVILY_MCP_SERVER_0_0_1 as g9,latestSaying as gA,messageText as gB,LoopRunProps as gC,runForwardedProps as gD,onSurfaceRequest as gE,setEditorOptions as gF,seedEditorChoice as gG,canOpenView as gH,useWorkspaceFullScreen as gI,targetRunsAgentInPage as gJ,useOptionalTeamSelection as gK,LoopAgentBlueprint as gL,LoopChatSuggestion as gM,agentIcon as gN,LoopFrontendTool as gO,agentServerOf as gP,LoopCommand as gQ,subagentsFor as gR,useChatAvailability as gS,noRuntimeSaid as gT,useSlotComponents as gU,LoopSlots as gV,onPromptFocusRequest as gW,generateMessageId as gX,useConfig as gY,useSkills as gZ,useSkillActions as g_,EVENTS_SKILL_SPEC_0_0_1 as ga,TEXT_SUMMARIZER_SKILL_SPEC_0_0_1 as gb,GITHUB_SKILL_SPEC_0_0_1 as gc,CRAWL_SKILL_SPEC_0_0_1 as gd,useAnonymousInferenceSession as ge,browserModelRequiresSignIn as gf,getAgentspecs as gg,useOptionalReactorPlatform as gh,messagesOfThread as gi,FluentEmoji as gj,PRESENCE_LINES as gk,useChatWords as gl,CHAT_PLUGIN_NAME as gm,INPUT_PROMPT_PLUGIN_NAME as gn,LoopChatSurface as go,LoopChatComposer as gp,LoopChatHeader as gq,LoopChatLayout as gr,LoopChatTurn as gs,turnWritersOf as gt,LoopChatExtras as gu,computed$1 as gv,useGate as gw,presenceState as gx,presenceToolOf as gy,newestIsAnswer as gz,renderOcticon as h,StaticNotebook as h$,readServerDecisions as h0,offeredModels as h1,AI_MODEL_CATALOGUE as h2,isChatModel as h3,ReactorSlot as h4,ReactorLazy as h5,ChatBase as h6,ScreenNormalIcon as h7,ScreenFullIcon as h8,SUGGESTION_CHIP_WIDTH as h9,ThemeManager as hA,ToolbarWidgetRegistry as hB,Selector$1 as hC,Printing as hD,WindowResolver as hE,jupyterFaviconIcon as hF,caretDownEmptyIcon as hG,addToolbarButtonClass as hH,NotebookActions as hI,Toolbar as hJ,translateKernelStatuses as hK,offlineBoltIcon as hL,circleIcon as hM,MessageLoop as hN,Collapser$1 as hO,ObservableJSON as hP,ConflatableMessage as hQ,jumpBackIcon as hR,jumpForwardIcon as hS,MarkdownCell as hT,Cell$1 as hU,trustedIcon as hV,notTrustedIcon as hW,runCell as hX,InputPrompt$1 as hY,NotebookPanel as hZ,setCellExecutor as h_,Truncate as ha,useAnonymousSessionStore as hb,signal$2 as hc,LoopAgentGate as hd,agentRuntimeStore as he,loopShapeVars as hf,NONE_EDITOR as hg,filterListIcon as hh,CommandPalette$1 as hi,h$7 as hj,LabIconStyle as hk,ILicensesClient as hl,Licenses as hm,copyrightIcon as hn,ToolbarButtonComponent as ho,bellIcon as hp,clientExports as hq,Button$3 as hr,ModalCommandPalette as hs,paletteIcon as ht,Throttler as hu,IKernelStatusModel as hv,KernelStatus$1 as hw,RunningSessions as hx,IThemeManager as hy,ISplashScreen as hz,SquareFillIcon as i,useProperties as i$,notebookIcon as i0,NotebookSearchProvider as i1,duplicateIcon as i2,addAboveIcon as i3,addBelowIcon as i4,children$1 as i5,ref$2 as i6,html$7 as i7,startSlotTemplate as i8,endSlotTemplate as i9,focusStrokeWidth$1 as iA,strokeWidth$1 as iB,controlCornerRadius$1 as iC,heightNumber$1 as iD,neutralFillStealthHover$1 as iE,neutralFillStealthActive$1 as iF,designUnit$1 as iG,typeRampBaseFontSize$1 as iH,typeRampBaseLineHeight$1 as iI,density$1 as iJ,typeRampPlus1FontSize$1 as iK,disabledOpacity$1 as iL,disabledCursor as iM,baseHeightMultiplier$1 as iN,neutralFillRest$1 as iO,neutralFillHover$1 as iP,neutralFillActive$1 as iQ,accentForegroundRest$1 as iR,display as iS,css as iT,forcedColorsStylesheetBehavior as iU,SystemColors as iV,cssPartial as iW,DesignToken as iX,neutralFillStealthRecipe$1 as iY,neutralFillRecipe$1 as iZ,useEventListener as i_,slotted as ia,elements as ib,FoundationElement as ic,isHTMLElement as id,__decorate$1 as ie,attr as ig,observable as ih,applyMixins as ii,StartEnd as ij,keyEnter as ik,keyArrowUp as il,keyArrowDown as im,keyArrowRight as io,keyArrowLeft as ip,keyEnd as iq,keyHome as ir,DOM as is,getDisplayedNodes as it,direction$1 as iu,neutralForegroundRest$1 as iv,neutralFillStealthRest$1 as iw,bodyFont$1 as ix,focusVisible as iy,accentFillFocus$1 as iz,jsxRuntimeExports as j,CheckboxOrRadioGroupCaption as j$,provideJupyterDesignSystem$1 as j0,ITableOfContentsTracker as j1,tocIcon as j2,numberingIcon as j3,expandAllIcon as j4,collapseAllIcon as j5,ellipsesIcon as j6,VisuallyHidden$1 as j7,StopIcon as j8,ViewPlugin as j9,NotebookCommandIds as jA,OutputAreaModel as jB,useJupyterReactStore as jC,newUuid as jD,NotebookPanelProvider as jE,addNotebookCommands as jF,WIDGET_MIMETYPE as jG,rendererFactory$1 as jH,rendererFactory as jI,getMarked as jJ,createLatexTypesetter as jK,YArray as jL,YText as jM,newUlid as jN,k$2 as jO,loopColors as jP,sunColors as jQ,ivoryColors as jR,sandColors as jS,earthColors as jT,matrixColors as jU,lovelyColors as jV,spatialColors as jW,datalayerColors as jX,getColorPalette as jY,CheckboxOrRadioGroupValidation as jZ,CheckboxOrRadioGroupLabel as j_,createRelativePositionFromTypeIndex as ja,createRelativePositionFromJSON as jb,tooltips as jc,Facet as jd,Annotation as je,layer as jf,StateField as jg,showTooltip as jh,createAbsolutePositionFromRelativePosition as ji,RectangleMarker as jj,YDocument as jk,createCellModelFromSharedType as jl,createCell as jm,YMap as jn,RawCellModel as jo,MarkdownCellModel as jp,CodeCellModel as jq,MINOR_VERSION as jr,MAJOR_VERSION as js,SessionContext as jt,StateEffect as ju,Decoration as jv,WidgetType as jw,kernelIcon as jx,DEFAULT_VARIANT as jy,MarimoReactive as jz,TrashIcon as k,qc as k$,useRenderForcingRef as k0,CheckboxOrRadioGroup$1 as k1,CheckboxGroupContext as k2,Checkbox as k3,RadioGroup$1 as k4,Radio as k5,SelectPanel as k6,Select$1 as k7,TextInputWithTokens as k8,object as k9,qi as kA,Pi as kB,isStream as kC,isExecuteResult as kD,isDisplayData as kE,isError$2 as kF,Xo as kG,Ki as kH,Yi as kI,er as kJ,T as kK,v$2 as kL,S$1 as kM,C as kN,m$2 as kO,x$5 as kP,y$3 as kQ,p$4 as kR,ol as kS,He$2 as kT,pn$2 as kU,Kr as kV,ur as kW,ls as kX,cn$1 as kY,_n as kZ,hn$2 as k_,preprocess$1 as ka,record$1 as kb,string$2 as kc,unknown$1 as kd,zodToToolParameters as ke,array as kf,_enum as kg,number$2 as kh,boolean$1 as ki,validateWithZod as kj,whitespace as kk,svg$2 as kl,find as km,stringify$1 as kn,stringify as ko,ccount as kp,zwitch as kq,html$4 as kr,htmlVoidElements as ks,C$1 as kt,Dt$4 as ku,u$2 as kv,dt$2 as kw,Go as kx,ns as ky,mn$1 as kz,libExports$3 as l,rKernelIcon as l$,Ie$2 as l0,cs as l1,dr as l2,Jl as l3,fn$2 as l4,hn$1 as l5,pn$1 as l6,Wo as l7,xt$2 as l8,Zs as l9,hpass as lA,AccordionPanel as lB,caretDownIcon as lC,AccordionLayout as lD,FormAssociated as lE,nullableNumberConverter as lF,ARIAGlobalStatesAndProperties as lG,neutralFillInputRest$1 as lH,neutralFillStrongRest$1 as lI,errorFillRest$1 as lJ,neutralFillInputHover$1 as lK,neutralFillStrongHover$1 as lL,errorFillHover$1 as lM,neutralFillStrongActive$1 as lN,errorFillActive$1 as lO,errorFillFocus$1 as lP,neutralStrokeRest$1 as lQ,__decorate as lR,searchIcon as lS,jsonIcon as lT,BoxLayout as lU,VirtualDOM as lV,TextModelFactory as lW,pdfIcon as lX,pythonIcon as lY,juliaIcon as lZ,spreadsheetIcon as l_,gc as la,On as lb,na as lc,ea as ld,ia as le,sa as lf,useJupyter as lg,decodeNamedCharacterReference as lh,requireReact as li,StyleModule as lj,jupyterHighlightStyle as lk,requireDayjs_min as ll,useFocusZone as lm,FocusKeys as ln,useSafeTimeout as lo,useSlots as lp,useProvidedRefOrCreate as lq,useResponsiveValue as lr,ScrollableRegion as ls,viewportRanges as lt,JupyterLiteServer as lu,Router as lv,ContextMenu as lw,TabPanel$1 as lx,TabBar as ly,DockPanel as lz,PlusIcon as m,ClassicWidgetManager as m$,yamlIcon as m0,imageIcon as m1,audioIcon as m2,videoIcon as m3,writeVarUint as m4,encodeStateVector as m5,writeVarUint8Array as m6,encodeStateAsUpdate as m7,readVarUint as m8,applyUpdate as m9,filter$5 as mA,ElementExt as mB,caretUpIcon as mC,Poll as mD,each$1 as mE,Application as mF,StackedPanel as mG,tabIcon as mH,Base64ModelFactory as mI,useTerminalStore as mJ,InputViewer as mK,basicSetup as mL,drawSelection as mM,indentOnInput as mN,highlightActiveLine as mO,highlightSpecialChars as mP,highlightSelectionMatches as mQ,defaultKeymap as mR,searchKeymap as mS,requestAPI$1 as mT,loadJupyterConfig as mU,createLiteServiceManager as mV,jupyterReactStore as mW,ANSWER_MARKER as mX,BuilderManagerLess as mY,CellAdapter as mZ,CellCommands as m_,readVarUint8Array as ma,readVarString as mb,ObservableV2 as mc,Awareness as md,toUint8Array$1 as me,length as mf,encodeAwarenessUpdate as mg,removeAwarenessStates as mh,isNode as mi,getUnixTime as mj,createEncoder as mk,min$1 as ml,pow as mm,createDecoder as mn,applyAwarenessUpdate as mo,BoxPanel as mp,Cell as mq,UndoManager as mr,Doc$1 as ms,SplitPanel as mt,RawCell as mu,isCodeCellModel as mv,Drag as mw,MimeData as mx,useConsoleStore as my,folderFavoriteIcon as mz,CodeIcon as n,isServedByJupyterLab as n$,CodeMirrorDatalayerEditor as n0,CodeMirrorEditor as n1,CodeMirrorOutputToolbar as n2,ContentsManagerLess as n3,DEFAULT_API_KERNEL_PREFIX_URL as n4,DEFAULT_JUPYTER_SERVER_TOKEN as n5,DEFAULT_JUPYTER_SERVER_URL as n6,DEFAULT_KERNEL_NAME as n7,DefaultExecutor as n8,EventsManagerLess as n9,UserManagerLess as nA,WidgetRenderer as nB,WorkspaceManagerLess as nC,cellSourceAsString as nD,cellsStore as nE,codeMirrorTheme as nF,consoleStore as nG,createLiteServer as nH,createServerSettings as nI,deleteCellsOperation as nJ,deleteCellsTool as nK,disableKernelReconnect as nL,disposeKernelConnections as nM,ensureJupyterAuth as nN,ensureJupyterConfig as nO,execute as nP,executeCodeOperation as nQ,executeCodeTool as nR,formatResponse as nS,getCookie as nT,getJupyterServerToken as nU,getJupyterServerUrl as nV,getKernelIndicatorMeta as nW,insertCellOperation as nX,insertCellTool as nY,isAnyCellRunning as nZ,isReactiveVariant as n_,ExecutionPhase as na,HELPER_NAME as nb,HTMLManager as nc,JupyterLabCss as nd,KERNEL_HELPER_SOURCE as ne,KERNEL_STATES as nf,KERNEL_STATE_LABELS as ng,KERNEL_STATE_VISUALS as nh,KernelActionMenu as ni,KernelExecutor as nj,KernelManagerLess as nk,KernelProgressBar as nl,KernelspecManagerLess as nm,MIME_TYPE$1 as nn,NbConvertManagerLess as no,OperationRunner as np,Output as nq,OutputAdapter as nr,OutputRenderer as ns,OutputViewer as nt,OutputViewerAdapter as nu,RenderedPlotly as nv,ServiceManagerLess as nw,SessionManagerLess as nx,SettingManagerLess as ny,TerminalManagerLess as nz,formatTokenCount as o,rn$1 as o$,jupyterLabTheme as o0,kernelsStore as o1,loadJupyterLabCss as o2,notebookToolDefinitions as o3,notebookToolOperations as o4,notebookTools as o5,outputsAsString as o6,outputsStore as o7,readAllCellsOperation as o8,readAllCellsTool as o9,bu as oA,Nu as oB,Wl as oC,Fr as oD,Li as oE,Vc as oF,Fo as oG,sn$1 as oH,vc as oI,tr as oJ,Sn as oK,Zo as oL,Cu as oM,Bs as oN,Me as oO,yn as oP,Se as oQ,Cn as oR,fn as oS,qr as oT,Ia as oU,zs as oV,gn$2 as oW,or as oX,Jr as oY,sn$2 as oZ,ln$1 as o_,readCellOperation as oa,readCellTool as ob,refreshJupyterLabPortalTheme as oc,renderKernelStateGlyph as od,renderWidgets as oe,rendererFactory$2 as of,resetJupyterConfig as og,runCellOperation as oh,runCellTool as oi,setJupyterServerToken as oj,setJupyterServerUrl as ok,sleep as ol,syncJupyterLabPortalTheme as om,terminalStore as on,toKernelState as oo,updateCellOperation as op,updateCellTool as oq,useCellsStore as or,useJupyterReactColormode as os,useJupyterReactStoreFromProps as ot,useKernelsStore as ou,useOutputsStore as ov,ThemeProvider as ow,Overlay$1 as ox,Fi as oy,Zl as oz,useSandboxService as p,Xe$2 as p$,nn$2 as p0,Vr as p1,nu as p2,du as p3,Va as p4,au as p5,La as p6,Is as p7,Dl as p8,h$1 as p9,oa as pA,Cn$1 as pB,et as pC,xn as pD,St as pE,Rt as pF,xt as pG,yn$1 as pH,It$1 as pI,Tt as pJ,l$2 as pK,a$2 as pL,d$2 as pM,s$2 as pN,Ue$2 as pO,dn$2 as pP,$e$2 as pQ,un$1 as pR,Bi as pS,It as pT,en$2 as pU,_$1 as pV,te$2 as pW,le$2 as pX,on$2 as pY,$t$3 as pZ,mn$2 as p_,Sn$1 as pa,Nn$1 as pb,ce$1 as pc,Tu as pd,vu as pe,ae$1 as pf,xt$3 as pg,St$3 as ph,Pc as pi,Lc as pj,Ic as pk,mt$3 as pl,rs as pm,an$1 as pn,Je$2 as po,Ft$1 as pp,Os as pq,Mt$1 as pr,gt as ps,Co as pt,Tn as pu,Dt as pv,So as pw,vn as px,kn$1 as py,xl as pz,useSignalValue$1 as q,Ul as q$,gr as q0,Ge$2 as q1,_r as q2,Ve$2 as q3,je$1 as q4,Ye$1 as q5,qe$2 as q6,Yt as q7,Ya as q8,Pe$2 as q9,Al as qA,No as qB,bo as qC,as as qD,_t as qE,eu as qF,fc as qG,Re as qH,Kc as qI,Wt$1 as qJ,z$2 as qK,ac as qL,On$1 as qM,Ht$1 as qN,Le$2 as qO,zr as qP,Bt$1 as qQ,Ll as qR,ui as qS,ec as qT,nc as qU,zt$1 as qV,Ir as qW,i$1 as qX,uu as qY,Aa as qZ,Wa as q_,Ja as qa,tu as qb,zl as qc,Fl as qd,Ma as qe,ja as qf,Hl as qg,Ba as qh,Bl as qi,Pr as qj,Pe as qk,uo as ql,mu as qm,iu as qn,ku as qo,Mo as qp,Rl as qq,wu as qr,Fn as qs,lc as qt,$s as qu,he as qv,Fe as qw,Ut$1 as qx,We as qy,Fs as qz,reactExports as r,oe$1 as r$,ql as r0,dc as r1,be as r2,ke as r3,ft as r4,pi as r5,x$4 as r6,z as r7,O$1 as r8,r$2 as r9,vi as rA,Ql as rB,ut$2 as rC,Gl as rD,ReactDOM as rE,M$2 as rF,PersonIcon as rG,Pt$1 as rH,s$1 as rI,f$3 as rJ,P$1 as rK,fe$1 as rL,PaperAirplaneIcon as rM,bn$2 as rN,TableIcon as rO,q as rP,ChecklistIcon as rQ,fn$1 as rR,GrabberIcon as rS,vo as rT,yo as rU,wo as rV,mo as rW,j$1 as rX,r$3 as rY,$2AODx$react as rZ,jt$1 as r_,t$2 as ra,Es as rb,_s as rc,vt$2 as rd,n$2 as re,b$1 as rf,nn$1 as rg,r$1 as rh,g$1 as ri,Tt$2 as rj,ys as rk,e$1 as rl,vl as rm,u$1 as rn,b$3 as ro,z$1 as rp,zi as rq,Ji as rr,ko as rs,To as rt,Ze$2 as ru,Qe$2 as rv,Mn$1 as rw,wn$1 as rx,En$1 as ry,xo as rz,sandboxIsLive as s,requireIsObject as s$,ie$2 as s0,PaintbrushIcon as s1,RowsIcon as s2,x$2 as s3,AlertFillIcon as s4,ArrowRightIcon as s5,BeakerIcon as s6,BellIcon as s7,BookIcon as s8,BroadcastIcon as s9,RssIcon as sA,ShareAndroidIcon as sB,ShieldCheckIcon as sC,ShieldIcon as sD,SidebarExpandIcon as sE,SkipIcon as sF,SlidersIcon as sG,SparkleFillIcon as sH,SquareCircleIcon as sI,SunIcon as sJ,TagIcon as sK,TasklistIcon as sL,ThumbsdownIcon as sM,ThumbsupIcon as sN,UnmuteIcon as sO,UploadIcon as sP,XCircleFillIcon as sQ,ZapIcon as sR,require_Symbol as sS,requireIsArguments as sT,requireIsArray as sU,require_arrayPush as sV,require_baseGetTag as sW,requireIsObjectLike as sX,require_MapCache as sY,require_Stack as sZ,require_baseIsEqual as s_,BrowserIcon as sa,BugIcon as sb,CircleSlashIcon as sc,CodeReviewIcon as sd,CpuIcon as se,CreditCardIcon as sf,DependabotIcon as sg,DeviceDesktopIcon as sh,DeviceMobileIcon as si,FoldIcon as sj,GearIcon as sk,GitBranchIcon as sl,GlobeIcon as sm,HeartIcon as sn,IssueOpenedIcon as so,LightBulbIcon as sp,LinkExternalIcon as sq,MegaphoneIcon as sr,MortarBoardIcon as ss,MuteIcon as st,OrganizationIcon as su,PackageIcon as sv,PaperclipIcon as sw,PeopleIcon as sx,PulseIcon as sy,RocketIcon as sz,timeLeft as t,TUTOR_VIEW as t$,requireKeys as t0,require_isIndex as t1,requireIsLength as t2,requireIdentity as t3,require_baseFor as t4,requireIsArrayLike as t5,require_baseUnary as t6,require_baseRest as t7,require_isIterateeCall as t8,require_Set as t9,getAugmentedNamespace as tA,index_esm as tB,__assign as tC,requireReactDom as tD,__extends as tE,__awaiter as tF,__rest as tG,__generator as tH,darker as tI,brighter as tJ,require$$0$4 as tK,requireBase64Js as tL,hsl as tM,requireObjectAssign as tN,ulid$1 as tO,AGENTS_VIEW as tP,CONTENTS_VIEW as tQ,DATALAYER_VIEW as tR,JWT_DATALAYER_ISSUER as tS,JWT_REFRESH_TOKEN_COOKIE_NAME as tT,LIBRARY_VIEW as tU,NAVIGATION_VIEW_HOMES as tV,RESERVATION_WARNING_TIME_MS as tW,SESSION_COOKIES as tX,SESSION_LOCAL_STORAGE_KEYS as tY,SESSION_OWNER_KEY as tZ,SETTINGS_VIEW as t_,require_setToArray as ta,require_SetCache as tb,require_cacheHas as tc,requireEq$1 as td,requireKeysIn as te,requireIsArrayLikeObject as tf,requireIsEqual as tg,requireIsPlainObject$1 as th,require_baseMerge as ti,require_createAssigner as tj,require_apply as tk,require_copyArray as tl,require_arrayEach as tm,requireCloneDeep as tn,requireFastDeepEqual as to,requireFastUri as tp,ForwardRef$2 as tq,ForwardRef$1 as tr,ForwardRef as ts,memoize$1 as tt,isPropValid as tu,tabbable as tv,focusable as tw,isTabbable as tx,getTabIndex as ty,isFocusable as tz,useNotebookStore$1 as u,claimSessionState as u0,forgetSessionState as u1,getOtelConsumeUrl as u2,getStoredToken as u3,getStoredUser as u4,isRememberableRoute as u5,isShellNeutralRoute as u6,loadRefreshTokenFromCookie as u7,navigationStore as u8,pageConfiguration as u9,profileStore as ua,registerSessionState as ub,storeToken as uc,storeUser as ud,useNavigationStore as ue,useProfile as uf,useProfileStore as ug,viewForRoute as uh,__spreadArray as ui,index$4 as uj,index$3 as uk,index$2 as ul,katex$1 as um,Lexical_prod as un,LexicalUtils_prod as uo,vM as v,datalayerCatalog as w,ChatBaseHeader as x,useContributions as y,LoopPromptPanel as z};
3804
+ `).trim();if(!Ru)throw new EmbedAttributeError("datalayer-app: the Appspec is empty.");let Iu;if(Ru.startsWith("{")){let Ou;try{Ou=JSON.parse(Ru)}catch(Pu){throw new EmbedAttributeError(`datalayer-app: the Appspec is not JSON (${Pu.message}).`)}Iu=parseAppspec(Ou)}else Iu=readAppspecYaml(Ru);return runnable(Iu)}function frameSrcOf(Au,lo,$u=""){return`${Au.replace(/\/+$/,"")}/public/apps/${encodeURIComponent(lo)}/run?embed=1${$u?`#token=${encodeURIComponent($u)}`:""}`}function frameInLanguage(Au,lo){if(!lo)return Au;const $u=Au.indexOf("#"),[Ru,Iu]=$u<0?[Au,""]:[Au.slice(0,$u),Au.slice($u)];return`${Ru}${Ru.includes("?")?"&":"?"}language=${encodeURIComponent(lo)}${Iu}`}async function readEmbeddedApp({api:Au,origin:lo,app:$u,token:Ru,fetcher:Iu=fetch}){const Ou=await Iu(`${Au.replace(/\/+$/,"")}/api/spacer/v1/apps/${encodeURIComponent($u)}/embedded`,{headers:{Authorization:`Bearer ${Ru}`}});if(Ou.status===401)return{kind:"said",text:"datalayer-app: the embed token expired or is not for this application.",expired:!0};if(!Ou.ok)return{kind:"said",text:`datalayer-app: the application could not be read (${Ou.status}).`};const Pu=await Ou.json();let Du;try{Du=JSON.parse(String(Pu.app?.model_s??"{}"))}catch{Du={}}if(!Du.spec)return{kind:"frame",src:frameSrcOf(lo,$u,Ru)};const Lu=runnable(parseAppspec(Du.spec));return Lu.kind==="decision"?{kind:"frame",src:frameSrcOf(lo,$u,Ru)}:{kind:"spec",app:Lu}}function currentScriptUrl(){try{const Au=document.currentScript;return Au?.src?new URL(Au.src,location.href).href:""}catch{return""}}function defineDatalayerAppElement(Au={}){if(typeof window>"u"||!("customElements"in window))return;const lo=Au.tag??EMBED_TAG,$u=customElements.get(lo);if($u)return $u;const Ru=Au.scriptUrl??currentScriptUrl(),Iu=Ru?new URL(Ru).origin:"",Ou=Ru?Ru.replace(/\.js(\?.*)?$/,".css"):"";class Pu extends HTMLElement{static get observedAttributes(){return EMBED_OBSERVED_ATTRIBUTES}root=null;frame=null;source=null;loading=0;passed={};offered={};windowPort=null;host={context:()=>this.passed,userToken:()=>this.getAttribute("user-token")||void 0,functions:this.offered,onWindowPort:Lu=>{this.windowPort=Lu},onEvent:Lu=>this.dispatchEvent(new CustomEvent(Lu.type,{detail:Lu.detail,bubbles:!0,composed:!0}))};get context(){return this.passed}set context(Lu){this.passed={...Lu??{}}}postWindowMessage(Lu){const ju=this.windowPort;return ju?ju(Lu):Promise.reject(new Error(`datalayer-app: ${WINDOW_NOT_YET}`))}get functions(){return this.offered}set functions(Lu){for(const ju of Object.keys(this.offered))delete this.offered[ju];Object.assign(this.offered,Lu??{})}constructor(){super(),this.attachShadow({mode:"open"}),this.onMessage=this.onMessage.bind(this),adoptPropertiesSetEarly(this)}get token(){return this.getAttribute("token")??""}set token(Lu){Lu?this.setAttribute("token",String(Lu)):this.removeAttribute("token")}get userToken(){return this.getAttribute("user-token")??""}set userToken(Lu){Lu?this.setAttribute("user-token",String(Lu)):this.removeAttribute("user-token")}connectedCallback(){window.addEventListener("message",this.onMessage),this.load()}disconnectedCallback(){window.removeEventListener("message",this.onMessage),this.unmount()}attributeChangedCallback(Lu,ju,Bu){if(!(!this.isConnected||ju===Bu)&&Lu!=="user-token"){if(Lu==="token"&&this.frame?.contentWindow&&Bu){this.frame.contentWindow.postMessage({type:EMBED_MESSAGES.token,token:Bu},this.origin());return}if(["mode","accent","theme","font","height","resume","language"].includes(Lu)){this.draw();return}this.load()}}origin(){return(this.getAttribute("origin")||Iu||location.origin).replace(/\/+$/,"")}inputs(){const Lu={};for(const Fu of EMBED_OBSERVED_ATTRIBUTES)Lu[Fu]=this.getAttribute(Fu);const ju=getComputedStyle(this),Bu={};for(const[Fu,zu]of Object.entries(EMBED_HOST_VARIABLES)){const qu=ju.getPropertyValue(zu).trim();qu&&(Bu[Fu]=qu.replace(/^["']|["']$/g,""))}return{attributes:Lu,variables:Bu}}async read(){const Lu=this.querySelector('script[type="application/yaml"], script[type="application/json"], script[type="text/yaml"]');if(Lu?.textContent?.trim())return{kind:"spec",app:appspecOfText(Lu.textContent)};const ju=this.getAttribute("spec");if(ju){const zu=await fetch(new URL(ju,location.href).href);return zu.ok?{kind:"spec",app:appspecOfText(await zu.text())}:{kind:"said",text:`datalayer-app: the Appspec at ${ju} could not be read (${zu.status}).`}}const Bu=this.getAttribute("app");if(!Bu)return{kind:"said",text:'datalayer-app: the "app" attribute names the application to show, or "spec" the address of its Appspec.'};const Fu=this.token;if(!Fu){const zu=await readVisitorApp({api:this.api(),app:Bu});return zu.kind==="decision"?{kind:"frame",src:frameSrcOf(this.origin(),zu.app)}:zu.kind==="said"?{kind:"said",text:zu.text}:{kind:"spec",app:zu.app,visitors:zu.visitors}}return readEmbeddedApp({api:this.api(),origin:this.origin(),app:Bu,token:Fu})}api(){return(this.getAttribute("api")||coreStore.getState().configuration?.spacerUrl||DEFAULT_API).replace(/\/+$/,"")}async load(){const Lu=++this.loading;let ju;try{ju=await this.read()}catch(Bu){ju={kind:"said",text:Bu instanceof Error?Bu.message:`datalayer-app: ${String(Bu)}`}}Lu!==this.loading||!this.isConnected||(this.source=ju,this.draw(),ju.kind==="said"&&ju.expired&&this.dispatchEvent(new CustomEvent("token-expired",{detail:{app:this.getAttribute("app")??""},bubbles:!0,composed:!0})))}unmount(){this.root?.unmount(),this.root=null,this.frame=null}skeleton(Lu){const ju=this.shadowRoot;if(this.unmount(),ju.replaceChildren(),Ou){const Fu=document.createElement("link");Fu.rel="stylesheet",Fu.href=Ou,ju.appendChild(Fu)}const Bu=document.createElement("style");return Bu.textContent=embedShadowCss(Lu),ju.appendChild(Bu),ju}say(Lu){this.setAttribute("data-embed-mode","inline");const ju=this.skeleton(),Bu=document.createElement("p");Bu.className="datalayer-app-said",Bu.setAttribute("role","status"),Bu.textContent=Lu,ju.appendChild(Bu)}draw(){const Lu=this.source;if(!Lu)return;if(Lu.kind==="said"){this.say(Lu.text);return}if(Lu.kind==="frame"){let Hu;try{Hu=languageOf(this.getAttribute("language"))}catch(Ku){this.say(Ku.message);return}this.setAttribute("data-embed-mode","inline");const Vu=this.skeleton(),Gu=document.createElement("iframe");Gu.className="datalayer-app-frame",Gu.src=frameInLanguage(Lu.src,Hu),Gu.title="Datalayer app",Gu.style.height=`${inlineHeightOf(this.getAttribute("height"))}px`,Gu.setAttribute("allow","clipboard-write"),Vu.appendChild(Gu),this.frame=Gu;return}let ju,Bu,Fu;try{ju=embedLookOf(this.inputs(),Lu.app),Bu=resumeOf(this.getAttribute("resume")),Fu=languageOf(this.getAttribute("language"))}catch(Hu){this.say(Hu.message);return}if(ju.mode==="assistant"){const Hu=embedAssistantCharacter(Lu.app);if("problem"in Hu){this.say(Hu.problem);return}}this.setAttribute("data-embed-mode",ju.mode);const zu=this.skeleton(getThemeConfig(ju.variant).themeStyles.css),qu=document.createElement("div");qu.className="datalayer-app-root",zu.appendChild(qu),this.root=clientExports.createRoot(qu);const Uu=this.getAttribute("server")||void 0;this.root.render(jsxRuntimeExports.jsx(me$3,{target:zu,children:jsxRuntimeExports.jsx(AppEmbed,{app:Lu.app,mode:ju.mode,accent:ju.accent,colorMode:ju.colorMode,font:ju.font,serverUrl:Uu,...Uu&&this.token?{embedToken:this.token}:{},...Lu.visitors?{visitors:Lu.visitors}:{},height:inlineHeightOf(this.getAttribute("height")),ownPortal:!0,host:this.host,resume:Bu,...Fu?{language:Fu}:{}})}))}onMessage(Lu){if(!this.frame||Lu.source!==this.frame.contentWindow||Lu.origin!==this.origin())return;const ju=Lu.data??{};ju.type===EMBED_MESSAGES.size&&typeof ju.height=="number"&&ju.height>0?this.frame.style.height=`${Math.ceil(ju.height)}px`:ju.type===EMBED_MESSAGES.decision?this.dispatchEvent(new CustomEvent("decision",{detail:ju.record,bubbles:!0,composed:!0})):ju.type===EMBED_MESSAGES.tokenExpired&&this.dispatchEvent(new CustomEvent("token-expired",{detail:{app:this.getAttribute("app")??""},bubbles:!0,composed:!0}))}}return customElements.define(lo,Pu),Pu}const SCRIPT_FILE="datalayer-app.js";defineDatalayerAppElement({scriptUrl:new URL(SCRIPT_FILE,import.meta.url).href});const mermaidVLURNSYL=Object.freeze(Object.defineProperty({__proto__:null,Mermaid:Ee$2},Symbol.toStringTag,{value:"Module"}));export{ExternalTokenizer as $,A2uiSurfaceComposed as A,Box as B,CheckIcon as C,Dialog$1 as D,InputPrompt as E,Signal as F,o$1 as G,Heading$2 as H,IconButton as I,LoopOpeningNotebook as J,LoopNotebookToolbarItem as K,Label as L,MessageProcessor as M,NO_SANDBOX_YET as N,LoopNotebookToolbar as O,PlayIcon as P,QueryClient as Q,LRLanguage as R,SANDBOX_KIND_LABELS as S,Text$5 as T,LanguageSupport as U,indentNodeProp as V,continuedIndent as W,foldNodeProp as X,styleTags as Y,tags as Z,__vitePreload as _,QueryClientProvider as a,base$2 as a$,ifNotIn as a0,completeFromList as a1,LRParser as a2,syntaxTree as a3,delimitedIndent as a4,foldInside as a5,getDefaultExportFromCjs as a6,WIDGET_VIEW_MIMETYPE as a7,MimeModel as a8,Lumino as a9,useSystemColorMode as aA,getThemeConfig as aB,JupyterReactTheme$1 as aC,l$1 as aD,v$1 as aE,a$1 as aF,Kernel as aG,registerSandboxServiceManager as aH,DatalayerThemeProvider as aI,de$1 as aJ,on$1 as aK,nl as aL,es as aM,H as aN,disposeServiceManager as aO,create$i as aP,setIfUndefined as aQ,create$8 as aR,fromBase64 as aS,onChange as aT,varStorage as aU,toBase64 as aV,offChange as aW,createUint8ArrayFromArrayBuffer as aX,map$6 as aY,WIDGET_STATE_MIMETYPE as aZ,ManagerBase as a_,RenderMimeRegistry as aa,standardRendererFactories as ab,purify$1 as ac,format$2 as ad,Token$2 as ae,Menu as af,DisposableDelegate as ag,ArrayExt as ah,Widget as ai,PanelLayout as aj,HoverBox as ak,IToolbarWidgetRegistry as al,ITranslator as am,createToolbarFactory as an,nullTranslator as ao,createDefaultFactory as ap,ObservableList as aq,Toolbar$2 as ar,ReactWidget as as,some$2 as at,ISanitizer as au,ICommandPalette as av,StatusBar as aw,useAgentsRuntimes as ax,xu as ay,useThemeStore as az,sandboxExecuteOverHttp as b,contribution as b$,controls as b0,SemVerCache as b1,JUPYTER_WIDGETS_VERSION as b2,JUPYTER_CONTROLS_VERSION as b3,shims as b4,semverExports as b5,requireLoader as b6,serialize_state as b7,Panel as b8,PromiseDelegate as b9,Prec as bA,keymap as bB,EditorView as bC,Language as bD,indentUnit as bE,foldService as bF,defineLanguageFacet as bG,CompletionContext as bH,EditorState as bI,languageDataProp as bJ,LanguageDescription as bK,ParseContext as bL,ContextTracker as bM,bracketMatchingHandle as bN,LocalTokenGroup as bO,NodeWeakMap as bP,IterMode as bQ,sublanguageProp as bR,flatIndent as bS,snippetCompletion as bT,LoopDocumentToolbarItem as bU,LoopDocumentToolbar as bV,LoopOpeningDocument as bW,useOptionalSandboxService as bX,IDLE_SANDBOX_SNAPSHOT_SIGNAL as bY,definePlugin as bZ,DOCUMENT_TOOLBAR_PLUGIN_NAME as b_,DEFAULT_SERVICE_URLS as ba,requestDatalayerAPI as bb,API_BASE_PATHS as bc,ActionList as bd,distExports as be,ActionListContainerContext as bf,BoxWithFallback as bg,merge$5 as bh,defaultSxProp as bi,useId as bj,reactDomExports as bk,useIsomorphicLayoutEffect$2 as bl,ChevronDownIcon as bm,classes$t as bn,SubItem as bo,Box$1 as bp,themeConfigs as bq,Parser$4 as br,NodeType as bs,NodeProp as bt,Tag$1 as bu,NodeSet as bv,Tree as bw,parseMixed as bx,EditorSelection as by,countColumn as bz,ButtonComponent as c,setToolbar as c$,KernelIndicator as c0,NOTEBOOK_TOOLBAR_PLUGIN_NAME as c1,useReactorPlatform as c2,AGENTS_PLUGIN_NAME as c3,IDLE_SANDBOX_TARGET_SIGNAL as c4,AGENTSPECS$1 as c5,useAgentRuntimes as c6,Eu as c7,Ke$2 as c8,_c as c9,SearchDocumentModel as cA,SearchDocumentView as cB,isResponsiveValue as cC,clsx as cD,Rgb as cE,rgbConvert as cF,define as cG,extend$3 as cH,Color as cI,commonjsRequire as cJ,TextInput$1 as cK,SearchIcon as cL,SyncIcon as cM,ToggleSwitch as cN,ChevronRightIcon as cO,StyledSpinner as cP,ToolbarButton as cQ,fileUploadIcon as cR,TextItem as cS,GroupItem as cT,libExports$2 as cU,WidgetTracker as cV,folderIcon as cW,linkIcon as cX,Clipboard as cY,downloadIcon as cZ,copyIcon as c_,is as ca,Ys as cb,PencilIcon as cc,SingletonLayout as cd,FocusTracker as ce,libExports$5 as cf,VDomModel as cg,TableOfContents as ch,JSONExt as ci,VDomRenderer as cj,LabIcon as ck,classes as cl,map$8 as cm,showErrorMessage as cn,AttachedProperty as co,addIcon as cp,launcherIcon as cq,MainAreaWidget as cr,find$5 as cs,TranslatorConnector as ct,Gettext as cu,DEFAULT_LANGUAGE_CODE as cv,normalizeDomain as cw,ITranslatorConnector as cx,Dialog as cy,showDialog$1 as cz,displayUrl as d,EditorThemeRegistry as d$,InputDialog as d0,Notification as d1,CommandRegistry as d2,closeIcon as d3,cutIcon as d4,pasteIcon as d5,newFolderIcon as d6,textEditorIcon as d7,markdownIcon as d8,refreshIcon as d9,jupyterIcon as dA,SettingRegistry as dB,MenuFactory as dC,moveUpIcon as dD,moveDownIcon as dE,Button$1 as dF,deleteIcon as dG,DOMUtils as dH,lineFormIcon as dI,deleteLine as dJ,toggleBlockComment as dK,toggleComment as dL,toggleTabFocusMode as dM,selectNextOccurrence as dN,foldable as dO,foldCode as dP,unfoldCode as dQ,foldState as dR,foldEffect as dS,unfoldEffect as dT,foldAll as dU,unfoldAll as dV,IEditorServices as dW,EditorLanguageRegistry as dX,parseMathIPython as dY,StreamLanguage as dZ,pythonBuiltin as d_,editIcon as da,fileIcon as db,stopIcon as dc,filterIcon as dd,DisposableSet as de,clearNumbering as df,getHeadingId as dg,addPrefix as dh,parseHeadings as di,filterHeadings as dj,StackedLayout as dk,ABCWidgetFactory as dl,DocumentWidget as dm,ITableOfContentsRegistry as dn,markdownRendererFactory as dp,CommandLinker as dq,SkeletonBox as dr,getBrightPalette as ds,useColorPalette as dt,SkeletonText as du,Tooltip as dv,ActionMenu as dw,KebabHorizontalIcon as dx,IWindowResolver as dy,buildIcon as dz,Link$1 as e,ListUnorderedIcon as e$,EditorExtensionRegistry as e0,ybinding as e1,CodeMirrorEditorFactory as e2,CodeMirrorMimeTypeService as e3,IPositionModel as e4,KERNEL_PROVIDER_ID as e5,Completer as e6,CompleterModel as e7,ProviderReconciliator as e8,CompletionHandler as e9,useLayoutStore as eA,useRuntimesStore as eB,color$1 as eC,OutputPrompt as eD,Stdin as eE,CodeCell as eF,notebookStore as eG,useJupyterLabCssLoaded as eH,TelescopeIcon as eI,XIcon as eJ,CounterLabel as eK,PauseIcon as eL,DownloadIcon as eM,SPAN_SOURCE_LABELS as eN,sourceOfSpan as eO,AGENT_SPAN_ATTRIBUTES as eP,describeAgentSpan as eQ,SpecMark as eR,rgb as eS,parse$4 as eT,UUID as eU,EN_US as eV,errorIcon as eW,Platform as eX,caretDownEmptyThinIcon as eY,StringExt as eZ,SegmentedControl as e_,historyIcon as ea,ICompletionProviderManager as eb,IInlineCompleterFactory as ec,KernelCompleterProvider as ed,CommandToolbarButton as ee,caretLeftIcon as ef,caretRightIcon as eg,checkIcon as eh,COMPLETER_ACTIVE_CLASS as ei,Debouncer as ej,ISessionContextDialogs as ek,SessionContextDialogs as el,saveIcon as em,addCommandToolbarButtonClass as en,UseSignal as eo,CommandToolbarButtonComponent as ep,createStore$1 as eq,useStore$1 as er,runtimesStore as es,DATALAYER_IAM_TOKEN_KEY as et,DATALAYER_IAM_USER_KEY as eu,coreStore as ev,iamStore as ew,layoutStore as ex,useCoreStore as ey,useIAMStore as ez,CopyIcon as f,AgentTools as f$,GraphIcon as f0,ProgressBar as f1,ClockIcon as f2,DatabaseIcon as f3,FileIcon as f4,ToolsIcon as f5,CommentDiscussionIcon as f6,AiModelIcon as f7,InfoIcon as f8,KeyIcon as f9,useOnOutsideClick as fA,useResizeObserver as fB,VisuallyHidden as fC,TriangleDownIcon as fD,qe$4 as fE,sx as fF,requireSerialize as fG,requireMessages as fH,mockSocketExports as fI,ObservableMap as fJ,exponent as fK,formatSpecifier as fL,formatPrefix as fM,CodeEditorWrapper as fN,CodeEditor as fO,IEditorMimeTypeService as fP,EditorSearchProvider as fQ,CodeMirrorEditor$1 as fR,getPrefix as fS,isMarkdown as fT,findNext as fU,gotoLine as fV,consoleIcon as fW,undoIcon as fX,redoIcon as fY,selectAll as fZ,Sanitizer as f_,devtools as fa,subscribeWithSelector as fb,persist as fc,CheckCircleFillIcon as fd,AlertIcon as fe,useAgentRuntimeMcpStatus as ff,useAgentRuntimeCodemodeStatus as fg,useAgentRuntimeContextSnapshot as fh,useAgentRuntimeFullContext as fi,useAgentRuntimeWsState as fj,useMutation as fk,useQuery as fl,ForwardRef$3 as fm,NoteIcon as fn,ServerIcon as fo,CheckCircleIcon as fp,XCircleIcon as fq,BriefcaseIcon as fr,SemanticCommand as fs,MenuBar as ft,runIcon as fu,fastForwardIcon as fv,getAnchoredPosition as fw,reactIsExports as fx,useTheme as fy,useOnEscapePress as fz,createAllAgentRuntimesTools as g,readServerCatalogue as g$,useToast as g0,isInsideJupyterLab as g1,FormControl$1 as g2,MailIcon as g3,Textarea as g4,$e$5 as g5,JUPYTER_NOTEBOOK_FRONTEND_TOOL_SPEC_0_0_1 as g6,LEXICAL_DOCUMENT_FRONTEND_TOOL_SPEC_0_0_1 as g7,RUNTIME_ECHO_BACKEND_TOOL_SPEC_0_0_1 as g8,TAVILY_MCP_SERVER_0_0_1 as g9,latestSaying as gA,messageText as gB,LoopRunProps as gC,runForwardedProps as gD,onSurfaceRequest as gE,setEditorOptions as gF,seedEditorChoice as gG,canOpenView as gH,useWorkspaceFullScreen as gI,targetRunsAgentInPage as gJ,useOptionalTeamSelection as gK,LoopAgentBlueprint as gL,LoopChatSuggestion as gM,agentIcon as gN,LoopFrontendTool as gO,agentServerOf as gP,LoopCommand as gQ,subagentsFor as gR,useChatAvailability as gS,noRuntimeSaid as gT,useSlotComponents as gU,LoopSlots as gV,onPromptFocusRequest as gW,generateMessageId as gX,useConfig as gY,useSkills as gZ,useSkillActions as g_,EVENTS_SKILL_SPEC_0_0_1 as ga,TEXT_SUMMARIZER_SKILL_SPEC_0_0_1 as gb,GITHUB_SKILL_SPEC_0_0_1 as gc,CRAWL_SKILL_SPEC_0_0_1 as gd,useAnonymousInferenceSession as ge,browserModelRequiresSignIn as gf,getAgentspecs as gg,useOptionalReactorPlatform as gh,messagesOfThread as gi,FluentEmoji as gj,PRESENCE_LINES as gk,useChatWords as gl,CHAT_PLUGIN_NAME as gm,INPUT_PROMPT_PLUGIN_NAME as gn,LoopChatSurface as go,LoopChatComposer as gp,LoopChatHeader as gq,LoopChatLayout as gr,LoopChatTurn as gs,turnWritersOf as gt,LoopChatExtras as gu,computed$1 as gv,useGate as gw,presenceState as gx,presenceToolOf as gy,newestIsAnswer as gz,renderOcticon as h,StaticNotebook as h$,readServerDecisions as h0,offeredModels as h1,AI_MODEL_CATALOGUE as h2,isChatModel as h3,ReactorSlot as h4,ReactorLazy as h5,ChatBase as h6,ScreenNormalIcon as h7,ScreenFullIcon as h8,SUGGESTION_CHIP_WIDTH as h9,ThemeManager as hA,ToolbarWidgetRegistry as hB,Selector$1 as hC,Printing as hD,WindowResolver as hE,jupyterFaviconIcon as hF,caretDownEmptyIcon as hG,addToolbarButtonClass as hH,NotebookActions as hI,Toolbar as hJ,translateKernelStatuses as hK,offlineBoltIcon as hL,circleIcon as hM,MessageLoop as hN,Collapser$1 as hO,ObservableJSON as hP,ConflatableMessage as hQ,jumpBackIcon as hR,jumpForwardIcon as hS,MarkdownCell as hT,Cell$1 as hU,trustedIcon as hV,notTrustedIcon as hW,runCell as hX,InputPrompt$1 as hY,NotebookPanel as hZ,setCellExecutor as h_,Truncate as ha,useAnonymousSessionStore as hb,signal$2 as hc,LoopAgentGate as hd,agentRuntimeStore as he,loopShapeVars as hf,NONE_EDITOR as hg,filterListIcon as hh,CommandPalette$1 as hi,h$7 as hj,LabIconStyle as hk,ILicensesClient as hl,Licenses as hm,copyrightIcon as hn,ToolbarButtonComponent as ho,bellIcon as hp,clientExports as hq,Button$3 as hr,ModalCommandPalette as hs,paletteIcon as ht,Throttler as hu,IKernelStatusModel as hv,KernelStatus$1 as hw,RunningSessions as hx,IThemeManager as hy,ISplashScreen as hz,SquareFillIcon as i,useProperties as i$,notebookIcon as i0,NotebookSearchProvider as i1,duplicateIcon as i2,addAboveIcon as i3,addBelowIcon as i4,children$1 as i5,ref$2 as i6,html$7 as i7,startSlotTemplate as i8,endSlotTemplate as i9,focusStrokeWidth$1 as iA,strokeWidth$1 as iB,controlCornerRadius$1 as iC,heightNumber$1 as iD,neutralFillStealthHover$1 as iE,neutralFillStealthActive$1 as iF,designUnit$1 as iG,typeRampBaseFontSize$1 as iH,typeRampBaseLineHeight$1 as iI,density$1 as iJ,typeRampPlus1FontSize$1 as iK,disabledOpacity$1 as iL,disabledCursor as iM,baseHeightMultiplier$1 as iN,neutralFillRest$1 as iO,neutralFillHover$1 as iP,neutralFillActive$1 as iQ,accentForegroundRest$1 as iR,display as iS,css as iT,forcedColorsStylesheetBehavior as iU,SystemColors as iV,cssPartial as iW,DesignToken as iX,neutralFillStealthRecipe$1 as iY,neutralFillRecipe$1 as iZ,useEventListener as i_,slotted as ia,elements as ib,FoundationElement as ic,isHTMLElement as id,__decorate$1 as ie,attr as ig,observable as ih,applyMixins as ii,StartEnd as ij,keyEnter as ik,keyArrowUp as il,keyArrowDown as im,keyArrowRight as io,keyArrowLeft as ip,keyEnd as iq,keyHome as ir,DOM as is,getDisplayedNodes as it,direction$1 as iu,neutralForegroundRest$1 as iv,neutralFillStealthRest$1 as iw,bodyFont$1 as ix,focusVisible as iy,accentFillFocus$1 as iz,jsxRuntimeExports as j,CheckboxOrRadioGroupCaption as j$,provideJupyterDesignSystem$1 as j0,ITableOfContentsTracker as j1,tocIcon as j2,numberingIcon as j3,expandAllIcon as j4,collapseAllIcon as j5,ellipsesIcon as j6,VisuallyHidden$1 as j7,StopIcon as j8,ViewPlugin as j9,NotebookCommandIds as jA,OutputAreaModel as jB,useJupyterReactStore as jC,newUuid as jD,NotebookPanelProvider as jE,addNotebookCommands as jF,WIDGET_MIMETYPE as jG,rendererFactory$1 as jH,rendererFactory as jI,getMarked as jJ,createLatexTypesetter as jK,YArray as jL,YText as jM,newUlid as jN,k$2 as jO,loopColors as jP,sunColors as jQ,ivoryColors as jR,sandColors as jS,earthColors as jT,matrixColors as jU,lovelyColors as jV,spatialColors as jW,datalayerColors as jX,getColorPalette as jY,CheckboxOrRadioGroupValidation as jZ,CheckboxOrRadioGroupLabel as j_,createRelativePositionFromTypeIndex as ja,createRelativePositionFromJSON as jb,tooltips as jc,Facet as jd,Annotation as je,layer as jf,StateField as jg,showTooltip as jh,createAbsolutePositionFromRelativePosition as ji,RectangleMarker as jj,YDocument as jk,createCellModelFromSharedType as jl,createCell as jm,YMap as jn,RawCellModel as jo,MarkdownCellModel as jp,CodeCellModel as jq,MINOR_VERSION as jr,MAJOR_VERSION as js,SessionContext as jt,StateEffect as ju,Decoration as jv,WidgetType as jw,kernelIcon as jx,DEFAULT_VARIANT as jy,MarimoReactive as jz,TrashIcon as k,qc as k$,useRenderForcingRef as k0,CheckboxOrRadioGroup$1 as k1,CheckboxGroupContext as k2,Checkbox as k3,RadioGroup$1 as k4,Radio as k5,SelectPanel as k6,Select$1 as k7,TextInputWithTokens as k8,object as k9,qi as kA,Pi as kB,isStream as kC,isExecuteResult as kD,isDisplayData as kE,isError$2 as kF,Xo as kG,Ki as kH,Yi as kI,er as kJ,T as kK,v$2 as kL,S$1 as kM,C as kN,m$2 as kO,x$5 as kP,y$3 as kQ,p$4 as kR,ol as kS,He$2 as kT,pn$2 as kU,Kr as kV,ur as kW,ls as kX,cn$1 as kY,_n as kZ,hn$2 as k_,preprocess$1 as ka,record$1 as kb,string$2 as kc,unknown$1 as kd,zodToToolParameters as ke,array as kf,_enum as kg,number$2 as kh,boolean$1 as ki,validateWithZod as kj,whitespace as kk,svg$2 as kl,find as km,stringify$1 as kn,stringify as ko,ccount as kp,zwitch as kq,html$4 as kr,htmlVoidElements as ks,C$1 as kt,Dt$4 as ku,u$2 as kv,dt$2 as kw,Go as kx,ns as ky,mn$1 as kz,libExports$3 as l,rKernelIcon as l$,Ie$2 as l0,cs as l1,dr as l2,Jl as l3,fn$2 as l4,hn$1 as l5,pn$1 as l6,Wo as l7,xt$2 as l8,Zs as l9,hpass as lA,AccordionPanel as lB,caretDownIcon as lC,AccordionLayout as lD,FormAssociated as lE,nullableNumberConverter as lF,ARIAGlobalStatesAndProperties as lG,neutralFillInputRest$1 as lH,neutralFillStrongRest$1 as lI,errorFillRest$1 as lJ,neutralFillInputHover$1 as lK,neutralFillStrongHover$1 as lL,errorFillHover$1 as lM,neutralFillStrongActive$1 as lN,errorFillActive$1 as lO,errorFillFocus$1 as lP,neutralStrokeRest$1 as lQ,__decorate as lR,searchIcon as lS,jsonIcon as lT,BoxLayout as lU,VirtualDOM as lV,TextModelFactory as lW,pdfIcon as lX,pythonIcon as lY,juliaIcon as lZ,spreadsheetIcon as l_,gc as la,On as lb,na as lc,ea as ld,ia as le,sa as lf,useJupyter as lg,decodeNamedCharacterReference as lh,requireReact as li,StyleModule as lj,jupyterHighlightStyle as lk,requireDayjs_min as ll,useFocusZone as lm,FocusKeys as ln,useSafeTimeout as lo,useSlots as lp,useProvidedRefOrCreate as lq,useResponsiveValue as lr,ScrollableRegion as ls,viewportRanges as lt,JupyterLiteServer as lu,Router as lv,ContextMenu as lw,TabPanel$1 as lx,TabBar as ly,DockPanel as lz,PlusIcon as m,ClassicWidgetManager as m$,yamlIcon as m0,imageIcon as m1,audioIcon as m2,videoIcon as m3,writeVarUint as m4,encodeStateVector as m5,writeVarUint8Array as m6,encodeStateAsUpdate as m7,readVarUint as m8,applyUpdate as m9,filter$5 as mA,ElementExt as mB,caretUpIcon as mC,Poll as mD,each$1 as mE,Application as mF,StackedPanel as mG,tabIcon as mH,Base64ModelFactory as mI,useTerminalStore as mJ,InputViewer as mK,basicSetup as mL,drawSelection as mM,indentOnInput as mN,highlightActiveLine as mO,highlightSpecialChars as mP,highlightSelectionMatches as mQ,defaultKeymap as mR,searchKeymap as mS,requestAPI$1 as mT,loadJupyterConfig as mU,createLiteServiceManager as mV,jupyterReactStore as mW,ANSWER_MARKER as mX,BuilderManagerLess as mY,CellAdapter as mZ,CellCommands as m_,readVarUint8Array as ma,readVarString as mb,ObservableV2 as mc,Awareness as md,toUint8Array$1 as me,length as mf,encodeAwarenessUpdate as mg,removeAwarenessStates as mh,isNode as mi,getUnixTime as mj,createEncoder as mk,min$1 as ml,pow as mm,createDecoder as mn,applyAwarenessUpdate as mo,BoxPanel as mp,Cell as mq,UndoManager as mr,Doc$1 as ms,SplitPanel as mt,RawCell as mu,isCodeCellModel as mv,Drag as mw,MimeData as mx,useConsoleStore as my,folderFavoriteIcon as mz,CodeIcon as n,isServedByJupyterLab as n$,CodeMirrorDatalayerEditor as n0,CodeMirrorEditor as n1,CodeMirrorOutputToolbar as n2,ContentsManagerLess as n3,DEFAULT_API_KERNEL_PREFIX_URL as n4,DEFAULT_JUPYTER_SERVER_TOKEN as n5,DEFAULT_JUPYTER_SERVER_URL as n6,DEFAULT_KERNEL_NAME as n7,DefaultExecutor as n8,EventsManagerLess as n9,UserManagerLess as nA,WidgetRenderer as nB,WorkspaceManagerLess as nC,cellSourceAsString as nD,cellsStore as nE,codeMirrorTheme as nF,consoleStore as nG,createLiteServer as nH,createServerSettings as nI,deleteCellsOperation as nJ,deleteCellsTool as nK,disableKernelReconnect as nL,disposeKernelConnections as nM,ensureJupyterAuth as nN,ensureJupyterConfig as nO,execute as nP,executeCodeOperation as nQ,executeCodeTool as nR,formatResponse as nS,getCookie as nT,getJupyterServerToken as nU,getJupyterServerUrl as nV,getKernelIndicatorMeta as nW,insertCellOperation as nX,insertCellTool as nY,isAnyCellRunning as nZ,isReactiveVariant as n_,ExecutionPhase as na,HELPER_NAME as nb,HTMLManager as nc,JupyterLabCss as nd,KERNEL_HELPER_SOURCE as ne,KERNEL_STATES as nf,KERNEL_STATE_LABELS as ng,KERNEL_STATE_VISUALS as nh,KernelActionMenu as ni,KernelExecutor as nj,KernelManagerLess as nk,KernelProgressBar as nl,KernelspecManagerLess as nm,MIME_TYPE$1 as nn,NbConvertManagerLess as no,OperationRunner as np,Output as nq,OutputAdapter as nr,OutputRenderer as ns,OutputViewer as nt,OutputViewerAdapter as nu,RenderedPlotly as nv,ServiceManagerLess as nw,SessionManagerLess as nx,SettingManagerLess as ny,TerminalManagerLess as nz,formatTokenCount as o,rn$1 as o$,jupyterLabTheme as o0,kernelsStore as o1,loadJupyterLabCss as o2,notebookToolDefinitions as o3,notebookToolOperations as o4,notebookTools as o5,outputsAsString as o6,outputsStore as o7,readAllCellsOperation as o8,readAllCellsTool as o9,bu as oA,Nu as oB,Wl as oC,Fr as oD,Li as oE,Vc as oF,Fo as oG,sn$1 as oH,vc as oI,tr as oJ,Sn as oK,Zo as oL,Cu as oM,Bs as oN,Me as oO,yn as oP,Se as oQ,Cn as oR,fn as oS,qr as oT,Ia as oU,zs as oV,gn$2 as oW,or as oX,Jr as oY,sn$2 as oZ,ln$1 as o_,readCellOperation as oa,readCellTool as ob,refreshJupyterLabPortalTheme as oc,renderKernelStateGlyph as od,renderWidgets as oe,rendererFactory$2 as of,resetJupyterConfig as og,runCellOperation as oh,runCellTool as oi,setJupyterServerToken as oj,setJupyterServerUrl as ok,sleep as ol,syncJupyterLabPortalTheme as om,terminalStore as on,toKernelState as oo,updateCellOperation as op,updateCellTool as oq,useCellsStore as or,useJupyterReactColormode as os,useJupyterReactStoreFromProps as ot,useKernelsStore as ou,useOutputsStore as ov,ThemeProvider as ow,Overlay$1 as ox,Fi as oy,Zl as oz,useSandboxService as p,Xe$2 as p$,nn$2 as p0,Vr as p1,nu as p2,du as p3,Va as p4,au as p5,La as p6,Is as p7,Dl as p8,h$1 as p9,oa as pA,Cn$1 as pB,et as pC,xn as pD,St as pE,Rt as pF,xt as pG,yn$1 as pH,It$1 as pI,Tt as pJ,l$2 as pK,a$2 as pL,d$2 as pM,s$2 as pN,Ue$2 as pO,dn$2 as pP,$e$2 as pQ,un$1 as pR,Bi as pS,It as pT,en$2 as pU,_$1 as pV,te$2 as pW,le$2 as pX,on$2 as pY,$t$3 as pZ,mn$2 as p_,Sn$1 as pa,Nn$1 as pb,ce$1 as pc,Tu as pd,vu as pe,ae$1 as pf,xt$3 as pg,St$3 as ph,Pc as pi,Lc as pj,Ic as pk,mt$3 as pl,rs as pm,an$1 as pn,Je$2 as po,Ft$1 as pp,Os as pq,Mt$1 as pr,gt as ps,Co as pt,Tn as pu,Dt as pv,So as pw,vn as px,kn$1 as py,xl as pz,useSignalValue$1 as q,Ul as q$,gr as q0,Ge$2 as q1,_r as q2,Ve$2 as q3,je$1 as q4,Ye$1 as q5,qe$2 as q6,Yt as q7,Ya as q8,Pe$2 as q9,Al as qA,No as qB,bo as qC,as as qD,_t as qE,eu as qF,fc as qG,Re as qH,Kc as qI,Wt$1 as qJ,z$2 as qK,ac as qL,On$1 as qM,Ht$1 as qN,Le$2 as qO,zr as qP,Bt$1 as qQ,Ll as qR,ui as qS,ec as qT,nc as qU,zt$1 as qV,Ir as qW,i$1 as qX,uu as qY,Aa as qZ,Wa as q_,Ja as qa,tu as qb,zl as qc,Fl as qd,Ma as qe,ja as qf,Hl as qg,Ba as qh,Bl as qi,Pr as qj,Pe as qk,uo as ql,mu as qm,iu as qn,ku as qo,Mo as qp,Rl as qq,wu as qr,Fn as qs,lc as qt,$s as qu,he as qv,Fe as qw,Ut$1 as qx,We as qy,Fs as qz,reactExports as r,oe$1 as r$,ql as r0,dc as r1,be as r2,ke as r3,ft as r4,pi as r5,x$4 as r6,z as r7,O$1 as r8,r$2 as r9,vi as rA,Ql as rB,ut$2 as rC,Gl as rD,ReactDOM as rE,M$2 as rF,PersonIcon as rG,Pt$1 as rH,s$1 as rI,f$3 as rJ,P$1 as rK,fe$1 as rL,PaperAirplaneIcon as rM,bn$2 as rN,TableIcon as rO,q as rP,ChecklistIcon as rQ,fn$1 as rR,GrabberIcon as rS,vo as rT,yo as rU,wo as rV,mo as rW,j$1 as rX,r$3 as rY,$2AODx$react as rZ,jt$1 as r_,t$2 as ra,Es as rb,_s as rc,vt$2 as rd,n$2 as re,b$1 as rf,nn$1 as rg,r$1 as rh,g$1 as ri,Tt$2 as rj,ys as rk,e$1 as rl,vl as rm,u$1 as rn,b$3 as ro,z$1 as rp,zi as rq,Ji as rr,ko as rs,To as rt,Ze$2 as ru,Qe$2 as rv,Mn$1 as rw,wn$1 as rx,En$1 as ry,xo as rz,sandboxIsLive as s,requireIsObject as s$,ie$2 as s0,PaintbrushIcon as s1,RowsIcon as s2,x$2 as s3,AlertFillIcon as s4,ArrowRightIcon as s5,BeakerIcon as s6,BellIcon as s7,BookIcon as s8,BroadcastIcon as s9,RssIcon as sA,ShareAndroidIcon as sB,ShieldCheckIcon as sC,ShieldIcon as sD,SidebarExpandIcon as sE,SkipIcon as sF,SlidersIcon as sG,SparkleFillIcon as sH,SquareCircleIcon as sI,SunIcon as sJ,TagIcon as sK,TasklistIcon as sL,ThumbsdownIcon as sM,ThumbsupIcon as sN,UnmuteIcon as sO,UploadIcon as sP,XCircleFillIcon as sQ,ZapIcon as sR,require_Symbol as sS,requireIsArguments as sT,requireIsArray as sU,require_arrayPush as sV,require_baseGetTag as sW,requireIsObjectLike as sX,require_MapCache as sY,require_Stack as sZ,require_baseIsEqual as s_,BrowserIcon as sa,BugIcon as sb,CircleSlashIcon as sc,CodeReviewIcon as sd,CpuIcon as se,CreditCardIcon as sf,DependabotIcon as sg,DeviceDesktopIcon as sh,DeviceMobileIcon as si,FoldIcon as sj,GearIcon as sk,GitBranchIcon as sl,GlobeIcon as sm,HeartIcon as sn,IssueOpenedIcon as so,LightBulbIcon as sp,LinkExternalIcon as sq,MegaphoneIcon as sr,MortarBoardIcon as ss,MuteIcon as st,OrganizationIcon as su,PackageIcon as sv,PaperclipIcon as sw,PeopleIcon as sx,PulseIcon as sy,RocketIcon as sz,timeLeft as t,TUTOR_VIEW as t$,requireKeys as t0,require_isIndex as t1,requireIsLength as t2,requireIdentity as t3,require_baseFor as t4,requireIsArrayLike as t5,require_baseUnary as t6,require_baseRest as t7,require_isIterateeCall as t8,require_Set as t9,getAugmentedNamespace as tA,index_esm as tB,__assign as tC,requireReactDom as tD,__extends as tE,__awaiter as tF,__rest as tG,__generator as tH,darker as tI,brighter as tJ,require$$0$4 as tK,requireBase64Js as tL,hsl as tM,requireObjectAssign as tN,ulid$1 as tO,AGENTS_VIEW as tP,CONTENTS_VIEW as tQ,DATALAYER_VIEW as tR,JWT_DATALAYER_ISSUER as tS,JWT_REFRESH_TOKEN_COOKIE_NAME as tT,LIBRARY_VIEW as tU,NAVIGATION_VIEW_HOMES as tV,RESERVATION_WARNING_TIME_MS as tW,SESSION_COOKIES as tX,SESSION_LOCAL_STORAGE_KEYS as tY,SESSION_OWNER_KEY as tZ,SETTINGS_VIEW as t_,require_setToArray as ta,require_SetCache as tb,require_cacheHas as tc,requireEq$1 as td,requireKeysIn as te,requireIsArrayLikeObject as tf,requireIsEqual as tg,requireIsPlainObject$1 as th,require_baseMerge as ti,require_createAssigner as tj,require_apply as tk,require_copyArray as tl,require_arrayEach as tm,requireCloneDeep as tn,requireFastDeepEqual as to,requireFastUri as tp,ForwardRef$2 as tq,ForwardRef$1 as tr,ForwardRef as ts,memoize$1 as tt,isPropValid as tu,tabbable as tv,focusable as tw,isTabbable as tx,getTabIndex as ty,isFocusable as tz,useNotebookStore$1 as u,claimSessionState as u0,forgetSessionState as u1,getOtelConsumeUrl as u2,getStoredToken as u3,getStoredUser as u4,isRememberableRoute as u5,isShellNeutralRoute as u6,loadRefreshTokenFromCookie as u7,navigationStore as u8,pageConfiguration as u9,profileStore as ua,registerSessionState as ub,storeToken as uc,storeUser as ud,useNavigationStore as ue,useProfile as uf,useProfileStore as ug,viewForRoute as uh,__spreadArray as ui,index$4 as uj,index$3 as uk,index$2 as ul,katex$1 as um,Lexical_prod as un,LexicalUtils_prod as uo,vM as v,datalayerCatalog as w,ChatBaseHeader as x,useContributions as y,LoopPromptPanel as z};