agent-world 0.12.2 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +15 -0
  2. package/dist/cli/hitl.d.ts +5 -1
  3. package/dist/cli/hitl.js +9 -3
  4. package/dist/cli/index.js +11 -9
  5. package/dist/core/activity-tracker.d.ts +12 -2
  6. package/dist/core/activity-tracker.d.ts.map +1 -1
  7. package/dist/core/activity-tracker.js +41 -5
  8. package/dist/core/activity-tracker.js.map +1 -1
  9. package/dist/core/create-agent-tool.d.ts +23 -25
  10. package/dist/core/create-agent-tool.d.ts.map +1 -1
  11. package/dist/core/create-agent-tool.js +241 -141
  12. package/dist/core/create-agent-tool.js.map +1 -1
  13. package/dist/core/events/memory-manager.js +1 -1
  14. package/dist/core/events/memory-manager.js.map +1 -1
  15. package/dist/core/events/orchestrator.d.ts.map +1 -1
  16. package/dist/core/events/orchestrator.js +14 -5
  17. package/dist/core/events/orchestrator.js.map +1 -1
  18. package/dist/core/events/persistence.d.ts +1 -1
  19. package/dist/core/events/persistence.d.ts.map +1 -1
  20. package/dist/core/events/persistence.js +1 -27
  21. package/dist/core/events/persistence.js.map +1 -1
  22. package/dist/core/events/publishers.d.ts +0 -9
  23. package/dist/core/events/publishers.d.ts.map +1 -1
  24. package/dist/core/events/publishers.js +10 -27
  25. package/dist/core/events/publishers.js.map +1 -1
  26. package/dist/core/events/subscribers.d.ts +1 -1
  27. package/dist/core/events/subscribers.d.ts.map +1 -1
  28. package/dist/core/events/subscribers.js +15 -7
  29. package/dist/core/events/subscribers.js.map +1 -1
  30. package/dist/core/hitl-tool.d.ts +79 -0
  31. package/dist/core/hitl-tool.d.ts.map +1 -0
  32. package/dist/core/hitl-tool.js +306 -0
  33. package/dist/core/hitl-tool.js.map +1 -0
  34. package/dist/core/hitl.d.ts +26 -6
  35. package/dist/core/hitl.d.ts.map +1 -1
  36. package/dist/core/hitl.js +82 -32
  37. package/dist/core/hitl.js.map +1 -1
  38. package/dist/core/index.d.ts +3 -2
  39. package/dist/core/index.d.ts.map +1 -1
  40. package/dist/core/index.js +3 -2
  41. package/dist/core/index.js.map +1 -1
  42. package/dist/core/llm-manager.d.ts +2 -0
  43. package/dist/core/llm-manager.d.ts.map +1 -1
  44. package/dist/core/llm-manager.js +16 -9
  45. package/dist/core/llm-manager.js.map +1 -1
  46. package/dist/core/managers.d.ts +24 -3
  47. package/dist/core/managers.d.ts.map +1 -1
  48. package/dist/core/managers.js +103 -52
  49. package/dist/core/managers.js.map +1 -1
  50. package/dist/core/mcp-server-registry.d.ts +3 -1
  51. package/dist/core/mcp-server-registry.d.ts.map +1 -1
  52. package/dist/core/mcp-server-registry.js +7 -1
  53. package/dist/core/mcp-server-registry.js.map +1 -1
  54. package/dist/core/tool-utils.d.ts +3 -1
  55. package/dist/core/tool-utils.d.ts.map +1 -1
  56. package/dist/core/tool-utils.js +55 -25
  57. package/dist/core/tool-utils.js.map +1 -1
  58. package/dist/core/types.d.ts +2 -17
  59. package/dist/core/types.d.ts.map +1 -1
  60. package/dist/core/types.js +0 -2
  61. package/dist/core/types.js.map +1 -1
  62. package/dist/core/utils.d.ts +9 -0
  63. package/dist/core/utils.d.ts.map +1 -1
  64. package/dist/core/utils.js +28 -3
  65. package/dist/core/utils.js.map +1 -1
  66. package/dist/public/assets/index-BW41BxMy.css +1 -0
  67. package/dist/public/assets/index-kO6UJFwK.js +96 -0
  68. package/dist/public/index.html +2 -2
  69. package/dist/server/api.js +29 -41
  70. package/dist/server/sse-handler.d.ts +3 -2
  71. package/dist/server/sse-handler.js +19 -11
  72. package/package.json +1 -1
  73. package/dist/public/assets/index-BO20H4xt.js +0 -96
  74. package/dist/public/assets/index-ETY7W5_S.css +0 -1
@@ -0,0 +1,96 @@
1
+ (function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const a of o.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(s){if(s.ep)return;s.ep=!0;const o=n(s);fetch(s.href,o)}})();const $r="3.38.0",As=`AppRun-${$r}`;class Dr{constructor(){this._events={}}on(e,n,r={}){this._events[e]=this._events[e]||[],this._events[e].push({fn:n,options:r})}off(e,n){const r=this._events[e]||[];this._events[e]=r.filter(s=>s.fn!==n)}find(e){return this._events[e]}run(e,...n){const r=this.getSubscribers(e,this._events);return console.assert(r&&r.length>0,"No subscriber for event: "+e),r.forEach(s=>{const{fn:o,options:a}=s;if(!o||typeof o!="function")return console.error(`AppRun event handler for '${e}' is not a function:`,o),!1;if(a.delay)this.delay(e,o,n,a);else try{Object.keys(a).length>0?o.apply(this,[...n,a]):o.apply(this,n)}catch(i){console.error(`Error in event handler for '${e}':`,i)}return!s.options.once}),r.length}once(e,n,r={}){this.on(e,n,{...r,once:!0})}delay(e,n,r,s){s._t&&clearTimeout(s._t),s._t=setTimeout(()=>{clearTimeout(s._t);try{Object.keys(s).length>0?n.apply(this,[...r,s]):n.apply(this,r)}catch(o){console.error(`Error in delayed event handler for '${e}':`,o)}},s.delay)}runAsync(e,...n){const r=this.getSubscribers(e,this._events);console.assert(r&&r.length>0,"No subscriber for event: "+e);const s=r.map(o=>{const{fn:a,options:i}=o;if(!a||typeof a!="function")return console.error(`AppRun async event handler for '${e}' is not a function:`,a),Promise.resolve(null);try{return Object.keys(i).length>0?a.apply(this,[...n,i]):a.apply(this,n)}catch(c){return console.error(`Error in async event handler for '${e}':`,c),Promise.reject(c)}});return Promise.all(s)}query(e,...n){return console.warn("app.query() is deprecated. Use app.runAsync() instead."),this.runAsync(e,...n)}getSubscribers(e,n){const r=n[e]||[];return n[e]=r.filter(s=>!s.options.once),Object.keys(n).filter(s=>s.endsWith("*")&&e.startsWith(s.replace("*",""))).sort((s,o)=>o.length-s.length).forEach(s=>r.push(...n[s].map(o=>({...o,options:{...o.options,event:e}})))),r}}const Ts=As;let Ft;const st=typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};st.app&&st._AppRunVersions?Ft=st.app:(Ft=new Dr,st.app=Ft,st._AppRunVersions=Ts);const _=Ft;function Le(t){return t?.target instanceof HTMLElement?t.target:null}function Es(t,e=document){try{return e.querySelector(t)}catch(n){return console.warn(`Invalid selector: ${t}`,n),null}}function Ns(t){try{return document.getElementById(t)}catch(e){return console.warn(`Error getting element by id: ${t}`,e),null}}const Or=t=>{if(!t)return[];const e=[];let n="",r=!1,s="";for(let o=0;o<t.length;o++){const a=t[o];a==="["&&!r?(n&&(e.push(n),n=""),r=!0):a==="]"&&r?(s?n=n.slice(1,-1):/^\d+$/.test(n)&&(n=parseInt(n,10)),e.push(n),n="",r=!1,s=""):(a==='"'||a==="'")&&r?(s?a===s&&(s=""):s=a,n+=a):a==="."&&!r?n&&(e.push(n),n=""):n+=a}return n&&e.push(n),e},Is=(t,e)=>{let n=t;for(const r of e){if(n==null)return;n=n[r]}return n},Cs=(t,e,n)=>{if(e.length===0)return n;const r={...t};let s=r;for(let o=0;o<e.length-1;o++){const a=e[o],i=e[o+1];s[a]==null?s[a]=typeof i=="number"?[]:{}:Array.isArray(s[a])?s[a]=[...s[a]]:typeof s[a]=="object"&&(s[a]={...s[a]}),s=s[a]}return s[e[e.length-1]]=n,r},$e=(t,e)=>{if(!e)return t.state||"";const n=Or(e),r=Is(t.state,n);return r!==void 0?r:""},De=(t,e,n)=>{if(!e){t.setState(n);return}const r=Or(e),s=t.state||{},o=Cs(s,r,n);t.setState(o)},_s=(t,e,n,r)=>{if(t.startsWith("$on")){const s=e[t];if(t=t.substring(1),typeof s=="boolean")e[t]=o=>r.run?r.run(t,o):_.run(t,o);else if(typeof s=="string")e[t]=o=>r.run?r.run(s,o):_.run(s,o);else if(typeof s=="function")e[t]=o=>r.setState(s(r.state,o));else if(Array.isArray(s)){const[o,...a]=s;typeof o=="string"?e[t]=i=>r.run?r.run(o,...a,i):_.run(o,...a,i):typeof o=="function"&&(e[t]=i=>r.setState(o(r.state,...a,i)))}}else if(t==="$bind"){const s=e.type||"text",o=typeof e[t]=="string"?e[t]:e.name;if(n==="input")switch(s){case"checkbox":e.checked=$e(r,o),e.onclick=a=>{const i=Le(a);i&&De(r,o||i.name,i.checked)};break;case"radio":e.checked=$e(r,o)===e.value,e.onclick=a=>{const i=Le(a);i&&De(r,o||i.name,i.value)};break;case"number":case"range":e.value=$e(r,o),e.oninput=a=>{const i=Le(a);i&&De(r,o||i.name,Number(i.value))};break;default:e.value=$e(r,o),e.oninput=a=>{const i=Le(a);i&&De(r,o||i.name,i.value)}}else n==="select"?(e.value=$e(r,o),e.onchange=a=>{const i=Le(a);i&&!i.multiple&&De(r,o||i.name,i.value)}):n==="option"?(e.selected=$e(r,o),e.onclick=a=>{const i=Le(a);i&&De(r,o||i.name,i.selected)}):n==="textarea"&&(e.innerHTML=$e(r,o),e.oninput=a=>{const i=Le(a);i&&De(r,o||i.name,i.value)})}else _.run("$",{key:t,tag:n,props:e,component:r})},qt=(t,e)=>{if(Array.isArray(t))return t.map(n=>qt(n,e));{let{type:n,tag:r,props:s,children:o}=t;return r=r||n,o=o||s?.children,s&&Object.keys(s).forEach(a=>{a.startsWith("$")&&(_s(a,s,r,e),delete s[a])}),o&&qt(o,e),t}};class xt{constructor(e,n,r){this.normal=n,this.property=e,r&&(this.space=r)}}xt.prototype.normal={};xt.prototype.property={};xt.prototype.space=void 0;function Pr(t,e){const n={},r={};for(const s of t)Object.assign(n,s.property),Object.assign(r,s.normal);return new xt(n,r,e)}function xn(t){return t.toLowerCase()}class le{constructor(e,n){this.attribute=n,this.property=e}}le.prototype.attribute="";le.prototype.booleanish=!1;le.prototype.boolean=!1;le.prototype.commaOrSpaceSeparated=!1;le.prototype.commaSeparated=!1;le.prototype.defined=!1;le.prototype.mustUseProperty=!1;le.prototype.number=!1;le.prototype.overloadedBoolean=!1;le.prototype.property="";le.prototype.spaceSeparated=!1;le.prototype.space=void 0;let Ms=0;const v=Pe(),F=Pe(),kn=Pe(),g=Pe(),M=Pe(),Ve=Pe(),ie=Pe();function Pe(){return 2**++Ms}const vn=Object.freeze(Object.defineProperty({__proto__:null,boolean:v,booleanish:F,commaOrSpaceSeparated:ie,commaSeparated:Ve,number:g,overloadedBoolean:kn,spaceSeparated:M},Symbol.toStringTag,{value:"Module"})),dn=Object.keys(vn);class Ln extends le{constructor(e,n,r,s){let o=-1;if(super(e,n),rr(this,"space",s),typeof r=="number")for(;++o<dn.length;){const a=dn[o];rr(this,dn[o],(r&vn[a])===vn[a])}}}Ln.prototype.defined=!0;function rr(t,e,n){n&&(t[e]=n)}function Ye(t){const e={},n={};for(const[r,s]of Object.entries(t.properties)){const o=new Ln(r,t.transform(t.attributes||{},r),s,t.space);t.mustUseProperty&&t.mustUseProperty.includes(r)&&(o.mustUseProperty=!0),e[r]=o,n[xn(r)]=r,n[xn(o.attribute)]=r}return new xt(e,n,t.space)}const Wr=Ye({properties:{ariaActiveDescendant:null,ariaAtomic:F,ariaAutoComplete:null,ariaBusy:F,ariaChecked:F,ariaColCount:g,ariaColIndex:g,ariaColSpan:g,ariaControls:M,ariaCurrent:null,ariaDescribedBy:M,ariaDetails:null,ariaDisabled:F,ariaDropEffect:M,ariaErrorMessage:null,ariaExpanded:F,ariaFlowTo:M,ariaGrabbed:F,ariaHasPopup:null,ariaHidden:F,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:M,ariaLevel:g,ariaLive:null,ariaModal:F,ariaMultiLine:F,ariaMultiSelectable:F,ariaOrientation:null,ariaOwns:M,ariaPlaceholder:null,ariaPosInSet:g,ariaPressed:F,ariaReadOnly:F,ariaRelevant:null,ariaRequired:F,ariaRoleDescription:M,ariaRowCount:g,ariaRowIndex:g,ariaRowSpan:g,ariaSelected:F,ariaSetSize:g,ariaSort:null,ariaValueMax:g,ariaValueMin:g,ariaValueNow:g,ariaValueText:null,role:null},transform(t,e){return e==="role"?e:"aria-"+e.slice(4).toLowerCase()}});function Ur(t,e){return e in t?t[e]:e}function Fr(t,e){return Ur(t,e.toLowerCase())}const Rs=Ye({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Ve,acceptCharset:M,accessKey:M,action:null,allow:null,allowFullScreen:v,allowPaymentRequest:v,allowUserMedia:v,alt:null,as:null,async:v,autoCapitalize:null,autoComplete:M,autoFocus:v,autoPlay:v,blocking:M,capture:null,charSet:null,checked:v,cite:null,className:M,cols:g,colSpan:null,content:null,contentEditable:F,controls:v,controlsList:M,coords:g|Ve,crossOrigin:null,data:null,dateTime:null,decoding:null,default:v,defer:v,dir:null,dirName:null,disabled:v,download:kn,draggable:F,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:v,formTarget:null,headers:M,height:g,hidden:kn,high:g,href:null,hrefLang:null,htmlFor:M,httpEquiv:M,id:null,imageSizes:null,imageSrcSet:null,inert:v,inputMode:null,integrity:null,is:null,isMap:v,itemId:null,itemProp:M,itemRef:M,itemScope:v,itemType:M,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:v,low:g,manifest:null,max:null,maxLength:g,media:null,method:null,min:null,minLength:g,multiple:v,muted:v,name:null,nonce:null,noModule:v,noValidate:v,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:v,optimum:g,pattern:null,ping:M,placeholder:null,playsInline:v,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:v,referrerPolicy:null,rel:M,required:v,reversed:v,rows:g,rowSpan:g,sandbox:M,scope:null,scoped:v,seamless:v,selected:v,shadowRootClonable:v,shadowRootDelegatesFocus:v,shadowRootMode:null,shape:null,size:g,sizes:null,slot:null,span:g,spellCheck:F,src:null,srcDoc:null,srcLang:null,srcSet:null,start:g,step:null,style:null,tabIndex:g,target:null,title:null,translate:null,type:null,typeMustMatch:v,useMap:null,value:F,width:g,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:M,axis:null,background:null,bgColor:null,border:g,borderColor:null,bottomMargin:g,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:v,declare:v,event:null,face:null,frame:null,frameBorder:null,hSpace:g,leftMargin:g,link:null,longDesc:null,lowSrc:null,marginHeight:g,marginWidth:g,noResize:v,noHref:v,noShade:v,noWrap:v,object:null,profile:null,prompt:null,rev:null,rightMargin:g,rules:null,scheme:null,scrolling:F,standby:null,summary:null,text:null,topMargin:g,valueType:null,version:null,vAlign:null,vLink:null,vSpace:g,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:v,disableRemotePlayback:v,prefix:null,property:null,results:g,security:null,unselectable:null},space:"html",transform:Fr}),Ls=Ye({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:ie,accentHeight:g,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:g,amplitude:g,arabicForm:null,ascent:g,attributeName:null,attributeType:null,azimuth:g,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:g,by:null,calcMode:null,capHeight:g,className:M,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:g,diffuseConstant:g,direction:null,display:null,dur:null,divisor:g,dominantBaseline:null,download:v,dx:null,dy:null,edgeMode:null,editable:null,elevation:g,enableBackground:null,end:null,event:null,exponent:g,externalResourcesRequired:null,fill:null,fillOpacity:g,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Ve,g2:Ve,glyphName:Ve,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:g,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:g,horizOriginX:g,horizOriginY:g,id:null,ideographic:g,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:g,k:g,k1:g,k2:g,k3:g,k4:g,kernelMatrix:ie,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:g,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:g,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:g,overlineThickness:g,paintOrder:null,panose1:null,path:null,pathLength:g,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:M,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:g,pointsAtY:g,pointsAtZ:g,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:ie,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:ie,rev:ie,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:ie,requiredFeatures:ie,requiredFonts:ie,requiredFormats:ie,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:g,specularExponent:g,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:g,strikethroughThickness:g,string:null,stroke:null,strokeDashArray:ie,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:g,strokeOpacity:g,strokeWidth:null,style:null,surfaceScale:g,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:ie,tabIndex:g,tableValues:null,target:null,targetX:g,targetY:g,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:ie,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:g,underlineThickness:g,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:g,values:null,vAlphabetic:g,vMathematical:g,vectorEffect:null,vHanging:g,vIdeographic:g,version:null,vertAdvY:g,vertOriginX:g,vertOriginY:g,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:g,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Ur}),zr=Ye({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(t,e){return"xlink:"+e.slice(5).toLowerCase()}}),Hr=Ye({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Fr}),Br=Ye({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(t,e){return"xml:"+e.slice(3).toLowerCase()}}),$s=/[A-Z]/g,sr=/-[a-z]/g,Ds=/^data[-\w.:]+$/i;function Os(t,e){const n=xn(e);let r=e,s=le;if(n in t.normal)return t.property[t.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&Ds.test(e)){if(e.charAt(4)==="-"){const o=e.slice(5).replace(sr,Ws);r="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=e.slice(4);if(!sr.test(o)){let a=o.replace($s,Ps);a.charAt(0)!=="-"&&(a="-"+a),e="data"+a}}s=Ln}return new s(r,e)}function Ps(t){return"-"+t.toLowerCase()}function Ws(t){return t.charAt(1).toUpperCase()}const Us=Pr([Wr,Rs,zr,Hr,Br],"html"),Fs=Pr([Wr,Ls,zr,Hr,Br],"svg"),or="_props",lr=new Map;function zs(t,e){if(e&&(e.class=e.class||e.className,delete e.className),!t||Object.keys(t).length===0)return e||{};if(!e||Object.keys(e).length===0){const r={};return Object.keys(t).forEach(s=>r[s]=null),r}const n={};return Object.keys(t).forEach(r=>{r in e||(n[r]=null)}),Object.keys(e).forEach(r=>n[r]=e[r]),n}function Hs(t){return t.length<=1?t.toLowerCase():t.split("-").map((e,n)=>n===0?e.toLowerCase():e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}function Bs(t,e){const n=`${t}:${e}`;let r=lr.get(n);return r===void 0&&(r=Os(e?Fs:Us,t)||null,lr.set(n,r)),r}function qs(t,e,n){const r=Hs(e.slice(5));n==null?delete t.dataset[r]:t.dataset[r]=String(n)}function js(t,e,n){e.startsWith("on")&&(!n||typeof n=="function"?t[e]=n:typeof n=="string"&&(n?t.setAttribute(e,n):t.removeAttribute(e)))}function ar(t,e,n){Gs(n)?t.setAttribute(e,e):t.removeAttribute(e)}function $t(t,e,n){try{t[e]=n}catch{zt(t,e,n,!1)}}function zt(t,e,n,r){if(n==null){t.removeAttribute(e);return}const s=String(n);if(r&&e.includes(":")){const[o]=e.split(":");o==="xlink"?t.setAttributeNS("http://www.w3.org/1999/xlink",e,s):t.setAttribute(e,s)}else t.setAttribute(e,s)}function Gs(t){return t==null||t===!1||t===""?!1:t===!0?!0:typeof t=="string"?t.toLowerCase()!=="false"&&t!=="0":!!t}function Vs(t,e,n,r){if(Ys(t,e))return;if(e==="style"){if(t.style.cssText&&(t.style.cssText=""),typeof n=="string")t.style.cssText=n;else if(n&&typeof n=="object")for(const o in n)t.style[o]!==n[o]&&(t.style[o]=n[o]);return}if(e==="key"){n!=null&&(t.key=n);return}if(e.startsWith("data-")){qs(t,e,n);return}if(e.startsWith("on")){js(t,e,n);return}if((t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.tagName==="SELECT")&&(e==="value"||e==="selected"||e==="selectedIndex")){$t(t,e,n);return}if(t.tagName==="INPUT"&&e==="checked"){$t(t,e,n),ar(t,e,n);return}const s=Bs(e,r);s?s.boolean||s.overloadedBoolean?ar(t,s.attribute,n):s.mustUseProperty&&!r?$t(t,s.property,n):zt(t,s.attribute,n,r):e.startsWith("aria-")||e==="role"?zt(t,e,n,r):e in t||t[e]!==void 0?$t(t,e,n):zt(t,e,n,r)}function Ys(t,e){return document.activeElement===t?["selectionStart","selectionEnd","selectionDirection"].includes(e):!!(e==="scrollTop"||e==="scrollLeft"||t instanceof HTMLMediaElement&&["currentTime","paused","playbackRate","volume"].includes(e))}function Qs(t){return/^[a-zA-Z_:][\w\-:.]*$/.test(t)&&!t.includes("<")&&!t.includes(">")&&!t.includes('"')&&!t.includes("'")}function $n(t,e,n){const r=t[or]||{},s=zs(r,e);t[or]=e||{},Xs(t,s,e,n)}function Xs(t,e,n,r){for(const s in e)Qs(s)&&Vs(t,s,e[s],r);e&&typeof e.ref=="function"&&window.requestAnimationFrame(()=>e.ref(t))}function Zs(t,...e){return qr(e)}function qr(t){const e=[],n=r=>{r!=null&&r!==""&&r!==!1&&e.push(typeof r=="function"||typeof r=="object"?r:`${r}`)};return t&&t.forEach(r=>{Array.isArray(r)?r.forEach(s=>n(s)):n(r)}),e}const ft={};let ir=0;const Ks=500,Js=1e3;function eo(){if(!(Object.keys(ft).length<=Js))for(const[t,e]of Object.entries(ft))e.isConnected||delete ft[t]}function to(t,e,...n){const r=qr(n);if(typeof t=="string")return{tag:t,props:e,children:r};if(Array.isArray(t))return t;if(t===void 0&&n)return r;if(Object.getPrototypeOf(t).__isAppRunComponent)return{tag:t,props:e,children:r};if(typeof t=="function")return t(e,r);throw new Error(`Unknown tag in vdom ${t}`)}const no=(t,e,n={})=>{if(e==null||e===!1)return;const r=typeof t=="string"&&t?document.getElementById(t)||document.querySelector(t):t;e=qt(e,n),ro(r,e,n)};function ro(t,e,n={}){if(e==null||e===!1||(e=Ht(e,n),!t))return;const r=t.nodeName==="SVG";Array.isArray(e)?Sn(t,e,r):Sn(t,[e],r)}function so(t,e){const n=t.nodeName,r=`${e.tag||""}`;return n.toUpperCase()===r.toUpperCase()}function hn(t,e,n){if(n=n||e.tag==="svg",!so(t,e)){t.parentNode.replaceChild(Gt(e,n),t);return}Sn(t,e.children,n),$n(t,e.props,n)}function Sn(t,e,n){const r=t.childNodes?.length||0,s=e?.length||0,o=Math.min(r,s);for(let i=0;i<o;i++){const c=e[i],d=t.childNodes[i];if(typeof c=="string")d.textContent!==c&&(d.nodeType===3?d.nodeValue=c:t.replaceChild(An(c),d));else if(c instanceof HTMLElement||c instanceof SVGElement)t.insertBefore(c,d);else{const h=c.props&&c.props.key;if(h)if(d.key===h)hn(t.childNodes[i],c,n);else{const y=ft[h];y?(t.insertBefore(y,d),hn(t.childNodes[i],c,n)):t.replaceChild(Gt(c,n),d)}else hn(t.childNodes[i],c,n)}}let a=t.childNodes?.length||0;for(;a>o;)t.removeChild(t.lastChild),a--;if(s>o){const i=document.createDocumentFragment();for(let c=o;c<e.length;c++)i.appendChild(Gt(e[c],n));t.appendChild(i)}}const jt=t=>{const e=document.createElement("section");return e.insertAdjacentHTML("afterbegin",t),Array.from(e.children)};function An(t){if(t?.indexOf("_html:")===0){const e=document.createElement("div");return e.insertAdjacentHTML("afterbegin",t.substring(6)),e}else return document.createTextNode(t??"")}function Gt(t,e){if(t instanceof HTMLElement||t instanceof SVGElement)return t;if(typeof t=="string")return An(t);if(!t.tag||typeof t.tag=="function")return An(JSON.stringify(t));e=e||t.tag==="svg";const n=e?document.createElementNS("http://www.w3.org/2000/svg",t.tag):document.createElement(t.tag);return $n(n,t.props,e),t.children&&t.children.forEach(r=>n.appendChild(Gt(r,e))),t.props&&t.props.key!==void 0&&(n.key=t.props.key,ft[t.props.key]=n,++ir>=Ks&&(eo(),ir=0)),n}function oo(t,e,n){const{tag:r,props:s,children:o}=t;let a=`_${n}`,i=s&&s.id;i?a=i:i=`_${n}${Date.now()}`;let c="section";s&&s.as&&(c=s.as,delete s.as),e.__componentCache||(e.__componentCache={});let d=e.__componentCache[a];if(!d||!(d instanceof r)||!d.element){const h=document.createElement(c);d=e.__componentCache[a]=new r({...s,children:o}).mount(h,{render:!0})}else d.renderState(d.state);if(d.mounted){const h=d.mounted(s,o,d.state);typeof h<"u"&&d.setState(h)}return $n(d.element,s,!1),d.element}function Ht(t,e,n=0){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(s=>Ht(s,e,n++));let r=t;if(t&&typeof t.tag=="function"&&Object.getPrototypeOf(t.tag).__isAppRunComponent&&(r=oo(t,e,n)),r&&Array.isArray(r.children)){const s=r.props?._component;if(s){let o=0;r.children=r.children.map(a=>Ht(a,s,o++))}else r.children=r.children.map(o=>Ht(o,e,n++))}return r}const lo=(t,e={})=>class extends HTMLElement{constructor(){super()}get component(){return this._component}get state(){return this._component.state}static get observedAttributes(){return(e.observedAttributes||[]).map(r=>r.toLowerCase())}connectedCallback(){if(this.isConnected&&!this._component){const r=e||{};this._shadowRoot=r.shadow?this.attachShadow({mode:"open"}):this;const s=r.observedAttributes||[],o=s.reduce((i,c)=>{const d=c.toLowerCase();return d!==c&&(i[d]=c),i},{});this._attrMap=i=>o[i]||i;const a={};Array.from(this.attributes).forEach(i=>a[this._attrMap(i.name)]=i.value),s.forEach(i=>{this[i]!==void 0&&(a[i]=this[i]),Object.defineProperty(this,i,{get(){return a[i]},set(c){this.attributeChangedCallback(i,a[i],c)},configurable:!0,enumerable:!0})}),requestAnimationFrame(()=>{const i=this.children?Array.from(this.children):[];if(this._component=new t({...a,children:i}).mount(this._shadowRoot,r),this._component._props=a,this._component.dispatchEvent=this.dispatchEvent.bind(this),this._component.mounted){const c=this._component.mounted(a,i,this._component.state);typeof c<"u"&&(this._component.state=c)}this.on=this._component.on.bind(this._component),this.run=this._component.run.bind(this._component),r.render!==!1&&this._component.run(".")})}}disconnectedCallback(){this._component?.unload?.(),this._component?.unmount?.(),this._component=null}attributeChangedCallback(r,s,o){if(this._component){const a=this._attrMap(r);this._component._props[a]=o,this._component.run("attributeChanged",a,s,o),o!==s&&e.render!==!1&&window.requestAnimationFrame(()=>{this._component.run(".")})}}},jr=(t,e,n)=>{typeof customElements<"u"&&customElements.define(t,lo(e,n))},Tn={meta:new WeakMap,defineMetadata(t,e,n){this.meta.has(n)||this.meta.set(n,{}),this.meta.get(n)[t]=e},getMetadataKeys(t){return t=Object.getPrototypeOf(t),this.meta.get(t)?Object.keys(this.meta.get(t)):[]},getMetadata(t,e){return e=Object.getPrototypeOf(e),this.meta.get(e)?this.meta.get(e)[t]:null}};function ao(t,e={}){return function(n,r){const s=t?t.toString():r;Tn.defineMetadata(`apprun-update:${s}`,{name:s,key:r,options:e},n)}}function io(t,e){return function(r){return jr(t,r,e),r}}const cr=t=>t,V=_;class Me{renderState(e,n=null){if(!this.view)return;let r=n||this.view(e);if(V.debug&&V.run("debug",{component:this,_:r?".":"-",state:e,vdom:r,el:this.element}),typeof document!="object")return;const s=typeof this.element=="string"&&this.element?Ns(this.element)||Es(this.element):this.element;if(!s){console.warn(`Component element not found: ${this.element}`);return}const o="_c";this.unload?(s._component!==this||s.getAttribute(o)!==this.tracking_id)&&(this.tracking_id=new Date().valueOf().toString(),s.setAttribute(o,this.tracking_id),typeof MutationObserver<"u"&&(this.observer||(this.observer=new MutationObserver(a=>{(a[0].oldValue===this.tracking_id||!document.body.contains(s))&&(this.unload(this.state),this.observer.disconnect(),this.observer=null)})),this.observer.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0,attributeFilter:[o]}))):s.removeAttribute&&s.removeAttribute(o),s._component=this,!n&&r&&(r=qt(r,this),this.options.transition&&document&&document.startViewTransition?document.startViewTransition(()=>V.render(s,r,this)):V.render(s,r,this)),this.rendered&&this.rendered(this.state)}setState(e,n={render:!0,history:!1}){const r=async o=>{try{for(;;){const{value:a,done:i}=await o.next();if(i)break;this.setState(a,n)}}catch(a){console.error("Error in async iterator:",a)}},s=e;if(s?.[Symbol.asyncIterator]){this.setState(r(s[Symbol.asyncIterator]()),n);return}else if(s?.[Symbol.iterator]&&typeof s.next=="function"){for(const o of s)this.setState(o,n);return}else if(e&&e instanceof Promise)Promise.resolve(e).then(o=>{this.setState(o,n),this._state=e});else{if(this._state=e,e==null)return;this.state=e,n.render!==!1&&(n.transition&&document&&document.startViewTransition?document.startViewTransition(()=>this.renderState(e)):this.renderState(e)),n.history!==!1&&this.enable_history&&(this._history=[...this._history,e],this._history_idx=this._history.length-1),typeof n.callback=="function"&&n.callback(this.state)}}constructor(e,n,r,s){this.state=e,this.view=n,this.update=r,this.options=s,this._app=new Dr,this._actions=[],this._global_events=[],this._history=[],this._history_idx=-1,this._history_prev=()=>{this._history_idx--,this._history_idx>=0?this.setState(this._history[this._history_idx],{render:!0,history:!1}):this._history_idx=0},this._history_next=()=>{this._history_idx++,this._history_idx<this._history.length?this.setState(this._history[this._history_idx],{render:!0,history:!1}):this._history_idx=this._history.length-1},this.start=(o=null,a)=>{if(this.mount(o,{render:!0,...a}),this.mounted&&typeof this.mounted=="function"){const i=this.mounted({},[],this.state);typeof i<"u"&&this.setState(i)}return this}}mount(e=null,n){return console.assert(!this.element,"Component already mounted."),this.options=n={...this.options,...n},this.element=e,this.global_event=n.global_event,this.enable_history=!!n.history,this.enable_history&&(this.on(n.history.prev||"history-prev",this._history_prev),this.on(n.history.next||"history-next",this._history_next)),n.route&&(this.update=this.update||{},this.update[n.route]||(this.update[n.route]=cr)),this.add_actions(),this.state=this.state??this.model??{},typeof this.state=="function"&&(this.state=this.state()),this.setState(this.state,{render:!!n.render,history:!0}),V.debug&&V.find("debug-create-component")?.length&&V.run("debug-create-component",this),this}is_global_event(e){return e&&(this.global_event||this._global_events.indexOf(e)>=0||e.startsWith("#")||e.startsWith("/")||e.startsWith("@"))}add_action(e,n,r={}){if(!n||typeof n!="function"){console.warn(`Component action for '${e}' is not a valid function:`,n);return}r.global&&this._global_events.push(e),this.on(e,(...s)=>{V.debug&&V.run("debug",{component:this,_:">",event:e,p:s,current_state:this.state,options:r});try{const o=n(this.state,...s);V.debug&&V.run("debug",{component:this,_:"<",event:e,p:s,newState:o,state:this.state,options:r}),this.setState(o,r)}catch(o){console.error(`Error in component action '${e}':`,o),V.debug&&V.run("debug",{component:this,_:"!",event:e,p:s,error:o,state:this.state,options:r})}},r)}add_actions(){const e=this.update||{};Tn.getMetadataKeys(this).forEach(r=>{if(r.startsWith("apprun-update:")){const s=Tn.getMetadata(r,this);e[s.name]=[this[s.key].bind(this),s.options]}});const n={};Array.isArray(e)?e.forEach(r=>{const[s,o,a]=r;s.toString().split(",").forEach(c=>n[c.trim()]=[o,a])}):Object.keys(e).forEach(r=>{const s=e[r];(typeof s=="function"||Array.isArray(s))&&r.split(",").forEach(o=>n[o.trim()]=s)}),n["."]||(n["."]=cr),Object.keys(n).forEach(r=>{const s=n[r];typeof s=="function"?this.add_action(r,s):Array.isArray(s)&&this.add_action(r,s[0],s[1])})}run(e,...n){if(this.state instanceof Promise)return Promise.resolve(this.state).then(r=>{this.state=r,this.run(e,...n)});{const r=e.toString();return this.is_global_event(r)?V.run(r,...n):this._app.run(r,...n)}}on(e,n,r){const s=e.toString();return this._actions.push({name:s,fn:n}),this.is_global_event(s)?V.on(s,n,r):this._app.on(s,n,r)}runAsync(e,...n){const r=e.toString();return this.is_global_event(r)?V.runAsync(r,...n):this._app.runAsync(r,...n)}query(e,...n){return console.warn("component.query() is deprecated. Use component.runAsync() instead."),this.runAsync(e,...n)}unmount(){this.observer?.disconnect(),this._actions.forEach(e=>{const{name:n,fn:r}=e;this.is_global_event(n)?V.off(n,r):this._app.off(n,r)})}}Me.__isAppRunComponent=!0;function co(t){return t?t.startsWith("#/")?t.substring(2).split("/"):t.startsWith("#")||t.startsWith("/")?t.substring(1).split("/"):t.split("/"):[]}function uo(t){return!t||t==="/"||t==="#"||t==="#/"?t:t.endsWith("/")?t.slice(0,-1):t}function ho(t){const e=t.filter(Boolean);e.length>11&&console.warn(`Deep route hierarchy detected: ${e.join("/")} (${e.length} levels)`)}function po(t,e){if(!e||e==="/"||e==="")return t;const n=e.startsWith("/")?e:"/"+e;if(t.startsWith(n)){const r=t.substring(n.length);return r.startsWith("/")?r:"/"+r}return t}function go(t,e){const n=[];for(let r=t.length;r>0;r--){const s=t.slice(0,r);let o="";switch(e){case"path":o="/"+s.join("/");break;case"hash":o="#"+s.join("/");break;case"hash-slash":o="#/"+s.join("/");break;case"non-prefixed":o=s.join("/");break}n.push(o)}return n}function mo(t,e){for(let n=0;n<t.length;n++){const r=t[n],s=_.find(r);if(s&&s.length>0){const o=t.length-n,a=e.slice(o);return{eventName:r,parameters:a}}}return null}function ur(){const t=_.find("#");if(t&&t.length>0){_.run("#"),_.run(_e,"#");return}const e=_.find("/");if(e&&e.length>0){_.run("/"),_.run(_e,"/");return}const n=_.find("#/");if(n&&n.length>0){_.run("#/"),_.run(_e,"#/");return}console.warn("No subscribers for event: "),_.run(wt,""),_.run(_e,"")}function fo(t){if(!t){ur();return}t=uo(t);const e=_.basePath;e&&(t=po(t,e));const n=co(t);ho(n);let r;t.startsWith("#/")?r="hash-slash":t.startsWith("#")?r="hash":t.startsWith("/")?r="path":r="non-prefixed";const s=go(n,r),o=mo(s,n);if(o)yo(o.eventName,...o.parameters);else if(s.length>0){const a=s[s.length-1];console.warn(`No subscribers for event: ${a}`),_.run(wt,t),_.run(_e,t)}else ur()}const yo=(t,...e)=>{if(!t||t===_e||t===wt)return;const n=_.find(t);!n||n.length===0?(console.warn(`No subscribers for event: ${t}`),_.run(wt,t,...e)):_.run(t,...e),_.run(_e,t,...e)},_e="//",wt="///",Ge=t=>{_.lastUrl!==t&&(_.lastUrl=t,fo(t))};function dr(t){return t&&typeof t=="object"&&typeof t.mount=="function"}function En(t){return typeof t=="function"&&t.prototype&&t.prototype.constructor===t&&(t.prototype.mount!==void 0||t.prototype.state!==void 0||t.prototype.view!==void 0)}function Gr(t){return typeof t=="function"&&!En(t)}async function bo(t,e=3){let n=t,r=0;for(;Gr(n)&&r<e;)try{const s=await n();if(s===n)break;n=s,r++}catch(s){console.error(`Error executing component function: ${s}`);break}return n}const wo=async(t,e)=>{for(const[n,r]of Object.entries(e)){if(!r||!n){console.error(`Invalid component configuration: component=${r}, route=${n}`);continue}if(dr(r)){const s={route:n};r.mount(t,s);continue}if(En(r)){const s=new r,o={route:n};s.mount(t,o);continue}if(Gr(r)){let s=await bo(r);if(dr(s)){const o={route:n};s.mount(t,o);continue}if(En(s)){const o=new s,a={route:n};o.mount(t,a);continue}_.on(n,(...o)=>{const a=r(...o);if(typeof t=="string"&&(t=document.querySelector(t),!t)){console.error(`Element not found: ${t}`);return}return _.render(t,a)});continue}console.error("Invalid component: component must be a class, instance, or function that returns a class/instance")}},l=_;if(!l.start){l.version=$r,l.h=l.createElement=to,l.render=no,l.Fragment=Zs,l.webComponent=jr,l.safeHTML=jt,l.start=(e,n,r,s,o)=>{const a={render:!0,global_event:!0,...o},i=new Me(n,r,s);return o&&o.rendered&&(i.rendered=o.rendered),o&&o.mounted&&(i.mounted=o.mounted),i.start(e,a),i},l.query=l.query||l.runAsync;const t=e=>{};if(l.on("/",t),l.on("debug",e=>t),l.on(_e,t),l.on(wt,t),l.route=Ge,l.on("route",e=>l.route&&l.route(e)),typeof document=="object"&&document.addEventListener("DOMContentLoaded",()=>{const e=document.body.hasAttribute("apprun-no-init")||l["no-init-route"]||!1,n=l.find("#")||l.find("#/")||!1;window.addEventListener("hashchange",()=>Ge(location.hash)),window.addEventListener("popstate",()=>Ge(location.pathname)),n?!e&&Ge(location.hash):(!e&&(()=>{const r=l.basePath||"";let s=location.pathname;r&&s.startsWith(r)&&(s=s.substring(r.length),s.startsWith("/")||(s="/"+s)),Ge(s)})(),document.body.addEventListener("click",r=>{const s=r.target;if(!s)return;const o=s.tagName==="A"?s:s.closest("a");if(o&&o.origin===location.origin&&o.pathname){r.preventDefault();const i=(l.basePath||"")+o.pathname;history.pushState(null,"",i),Ge(o.pathname)}}))}),typeof window=="object"){const e=window;e.Component=Me,e._React=e.React,e.React=l,e.on=ao,e.customElement=io,e.safeHTML=jt}l.use_render=(e,n=0)=>{n===0?l.render=(r,s)=>e(s,r):l.render=(r,s)=>e(r,s)},l.use_react=(e,n)=>{if(!e||!n){console.error("AppRun use_react: React and ReactDOM parameters are required");return}if(typeof e.createElement!="function"){console.error("AppRun use_react: Invalid React object - createElement method not found");return}if(!e.Fragment){console.error("AppRun use_react: Invalid React object - Fragment not found");return}if(l.h=l.createElement=e.createElement,l.Fragment=e.Fragment,e.version&&e.version.startsWith("18")){if(!n.createRoot||typeof n.createRoot!="function"){console.error("AppRun use_react: ReactDOM.createRoot not found in React 18+");return}l.render=(r,s)=>{!r||s===void 0||(r._root||(r._root=n.createRoot(r)),r._root.render(s))}}else{if(!n.render||typeof n.render!="function"){console.error("AppRun use_react: ReactDOM.render not found in legacy React");return}l.render=(r,s)=>n.render(s,r)}},l.addComponents=wo}const xo=()=>l.h("div",{id:"main",className:"w-full min-h-screen"},l.h("div",{id:"pages"})),ko="/api";async function D(t,e={}){const n=`${ko}${t}`;try{const r=await fetch(n,{headers:{"Content-Type":"application/json",...e.headers},...e});if(!r.ok){let s=`HTTP ${r.status}: ${r.statusText}`,o=null;try{const i=await r.json();i.error&&(s=i.error,i.code&&(s+=` (${i.code})`),i.details&&(o=i.details))}catch{}const a=new Error(s);throw o&&(a.details=o),a}return r}catch(r){throw console.error(`API request failed for ${t}:`,r),r}}async function vo(){return(await D("/worlds")).json()}async function So(t){if(!t)throw new Error("World name is required");return(await D(`/worlds/${encodeURIComponent(t)}`)).json()}async function Ao(t){if(!t||!t.name)throw new Error("World data with name is required");const e={id:t.id??"",name:t.name,description:t.description||"",turnLimit:t.turnLimit??5,mainAgent:t.mainAgent??null,chatLLMProvider:t.chatLLMProvider,chatLLMModel:t.chatLLMModel,mcpConfig:t.mcpConfig,variables:t.variables,agents:t.agents??[],currentChatId:t.currentChatId??"",chats:t.chats??[]};return(await D("/worlds",{method:"POST",body:JSON.stringify(e)})).json()}async function To(t,e){if(!t||!e)throw new Error("World name and update data are required");return(await D(`/worlds/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(e)})).json()}async function Eo(t){if(!t)throw new Error("World name is required");await D(`/worlds/${encodeURIComponent(t)}`,{method:"DELETE"})}async function No(t,e){if(!t||!e)throw new Error("World name and agent data are required");return(await D(`/worlds/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(e)})).json()}async function Io(t,e,n){if(!t||!e||!n)throw new Error("World name, agent name, and update data are required");return(await D(`/worlds/${encodeURIComponent(t)}/agents/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})).json()}async function Co(t,e){if(!t||!e)throw new Error("World name and agent name are required");await D(`/worlds/${encodeURIComponent(t)}/agents/${encodeURIComponent(e)}`,{method:"DELETE"})}async function _o(t,e){if(!t||!e)throw new Error("World name and agent name are required");await D(`/worlds/${encodeURIComponent(t)}/agents/${encodeURIComponent(e)}/memory`,{method:"DELETE"})}async function Mo(t){if(!t)throw new Error("World name is required");const e=await D(`/worlds/${encodeURIComponent(t)}/export`),n=e.headers.get("Content-Disposition");let r=`${t}-export.md`;if(n){const c=n.match(/filename="(.+)"/);c&&(r=c[1])}const s=await e.text(),o=new Blob([s],{type:"text/markdown"}),a=URL.createObjectURL(o),i=document.createElement("a");i.href=a,i.download=r,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(a)}async function Ro(t){if(!t)throw new Error("World name is required");return(await D(`/worlds/${encodeURIComponent(t)}/export`)).text()}async function Lo(t,e){return await(await D(`/worlds/${encodeURIComponent(t)}/setChat/${encodeURIComponent(e)}`,{method:"POST"})).json()}async function $o(t,e){if(!t||!e)throw new Error("World name and chat ID are required");await D(`/worlds/${encodeURIComponent(t)}/chats/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Do(t){if(!t)throw new Error("World name is required");return await(await D(`/worlds/${encodeURIComponent(t)}/chats`,{method:"POST"})).json()}async function Oo(t,e,n){if(!t||!e||!n)throw new Error("World name, message ID, and chat ID are required");return(await D(`/worlds/${encodeURIComponent(t)}/messages/${encodeURIComponent(e)}`,{method:"DELETE",body:JSON.stringify({chatId:n})})).json()}async function Po(t,e,n,r){if(!t||!e||!r||!n?.trim())throw new Error("World name, message ID, chat ID, and new content are required");return(await D(`/worlds/${encodeURIComponent(t)}/messages/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify({chatId:r,newContent:n,stream:!1})})).json()}async function Wo(t,e,n,r){const s=String(e||"").trim(),o=String(n||"").trim();if(!t||!s||!o)throw new Error("World name, request ID, and optionId are required");return(await D(`/worlds/${encodeURIComponent(t)}/hitl/respond`,{method:"POST",body:JSON.stringify({requestId:s,optionId:o,chatId:r??null})})).json()}async function Uo(t,e,n="human"){if(!t||!e?.trim())throw new Error("World name and non-empty message are required");return D(`/worlds/${encodeURIComponent(t)}/messages`,{method:"POST",body:JSON.stringify({message:e,sender:n})})}async function Fo(t,e){if(!t||!e)throw new Error("World name and chat ID are required");return(await D(`/worlds/${encodeURIComponent(t)}/messages/stop`,{method:"POST",body:JSON.stringify({chatId:e})})).json()}const z={apiRequest:D,getWorlds:vo,getWorld:So,createWorld:Ao,updateWorld:To,deleteWorld:Eo,exportWorldToMarkdown:Mo,getWorldMarkdown:Ro,createAgent:No,updateAgent:Io,deleteAgent:Co,clearAgentMemory:_o,setChat:Lo,deleteChat:$o,newChat:Do,deleteMessage:Oo,editMessage:Po,respondHitlOption:Wo,stopMessageProcessing:Fo,sendMessage:Uo};function Xt(t){if(!t)return{message:"Unknown error occurred"};const e=t.message||"Unknown error occurred";return t.details&&Array.isArray(t.details)?{message:e,details:t.details}:{message:e}}function Vr(t){let n=`${t.path.length>0?t.path.join("."):"unknown field"}: ${t.message}`;return t.expected&&t.received&&(n+=` (expected ${t.expected}, received ${t.received})`),n}const zo=t=>({mode:t.mode||"create",world:{...Yr(),...t.world||{}},parentComponent:t.parentComponent,loading:!1,error:null,errorDetails:null}),Yr=()=>({name:"",description:"",turnLimit:5,mainAgent:null,chatLLMProvider:"ollama",chatLLMModel:"llama3.2:3b",mcpConfig:null,variables:""}),hr=async function*(t){if(!t.world.name.trim()){yield{...t,error:"World name is required"};return}if(t.world.mcpConfig&&t.world.mcpConfig.trim())try{JSON.parse(t.world.mcpConfig)}catch{yield{...t,error:"MCP Config must be valid JSON"};return}yield{...t,loading:!0,error:null};try{t.mode==="create"?await z.createWorld(t.world):await z.updateWorld(t.world.name,t.world);const e=t.mode==="create"?"World created successfully!":"World updated successfully!";yield{...t,loading:!1,successMessage:e},setTimeout(()=>{t.mode==="create"?window.location.href="/World/"+encodeURIComponent(t.world.name):location.reload()},2e3)}catch(e){const n=Xt(e);yield{...t,loading:!1,error:n.message,errorDetails:n.details||null}}},pr=async function*(t){yield{...t,loading:!0,error:null};try{await z.deleteWorld(t.world.name),yield{...t,loading:!1,successMessage:"World deleted successfully!"},setTimeout(()=>{location.reload()},2e3)}catch(e){const n=Xt(e);yield{...t,loading:!1,error:n.message,errorDetails:n.details||null}}},ot=t=>{t?.parentComponent&&typeof t.parentComponent.run=="function"?t.parentComponent.run("close-world-edit"):l.run("close-world-edit")};class Qr extends Me{mounted=e=>zo(e);state={mode:"create",world:Yr(),parentComponent:void 0,loading:!1,error:null,errorDetails:null,successMessage:null};view=e=>{if(e.successMessage)return l.h("div",{className:"modal-backdrop"},l.h("div",{className:"modal-content edit-modal",onclick:o=>o.stopPropagation()},l.h("div",{className:"modal-header"},l.h("h2",{className:"modal-title"},"Success!"),l.h("button",{className:"modal-close-btn",$onclick:ot,title:"Close"},"×")),l.h("div",{className:"modal-body"},l.h("div",{className:"success-message"},l.h("p",null,e.successMessage)))));const n=e.mode==="edit",r=e.mode==="delete";let s;return r?s=`Delete ${e.world.name||"World"}`:n?s=`Edit ${e.world.name||"World"}`:s="Create New World",l.h("div",{className:"modal-backdrop"},l.h("div",{className:"modal-content edit-modal",onclick:o=>o.stopPropagation()},l.h("div",{className:"modal-header"},l.h("h2",{className:"modal-title"},s),l.h("button",{className:"modal-close-btn",$onclick:ot,title:"Close"},"×")),l.h("div",{className:"modal-body"},e.error&&l.h("div",{className:"error-message"},l.h("div",{className:"error-main"},e.error),e.errorDetails&&e.errorDetails.length>0&&l.h("div",{className:"error-details"},l.h("div",{className:"error-details-title"},"Validation errors:"),l.h("ul",{className:"error-details-list"},e.errorDetails.map((o,a)=>l.h("li",{key:a,className:"error-detail-item"},Vr(o)))))),r?l.h("div",{className:"delete-confirmation"},l.h("p",{className:"delete-confirmation-text"},"Are you sure you want to delete ",l.h("span",{className:"delete-confirmation-name"},'"',e.world.name,'"'),"?"),l.h("p",{className:"delete-confirmation-text"},"This action cannot be undone and will delete all agents and messages in this world.")):l.h("form",{className:"world-form"},l.h("div",{className:"form-section"},l.h("div",{className:`form-group ${n?"hidden":""}`},l.h("label",{htmlFor:"world-name"},"World Name *"),l.h("input",{id:"world-name",type:"text",className:"form-input",placeholder:"Enter world name",value:e.world.name,$bind:"world.name",disabled:e.loading})),l.h("div",{className:"form-group"},l.h("label",{htmlFor:"world-description"},"Description"),l.h("input",{id:"world-description",type:"text",className:"form-input",placeholder:"Brief description of the world",value:e.world.description,$bind:"world.description",disabled:e.loading})),l.h("div",{className:"form-group"},l.h("label",{htmlFor:"world-main-agent"},"Main Agent"),l.h("input",{id:"world-main-agent",type:"text",className:"form-input",placeholder:"Agent ID or name (optional)",value:e.world.mainAgent||"",$bind:"world.mainAgent",disabled:e.loading})),l.h("div",{className:"form-row"},l.h("div",{className:"form-group"},l.h("label",{htmlFor:"world-chat-provider"},"Chat LLM Provider"),l.h("select",{id:"world-chat-provider",className:"form-select",value:e.world.chatLLMProvider,$bind:"world.chatLLMProvider",disabled:e.loading},l.h("option",{value:"",selected:!e.world.chatLLMProvider},"Select provider"),l.h("option",{value:"openai",selected:e.world.chatLLMProvider==="openai"},"OpenAI"),l.h("option",{value:"anthropic",selected:e.world.chatLLMProvider==="anthropic"},"Anthropic"),l.h("option",{value:"google",selected:e.world.chatLLMProvider==="google"},"Google"),l.h("option",{value:"azure",selected:e.world.chatLLMProvider==="azure"},"Azure"),l.h("option",{value:"ollama",selected:e.world.chatLLMProvider==="ollama"},"Ollama"))),l.h("div",{className:"form-group"},l.h("label",{htmlFor:"world-chat-model"},"Chat LLM Model"),l.h("input",{id:"world-chat-model",type:"text",className:"form-input",placeholder:"e.g. gpt-4, claude-3-sonnet, llama3.2:3b",value:e.world.chatLLMModel,$bind:"world.chatLLMModel",disabled:e.loading}))),l.h("div",{className:"form-group"},l.h("label",{htmlFor:"world-turn-limit"},"Turn Limit"),l.h("input",{id:"world-turn-limit",type:"number",className:"form-input",placeholder:"5",min:"1",max:"50",value:e.world.turnLimit,$bind:"world.turnLimit",disabled:e.loading})),l.h("div",{className:"form-section"},l.h("div",{className:"form-group"},l.h("label",{htmlFor:"world-variables"},"Variables (.env)"),l.h("textarea",{id:"world-variables",className:"form-textarea world-mcp-textarea",placeholder:"working_directory=/path/to/project\\nproject_name=agent-world",rows:8,value:e.world.variables||"",$bind:"world.variables",disabled:e.loading}),l.h("small",{className:"form-help-text"},"Example: ",l.h("code",null,"working_directory=/path/to/project"))),l.h("div",{className:"form-group"},l.h("label",{htmlFor:"world-mcp"},"MCP Servers"),l.h("textarea",{id:"world-mcp",className:"form-textarea world-mcp-textarea",placeholder:"Enter MCP servers configuration as JSON...",rows:12,value:e.world.mcpConfig||"",$bind:"world.mcpConfig",disabled:e.loading})))))),l.h("div",{className:"modal-footer"},l.h("div",{className:"modal-actions"},r?l.h("div",{className:"modal-primary-actions",style:"margin-left: auto;"},l.h("button",{className:"btn btn-secondary",$onclick:ot,disabled:e.loading},"Cancel"),l.h("button",{className:"btn btn-danger",$onclick:[pr],disabled:e.loading},e.loading?"Deleting...":"Delete")):n?l.h(l.Fragment,null,l.h("button",{className:"btn btn-danger",$onclick:[pr],disabled:e.loading,title:"Delete world"},e.loading?"Deleting...":"Delete"),l.h("div",{className:"modal-primary-actions"},l.h("button",{className:"btn btn-secondary",$onclick:ot,disabled:e.loading},"Cancel"),l.h("button",{className:"btn btn-primary",$onclick:[hr],disabled:e.loading||!e.world.name.trim()},e.loading?"Saving...":"Update"))):l.h("div",{className:"modal-primary-actions",style:"margin-left: auto;"},l.h("button",{className:"btn btn-secondary",$onclick:ot,disabled:e.loading},"Cancel"),l.h("button",{className:"btn btn-primary",$onclick:[hr],disabled:e.loading||!e.world.name.trim()},e.loading?"Saving...":"Create"))))))}}class Ho extends Me{state=async()=>{try{return{worlds:await z.getWorlds(),currentIndex:0,loading:!1,error:null,showWorldEdit:!1,worldEditMode:"create",selectedWorldForEdit:null}}catch(e){return{worlds:[],currentIndex:0,loading:!1,error:e.message||"Failed to load worlds",showWorldEdit:!1,worldEditMode:"create",selectedWorldForEdit:null}}};view=e=>e.loading?l.h("div",{className:"max-w-7xl mx-auto px-8 py-4"},l.h("div",{className:"flex flex-col items-center justify-center min-h-screen"},l.h("div",{className:"text-2xl text-text-secondary"},"Loading worlds..."))):e.error?l.h("div",{className:"max-w-7xl mx-auto px-8 py-4"},l.h("div",{className:"flex flex-col items-center justify-center min-h-screen gap-4"},l.h("div",{className:"text-center"},l.h("h3",{className:"text-2xl font-bold text-text-primary mb-2"},"Error loading worlds"),l.h("p",{className:"text-lg text-text-secondary mb-4"},e.error),l.h("button",{className:"btn btn-primary px-6 py-3",$onclick:"/"},"Retry")))):e.worlds.length===0?l.h("div",{className:"max-w-7xl mx-auto px-8 py-4"},l.h("div",{className:"flex flex-col items-center justify-center min-h-screen gap-4"},l.h("div",{className:"text-center"},l.h("h3",{className:"text-2xl font-bold text-text-primary mb-2"},"No worlds found"),l.h("p",{className:"text-lg text-text-secondary mb-4"},"Create your first world to get started!"),l.h("button",{className:"btn btn-primary px-6 py-3",$onclick:"open-world-create"},"Create World")))):l.h("div",{className:"max-w-7xl mx-auto px-8 py-4 min-h-screen flex flex-col justify-center"},l.h("div",{className:"flex justify-center mb-8"},l.h("h1",{className:"banner-title text-4xl tablet:text-5xl desktop:text-6xl font-bold text-center"},"PICK YOUR WORLD")),l.h("div",{className:"flex justify-center mb-8"},l.h("div",{className:"world-carousel flex items-center justify-center gap-4"},l.h("button",{className:"btn carousel-arrow w-16 h-16 tablet:w-20 tablet:h-20 flex items-center justify-center text-4xl",$onclick:"prev-world"},"‹"),l.h("div",{className:"world-cards flex items-center gap-4"},e.worlds.map((n,r)=>{const s=r===e.currentIndex;let o=!1;return e.worlds.length<=3?o=!0:o=Math.abs(r-e.currentIndex)<=1,o?l.h("button",{className:`btn world-card-btn ${s?"btn-primary center":"btn-secondary side"} flex flex-col items-center justify-center min-w-48 h-48 tablet:min-w-40 tablet:h-40 mobile:min-w-36 mobile:h-36 rounded-2xl shadow-sm`,$onclick:s?["enter-world",n]:["select-world",n]},l.h("span",{className:"world-name text-lg font-medium"},n.name)):null})),l.h("button",{className:"btn carousel-arrow w-16 h-16 tablet:w-20 tablet:h-20 flex items-center justify-center text-4xl",$onclick:"next-world"},"›"))),l.h("div",{className:"flex justify-center mb-8"},l.h("div",{className:"world-indicators flex gap-2"},e.worlds.map((n,r)=>l.h("button",{className:`world-dot ${r===e.currentIndex?"active":""}`,$onclick:["select-world",n],title:n.name})))),l.h("div",{className:"flex justify-center"},l.h("div",{className:"description-card max-w-2xl w-full p-6 rounded-xl shadow-md"},l.h("h4",{className:"description-title text-2xl font-bold text-center mb-4"},e.worlds[e.currentIndex]?.name||"Unknown World"),l.h("p",{className:"description-text text-base text-center text-text-secondary mb-6"},e.worlds[e.currentIndex]?.description||"No description available"),l.h("div",{className:"action-buttons flex items-center justify-center gap-4"},l.h("button",{className:"btn add-world-btn w-12 h-12 flex items-center justify-center rounded-lg",title:"Add New World",$onclick:"open-world-create"},l.h("span",{className:"plus-icon text-2xl"},"+")),l.h("a",{href:"/World/"+encodeURIComponent(e.worlds[e.currentIndex]?.id||e.worlds[e.currentIndex]?.name||"")},l.h("button",{className:"btn btn-primary enter-btn px-8 py-3 rounded-lg text-lg"},"Enter ",e.worlds[e.currentIndex]?.name||"World")),l.h("button",{className:"btn add-world-btn delete-world-btn w-12 h-12 flex items-center justify-center rounded-lg",title:"Delete World",$onclick:["open-world-delete",e.worlds[e.currentIndex]]},l.h("span",{className:"plus-icon text-2xl"},"×"))))),e.showWorldEdit&&l.h(Qr,{world:e.selectedWorldForEdit,mode:e.worldEditMode,parentComponent:this}));update={"prev-world":e=>({...e,currentIndex:e.currentIndex>0?e.currentIndex-1:e.worlds.length-1}),"next-world":e=>({...e,currentIndex:e.currentIndex<e.worlds.length-1?e.currentIndex+1:0}),"select-world":(e,n)=>{const r=e.worlds.findIndex(s=>s.id&&s.id===n.id||s.name===n.name);return{...e,currentIndex:r>=0?r:e.currentIndex}},"enter-world":(e,n)=>{window.location.href="/World/"+encodeURIComponent(n.id||n.name)},"open-world-create":e=>({...e,showWorldEdit:!0,worldEditMode:"create",selectedWorldForEdit:null}),"open-world-edit":(e,n)=>({...e,showWorldEdit:!0,worldEditMode:"edit",selectedWorldForEdit:n}),"open-world-delete":(e,n)=>({...e,showWorldEdit:!0,worldEditMode:"delete",selectedWorldForEdit:n}),"close-world-edit":e=>({...e,showWorldEdit:!1}),"world-saved":e=>{location.reload()},"world-deleted":e=>{location.reload()}}}function oe(t){return t?t.replace(/\s+/g,"-").replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[^a-zA-Z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").toLowerCase():""}var Y=(t=>(t.SYSTEM="system",t.WORLD="world",t.AGENT="agent",t.HUMAN="human",t))(Y||{});function lt(t){if(!t)return"system";const e=t.toLowerCase();return e==="human"||e==="user"||e==="you"?"human":e==="system"?"system":e==="world"?"world":"agent"}function Dn(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var We=Dn();function Xr(t){We=t}var yt={exec:()=>null};function I(t,e=""){let n=typeof t=="string"?t:t.source,r={replace:(s,o)=>{let a=typeof o=="string"?o:o.source;return a=a.replace(te.caret,"$1"),n=n.replace(s,a),r},getRegex:()=>new RegExp(n,e)};return r}var Bo=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),te={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}#`),htmlBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}<(?:[a-z].*>|!--)`,"i")},qo=/^(?:[ \t]*(?:\n|$))+/,jo=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Go=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,kt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Vo=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,On=/(?:[*+-]|\d{1,9}[.)])/,Zr=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Kr=I(Zr).replace(/bull/g,On).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Yo=I(Zr).replace(/bull/g,On).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Pn=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Qo=/^[^\n]+/,Wn=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Xo=I(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Wn).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Zo=I(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,On).getRegex(),Zt="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|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Un=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ko=I("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Un).replace("tag",Zt).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Jr=I(Pn).replace("hr",kt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Zt).getRegex(),Jo=I(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Jr).getRegex(),Fn={blockquote:Jo,code:jo,def:Xo,fences:Go,heading:Vo,hr:kt,html:Ko,lheading:Kr,list:Zo,newline:qo,paragraph:Jr,table:yt,text:Qo},gr=I("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",kt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Zt).getRegex(),el={...Fn,lheading:Yo,table:gr,paragraph:I(Pn).replace("hr",kt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",gr).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Zt).getRegex()},tl={...Fn,html:I(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Un).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:yt,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:I(Pn).replace("hr",kt).replace("heading",` *#{1,6} *[^
2
+ ]`).replace("lheading",Kr).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},nl=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,rl=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,es=/^( {2,}|\\)\n(?!\s*$)/,sl=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Kt=/[\p{P}\p{S}]/u,zn=/[\s\p{P}\p{S}]/u,ts=/[^\s\p{P}\p{S}]/u,ol=I(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,zn).getRegex(),ns=/(?!~)[\p{P}\p{S}]/u,ll=/(?!~)[\s\p{P}\p{S}]/u,al=/(?:[^\s\p{P}\p{S}]|~)/u,il=I(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Bo?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),rs=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,cl=I(rs,"u").replace(/punct/g,Kt).getRegex(),ul=I(rs,"u").replace(/punct/g,ns).getRegex(),ss="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",dl=I(ss,"gu").replace(/notPunctSpace/g,ts).replace(/punctSpace/g,zn).replace(/punct/g,Kt).getRegex(),hl=I(ss,"gu").replace(/notPunctSpace/g,al).replace(/punctSpace/g,ll).replace(/punct/g,ns).getRegex(),pl=I("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ts).replace(/punctSpace/g,zn).replace(/punct/g,Kt).getRegex(),gl=I(/\\(punct)/,"gu").replace(/punct/g,Kt).getRegex(),ml=I(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[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])?)+(?![-_])/).getRegex(),fl=I(Un).replace("(?:-->|$)","-->").getRegex(),yl=I("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",fl).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Vt=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,bl=I(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",Vt).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),os=I(/^!?\[(label)\]\[(ref)\]/).replace("label",Vt).replace("ref",Wn).getRegex(),ls=I(/^!?\[(ref)\](?:\[\])?/).replace("ref",Wn).getRegex(),wl=I("reflink|nolink(?!\\()","g").replace("reflink",os).replace("nolink",ls).getRegex(),mr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Hn={_backpedal:yt,anyPunctuation:gl,autolink:ml,blockSkip:il,br:es,code:rl,del:yt,emStrongLDelim:cl,emStrongRDelimAst:dl,emStrongRDelimUnd:pl,escape:nl,link:bl,nolink:ls,punctuation:ol,reflink:os,reflinkSearch:wl,tag:yl,text:sl,url:yt},xl={...Hn,link:I(/^!?\[(label)\]\((.*?)\)/).replace("label",Vt).getRegex(),reflink:I(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Vt).getRegex()},Nn={...Hn,emStrongRDelimAst:hl,emStrongLDelim:ul,url:I(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",mr).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:I(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",mr).getRegex()},kl={...Nn,br:I(es).replace("{2,}","*").getRegex(),text:I(Nn.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Dt={normal:Fn,gfm:el,pedantic:tl},at={normal:Hn,gfm:Nn,breaks:kl,pedantic:xl},vl={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},fr=t=>vl[t];function Se(t,e){if(e){if(te.escapeTest.test(t))return t.replace(te.escapeReplace,fr)}else if(te.escapeTestNoEncode.test(t))return t.replace(te.escapeReplaceNoEncode,fr);return t}function yr(t){try{t=encodeURI(t).replace(te.percentDecode,"%")}catch{return null}return t}function br(t,e){let n=t.replace(te.findPipe,(o,a,i)=>{let c=!1,d=a;for(;--d>=0&&i[d]==="\\";)c=!c;return c?"|":" |"}),r=n.split(te.splitPipe),s=0;if(r[0].trim()||r.shift(),r.length>0&&!r.at(-1)?.trim()&&r.pop(),e)if(r.length>e)r.splice(e);else for(;r.length<e;)r.push("");for(;s<r.length;s++)r[s]=r[s].trim().replace(te.slashPipe,"|");return r}function it(t,e,n){let r=t.length;if(r===0)return"";let s=0;for(;s<r&&t.charAt(r-s-1)===e;)s++;return t.slice(0,r-s)}function Sl(t,e){if(t.indexOf(e[1])===-1)return-1;let n=0;for(let r=0;r<t.length;r++)if(t[r]==="\\")r++;else if(t[r]===e[0])n++;else if(t[r]===e[1]&&(n--,n<0))return r;return n>0?-2:-1}function wr(t,e,n,r,s){let o=e.href,a=e.title||null,i=t[1].replace(s.other.outputLinkReplace,"$1");r.state.inLink=!0;let c={type:t[0].charAt(0)==="!"?"image":"link",raw:n,href:o,title:a,text:i,tokens:r.inlineTokens(i)};return r.state.inLink=!1,c}function Al(t,e,n){let r=t.match(n.other.indentCodeCompensation);if(r===null)return e;let s=r[1];return e.split(`
3
+ `).map(o=>{let a=o.match(n.other.beginningSpace);if(a===null)return o;let[i]=a;return i.length>=s.length?o.slice(s.length):o}).join(`
4
+ `)}var Yt=class{options;rules;lexer;constructor(t){this.options=t||We}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let n=e[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:e[0],codeBlockStyle:"indented",text:this.options.pedantic?n:it(n,`
5
+ `)}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let n=e[0],r=Al(n,e[3]||"",this.rules);return{type:"code",raw:n,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:r}}}heading(t){let e=this.rules.block.heading.exec(t);if(e){let n=e[2].trim();if(this.rules.other.endingHash.test(n)){let r=it(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:e[0],depth:e[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(t){let e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:it(e[0],`
6
+ `)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=it(e[0],`
7
+ `).split(`
8
+ `),r="",s="",o=[];for(;n.length>0;){let a=!1,i=[],c;for(c=0;c<n.length;c++)if(this.rules.other.blockquoteStart.test(n[c]))i.push(n[c]),a=!0;else if(!a)i.push(n[c]);else break;n=n.slice(c);let d=i.join(`
9
+ `),h=d.replace(this.rules.other.blockquoteSetextReplace,`
10
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}
11
+ ${d}`:d,s=s?`${s}
12
+ ${h}`:h;let y=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(h,o,!0),this.lexer.state.top=y,n.length===0)break;let k=o.at(-1);if(k?.type==="code")break;if(k?.type==="blockquote"){let S=k,b=S.raw+`
13
+ `+n.join(`
14
+ `),E=this.blockquote(b);o[o.length-1]=E,r=r.substring(0,r.length-S.raw.length)+E.raw,s=s.substring(0,s.length-S.text.length)+E.text;break}else if(k?.type==="list"){let S=k,b=S.raw+`
15
+ `+n.join(`
16
+ `),E=this.list(b);o[o.length-1]=E,r=r.substring(0,r.length-k.raw.length)+E.raw,s=s.substring(0,s.length-S.raw.length)+E.raw,n=b.substring(o.at(-1).raw.length).split(`
17
+ `);continue}}return{type:"blockquote",raw:r,tokens:o,text:s}}}list(t){let e=this.rules.block.list.exec(t);if(e){let n=e[1].trim(),r=n.length>1,s={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let o=this.rules.other.listItemRegex(n),a=!1;for(;t;){let c=!1,d="",h="";if(!(e=o.exec(t))||this.rules.block.hr.test(t))break;d=e[0],t=t.substring(d.length);let y=e[2].split(`
18
+ `,1)[0].replace(this.rules.other.listReplaceTabs,E=>" ".repeat(3*E.length)),k=t.split(`
19
+ `,1)[0],S=!y.trim(),b=0;if(this.options.pedantic?(b=2,h=y.trimStart()):S?b=e[1].length+1:(b=e[2].search(this.rules.other.nonSpaceChar),b=b>4?1:b,h=y.slice(b),b+=e[1].length),S&&this.rules.other.blankLine.test(k)&&(d+=k+`
20
+ `,t=t.substring(k.length+1),c=!0),!c){let E=this.rules.other.nextBulletRegex(b),X=this.rules.other.hrRegex(b),B=this.rules.other.fencesBeginRegex(b),L=this.rules.other.headingBeginRegex(b),O=this.rules.other.htmlBeginRegex(b);for(;t;){let $=t.split(`
21
+ `,1)[0],ce;if(k=$,this.options.pedantic?(k=k.replace(this.rules.other.listReplaceNesting," "),ce=k):ce=k.replace(this.rules.other.tabCharGlobal," "),B.test(k)||L.test(k)||O.test(k)||E.test(k)||X.test(k))break;if(ce.search(this.rules.other.nonSpaceChar)>=b||!k.trim())h+=`
22
+ `+ce.slice(b);else{if(S||y.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||B.test(y)||L.test(y)||X.test(y))break;h+=`
23
+ `+k}!S&&!k.trim()&&(S=!0),d+=$+`
24
+ `,t=t.substring($.length+1),y=ce.slice(b)}}s.loose||(a?s.loose=!0:this.rules.other.doubleBlankLine.test(d)&&(a=!0)),s.items.push({type:"list_item",raw:d,task:!!this.options.gfm&&this.rules.other.listIsTask.test(h),loose:!1,text:h,tokens:[]}),s.raw+=d}let i=s.items.at(-1);if(i)i.raw=i.raw.trimEnd(),i.text=i.text.trimEnd();else return;s.raw=s.raw.trimEnd();for(let c of s.items){if(this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]),c.task){if(c.text=c.text.replace(this.rules.other.listReplaceTask,""),c.tokens[0]?.type==="text"||c.tokens[0]?.type==="paragraph"){c.tokens[0].raw=c.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),c.tokens[0].text=c.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}}let d=this.rules.other.listTaskCheckbox.exec(c.raw);if(d){let h={type:"checkbox",raw:d[0]+" ",checked:d[0]!=="[ ]"};c.checked=h.checked,s.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=h.raw+c.tokens[0].raw,c.tokens[0].text=h.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(h)):c.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):c.tokens.unshift(h)}}if(!s.loose){let d=c.tokens.filter(y=>y.type==="space"),h=d.length>0&&d.some(y=>this.rules.other.anyLine.test(y.raw));s.loose=h}}if(s.loose)for(let c of s.items){c.loose=!0;for(let d of c.tokens)d.type==="text"&&(d.type="paragraph")}return s}}html(t){let e=this.rules.block.html.exec(t);if(e)return{type:"html",block:!0,raw:e[0],pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:e[0]}}def(t){let e=this.rules.block.def.exec(t);if(e){let n=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:n,raw:e[0],href:r,title:s}}}table(t){let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let n=br(e[1]),r=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),s=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
25
+ `):[],o={type:"table",raw:e[0],header:[],align:[],rows:[]};if(n.length===r.length){for(let a of r)this.rules.other.tableAlignRight.test(a)?o.align.push("right"):this.rules.other.tableAlignCenter.test(a)?o.align.push("center"):this.rules.other.tableAlignLeft.test(a)?o.align.push("left"):o.align.push(null);for(let a=0;a<n.length;a++)o.header.push({text:n[a],tokens:this.lexer.inline(n[a]),header:!0,align:o.align[a]});for(let a of s)o.rows.push(br(a,o.header.length).map((i,c)=>({text:i,tokens:this.lexer.inline(i),header:!1,align:o.align[c]})));return o}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e)return{type:"heading",raw:e[0],depth:e[2].charAt(0)==="="?1:2,text:e[1],tokens:this.lexer.inline(e[1])}}paragraph(t){let e=this.rules.block.paragraph.exec(t);if(e){let n=e[1].charAt(e[1].length-1)===`
26
+ `?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:n,tokens:this.lexer.inline(n)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let n=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let o=it(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=Sl(e[2],"()");if(o===-2)return;if(o>-1){let a=(e[0].indexOf("!")===0?5:4)+e[1].length+o;e[2]=e[2].substring(0,o),e[0]=e[0].substring(0,a).trim(),e[3]=""}}let r=e[2],s="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(r);o&&(r=o[1],s=o[3])}else s=e[3]?e[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),wr(e,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:s&&s.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(t,e){let n;if((n=this.rules.inline.reflink.exec(t))||(n=this.rules.inline.nolink.exec(t))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),s=e[r.toLowerCase()];if(!s){let o=n[0].charAt(0);return{type:"text",raw:o,text:o}}return wr(n,s,n[0],this.lexer,this.rules)}}emStrong(t,e,n=""){let r=this.rules.inline.emStrongLDelim.exec(t);if(!(!r||r[3]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[2])||!n||this.rules.inline.punctuation.exec(n))){let s=[...r[0]].length-1,o,a,i=s,c=0,d=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,e=e.slice(-1*t.length+s);(r=d.exec(e))!=null;){if(o=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!o)continue;if(a=[...o].length,r[3]||r[4]){i+=a;continue}else if((r[5]||r[6])&&s%3&&!((s+a)%3)){c+=a;continue}if(i-=a,i>0)continue;a=Math.min(a,a+i+c);let h=[...r[0]][0].length,y=t.slice(0,s+r.index+h+a);if(Math.min(s,a)%2){let S=y.slice(1,-1);return{type:"em",raw:y,text:S,tokens:this.lexer.inlineTokens(S)}}let k=y.slice(2,-2);return{type:"strong",raw:y,text:k,tokens:this.lexer.inlineTokens(k)}}}}codespan(t){let e=this.rules.inline.code.exec(t);if(e){let n=e[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),s=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&s&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:e[0],text:n}}}br(t){let e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t){let e=this.rules.inline.del.exec(t);if(e)return{type:"del",raw:e[0],text:e[2],tokens:this.lexer.inlineTokens(e[2])}}autolink(t){let e=this.rules.inline.autolink.exec(t);if(e){let n,r;return e[2]==="@"?(n=e[1],r="mailto:"+n):(n=e[1],r=n),{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(t){let e;if(e=this.rules.inline.url.exec(t)){let n,r;if(e[2]==="@")n=e[0],r="mailto:"+n;else{let s;do s=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(s!==e[0]);n=e[0],e[1]==="www."?r="http://"+e[0]:r=e[0]}return{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let n=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:n}}}},pe=class In{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||We,this.options.tokenizer=this.options.tokenizer||new Yt,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:te,block:Dt.normal,inline:at.normal};this.options.pedantic?(n.block=Dt.pedantic,n.inline=at.pedantic):this.options.gfm&&(n.block=Dt.gfm,this.options.breaks?n.inline=at.breaks:n.inline=at.gfm),this.tokenizer.rules=n}static get rules(){return{block:Dt,inline:at}}static lex(e,n){return new In(n).lex(e)}static lexInline(e,n){return new In(n).inlineTokens(e)}lex(e){e=e.replace(te.carriageReturn,`
27
+ `),this.blockTokens(e,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,n=[],r=!1){for(this.options.pedantic&&(e=e.replace(te.tabCharGlobal," ").replace(te.spaceLine,""));e;){let s;if(this.options.extensions?.block?.some(a=>(s=a.call({lexer:this},e,n))?(e=e.substring(s.raw.length),n.push(s),!0):!1))continue;if(s=this.tokenizer.space(e)){e=e.substring(s.raw.length);let a=n.at(-1);s.raw.length===1&&a!==void 0?a.raw+=`
28
+ `:n.push(s);continue}if(s=this.tokenizer.code(e)){e=e.substring(s.raw.length);let a=n.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
29
+ `)?"":`
30
+ `)+s.raw,a.text+=`
31
+ `+s.text,this.inlineQueue.at(-1).src=a.text):n.push(s);continue}if(s=this.tokenizer.fences(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.heading(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.hr(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.blockquote(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.list(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.html(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.def(e)){e=e.substring(s.raw.length);let a=n.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
32
+ `)?"":`
33
+ `)+s.raw,a.text+=`
34
+ `+s.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[s.tag]||(this.tokens.links[s.tag]={href:s.href,title:s.title},n.push(s));continue}if(s=this.tokenizer.table(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.lheading(e)){e=e.substring(s.raw.length),n.push(s);continue}let o=e;if(this.options.extensions?.startBlock){let a=1/0,i=e.slice(1),c;this.options.extensions.startBlock.forEach(d=>{c=d.call({lexer:this},i),typeof c=="number"&&c>=0&&(a=Math.min(a,c))}),a<1/0&&a>=0&&(o=e.substring(0,a+1))}if(this.state.top&&(s=this.tokenizer.paragraph(o))){let a=n.at(-1);r&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
35
+ `)?"":`
36
+ `)+s.raw,a.text+=`
37
+ `+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(s),r=o.length!==e.length,e=e.substring(s.raw.length);continue}if(s=this.tokenizer.text(e)){e=e.substring(s.raw.length);let a=n.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
38
+ `)?"":`
39
+ `)+s.raw,a.text+=`
40
+ `+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(s);continue}if(e){let a="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(a);break}else throw new Error(a)}}return this.state.top=!0,n}inline(e,n=[]){return this.inlineQueue.push({src:e,tokens:n}),n}inlineTokens(e,n=[]){let r=e,s=null;if(this.tokens.links){let c=Object.keys(this.tokens.links);if(c.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(r))!=null;)c.includes(s[0].slice(s[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(s=this.tokenizer.rules.inline.anyPunctuation.exec(r))!=null;)r=r.slice(0,s.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(s=this.tokenizer.rules.inline.blockSkip.exec(r))!=null;)o=s[2]?s[2].length:0,r=r.slice(0,s.index+o)+"["+"a".repeat(s[0].length-o-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let a=!1,i="";for(;e;){a||(i=""),a=!1;let c;if(this.options.extensions?.inline?.some(h=>(c=h.call({lexer:this},e,n))?(e=e.substring(c.raw.length),n.push(c),!0):!1))continue;if(c=this.tokenizer.escape(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.tag(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.link(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(c.raw.length);let h=n.at(-1);c.type==="text"&&h?.type==="text"?(h.raw+=c.raw,h.text+=c.text):n.push(c);continue}if(c=this.tokenizer.emStrong(e,r,i)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.codespan(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.br(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.del(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.autolink(e)){e=e.substring(c.raw.length),n.push(c);continue}if(!this.state.inLink&&(c=this.tokenizer.url(e))){e=e.substring(c.raw.length),n.push(c);continue}let d=e;if(this.options.extensions?.startInline){let h=1/0,y=e.slice(1),k;this.options.extensions.startInline.forEach(S=>{k=S.call({lexer:this},y),typeof k=="number"&&k>=0&&(h=Math.min(h,k))}),h<1/0&&h>=0&&(d=e.substring(0,h+1))}if(c=this.tokenizer.inlineText(d)){e=e.substring(c.raw.length),c.raw.slice(-1)!=="_"&&(i=c.raw.slice(-1)),a=!0;let h=n.at(-1);h?.type==="text"?(h.raw+=c.raw,h.text+=c.text):n.push(c);continue}if(e){let h="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(h);break}else throw new Error(h)}}return n}},Qt=class{options;parser;constructor(t){this.options=t||We}space(t){return""}code({text:t,lang:e,escaped:n}){let r=(e||"").match(te.notSpaceStart)?.[0],s=t.replace(te.endingNewline,"")+`
41
+ `;return r?'<pre><code class="language-'+Se(r)+'">'+(n?s:Se(s,!0))+`</code></pre>
42
+ `:"<pre><code>"+(n?s:Se(s,!0))+`</code></pre>
43
+ `}blockquote({tokens:t}){return`<blockquote>
44
+ ${this.parser.parse(t)}</blockquote>
45
+ `}html({text:t}){return t}def(t){return""}heading({tokens:t,depth:e}){return`<h${e}>${this.parser.parseInline(t)}</h${e}>
46
+ `}hr(t){return`<hr>
47
+ `}list(t){let e=t.ordered,n=t.start,r="";for(let a=0;a<t.items.length;a++){let i=t.items[a];r+=this.listitem(i)}let s=e?"ol":"ul",o=e&&n!==1?' start="'+n+'"':"";return"<"+s+o+`>
48
+ `+r+"</"+s+`>
49
+ `}listitem(t){return`<li>${this.parser.parse(t.tokens)}</li>
50
+ `}checkbox({checked:t}){return"<input "+(t?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:t}){return`<p>${this.parser.parseInline(t)}</p>
51
+ `}table(t){let e="",n="";for(let s=0;s<t.header.length;s++)n+=this.tablecell(t.header[s]);e+=this.tablerow({text:n});let r="";for(let s=0;s<t.rows.length;s++){let o=t.rows[s];n="";for(let a=0;a<o.length;a++)n+=this.tablecell(o[a]);r+=this.tablerow({text:n})}return r&&(r=`<tbody>${r}</tbody>`),`<table>
52
+ <thead>
53
+ `+e+`</thead>
54
+ `+r+`</table>
55
+ `}tablerow({text:t}){return`<tr>
56
+ ${t}</tr>
57
+ `}tablecell(t){let e=this.parser.parseInline(t.tokens),n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>
58
+ `}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${Se(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:n}){let r=this.parser.parseInline(n),s=yr(t);if(s===null)return r;t=s;let o='<a href="'+t+'"';return e&&(o+=' title="'+Se(e)+'"'),o+=">"+r+"</a>",o}image({href:t,title:e,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let s=yr(t);if(s===null)return Se(n);t=s;let o=`<img src="${t}" alt="${n}"`;return e&&(o+=` title="${Se(e)}"`),o+=">",o}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:Se(t.text)}},Bn=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},ge=class Cn{options;renderer;textRenderer;constructor(e){this.options=e||We,this.options.renderer=this.options.renderer||new Qt,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Bn}static parse(e,n){return new Cn(n).parse(e)}static parseInline(e,n){return new Cn(n).parseInline(e)}parse(e){let n="";for(let r=0;r<e.length;r++){let s=e[r];if(this.options.extensions?.renderers?.[s.type]){let a=s,i=this.options.extensions.renderers[a.type].call({parser:this},a);if(i!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(a.type)){n+=i||"";continue}}let o=s;switch(o.type){case"space":{n+=this.renderer.space(o);break}case"hr":{n+=this.renderer.hr(o);break}case"heading":{n+=this.renderer.heading(o);break}case"code":{n+=this.renderer.code(o);break}case"table":{n+=this.renderer.table(o);break}case"blockquote":{n+=this.renderer.blockquote(o);break}case"list":{n+=this.renderer.list(o);break}case"checkbox":{n+=this.renderer.checkbox(o);break}case"html":{n+=this.renderer.html(o);break}case"def":{n+=this.renderer.def(o);break}case"paragraph":{n+=this.renderer.paragraph(o);break}case"text":{n+=this.renderer.text(o);break}default:{let a='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return n}parseInline(e,n=this.renderer){let r="";for(let s=0;s<e.length;s++){let o=e[s];if(this.options.extensions?.renderers?.[o.type]){let i=this.options.extensions.renderers[o.type].call({parser:this},o);if(i!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(o.type)){r+=i||"";continue}}let a=o;switch(a.type){case"escape":{r+=n.text(a);break}case"html":{r+=n.html(a);break}case"link":{r+=n.link(a);break}case"image":{r+=n.image(a);break}case"checkbox":{r+=n.checkbox(a);break}case"strong":{r+=n.strong(a);break}case"em":{r+=n.em(a);break}case"codespan":{r+=n.codespan(a);break}case"br":{r+=n.br(a);break}case"del":{r+=n.del(a);break}case"text":{r+=n.text(a);break}default:{let i='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(i),"";throw new Error(i)}}}return r}},mt=class{options;block;constructor(t){this.options=t||We}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(){return this.block?pe.lex:pe.lexInline}provideParser(){return this.block?ge.parse:ge.parseInline}},Tl=class{defaults=Dn();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=ge;Renderer=Qt;TextRenderer=Bn;Lexer=pe;Tokenizer=Yt;Hooks=mt;constructor(...t){this.use(...t)}walkTokens(t,e){let n=[];for(let r of t)switch(n=n.concat(e.call(this,r)),r.type){case"table":{let s=r;for(let o of s.header)n=n.concat(this.walkTokens(o.tokens,e));for(let o of s.rows)for(let a of o)n=n.concat(this.walkTokens(a.tokens,e));break}case"list":{let s=r;n=n.concat(this.walkTokens(s.items,e));break}default:{let s=r;this.defaults.extensions?.childTokens?.[s.type]?this.defaults.extensions.childTokens[s.type].forEach(o=>{let a=s[o].flat(1/0);n=n.concat(this.walkTokens(a,e))}):s.tokens&&(n=n.concat(this.walkTokens(s.tokens,e)))}}return n}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(s=>{if(!s.name)throw new Error("extension name required");if("renderer"in s){let o=e.renderers[s.name];o?e.renderers[s.name]=function(...a){let i=s.renderer.apply(this,a);return i===!1&&(i=o.apply(this,a)),i}:e.renderers[s.name]=s.renderer}if("tokenizer"in s){if(!s.level||s.level!=="block"&&s.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=e[s.level];o?o.unshift(s.tokenizer):e[s.level]=[s.tokenizer],s.start&&(s.level==="block"?e.startBlock?e.startBlock.push(s.start):e.startBlock=[s.start]:s.level==="inline"&&(e.startInline?e.startInline.push(s.start):e.startInline=[s.start]))}"childTokens"in s&&s.childTokens&&(e.childTokens[s.name]=s.childTokens)}),r.extensions=e),n.renderer){let s=this.defaults.renderer||new Qt(this.defaults);for(let o in n.renderer){if(!(o in s))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let a=o,i=n.renderer[a],c=s[a];s[a]=(...d)=>{let h=i.apply(s,d);return h===!1&&(h=c.apply(s,d)),h||""}}r.renderer=s}if(n.tokenizer){let s=this.defaults.tokenizer||new Yt(this.defaults);for(let o in n.tokenizer){if(!(o in s))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let a=o,i=n.tokenizer[a],c=s[a];s[a]=(...d)=>{let h=i.apply(s,d);return h===!1&&(h=c.apply(s,d)),h}}r.tokenizer=s}if(n.hooks){let s=this.defaults.hooks||new mt;for(let o in n.hooks){if(!(o in s))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let a=o,i=n.hooks[a],c=s[a];mt.passThroughHooks.has(o)?s[a]=d=>{if(this.defaults.async&&mt.passThroughHooksRespectAsync.has(o))return(async()=>{let y=await i.call(s,d);return c.call(s,y)})();let h=i.call(s,d);return c.call(s,h)}:s[a]=(...d)=>{if(this.defaults.async)return(async()=>{let y=await i.apply(s,d);return y===!1&&(y=await c.apply(s,d)),y})();let h=i.apply(s,d);return h===!1&&(h=c.apply(s,d)),h}}r.hooks=s}if(n.walkTokens){let s=this.defaults.walkTokens,o=n.walkTokens;r.walkTokens=function(a){let i=[];return i.push(o.call(this,a)),s&&(i=i.concat(s.call(this,a))),i}}this.defaults={...this.defaults,...r}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return pe.lex(t,e??this.defaults)}parser(t,e){return ge.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let r={...n},s={...this.defaults,...r},o=this.onError(!!s.silent,!!s.async);if(this.defaults.async===!0&&r.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(s.hooks&&(s.hooks.options=s,s.hooks.block=t),s.async)return(async()=>{let a=s.hooks?await s.hooks.preprocess(e):e,i=await(s.hooks?await s.hooks.provideLexer():t?pe.lex:pe.lexInline)(a,s),c=s.hooks?await s.hooks.processAllTokens(i):i;s.walkTokens&&await Promise.all(this.walkTokens(c,s.walkTokens));let d=await(s.hooks?await s.hooks.provideParser():t?ge.parse:ge.parseInline)(c,s);return s.hooks?await s.hooks.postprocess(d):d})().catch(o);try{s.hooks&&(e=s.hooks.preprocess(e));let a=(s.hooks?s.hooks.provideLexer():t?pe.lex:pe.lexInline)(e,s);s.hooks&&(a=s.hooks.processAllTokens(a)),s.walkTokens&&this.walkTokens(a,s.walkTokens);let i=(s.hooks?s.hooks.provideParser():t?ge.parse:ge.parseInline)(a,s);return s.hooks&&(i=s.hooks.postprocess(i)),i}catch(a){return o(a)}}}onError(t,e){return n=>{if(n.message+=`
59
+ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error occurred:</p><pre>"+Se(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},Oe=new Tl;function C(t,e){return Oe.parse(t,e)}C.options=C.setOptions=function(t){return Oe.setOptions(t),C.defaults=Oe.defaults,Xr(C.defaults),C};C.getDefaults=Dn;C.defaults=We;C.use=function(...t){return Oe.use(...t),C.defaults=Oe.defaults,Xr(C.defaults),C};C.walkTokens=function(t,e){return Oe.walkTokens(t,e)};C.parseInline=Oe.parseInline;C.Parser=ge;C.parser=ge.parse;C.Renderer=Qt;C.TextRenderer=Bn;C.Lexer=pe;C.lexer=pe.lex;C.Tokenizer=Yt;C.Hooks=mt;C.parse=C;C.options;C.setOptions;C.use;C.walkTokens;C.parseInline;ge.parse;pe.lex;const{entries:as,setPrototypeOf:xr,isFrozen:El,getPrototypeOf:Nl,getOwnPropertyDescriptor:Il}=Object;let{freeze:ne,seal:de,create:_n}=Object,{apply:Mn,construct:Rn}=typeof Reflect<"u"&&Reflect;ne||(ne=function(e){return e});de||(de=function(e){return e});Mn||(Mn=function(e,n){for(var r=arguments.length,s=new Array(r>2?r-2:0),o=2;o<r;o++)s[o-2]=arguments[o];return e.apply(n,s)});Rn||(Rn=function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),s=1;s<n;s++)r[s-1]=arguments[s];return new e(...r)});const Ot=re(Array.prototype.forEach),Cl=re(Array.prototype.lastIndexOf),kr=re(Array.prototype.pop),ct=re(Array.prototype.push),_l=re(Array.prototype.splice),Bt=re(String.prototype.toLowerCase),pn=re(String.prototype.toString),gn=re(String.prototype.match),ut=re(String.prototype.replace),Ml=re(String.prototype.indexOf),Rl=re(String.prototype.trim),he=re(Object.prototype.hasOwnProperty),ee=re(RegExp.prototype.test),dt=Ll(TypeError);function re(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),s=1;s<n;s++)r[s-1]=arguments[s];return Mn(t,e,r)}}function Ll(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return Rn(t,n)}}function A(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Bt;xr&&xr(t,null);let r=e.length;for(;r--;){let s=e[r];if(typeof s=="string"){const o=n(s);o!==s&&(El(e)||(e[r]=o),s=o)}t[s]=!0}return t}function $l(t){for(let e=0;e<t.length;e++)he(t,e)||(t[e]=null);return t}function fe(t){const e=_n(null);for(const[n,r]of as(t))he(t,n)&&(Array.isArray(r)?e[n]=$l(r):r&&typeof r=="object"&&r.constructor===Object?e[n]=fe(r):e[n]=r);return e}function ht(t,e){for(;t!==null;){const r=Il(t,e);if(r){if(r.get)return re(r.get);if(typeof r.value=="function")return re(r.value)}t=Nl(t)}function n(){return null}return n}const vr=ne(["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"]),mn=ne(["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"]),fn=ne(["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"]),Dl=ne(["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"]),yn=ne(["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"]),Ol=ne(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Sr=ne(["#text"]),Ar=ne(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","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","slot"]),bn=ne(["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"]),Tr=ne(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","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"]),Pt=ne(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Pl=de(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Wl=de(/<%[\w\W]*|[\w\W]*%>/gm),Ul=de(/\$\{[\w\W]*/gm),Fl=de(/^data-[\-\w.\u00B7-\uFFFF]+$/),zl=de(/^aria-[\-\w]+$/),is=de(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Hl=de(/^(?:\w+script|data):/i),Bl=de(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),cs=de(/^html$/i),ql=de(/^[a-z][.\w]*(-[.\w]+)+$/i);var Er=Object.freeze({__proto__:null,ARIA_ATTR:zl,ATTR_WHITESPACE:Bl,CUSTOM_ELEMENT:ql,DATA_ATTR:Fl,DOCTYPE_NAME:cs,ERB_EXPR:Wl,IS_ALLOWED_URI:is,IS_SCRIPT_OR_DATA:Hl,MUSTACHE_EXPR:Pl,TMPLIT_EXPR:Ul});const pt={element:1,text:3,progressingInstruction:7,comment:8,document:9},jl=function(){return typeof window>"u"?null:window},Gl=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null;const s="data-tt-policy-suffix";n&&n.hasAttribute(s)&&(r=n.getAttribute(s));const o="dompurify"+(r?"#"+r:"");try{return e.createPolicy(o,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+o+" could not be created."),null}},Nr=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function us(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:jl();const e=x=>us(x);if(e.version="3.3.1",e.removed=[],!t||!t.document||t.document.nodeType!==pt.document||!t.Element)return e.isSupported=!1,e;let{document:n}=t;const r=n,s=r.currentScript,{DocumentFragment:o,HTMLTemplateElement:a,Node:i,Element:c,NodeFilter:d,NamedNodeMap:h=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:y,DOMParser:k,trustedTypes:S}=t,b=c.prototype,E=ht(b,"cloneNode"),X=ht(b,"remove"),B=ht(b,"nextSibling"),L=ht(b,"childNodes"),O=ht(b,"parentNode");if(typeof a=="function"){const x=n.createElement("template");x.content&&x.content.ownerDocument&&(n=x.content.ownerDocument)}let $,ce="";const{implementation:Qe,createNodeIterator:Jt,createDocumentFragment:vt,getElementsByTagName:en}=n,{importNode:tn}=r;let q=Nr();e.isSupported=typeof as=="function"&&typeof O=="function"&&Qe&&Qe.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:Xe,ERB_EXPR:ye,TMPLIT_EXPR:be,DATA_ATTR:nn,ARIA_ATTR:rn,IS_SCRIPT_OR_DATA:sn,ATTR_WHITESPACE:Ze,CUSTOM_ELEMENT:Ae}=Er;let{IS_ALLOWED_URI:St}=Er,P=null;const At=A({},[...vr,...mn,...fn,...yn,...Sr]);let p=null;const T=A({},[...Ar,...bn,...Tr,...Pt]);let w=Object.seal(_n(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}})),N=null,Z=null;const ae=Object.seal(_n(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let Ke=!0,Je=!0,Tt=!1,Ue=!0,Te=!1,Fe=!0,we=!1,et=!1,tt=!1,Ee=!1,ze=!1,He=!1,Et=!0,Nt=!1;const It="user-content-";let nt=!0,Ne=!1,Ie={},ue=null;const K=A({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let j=null;const Ce=A({},["audio","video","img","source","image","track"]);let Ct=null;const qn=A({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),_t="http://www.w3.org/1998/Math/MathML",Mt="http://www.w3.org/2000/svg",xe="http://www.w3.org/1999/xhtml";let Be=xe,on=!1,ln=null;const ys=A({},[_t,Mt,xe],pn);let Rt=A({},["mi","mo","mn","ms","mtext"]),Lt=A({},["annotation-xml"]);const bs=A({},["title","style","font","a","script"]);let rt=null;const ws=["application/xhtml+xml","text/html"],xs="text/html";let H=null,qe=null;const ks=n.createElement("form"),jn=function(u){return u instanceof RegExp||u instanceof Function},an=function(){let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(qe&&qe===u)){if((!u||typeof u!="object")&&(u={}),u=fe(u),rt=ws.indexOf(u.PARSER_MEDIA_TYPE)===-1?xs:u.PARSER_MEDIA_TYPE,H=rt==="application/xhtml+xml"?pn:Bt,P=he(u,"ALLOWED_TAGS")?A({},u.ALLOWED_TAGS,H):At,p=he(u,"ALLOWED_ATTR")?A({},u.ALLOWED_ATTR,H):T,ln=he(u,"ALLOWED_NAMESPACES")?A({},u.ALLOWED_NAMESPACES,pn):ys,Ct=he(u,"ADD_URI_SAFE_ATTR")?A(fe(qn),u.ADD_URI_SAFE_ATTR,H):qn,j=he(u,"ADD_DATA_URI_TAGS")?A(fe(Ce),u.ADD_DATA_URI_TAGS,H):Ce,ue=he(u,"FORBID_CONTENTS")?A({},u.FORBID_CONTENTS,H):K,N=he(u,"FORBID_TAGS")?A({},u.FORBID_TAGS,H):fe({}),Z=he(u,"FORBID_ATTR")?A({},u.FORBID_ATTR,H):fe({}),Ie=he(u,"USE_PROFILES")?u.USE_PROFILES:!1,Ke=u.ALLOW_ARIA_ATTR!==!1,Je=u.ALLOW_DATA_ATTR!==!1,Tt=u.ALLOW_UNKNOWN_PROTOCOLS||!1,Ue=u.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Te=u.SAFE_FOR_TEMPLATES||!1,Fe=u.SAFE_FOR_XML!==!1,we=u.WHOLE_DOCUMENT||!1,Ee=u.RETURN_DOM||!1,ze=u.RETURN_DOM_FRAGMENT||!1,He=u.RETURN_TRUSTED_TYPE||!1,tt=u.FORCE_BODY||!1,Et=u.SANITIZE_DOM!==!1,Nt=u.SANITIZE_NAMED_PROPS||!1,nt=u.KEEP_CONTENT!==!1,Ne=u.IN_PLACE||!1,St=u.ALLOWED_URI_REGEXP||is,Be=u.NAMESPACE||xe,Rt=u.MATHML_TEXT_INTEGRATION_POINTS||Rt,Lt=u.HTML_INTEGRATION_POINTS||Lt,w=u.CUSTOM_ELEMENT_HANDLING||{},u.CUSTOM_ELEMENT_HANDLING&&jn(u.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(w.tagNameCheck=u.CUSTOM_ELEMENT_HANDLING.tagNameCheck),u.CUSTOM_ELEMENT_HANDLING&&jn(u.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(w.attributeNameCheck=u.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),u.CUSTOM_ELEMENT_HANDLING&&typeof u.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(w.allowCustomizedBuiltInElements=u.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Te&&(Je=!1),ze&&(Ee=!0),Ie&&(P=A({},Sr),p=[],Ie.html===!0&&(A(P,vr),A(p,Ar)),Ie.svg===!0&&(A(P,mn),A(p,bn),A(p,Pt)),Ie.svgFilters===!0&&(A(P,fn),A(p,bn),A(p,Pt)),Ie.mathMl===!0&&(A(P,yn),A(p,Tr),A(p,Pt))),u.ADD_TAGS&&(typeof u.ADD_TAGS=="function"?ae.tagCheck=u.ADD_TAGS:(P===At&&(P=fe(P)),A(P,u.ADD_TAGS,H))),u.ADD_ATTR&&(typeof u.ADD_ATTR=="function"?ae.attributeCheck=u.ADD_ATTR:(p===T&&(p=fe(p)),A(p,u.ADD_ATTR,H))),u.ADD_URI_SAFE_ATTR&&A(Ct,u.ADD_URI_SAFE_ATTR,H),u.FORBID_CONTENTS&&(ue===K&&(ue=fe(ue)),A(ue,u.FORBID_CONTENTS,H)),u.ADD_FORBID_CONTENTS&&(ue===K&&(ue=fe(ue)),A(ue,u.ADD_FORBID_CONTENTS,H)),nt&&(P["#text"]=!0),we&&A(P,["html","head","body"]),P.table&&(A(P,["tbody"]),delete N.tbody),u.TRUSTED_TYPES_POLICY){if(typeof u.TRUSTED_TYPES_POLICY.createHTML!="function")throw dt('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof u.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw dt('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');$=u.TRUSTED_TYPES_POLICY,ce=$.createHTML("")}else $===void 0&&($=Gl(S,s)),$!==null&&typeof ce=="string"&&(ce=$.createHTML(""));ne&&ne(u),qe=u}},Gn=A({},[...mn,...fn,...Dl]),Vn=A({},[...yn,...Ol]),vs=function(u){let m=O(u);(!m||!m.tagName)&&(m={namespaceURI:Be,tagName:"template"});const f=Bt(u.tagName),R=Bt(m.tagName);return ln[u.namespaceURI]?u.namespaceURI===Mt?m.namespaceURI===xe?f==="svg":m.namespaceURI===_t?f==="svg"&&(R==="annotation-xml"||Rt[R]):!!Gn[f]:u.namespaceURI===_t?m.namespaceURI===xe?f==="math":m.namespaceURI===Mt?f==="math"&&Lt[R]:!!Vn[f]:u.namespaceURI===xe?m.namespaceURI===Mt&&!Lt[R]||m.namespaceURI===_t&&!Rt[R]?!1:!Vn[f]&&(bs[f]||!Gn[f]):!!(rt==="application/xhtml+xml"&&ln[u.namespaceURI]):!1},me=function(u){ct(e.removed,{element:u});try{O(u).removeChild(u)}catch{X(u)}},Re=function(u,m){try{ct(e.removed,{attribute:m.getAttributeNode(u),from:m})}catch{ct(e.removed,{attribute:null,from:m})}if(m.removeAttribute(u),u==="is")if(Ee||ze)try{me(m)}catch{}else try{m.setAttribute(u,"")}catch{}},Yn=function(u){let m=null,f=null;if(tt)u="<remove></remove>"+u;else{const W=gn(u,/^[\r\n\t ]+/);f=W&&W[0]}rt==="application/xhtml+xml"&&Be===xe&&(u='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+u+"</body></html>");const R=$?$.createHTML(u):u;if(Be===xe)try{m=new k().parseFromString(R,rt)}catch{}if(!m||!m.documentElement){m=Qe.createDocument(Be,"template",null);try{m.documentElement.innerHTML=on?ce:R}catch{}}const J=m.body||m.documentElement;return u&&f&&J.insertBefore(n.createTextNode(f),J.childNodes[0]||null),Be===xe?en.call(m,we?"html":"body")[0]:we?m.documentElement:J},Qn=function(u){return Jt.call(u.ownerDocument||u,u,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},cn=function(u){return u instanceof y&&(typeof u.nodeName!="string"||typeof u.textContent!="string"||typeof u.removeChild!="function"||!(u.attributes instanceof h)||typeof u.removeAttribute!="function"||typeof u.setAttribute!="function"||typeof u.namespaceURI!="string"||typeof u.insertBefore!="function"||typeof u.hasChildNodes!="function")},Xn=function(u){return typeof i=="function"&&u instanceof i};function ke(x,u,m){Ot(x,f=>{f.call(e,u,m,qe)})}const Zn=function(u){let m=null;if(ke(q.beforeSanitizeElements,u,null),cn(u))return me(u),!0;const f=H(u.nodeName);if(ke(q.uponSanitizeElement,u,{tagName:f,allowedTags:P}),Fe&&u.hasChildNodes()&&!Xn(u.firstElementChild)&&ee(/<[/\w!]/g,u.innerHTML)&&ee(/<[/\w!]/g,u.textContent)||u.nodeType===pt.progressingInstruction||Fe&&u.nodeType===pt.comment&&ee(/<[/\w]/g,u.data))return me(u),!0;if(!(ae.tagCheck instanceof Function&&ae.tagCheck(f))&&(!P[f]||N[f])){if(!N[f]&&Jn(f)&&(w.tagNameCheck instanceof RegExp&&ee(w.tagNameCheck,f)||w.tagNameCheck instanceof Function&&w.tagNameCheck(f)))return!1;if(nt&&!ue[f]){const R=O(u)||u.parentNode,J=L(u)||u.childNodes;if(J&&R){const W=J.length;for(let se=W-1;se>=0;--se){const ve=E(J[se],!0);ve.__removalCount=(u.__removalCount||0)+1,R.insertBefore(ve,B(u))}}}return me(u),!0}return u instanceof c&&!vs(u)||(f==="noscript"||f==="noembed"||f==="noframes")&&ee(/<\/no(script|embed|frames)/i,u.innerHTML)?(me(u),!0):(Te&&u.nodeType===pt.text&&(m=u.textContent,Ot([Xe,ye,be],R=>{m=ut(m,R," ")}),u.textContent!==m&&(ct(e.removed,{element:u.cloneNode()}),u.textContent=m)),ke(q.afterSanitizeElements,u,null),!1)},Kn=function(u,m,f){if(Et&&(m==="id"||m==="name")&&(f in n||f in ks))return!1;if(!(Je&&!Z[m]&&ee(nn,m))){if(!(Ke&&ee(rn,m))){if(!(ae.attributeCheck instanceof Function&&ae.attributeCheck(m,u))){if(!p[m]||Z[m]){if(!(Jn(u)&&(w.tagNameCheck instanceof RegExp&&ee(w.tagNameCheck,u)||w.tagNameCheck instanceof Function&&w.tagNameCheck(u))&&(w.attributeNameCheck instanceof RegExp&&ee(w.attributeNameCheck,m)||w.attributeNameCheck instanceof Function&&w.attributeNameCheck(m,u))||m==="is"&&w.allowCustomizedBuiltInElements&&(w.tagNameCheck instanceof RegExp&&ee(w.tagNameCheck,f)||w.tagNameCheck instanceof Function&&w.tagNameCheck(f))))return!1}else if(!Ct[m]){if(!ee(St,ut(f,Ze,""))){if(!((m==="src"||m==="xlink:href"||m==="href")&&u!=="script"&&Ml(f,"data:")===0&&j[u])){if(!(Tt&&!ee(sn,ut(f,Ze,"")))){if(f)return!1}}}}}}}return!0},Jn=function(u){return u!=="annotation-xml"&&gn(u,Ae)},er=function(u){ke(q.beforeSanitizeAttributes,u,null);const{attributes:m}=u;if(!m||cn(u))return;const f={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:p,forceKeepAttr:void 0};let R=m.length;for(;R--;){const J=m[R],{name:W,namespaceURI:se,value:ve}=J,je=H(W),un=ve;let G=W==="value"?un:Rl(un);if(f.attrName=je,f.attrValue=G,f.keepAttr=!0,f.forceKeepAttr=void 0,ke(q.uponSanitizeAttribute,u,f),G=f.attrValue,Nt&&(je==="id"||je==="name")&&(Re(W,u),G=It+G),Fe&&ee(/((--!?|])>)|<\/(style|title|textarea)/i,G)){Re(W,u);continue}if(je==="attributename"&&gn(G,"href")){Re(W,u);continue}if(f.forceKeepAttr)continue;if(!f.keepAttr){Re(W,u);continue}if(!Ue&&ee(/\/>/i,G)){Re(W,u);continue}Te&&Ot([Xe,ye,be],nr=>{G=ut(G,nr," ")});const tr=H(u.nodeName);if(!Kn(tr,je,G)){Re(W,u);continue}if($&&typeof S=="object"&&typeof S.getAttributeType=="function"&&!se)switch(S.getAttributeType(tr,je)){case"TrustedHTML":{G=$.createHTML(G);break}case"TrustedScriptURL":{G=$.createScriptURL(G);break}}if(G!==un)try{se?u.setAttributeNS(se,W,G):u.setAttribute(W,G),cn(u)?me(u):kr(e.removed)}catch{Re(W,u)}}ke(q.afterSanitizeAttributes,u,null)},Ss=function x(u){let m=null;const f=Qn(u);for(ke(q.beforeSanitizeShadowDOM,u,null);m=f.nextNode();)ke(q.uponSanitizeShadowNode,m,null),Zn(m),er(m),m.content instanceof o&&x(m.content);ke(q.afterSanitizeShadowDOM,u,null)};return e.sanitize=function(x){let u=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},m=null,f=null,R=null,J=null;if(on=!x,on&&(x="<!-->"),typeof x!="string"&&!Xn(x))if(typeof x.toString=="function"){if(x=x.toString(),typeof x!="string")throw dt("dirty is not a string, aborting")}else throw dt("toString is not a function");if(!e.isSupported)return x;if(et||an(u),e.removed=[],typeof x=="string"&&(Ne=!1),Ne){if(x.nodeName){const ve=H(x.nodeName);if(!P[ve]||N[ve])throw dt("root node is forbidden and cannot be sanitized in-place")}}else if(x instanceof i)m=Yn("<!---->"),f=m.ownerDocument.importNode(x,!0),f.nodeType===pt.element&&f.nodeName==="BODY"||f.nodeName==="HTML"?m=f:m.appendChild(f);else{if(!Ee&&!Te&&!we&&x.indexOf("<")===-1)return $&&He?$.createHTML(x):x;if(m=Yn(x),!m)return Ee?null:He?ce:""}m&&tt&&me(m.firstChild);const W=Qn(Ne?x:m);for(;R=W.nextNode();)Zn(R),er(R),R.content instanceof o&&Ss(R.content);if(Ne)return x;if(Ee){if(ze)for(J=vt.call(m.ownerDocument);m.firstChild;)J.appendChild(m.firstChild);else J=m;return(p.shadowroot||p.shadowrootmode)&&(J=tn.call(r,J,!0)),J}let se=we?m.outerHTML:m.innerHTML;return we&&P["!doctype"]&&m.ownerDocument&&m.ownerDocument.doctype&&m.ownerDocument.doctype.name&&ee(cs,m.ownerDocument.doctype.name)&&(se="<!DOCTYPE "+m.ownerDocument.doctype.name+`>
60
+ `+se),Te&&Ot([Xe,ye,be],ve=>{se=ut(se,ve," ")}),$&&He?$.createHTML(se):se},e.setConfig=function(){let x=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};an(x),et=!0},e.clearConfig=function(){qe=null,et=!1},e.isValidAttribute=function(x,u,m){qe||an({});const f=H(x),R=H(u);return Kn(f,R,m)},e.addHook=function(x,u){typeof u=="function"&&ct(q[x],u)},e.removeHook=function(x,u){if(u!==void 0){const m=Cl(q[x],u);return m===-1?void 0:_l(q[x],m,1)[0]}return kr(q[x])},e.removeHooks=function(x){q[x]=[]},e.removeAllHooks=function(){q=Nr()},e}var Wt=us();const Vl=typeof window<"u"&&Wt&&Wt.default?Wt.default:Wt;C.setOptions({gfm:!0,breaks:!0});const Yl=["p","br","strong","em","u","strike","del","s","h1","h2","h3","h4","h5","h6","ul","ol","li","blockquote","code","pre","table","thead","tbody","tr","th","td","a","img","hr","div","span"],Ql={a:["href","title"],img:["src","alt","title","width","height"],table:["class"],th:["align","class"],td:["align","class"],code:["class"],pre:["class"],div:["class"],span:["class"]};function ds(t){if(!t||typeof t!="string")return"";try{const e=C(t);return Vl.sanitize(e,{ALLOWED_TAGS:Yl,ALLOWED_ATTR:Ql,ALLOW_DATA_ATTR:!1,ALLOW_UNKNOWN_PROTOCOLS:!1,FORBID_TAGS:["script","object","embed","form","input","button"],FORBID_ATTR:["onload","onerror","onclick","onmouseover","onfocus","onblur"]})}catch(e){return console.error("Error rendering markdown:",e),t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}}function hs(t){return t.type==="tool"}function Xl(t){return t.length>5e4?{content:t.substring(0,5e4),wasTruncated:!0}:{content:t,wasTruncated:!1}}function Zl(t){return t.streamType==="stderr"}function Kl(t){if(t.isToolStreaming)return l.h("div",{className:"tool-stream-output"},l.h("div",{className:"tool-stream-header"},"⚙️ Executing..."),l.h("div",{className:`tool-stream-content ${t.streamType==="stderr"?"stderr":"stdout"}`},l.h("pre",{className:"tool-output-text"},t.text||"(waiting for output...)")));if(hs(t)){const{content:e,wasTruncated:n}=Xl(t.text),r=t.isToolOutputExpanded||!1,s=Zl(t)?"tool-output-stderr":"tool-output-stdout";return l.h("div",{className:"tool-output-container"},l.h("div",{className:"tool-output-header"},l.h("button",{className:"tool-output-toggle",$onclick:["toggle-tool-output",t.id],title:r?"Collapse output":"Expand output"},l.h("span",{className:"toggle-icon"},r?"▼":"▶"),l.h("span",{className:"tool-label"},"⚙️ Tool output"))),r&&l.h("div",{className:`tool-output-content ${s}`},l.h("pre",{className:"tool-output-text"},e),n&&l.h("div",{className:"tool-output-truncated"},"⚠️ Output truncated (exceeded 50,000 characters)")))}return l.h("div",{className:"message-content"},jt(ds(t.text||"")))}function Jl(t){const{isBusy:e,label:n}=t,r=e?"activity-pulse active":"activity-pulse idle";return l.h("div",{className:"activity-pulse-container",role:"status","aria-live":"polite"},l.h("div",{className:r,role:"status","aria-label":e?"Busy":"Idle"}),n&&l.h("span",{className:"activity-label"},n))}function ea(t){const e=Math.floor(t/1e3),n=Math.floor(e/3600),r=Math.floor(e%3600/60),s=e%60,o=a=>a<10?"0"+a:String(a);return n>0?`${n}:${o(r)}:${o(s)}`:`${r}:${o(s)}`}function ta(t){const{elapsedMs:e,showIcon:n=!0}=t;return e===0?null:l.h("div",{className:"elapsed-counter",role:"timer"},n&&l.h("span",{className:"clock-icon"},"⏱️"),l.h("span",{className:"elapsed-time"},ea(e)))}function na(t){const e=t.activeAgent||null,n=Array.isArray(t.queuedAgents)?t.queuedAgents:[];if(!e&&n.length===0)return null;const r=n.slice(0,3),s=n.length-r.length;return l.h("div",{className:"agent-queue-display",role:"status","aria-live":"polite"},e?l.h("div",{className:"agent-queue-active",title:`Active: ${e.name}`},l.h("div",{className:`message-avatar agent-sprite sprite-${e.spriteIndex}`}),l.h("span",{className:"agent-queue-active-dot","aria-hidden":"true"})):null,r.length>0?l.h("div",{className:"agent-queue-list",title:"Queued agents"},r.map(o=>l.h("div",{key:`${o.name}-${o.spriteIndex}`,className:"agent-queue-item",title:o.name},l.h("div",{className:`message-avatar agent-sprite sprite-${o.spriteIndex}`}))),s>0?l.h("div",{className:"agent-queue-overflow"},"+",s):null):null)}const ra=!1,wn=4;function sa(t){const{currentChatId:e,isWaiting:n,isBusy:r,isStopping:s,isSending:o,hasActiveHitlPrompt:a,userInput:i}=t,c=!!e&&(n||r),d=c?s:!i.trim()||o||n||s||a;return{canStopCurrentSession:c,actionButtonDisabled:d,actionButtonClass:c?"send-button stop-button":"send-button",actionButtonText:c?s?"Stopping...":"Stop":o?"Sending...":"Send"}}function oa(t){const{worldName:e,messages:n=[],rawMessages:r=[],userInput:s="",messagesLoading:o,isSending:a,isWaiting:i,needScroll:c=!1,activeAgent:d,agents:h=[],currentChat:y,currentChatId:k=null,editingMessageId:S=null,editingText:b="",agentFilters:E=[],isBusy:X=!1,elapsedMs:B=0,isStopping:L=!1,activeHitlPrompt:O=null,submittingHitlRequestId:$=null}=t,Qe=O?"Resolve pending HITL prompt before sending a new message...":!i?"Type your message...":"Waiting for agents...",Jt=a||i||L||!!O,{canStopCurrentSession:vt,actionButtonDisabled:en,actionButtonClass:tn,actionButtonText:q}=sa({currentChatId:k,isWaiting:i,isBusy:X,isStopping:L,isSending:a,hasActiveHitlPrompt:!!O,userInput:s}),Xe=d?.name?.trim()||h[0]?.name?.trim()||"Agent",ye=new Map,be=new Map;for(const p of h){const T=oe(p.name),w=oe(p.id);ye.set(T,p.spriteIndex),be.set(w,p.spriteIndex)}const nn=h.filter(p=>p.name!==d?.name).map(p=>({name:p.name,spriteIndex:p.spriteIndex})),rn=p=>{const T=oe(p.sender),w=oe(p.fromAgentId);return T!==w&&!p.isStreaming},sn=p=>{const T=oe(p.fromAgentId||"");if(T){const Z=h.find(ae=>oe(ae.id)===T);if(Z)return Z.autoReply===!1}const w=oe(p.sender||"");return w?h.find(Z=>oe(Z.id)===w||oe(Z.name)===w)?.autoReply===!1:!1},Ze=(p,T)=>{if(!p.replyToMessageId)return null;const w=T.find(ae=>ae.messageId===p.replyToMessageId);return w?lt(w.sender)===Y.HUMAN?"HUMAN":w.sender:null},Ae=E.length>0?(()=>{const p=r.filter(N=>lt(N.sender)===Y.HUMAN?!0:N.ownerAgentId&&E.includes(N.ownerAgentId)),T=new Map,w=[];for(const N of p)lt(N.sender)===Y.HUMAN&&N.messageId?T.has(N.messageId)||(T.set(N.messageId,N),w.push(N)):w.push(N);return w})():n,St=p=>{if(p.isToolEvent&&!p.isToolStreaming)return!0;try{const T=p.text.trim(),w=T.startsWith("@")?T.substring(T.indexOf(",")+1).trim():T;if(w.startsWith("{")&&w.endsWith("}")){const N=JSON.parse(w);if(N.__type==="tool_result"&&N.tool_call_id)return!0}}catch{}return!1},P=(p,T)=>p===Y.HUMAN||T?"message-row-left":"message-row-right",At=p=>{const T=lt(p.sender);if(T===Y.HUMAN||T===Y.SYSTEM||T===Y.WORLD)return wn;const w=oe(p.sender||""),N=oe(p.fromAgentId||"");return ye.has(w)?ye.get(w):be.has(w)?be.get(w):be.has(N)?be.get(N):ye.has(N)?ye.get(N):wn};return l.h("fieldset",{className:"chat-fieldset"},l.h("legend",null,e," ",y?` - ${y}`:l.h("span",{className:"unsaved-indicator",title:"Unsaved chat"}," ●"),l.h(na,{activeAgent:d?{name:d.name,spriteIndex:d.spriteIndex}:null,queuedAgents:nn}),l.h(Jl,{isBusy:X||!1}),(X||B&&B>0)&&l.h(ta,{elapsedMs:B||0})),l.h("div",{className:"chat-container"},l.h("div",{className:"conversation-area",ref:(p,T)=>{p&&c&&requestAnimationFrame(()=>{p.scrollTop=p.scrollHeight,T&&(T.needScroll=!1)})}},o?l.h("div",{className:"loading-messages"},"Loading messages..."):Ae.length===0?l.h("div",{className:"no-messages"},"No messages yet. Start a conversation!"):Ae.map((p,T)=>{if(St(p))return null;if(p.logEvent){const j=!!p.isLogExpanded;let Ce=null;if(p.logEvent.data!==void 0)try{Ce=JSON.stringify(p.logEvent.data,null,2)}catch{Ce=String(p.logEvent.data)}return l.h("div",{key:p.id||"log-"+T,className:"message log-message"},l.h("button",{type:"button",className:"log-header","aria-expanded":j,$onclick:["toggle-log-details",p.id||`log-${T}`]},l.h("span",{className:`log-dot ${p.logEvent.level}`}),l.h("span",{className:"log-category"},p.logEvent.category),l.h("span",{className:"log-content"},p.logEvent.message),l.h("span",{className:"log-toggle-icon","aria-hidden":"true"},j?"▲":"▼")),j&&l.h("pre",{className:"log-details"},Ce??"No additional details"))}if(p.worldEvent)return null;const w=lt(p.sender),N=rn(p),Z=p.type==="user"||p.type==="human",ae=()=>{if(!p.replyToMessageId)return!1;const j=Ae.find(Ce=>Ce.messageId===p.replyToMessageId);return j?j.sender===p.fromAgentId:!1},Ke=Z&&p.replyToMessageId&&ae(),Je=!!p.replyToMessageId,Tt=p.messageId?Ae.some(j=>j.replyToMessageId===p.messageId):!1,Ue=Z&&w===Y.AGENT&&N&&!p.isStreaming&&(Je?!Ke:!Tt);if(Ue)return null;const Te=w===Y.HUMAN?"user-message":"agent-message",Fe=w===Y.SYSTEM?"system-message":"",we=N&&!Ue&&w!==Y.HUMAN?"cross-agent-message":"",et=Ue?"memory-only-message":"",tt=hs(p)?"tool-message":"",Ee=`message ${Te} ${Fe} ${we} ${et} ${tt}`.trim(),ze=P(w,N),He=w===Y.HUMAN,Et=At(p),Nt=w===Y.HUMAN?"HUMAN":p.sender||"Agent",It=w===Y.HUMAN,nt=S===p.id,Ne=b.trim(),Ie=String(p.text||"").trim(),ue=!!Ne&&Ne!==Ie;let K="";if(It)K="From: HUMAN",p.seenByAgents&&p.seenByAgents.length>0&&(K+=`
61
+ To: ${p.seenByAgents.join(", ")}`);else if(w===Y.AGENT)if(sn(p))K=p.sender;else if(Ke){const j=Ze(p,Ae);j?K=`Agent: ${p.sender} (reply to ${j})`:K=`Agent: ${p.sender} (reply)`}else if(p.type==="assistant"||p.type==="agent"){const j=Ze(p,Ae);j?K=`Agent: ${p.sender} (reply to ${j})`:K=`Agent: ${p.sender} (reply)`}else N&&Z?K=`Agent: ${p.sender} (message from ${p.fromAgentId||p.sender})`:K=`Agent: ${p.sender}`;else Y.SYSTEM,K=p.sender;return l.h("div",{key:p.id||"msg-"+T,className:`message-row ${ze}`},l.h("div",{className:"message-avatar-container",title:Nt},l.h("div",{className:He?"message-avatar message-avatar-empty":`message-avatar agent-sprite sprite-${Et}`})),l.h("div",{className:Ee},l.h("div",{className:"message-sender",style:{whiteSpace:"pre-line"}},K),nt?l.h("div",{className:"message-edit-container"},l.h("textarea",{className:"message-edit-input",value:b,$oninput:"update-edit-text",rows:3,autoFocus:!0}),l.h("div",{className:"message-edit-actions"},l.h("button",{className:"btn-primary",$onclick:["save-edit-message",p.id],disabled:!ue},"Update"),l.h("button",{className:"btn-secondary",$onclick:"cancel-edit-message"},"Cancel"))):l.h(l.Fragment,null,Kl(p),It&&!p.isStreaming&&l.h("div",{className:"message-actions"},l.h("button",{className:"message-edit-btn",$onclick:["start-edit-message",{messageId:p.id,text:p.text}],title:"Edit message",disabled:!p.messageId||p.userEntered},"✏️"),l.h("button",{className:"message-delete-btn",$onclick:["show-delete-message-confirm",{messageId:p.id,backendMessageId:p.messageId,messageText:p.text,userEntered:p.userEntered}],title:"Delete message and all after it",disabled:!p.messageId||p.userEntered},"🗑️"))),l.h("div",{className:"message-timestamp"},p.createdAt?new Date(p.createdAt).toLocaleTimeString():"Now"),p.isStreaming&&l.h("div",{className:"streaming-indicator"},l.h("div",{className:"streaming-content"},l.h("div",{className:`agent-sprite sprite-${d?.spriteIndex??0}`}),l.h("span",null,"responding ..."))),p.hasError&&l.h("div",{className:"error-indicator"},"Error: ",p.errorMessage),ra))}),i&&l.h("div",{className:"message-row message-row-left"},l.h("div",{className:"message-avatar-container",title:"HUMAN"},l.h("div",{className:"message-avatar message-avatar-empty"})),l.h("div",{className:"message user-message waiting-message"},l.h("div",{className:"message-content"},l.h("div",{className:"waiting-inline-status"},l.h("span",{className:"waiting-inline-dot","aria-hidden":"true"}),l.h("span",null,Xe," is working..."))))),O?l.h("div",{className:"message-row message-row-left"},l.h("div",{className:"message-avatar-container",title:"Human input required"},l.h("div",{className:"message-avatar sprite-4"})),l.h("div",{className:"message system-message hitl-inline-message"},l.h("div",{className:"message-sender"},O.title||"Human input required"),l.h("div",{className:"message-content"},(O.message||"Please choose an option to continue.").replace(/\n\s*\n+/g,`
62
+ `)),l.h("div",{className:"hitl-inline-actions hitl-inline-option-actions"},O.options.map(p=>{const T=$===O.requestId;return l.h("button",{key:p.id,className:"btn-secondary px-4 py-2 rounded shrink-0",disabled:T,$onclick:["respond-hitl-option",{requestId:O.requestId,optionId:p.id,chatId:O.chatId}]},l.h("div",{className:"font-bold"},p.label))})))):null),l.h("div",{className:"input-area"},l.h("div",{className:"input-container"},l.h("input",{type:"text",className:"message-input",placeholder:Qe,value:s||"",$oninput:"update-input",$onkeypress:"key-press",disabled:Jt}),l.h("button",{className:tn,$onclick:vt?"stop-message-processing":"send-message",disabled:en,title:vt?"Stop processing":"Send message"},q)))))}function la(t,e){const n=String(e||"").trim().toLowerCase();return n?t.filter(r=>String(r?.name||"").toLowerCase().includes(n)):t}function aa(t){const{world:e,chatSearchQuery:n}=t,r=e&&e.agents&&e.agents.length>0,s=e?.chats||[],o=la(s,n),a=e?.currentChatId??null;return app.h("fieldset",{className:"settings-fieldset"},app.h("legend",null,"Chat History"),app.h("div",{className:"chat-history-controls"},app.h("input",{type:"text",className:"message-input chat-history-search-input",placeholder:"Search chats...",value:n||"",$oninput:"update-chat-search"}),app.h("button",{className:"new-chat-btn",$onclick:"create-new-chat",title:r?"Create new chat session":"Create an agent first to enable new chats","aria-label":r?"Create new chat session":"Create an agent first to enable new chats",disabled:!r},app.h("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},app.h("path",{d:"M12 5v14M5 12h14"})))),app.h("div",{className:"chat-history-container"},s.length===0?app.h("div",{className:"no-chats"},app.h("p",null,"No chat history entries found."),app.h("p",null,"Start a conversation with agents to auto-save chats.")):o.length===0?app.h("div",{className:"no-chats"},app.h("p",null,'No chats match "',n,'".')):app.h("ul",{className:"chat-list simplified-chat-list"},o.map(i=>{const c=a===i.id;return app.h("li",{key:i.id,$onclick:["load-chat-from-history",i.id],className:`chat-item simplified-chat-item chat-list-li${c?" current":""}`},app.h("span",{className:`chat-title clickable chat-list-title${c?" current":""}`,title:i.name},i.name),app.h("button",{className:"chat-close-btn chat-list-close-btn",$onclick:["chat-history-show-delete-confirm",i],title:"Delete chat"},"×"))}))))}const ia=t=>({mode:t.mode||"create",worldName:t.worldName,agent:t.agent||ps,parentComponent:t.parentComponent,loading:!1,error:null,errorDetails:null}),ps={name:"",description:"",autoReply:!0,provider:"ollama",model:"llama3.2:3b",temperature:.7,maxTokens:2048,systemPrompt:"You are a helpful assistant."};function ca(t){const{type:e,...n}=t;return n}const Ir=async function*(t){if(!t.agent.name.trim()){yield{...t,error:"Agent name is required"};return}yield{...t,loading:!0,error:null};try{const e=ca(t.agent);t.mode==="create"?await z.createAgent(t.worldName,e):await z.updateAgent(t.worldName,t.agent.name,e);const n=t.mode==="create"?"Agent created successfully!":"Agent updated successfully!";yield{...t,loading:!1,successMessage:n},setTimeout(()=>{t.parentComponent.run("agent-saved")},2e3)}catch(e){const n=Xt(e);yield{...t,loading:!1,error:n.message,errorDetails:n.details||null}}},Cr=async function*(t){yield{...t,loading:!0,error:null};try{await z.deleteAgent(t.worldName,t.agent.name),yield{...t,loading:!1,successMessage:"Agent deleted successfully!"},setTimeout(()=>{t.parentComponent.run("agent-deleted")},2e3)}catch(e){const n=Xt(e);yield{...t,loading:!1,error:n.message,errorDetails:n.details||null}}},gt=t=>{t?.parentComponent&&typeof t.parentComponent.run=="function"?t.parentComponent.run("close-agent-edit"):l.run("close-agent-edit")};class ua extends Me{mounted=e=>ia(e);state={mode:"create",worldName:"",agent:ps,parentComponent:void 0,loading:!0,error:null,errorDetails:null};view=e=>{if(e.loading)return l.h("div",{className:"modal-backdrop"},l.h("div",{className:"modal-content edit-modal"},l.h("div",{className:"modal-body"},l.h("div",{className:"loading-spinner"},e.mode==="create"?"Creating agent...":e.mode==="edit"?"Updating agent...":"Deleting agent..."))));if(e.successMessage)return l.h("div",{className:"modal-backdrop"},l.h("div",{className:"modal-content edit-modal",onclick:o=>o.stopPropagation()},l.h("div",{className:"modal-header"},l.h("h2",{className:"modal-title"},"Success!"),l.h("button",{className:"modal-close-btn",$onclick:gt,title:"Close"},"×")),l.h("div",{className:"modal-body"},l.h("div",{className:"success-message"},l.h("p",null,e.successMessage)))));const n=e.mode==="edit",r=e.mode==="delete";let s;return r?s=`Delete ${e.agent.name||"Agent"}`:n?s=`Edit ${e.agent.name||"Agent"}`:s="Create New Agent",l.h("div",{className:"modal-backdrop"},l.h("div",{className:"modal-content edit-modal",onclick:o=>o.stopPropagation()},l.h("div",{className:"modal-header"},l.h("h2",{className:"modal-title"},s),l.h("button",{className:"modal-close-btn",$onclick:gt,title:"Close"},"×")),l.h("div",{className:"modal-body"},e.error&&l.h("div",{className:"error-message"},l.h("div",{className:"error-main"},e.error),e.errorDetails&&e.errorDetails.length>0&&l.h("div",{className:"error-details"},l.h("div",{className:"error-details-title"},"Validation errors:"),l.h("ul",{className:"error-details-list"},e.errorDetails.map((o,a)=>l.h("li",{key:a,className:"error-detail-item"},Vr(o)))))),r?l.h("div",{className:"delete-confirmation"},l.h("p",{className:"delete-confirmation-text"},"Are you sure you want to delete ",l.h("span",{className:"delete-confirmation-name"},'"',e.agent.name,'"'),"?"),l.h("p",{className:"delete-confirmation-text"},"This action cannot be undone.")):l.h("form",{className:"agent-form"},l.h("div",{className:`form-group ${n?"hidden":""}`},l.h("div",{className:"form-row"},l.h("div",{className:"form-group"},l.h("label",{htmlFor:"agent-name"},"Agent Name *"),l.h("input",{id:"agent-name",type:"text",className:"form-input",placeholder:"Enter agent name",value:e.agent.name,$bind:"agent.name",disabled:e.loading})))),l.h("div",{className:"form-section"},l.h("div",{className:"form-group"},l.h("div",{className:"form-checkbox-row"},l.h("input",{id:"agent-auto-reply",type:"checkbox",checked:e.agent.autoReply!==!1,$bind:"agent.autoReply",disabled:e.loading}),l.h("label",{htmlFor:"agent-auto-reply",className:"form-checkbox-title"},"Auto Reply")),l.h("p",{className:"form-help-text form-checkbox-help"},"Automatically reply to sender when no explicit @mention is provided")),l.h("div",{className:"form-row"},l.h("div",{className:"form-group"},l.h("label",{htmlFor:"agent-provider"},"Provider"),l.h("select",{id:"agent-provider",className:"form-select",value:e.agent.provider,$bind:"agent.provider",disabled:e.loading},l.h("option",{value:"",selected:!e.agent.provider},"Select provider"),l.h("option",{value:"openai",selected:e.agent.provider==="openai"},"OpenAI"),l.h("option",{value:"anthropic",selected:e.agent.provider==="anthropic"},"Anthropic"),l.h("option",{value:"google",selected:e.agent.provider==="google"},"Google"),l.h("option",{value:"azure",selected:e.agent.provider==="azure"},"Azure"),l.h("option",{value:"ollama",selected:e.agent.provider==="ollama"},"Ollama"))),l.h("div",{className:"form-group"},l.h("label",{htmlFor:"agent-model"},"Model"),l.h("input",{id:"agent-model",type:"text",className:"form-input",placeholder:"e.g. gpt-4, claude-3-sonnet, llama3.2:3b",value:e.agent.model,$bind:"agent.model",disabled:e.loading})))),l.h("div",{className:"form-section"},l.h("div",{className:"form-row"},l.h("div",{className:"form-group"},l.h("label",{htmlFor:"agent-temperature"},"Temperature"),l.h("input",{id:"agent-temperature",type:"number",className:"form-input",placeholder:"0.0 - 2.0",min:"0",max:"2",step:"0.1",value:e.agent.temperature,$bind:"agent.temperature",disabled:e.loading})),l.h("div",{className:"form-group"},l.h("label",{htmlFor:"agent-max-tokens"},"Max Tokens"),l.h("input",{id:"agent-max-tokens",type:"number",className:"form-input",placeholder:"e.g. 2048",min:"1",max:"32768",step:"1",value:e.agent.maxTokens,$bind:"agent.maxTokens",disabled:e.loading})))),l.h("div",{className:"form-section"},l.h("div",{className:"form-group"},l.h("label",{htmlFor:"agent-prompt"},"System Prompt"),l.h("textarea",{id:"agent-prompt",className:"form-textarea agent-system-prompt-textarea",placeholder:"Enter the system prompt for this agent...",rows:12,value:e.agent.systemPrompt,$bind:"agent.systemPrompt",disabled:e.loading}))))),l.h("div",{className:"modal-footer"},l.h("div",{className:"modal-actions"},r?l.h("div",{className:"modal-primary-actions",style:"margin-left: auto;"},l.h("button",{className:"btn btn-secondary",$onclick:gt,disabled:e.loading},"Cancel"),l.h("button",{className:"btn btn-danger",$onclick:[Cr],disabled:e.loading},e.loading?"Deleting...":"Delete")):n?l.h(l.Fragment,null,l.h("button",{className:"btn btn-danger",$onclick:[Cr],disabled:e.loading,title:"Delete agent"},e.loading?"Deleting...":"Delete"),l.h("div",{className:"modal-primary-actions"},l.h("button",{className:"btn btn-secondary",$onclick:gt,disabled:e.loading},"Cancel"),l.h("button",{className:"btn btn-primary",$onclick:[Ir],disabled:e.loading||!e.agent.name.trim()},e.loading?"Saving...":"Update"))):l.h("div",{className:"modal-primary-actions",style:"margin-left: auto;"},l.h("button",{className:"btn btn-secondary",$onclick:gt,disabled:e.loading},"Cancel"),l.h("button",{className:"btn btn-primary",$onclick:[Ir],disabled:e.loading||!e.agent.name.trim()},e.loading?"Saving...":"Create"))))))}}function da(t,e){return{...t,userInput:e}}function ha(t,e){return t==="Enter"&&!!e?.trim()}function pa(t,e){const n=t?.trim();if(!n)return null;const r={id:`user-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,sender:"human",text:n,createdAt:new Date,type:"user",userEntered:!0,worldName:e};return{text:n,message:r}}function ga(t,e){return{...t,messages:[...t.messages||[],e],userInput:"",isSending:!0,needScroll:!0}}function ma(t){return{...t,isSending:!1}}function fa(t,e){return{...t,isSending:!1,isWaiting:!1,error:e}}function ya(t,e,n){return{...t,editingMessageId:e,editingText:n}}function ba(t){return{...t,editingMessageId:null,editingText:""}}function wa(t,e){return{...t,editingText:e}}function xa(t,e,n,r,s){const o=t.messages.find(a=>a.id===e);return!o||!o.messageId||!t.currentChat?.id?(console.warn("Delete blocked:",{noMessage:!o,noMessageId:!o?.messageId,noChatId:!t.currentChat?.id}),t):{...t,messageToDelete:{id:e,messageId:o.messageId,chatId:t.currentChat.id}}}function ka(t){return{...t,messageToDelete:null}}function va(t,e){return{...t,chatToDelete:e}}function Sa(t){return{...t,chatToDelete:null}}function _r(t){return{...t,loading:!0}}function Aa(t){return{...t,loading:!0,chatToDelete:null}}function Ut(t,e,n=!1){return{...t,loading:!1,chatToDelete:n?null:t.chatToDelete,error:e}}function Mr(t,e){const n=encodeURIComponent(t);return e?`/World/${n}/${encodeURIComponent(e)}`:`/World/${n}`}async function Ta(t,e,n){try{await z.deleteAgent(n,e.name);const r=t.agents.filter(o=>o.id!==e.id),s=t.selectedAgent?.id===e.id;return{success:!0,changes:{agents:r,messages:t.messages.filter(o=>o.sender!==e.name),selectedAgent:s?null:t.selectedAgent,selectedSettingsTarget:s?"world":t.selectedSettingsTarget}}}catch(r){return{success:!1,error:r.message||"Failed to delete agent",changes:{agents:t.agents,messages:t.messages,selectedAgent:t.selectedAgent,selectedSettingsTarget:t.selectedSettingsTarget}}}}async function Ea(t,e,n){const r={agents:t.world?.agents??[],messages:t.messages||[],selectedAgent:t.selectedAgent,selectedSettingsTarget:t.selectedSettingsTarget},s=await Ta(r,e,n);return s.success?{...t,world:t.world?{...t.world,agents:s.changes.agents}:null,messages:s.changes.messages,selectedAgent:s.changes.selectedAgent,selectedSettingsTarget:s.changes.selectedSettingsTarget}:{...t,error:s.error||null}}async function Na(t,e,n){try{await z.clearAgentMemory(n,e.name);const r=t.agents.map(o=>o.id===e.id?{...o,messageCount:0}:o),s=t.selectedAgent?.id===e.id?{...t.selectedAgent,messageCount:0}:t.selectedAgent;return{success:!0,changes:{agents:r,messages:t.messages.filter(o=>o.sender!==e.name),selectedAgent:s}}}catch(r){return{success:!1,error:r.message||"Failed to clear agent messages",changes:{agents:t.agents,messages:t.messages,selectedAgent:t.selectedAgent}}}}async function Ia(t,e,n){const r={agents:t.world?.agents??[],messages:t.messages||[],selectedAgent:t.selectedAgent,selectedSettingsTarget:t.selectedSettingsTarget},s=await Na(r,e,n);return s.success?{...t,world:t.world?{...t.world,agents:s.changes.agents}:null,messages:s.changes.messages,selectedAgent:s.changes.selectedAgent}:{...t,error:s.error||null}}async function Ca(t,e){try{await Promise.all(t.agents.map(s=>z.clearAgentMemory(e,s.name)));const n=t.agents.map(s=>({...s,messageCount:0})),r=t.selectedAgent?{...t.selectedAgent,messageCount:0}:null;return{success:!0,changes:{agents:n,messages:[],selectedAgent:r}}}catch(n){return{success:!1,error:n.message||"Failed to clear world messages",changes:{agents:t.agents,messages:t.messages,selectedAgent:t.selectedAgent}}}}async function _a(t,e){const n={agents:t.world?.agents??[],messages:t.messages||[],selectedAgent:t.selectedAgent,selectedSettingsTarget:t.selectedSettingsTarget},r=await Ca(n,e);return r.success?{...t,world:t.world?{...t.world,agents:r.changes.agents}:null,messages:r.changes.messages,selectedAgent:r.changes.selectedAgent}:{...t,error:r.error||null}}async function Ma(t){try{return typeof window<"u"&&(window.location.href=`/api/worlds/${encodeURIComponent(t)}/export`),{success:!0}}catch(e){return{success:!1,error:e.message||"Failed to export world"}}}async function Ra(t,e){const n=await Ma(e);return n.success?t:{...t,error:n.error||null}}async function La(t){try{const e=await z.getWorldMarkdown(t),n=ds(e),r=Da(n,t);if(typeof window<"u"){const s=window.open();s&&(s.document.write(r),s.document.close())}return{success:!0,htmlContent:r}}catch(e){return{success:!1,error:e.message||"Failed to view world markdown"}}}async function $a(t,e){const n=await La(e);return n.success?t:{...t,error:n.error||null}}function Da(t,e){return`<!DOCTYPE html>
63
+ <html lang="en">
64
+ <head>
65
+ <meta charset="UTF-8">
66
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
67
+ <title>World Export: ${e}</title>
68
+ <style>
69
+ body {
70
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
71
+ max-width: 800px;
72
+ margin: 0 auto;
73
+ padding: 20px;
74
+ line-height: 1.6;
75
+ color: #333;
76
+ }
77
+ h1, h2, h3 { color: #2c3e50; }
78
+ h1 { border-bottom: 2px solid #3498db; padding-bottom: 10px; }
79
+ h2 { border-bottom: 1px solid #bdc3c7; padding-bottom: 5px; }
80
+ code {
81
+ background: #f8f9fa;
82
+ padding: 2px 4px;
83
+ border-radius: 3px;
84
+ font-family: 'Monaco', 'Consolas', monospace;
85
+ }
86
+ pre { background: #f8f9fa; padding: 15px; border-radius: 5px; overflow-x: auto; }
87
+ pre code { background: none; padding: 0; }
88
+ ul { padding-left: 20px; }
89
+ li { margin-bottom: 5px; }
90
+ hr { border: none; height: 1px; background: #bdc3c7; margin: 30px 0; }
91
+ strong { color: #2c3e50; }
92
+ </style>
93
+ </head>
94
+ <body>${t}</body>
95
+ </html>`}function Oa(t,e){return!e||!t.messages?{success:!1,changes:{messages:t.messages,needScroll:t.needScroll}}:{success:!0,changes:{messages:t.messages.map(r=>String(r.id)===String(e)?{...r,isLogExpanded:!r.isLogExpanded}:r),needScroll:!1}}}function Pa(t,e){const n={messages:t.messages,needScroll:t.needScroll},r=Oa(n,e);return r.success?{...t,messages:r.changes.messages,needScroll:r.changes.needScroll}:t}function Wa(t){const e=t&&typeof t=="object"?t:null,n=e&&typeof e.content=="object"?e.content:null,r=String(n?.eventType||"").trim();if(!n||r!=="hitl-option-request")return null;const s=String(n.requestId||"").trim();if(!s)return null;const o=Array.isArray(n.options)?n.options.map(d=>{const h=d&&typeof d=="object"?d:null;return{id:String(h?.id||"").trim(),label:String(h?.label||"").trim(),description:h?.description?String(h.description):void 0}}).filter(d=>d.id.length>0&&d.label.length>0):[];if(o.length===0)return null;const a=String(n.defaultOptionId||"").trim(),i=o.some(d=>d.id===a)?a:o.find(d=>d.id==="no")?.id||o[0].id,c=n.metadata&&typeof n.metadata=="object"?{refreshAfterDismiss:n.metadata.refreshAfterDismiss===!0,kind:typeof n.metadata.kind=="string"?String(n.metadata.kind):void 0}:void 0;return{requestId:s,chatId:e?.chatId?String(e.chatId):null,title:String(n.title||"Approval required").trim()||"Approval required",message:String(n.message||"").trim(),mode:"option",options:o,...i?{defaultOptionId:i}:{},...c?{metadata:c}:{}}}function Ua(t,e){const n=Array.isArray(t)?t:[];return n.some(r=>r.requestId===e.requestId)?n:[...n,e]}function Rr(t,e){return(Array.isArray(t)?t:[]).filter(r=>r.requestId!==e)}function Lr(t,e){const n=String(e||"").trim();if(!n)return!1;const r=t?.chats;if(Array.isArray(r))return r.some(s=>String(s?.id||"").trim()===n);if(r instanceof Map)return r.has(n);if(r&&typeof r=="object"){const s=r;return Object.prototype.hasOwnProperty.call(s,n)?!0:Object.values(s).some(o=>String(o?.id||"").trim()===n)}return!1}function Fa(t,e){const n=String(e||"").trim();if(n&&Lr(t,n))return n;const r=String(t?.currentChatId||"").trim();return r&&Lr(t,r)?r:null}const Q=(t,e)=>{l.run(t,e)};let U={activeMessages:new Map,currentWorldName:null};const za=t=>{if(!(!t||typeof t!="object"))switch(t.type){case"sse":Ha(t.data);break;case"system":Q("handleSystemEvent",t.data);break;case"message":Q("handleMessageEvent",t.data);break;case"error":Q("handleError",{message:t.message||"SSE error"});break;case"world":Q("handleWorldActivity",t.data??t.payload??t);break}},Ha=t=>{const e=t;if(!e)return;const n=e.messageId,r=e.agentName;switch(e.type){case"start":U.activeMessages.set(n,{content:"",sender:r,messageId:n,isStreaming:!0}),Q("handleStreamStart",{messageId:n,sender:r,worldName:e.worldName||U.currentWorldName});break;case"chunk":const s=U.activeMessages.get(n);if(s){const i=e.accumulatedContent!==void 0?e.accumulatedContent:s.content+(e.content||"");s.content=i;const c=e.tool_calls;Q("handleStreamChunk",{messageId:n,sender:r,content:i,isAccumulated:e.accumulatedContent!==void 0,worldName:e.worldName||U.currentWorldName,tool_calls:c})}break;case"tool-start":e.toolExecution||console.warn("tool-start event missing toolExecution:",{eventData:e,messageId:n,agentName:r}),Q("handleToolStart",{messageId:n,sender:r,toolExecution:e.toolExecution,worldName:e.worldName||U.currentWorldName});break;case"tool-progress":Q("handleToolProgress",{messageId:n,sender:r,toolExecution:e.toolExecution,worldName:e.worldName||U.currentWorldName});break;case"tool-result":e.toolExecution||console.warn("tool-result event missing toolExecution:",{eventData:e,messageId:n,agentName:r}),Q("handleToolResult",{messageId:n,sender:r,toolExecution:e.toolExecution,worldName:e.worldName||U.currentWorldName});break;case"tool-error":e.toolExecution||console.warn("tool-error event missing toolExecution:",{eventData:e,messageId:n,agentName:r}),Q("handleToolError",{messageId:n,sender:r,toolExecution:e.toolExecution,worldName:e.worldName||U.currentWorldName});break;case"tool-stream":const o=U.activeMessages.get(n);if(o){const i=e.accumulatedContent!==void 0?e.accumulatedContent:o.content+(e.content||"");o.content=i,Q("handleToolStream",{messageId:n,agentName:r,content:i,stream:e.stream||"stdout",accumulatedContent:i,worldName:e.worldName||U.currentWorldName}),console.log("[tool-stream] Accumulated output:",{messageId:n,stream:e.stream,chunkLength:e.content?.length,totalLength:i.length})}else U.activeMessages.set(n,{content:e.content||"",sender:r,messageId:n,isStreaming:!0}),Q("handleToolStream",{messageId:n,agentName:r,content:e.content||"",stream:e.stream||"stdout",accumulatedContent:e.content||"",worldName:e.worldName||U.currentWorldName}),console.log("[tool-stream] Started new stream:",{messageId:n,stream:e.stream,contentLength:e.content?.length});break;case"end":const a=U.activeMessages.get(n);if(a){const i=e.finalContent!==void 0?e.finalContent:a.content;Q("handleStreamEnd",{messageId:n,sender:r,content:i,worldName:e.worldName||U.currentWorldName}),U.activeMessages.delete(n)}break;case"error":Q("handleStreamError",{messageId:n,sender:r,error:e.error||"Streaming error",worldName:e.worldName||U.currentWorldName}),U.activeMessages.delete(n);break;case"log":Q("handleLogEvent",{messageId:e.messageId,logEvent:e.logEvent,worldName:e.worldName||U.currentWorldName});break}};async function Ba(t,e,n,r,s,o){let a="HUMAN",i,c,d=r,h=s,y=o;if(typeof n=="string"?a=n:n===void 0?a="HUMAN":(a=n.sender??"HUMAN",i=n.chatId,c=n.historyMessages,d=n.onMessage??d,h=n.onError??h,y=n.onComplete??y),!t||!e?.trim())throw new Error("World name and non-empty message are required");const k={message:e,sender:a};return i&&(k.chatId=i),c&&c.length>0&&(k.messages=c),gs(t,`/worlds/${encodeURIComponent(t)}/messages`,{method:"POST",requestPayload:k,onMessage:d,onError:h,onComplete:y})}async function qa(t,e,n,r,s,o,a,i){if(!t||!e||!r||!n?.trim())throw new Error("World name, message ID, chat ID, and new content are required");return gs(t,`/worlds/${encodeURIComponent(t)}/messages/${encodeURIComponent(e)}`,{method:"PUT",requestPayload:{chatId:r,newContent:n,stream:!0},onMessage:o,onError:a,onComplete:i,awaitCompletion:s?.awaitCompletion})}async function gs(t,e,n){U.currentWorldName=t;const s=(await D(e,{method:n.method,body:JSON.stringify(n.requestPayload),headers:{"Content-Type":"application/json",Accept:"text/event-stream","Cache-Control":"no-cache"}})).body.getReader(),o=new TextDecoder;let a="",i=!0,c=null,d=null;const h=n.awaitCompletion?new Promise((S,b)=>{c=S,d=b}):null,y=()=>{if(i){i=!1;try{s.cancel()}catch(S){console.warn("Error canceling SSE reader:",S)}}};return(async()=>{try{for(;i;){const{done:S,value:b}=await s.read();if(S)break;a+=o.decode(b,{stream:!0});const E=a.split(`
96
+ `);a=E.pop()||"";for(const X of E)if(!(X.trim()===""||!X.startsWith("data: ")))try{const B=X.slice(6).trim();if(B==="")continue;const L=JSON.parse(B);if(n.awaitCompletion&&L.type==="error"){const O=new Error(L.message||"Failed to edit message");n.onError?.(O),d?.(O),y();return}za(L),n.onMessage?.(L),L.type==="complete"&&(n.onComplete?.(L.payload||L),c?.())}catch(B){console.error("Error parsing SSE data:",B);const L={message:"Failed to parse SSE data"};Q("handleError",L),n.onError?.(new Error(L.message)),d?.(new Error(L.message))}}}catch(S){console.error("SSE stream error:",S);const b={message:S.message||"SSE stream error"};Q("handleError",b),n.onError?.(S),d?.(S)}finally{y()}})(),h&&await h,y}const ja=(t,e)=>{const{messageId:n,sender:r}=e;return t.messages=t.messages.filter(o=>!o.userEntered),t.messages.push({sender:r,text:"...",isStreaming:!0,messageId:n}),{...t,needScroll:!0}},Ga=(t,e)=>{const{messageId:n,sender:r,content:s,tool_calls:o}=e,a=[...t.messages||[]],i=t.activeStreamMessageId??n;for(let c=a.length-1;c>=0;c--)if(a[c].isStreaming&&(a[c].messageId===n||a[c].messageId===i))return a[c]={...a[c],text:s||"",createdAt:new Date,...o&&{tool_calls:o}},{...t,messages:a,activeStreamMessageId:i,needScroll:!0};return{...t,messages:[...a,{sender:r,text:s||"",isStreaming:!0,messageId:i,...o&&{tool_calls:o}}],activeStreamMessageId:i,needScroll:!0}},Va=(t,e)=>{const r=t.activeStreamMessageId??e.messageId;return t.messages=t.messages.filter(s=>!(s.isStreaming&&s.messageId===r)),{...t,activeStreamMessageId:void 0,needScroll:!1}},Ya=(t,e)=>{const{messageId:n,sender:r,error:s}=e,a=t.activeStreamMessageId??n;let i=!1;const c=(t.messages||[]).map(h=>h.isStreaming&&(h.messageId===a||!n&&h.sender===r&&h.type==="agent-stream")?(i=!0,{...h,isStreaming:!1,hasError:!0,errorMessage:s}):h),d=i?c:[...t.messages||[],{id:`stream-error-${Date.now()}`,sender:r||"System",text:"",isStreaming:!1,hasError:!0,errorMessage:s,messageId:a,type:"error"}];return{...t,messages:d,activeStreamMessageId:void 0,isWaiting:!1}},Qa=(t,e)=>{const{logEvent:n}=e;if(!n)return t;console.log(`[${n.level.toUpperCase()}] ${n.category}: ${n.message}`,{timestamp:n.timestamp,data:n.data,messageId:n.messageId,fullLogEvent:n});const r=`log-${n.messageId||Date.now()}-${Math.random().toString(36).substring(2,9)}`;let s=n.message;if(n.level==="error"&&n.data){const a=n.data.error||n.data.message||n.data.errorMessage;a&&(s=`${n.message}: ${a}`)}const o={id:r,sender:"system",text:s,createdAt:new Date(n.timestamp),type:"log",logEvent:n,isLogExpanded:!1,messageId:r,worldName:e.worldName||U.currentWorldName};return{...t,messages:[...t.messages||[],o],needScroll:!0}},Xa=(t,e)=>{const{messageId:n,sender:r,toolExecution:s}=e;if(!s||!s.toolName)return console.warn("handleToolStart: Missing or invalid toolExecution data",{data:e,toolExecution:s}),t;const o={sender:r,text:`🔧 Starting ${s.toolName}...`,isToolEvent:!0,toolEventType:"start",toolExecution:s,messageId:`${n}-tool-${s.toolCallId}`,createdAt:new Date,type:"tool-start"};return{...t,messages:[...t.messages||[],o],needScroll:!0}},Za=(t,e)=>{const{messageId:n,sender:r,toolExecution:s}=e;if(!s||!s.toolName)return console.warn("handleToolProgress: Missing or invalid toolExecution data",{data:e,toolExecution:s}),t;const o=[...t.messages||[]],a=o.findIndex(i=>i.messageId===`${n}-tool-${s.toolCallId}`&&i.toolEventType==="start");return a!==-1&&(o[a]={...o[a],text:`⚙️ Executing ${s.toolName}...`,toolEventType:"progress",toolExecution:s}),{...t,messages:o,needScroll:!0}},Ka=(t,e)=>{const{messageId:n,sender:r,toolExecution:s}=e;if(!s||!s.toolName)return console.warn("handleToolResult: Missing or invalid toolExecution data",{data:e,toolExecution:s}),t;const o=[...t.messages||[]],a=o.findIndex(i=>i.messageId===`${n}-tool-${s.toolCallId}`&&i.isToolEvent);if(a!==-1){const i=typeof s.result=="string"?s.result.slice(0,100):JSON.stringify(s.result).slice(0,100);o[a]={...o[a],text:`✅ ${s.toolName} completed (${s.duration}ms)`,toolEventType:"result",toolExecution:s,expandable:!0,resultPreview:i.length<100?i:i+"..."}}return{...t,messages:o,needScroll:!0}},Ja=(t,e)=>{const{messageId:n,sender:r,toolExecution:s}=e;if(!s||!s.toolName)return console.warn("handleToolError: Missing or invalid toolExecution data",{data:e,toolExecution:s}),t;const o=[...t.messages||[]],a=o.findIndex(i=>i.messageId===`${n}-tool-${s.toolCallId}`&&i.isToolEvent);if(a!==-1)o[a]={...o[a],text:`❌ ${s.toolName} failed: ${s.error}`,toolEventType:"error",toolExecution:s,hasError:!0};else{const i={sender:r,text:`❌ Tool ${s.toolName} failed: ${s.error}`,isToolEvent:!0,toolEventType:"error",toolExecution:s,messageId:`${n}-tool-error-${s.toolCallId}`,createdAt:new Date,type:"tool-error",hasError:!0};return{...t,messages:[...o,i],needScroll:!0}}return{...t,messages:o,needScroll:!0}},ei=(t,e)=>{const{messageId:n,agentName:r,content:s,stream:o}=e,{createToolStreamState:a}=require("../domain/sse-streaming");return a(t,{messageId:n,agentName:r,content:s,stream:o||"stdout"})},ms=(t,e)=>{const n=oe(t.sender||e);let r;n==="human"||n==="user"?r="user":t.role==="tool"?r="tool":t.role==="user"?r="user":(t.role,r="agent");const s=r==="user";if(!t.messageId){const h=t.createdAt?new Date(t.createdAt).getTime():Date.now(),y=(t.content||"").substring(0,20).replace(/\s/g,"");t.messageId=`fallback-${h}-${y.substring(0,10)}`}const a=s&&(n!=="human"&&n!=="user");let i,c;a?(i=oe(e),c=n):(i=n,c=t.agentId||(s?void 0:e));const d=t;return{id:`msg-${Date.now()+Math.random()}`,sender:i,text:t.content||"",messageId:t.messageId,chatId:t.chatId,replyToMessageId:t.replyToMessageId,createdAt:t.createdAt||new Date,type:r,fromAgentId:c,ownerAgentId:oe(e),role:t.role,tool_calls:d.tool_calls||d.toolCalls,tool_call_id:d.tool_call_id||d.toolCallId}},fs=(t,e=[])=>{const n=new Map,r=[],s=new Map;e.forEach(o=>s.set(o.id,o));for(const o of t)if((o.type==="user"||(o.sender||"").toLowerCase()==="human"||(o.sender||"").toLowerCase()==="user")&&o.messageId){if(!n.get(o.messageId)){let c;o.fromAgentId?c=[o.fromAgentId]:e.length===1?c=[e[0].id]:c=[],n.set(o.messageId,{...o,seenByAgents:c})}}else r.push(o);return[...Array.from(n.values()),...r].sort((o,a)=>{const i=new Date(o.createdAt||0).getTime(),c=new Date(a.createdAt||0).getTime();if(i!==c)return i-c;const d=o.type==="agent"||o.type==="assistant"?0:o.type==="user"||o.type==="human"?1:2,h=a.type==="agent"||a.type==="assistant"?0:a.type==="user"||a.type==="human"?1:2;return d-h})},ti=t=>{if(t.debounceFrameId!==null)return t;const e=requestAnimationFrame(()=>{l.run("flush-stream-updates")});return{...t,debounceFrameId:e}},ni=t=>{if(t.elapsedIntervalId!==null)return t;const e=Date.now(),n=window.setInterval(()=>{l.run("update-elapsed-time")},1e3);return{...t,activityStartTime:e,elapsedIntervalId:n,elapsedMs:0}},ri=t=>(t.elapsedIntervalId!==null&&clearInterval(t.elapsedIntervalId),{...t,elapsedIntervalId:null,activityStartTime:null,elapsedMs:0}),si=t=>t.activeTools.length>0||t.pendingStreamUpdates.size>0,oi=(t,e)=>Ya(t,e),li=(t,e)=>{let n=Xa(t,e);const r={toolUseId:e.messageId||`tool-${Date.now()}`,toolName:e.toolExecution?.toolName||"unknown",toolInput:e.toolExecution?.input,status:"running",result:null,errorMessage:null,progress:null,startedAt:new Date().toISOString(),completedAt:null};return n={...n,activeTools:[...n.activeTools,r],isBusy:!0},n.elapsedIntervalId===null&&(n=ni(n)),n},ai=(t,e)=>Za(t,e),ii=(t,e)=>{let n=Ka(t,e);const r=e.messageId;n={...n,activeTools:n.activeTools.filter(o=>o.toolUseId!==r)};const s=si(n);return n={...n,isBusy:s},!s&&n.elapsedIntervalId!==null&&(n=ri(n)),n},ci=(t,e)=>Ja(t,e),ui=(t,e)=>{const{messageId:n,content:r}=e,s=new Map(t.pendingStreamUpdates);s.set(n,r||"");let o={...t,pendingStreamUpdates:s};return o=ti(o),o=Ga(o,e),o},di=(t,e)=>ei(t,e),hi=(t,e)=>{if(!e||e.type!=="response-start"&&e.type!=="response-end"&&e.type!=="idle"){console.log("[World] Invalid event type, no state change");return}const n=typeof e.activityId=="number"?e.activityId:null,r=typeof e.pendingOperations=="number"?e.pendingOperations:0,s=typeof e.source=="string"?e.source:"",o=r>0;if(e.type==="response-start"?console.log(`[World] Processing started | pending: ${r} | activityId: ${n} | source: ${s} | isWaiting: ${t.isWaiting} → ${o}`):e.type==="idle"&&r===0?console.log(`[World] All processing complete | pending: ${r} | activityId: ${n} | source: ${s} | isWaiting: ${t.isWaiting} → ${o}`):e.type==="response-end"&&console.log(`[World] Processing ended | pending: ${r} | activityId: ${n} | source: ${s} | isWaiting: ${t.isWaiting} → ${o}`),t.isWaiting!==o)return{...t,isWaiting:o,needScroll:!0}};async function*bt(t,e,n){if(!e){location.href="/";return}try{const r=decodeURIComponent(e);t.selectedSettingsTarget="world",t.worldName=r,t.loading=!0;const s=await z.getWorld(r);if(!s)throw new Error("World not found: "+r);n=Fa(s,n)||void 0,s.currentChatId!==n&&n&&await z.setChat(r,n);let o=[];const a=Array.from(s.agents.values());for(const c of a){c.spriteIndex=a.indexOf(c)%9,c.messageCount=0;for(const d of c.memory||[])if(d.chatId===n){c.messageCount++;const h=ms(d,c.name);o.push(h)}}const i=fs([...o],a);yield{...t,world:s,currentChat:s.chats.find(c=>c.id===n)||null,messages:i,rawMessages:o,loading:!1,needScroll:!0,lastUserMessageText:null}}catch(r){yield{...t,error:r.message||"Failed to load world data",loading:!1,needScroll:!1,lastUserMessageText:t.lastUserMessageText??null}}}const pi=async(t,e)=>{const n=e&&typeof e=="object"?e:null,r=n&&"content"in n?n.content:e,s=r&&typeof r=="object"?r:null,o=s&&typeof s.eventType=="string"&&s.eventType||(typeof r=="string"?r:null)||(typeof e=="string"?e:null),a={id:`system-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,type:"system",sender:"SYSTEM",text:"",createdAt:new Date,worldEvent:{type:"system",category:"system",message:typeof r=="string"&&r||typeof o=="string"&&o||(n&&typeof n.message=="string"?n.message:"")||"System event",timestamp:new Date().toISOString(),data:n||void 0,messageId:`system-${Date.now()}`},isLogExpanded:!1},i={...t,messages:[...t.messages||[],a],needScroll:!0};if(o==="chat-title-updated"){const d=i.currentChat?.id||i.world?.currentChatId||void 0,h=bt(i,i.worldName,d);for await(const y of h)return{...i,...y}}if(o==="agent-created"){const d=i.currentChat?.id||i.world?.currentChatId||void 0,h=bt(i,i.worldName,d);for await(const y of h)return{...i,...y}}const c=Wa(e);if(c){const d=i.hitlPromptQueue||[],h=Ua(d,c);return{...i,hitlPromptQueue:h}}return i},gi=(t,e)=>{const n=e||{},r=t.currentChat?.id||t.world?.currentChatId||null,s=n.chatId??null;if(r&&(!s||s!==r))return t;const o=n.sender;if(n.content&&typeof n.content=="string")try{if(JSON.parse(n.content).__type==="tool_result")return t}catch{}let a;if(t.world?.agents){const b=t.world.agents.find(E=>E.name.toLowerCase()===o.toLowerCase());b&&(b.messageCount||(b.messageCount=0),b.messageCount++,a=b.id)}const i=n.content||n.message||"";let c;n.role==="tool"?c="tool":n.role==="user"||o==="human"||o==="user"?c="user":n.role==="assistant"?c="agent":c=n.type||"message";const d={id:n.id||`msg-${Date.now()+Math.random()}`,type:c,sender:o,text:i,createdAt:n.createdAt||new Date().toISOString(),fromAgentId:a,messageId:n.messageId,chatId:n.chatId,replyToMessageId:n.replyToMessageId,role:n.role},h=t.messages||[],y=(o||"").toLowerCase();if((y==="human"||y==="user")&&n.messageId){const b=h.findIndex(E=>E.messageId===n.messageId||E.userEntered&&E.text===d.text);if(b!==-1){if(h[b].messageId===n.messageId)return t;const X=h.map((B,L)=>L===b?{...B,messageId:n.messageId,chatId:n.chatId??B.chatId,createdAt:n.createdAt||B.createdAt,userEntered:!1,seenByAgents:a?[a]:[]}:B);return{...t,messages:X}}}const S=h.findIndex(b=>b?.isStreaming&&(b.sender||"").toLowerCase()===y);if(S!==-1){const b=h.map((E,X)=>X!==S?E:{...E,...d,id:d.id,isStreaming:!1,messageId:d.messageId??E.messageId}).filter(E=>!!E&&!E.userEntered);return{...t,messages:b}}return t.messages=h.filter(b=>!b.userEntered&&!(b.isStreaming&&(b.sender||"").toLowerCase()===y)),t.messages.push(d),{...t}},mi=(t,e)=>{const n=e.message||"SSE error",r={id:Date.now()+Math.random(),type:"error",sender:"System",text:n,createdAt:new Date().toISOString(),worldName:t.worldName,hasError:!0};return{...t,error:n,messages:[...t.messages||[],r],needScroll:!0}},fi={initWorld:bt,"/World":bt,"update-input":(t,e)=>da(t,e.target.value),"key-press":(t,e)=>{(t.hitlPromptQueue||[]).length>0||ha(e.key,t.userInput)&&l.run("send-message")},"send-message":async t=>{if((t.hitlPromptQueue||[]).length>0)return{...t,error:"Resolve the pending HITL prompt before sending a new message."};const e=pa(t.userInput,t.worldName);if(!e)return t;const r={...ga(t,e.message),lastUserMessageText:e.text};try{return await Ba(t.worldName,e.text,{sender:"HUMAN",chatId:t.currentChat?.id||t.world?.currentChatId||void 0}),ma(r)}catch(s){return fa(r,s.message||"Failed to send message")}},"stop-message-processing":async function*(t){const e=t.currentChat?.id||t.world?.currentChatId||null;if(!e){yield{...t,error:"No active chat session to stop."};return}if(t.isStopping)return;const n={...t,isStopping:!0,error:null};yield n;try{const r=await z.stopMessageProcessing(t.worldName,e),s=!!r?.stopped||r?.reason==="no-active-process";s&&(n.debounceFrameId!==null&&cancelAnimationFrame(n.debounceFrameId),n.elapsedIntervalId!==null&&clearInterval(n.elapsedIntervalId)),yield{...n,isStopping:!1,isWaiting:s?!1:n.isWaiting,isBusy:s?!1:n.isBusy,activeTools:s?[]:n.activeTools,pendingStreamUpdates:s?new Map:n.pendingStreamUpdates,debounceFrameId:s?null:n.debounceFrameId,elapsedIntervalId:s?null:n.elapsedIntervalId,activityStartTime:s?null:n.activityStartTime,elapsedMs:s?0:n.elapsedMs,needScroll:s?!0:n.needScroll,error:null}}catch(r){yield{...n,isStopping:!1,error:r?.message||"Failed to stop message processing."}}},handleStreamStart:ja,handleStreamChunk:ui,handleStreamEnd:Va,handleStreamError:oi,handleLogEvent:Qa,handleMessageEvent:gi,handleSystemEvent:pi,"respond-hitl-option":async function*(t,e){const n=String(e?.requestId||"").trim(),r=String(e?.optionId||"").trim();if(!n||!r){yield{...t,error:"Invalid HITL response payload."};return}const s=(t.hitlPromptQueue||[]).find(o=>o.requestId===n);if(!s){yield{...t,error:`HITL request '${n}' not found.`};return}yield{...t,submittingHitlRequestId:n,error:null};try{const o=await z.respondHitlOption(t.worldName,n,r,e?.chatId??s.chatId??null);if(!o?.accepted){yield{...t,submittingHitlRequestId:null,error:o?.reason||"HITL response was not accepted."};return}if(yield{...t,submittingHitlRequestId:null,hitlPromptQueue:Rr(t.hitlPromptQueue||[],n)},s?.metadata?.refreshAfterDismiss){const a=t.currentChat?.id||t.world?.currentChatId||void 0,i=bt(t,t.worldName,a);for await(const c of i)yield{...t,...c,submittingHitlRequestId:null,hitlPromptQueue:Rr(c.hitlPromptQueue||t.hitlPromptQueue||[],n)}}}catch(o){yield{...t,submittingHitlRequestId:null,error:o?.message||"Failed to submit HITL response."}}},handleError:mi,handleToolError:ci,handleToolStart:li,handleToolProgress:ai,handleToolResult:ii,handleToolStream:di,handleWorldActivity:(t,e)=>hi(t,e),"flush-stream-updates":t=>{if(t.pendingStreamUpdates.size===0)return{...t,debounceFrameId:null};const e=t.messages.map(n=>{const r=t.pendingStreamUpdates.get(n.messageId);return r?{...n,text:r}:n});return{...t,messages:e,pendingStreamUpdates:new Map,debounceFrameId:null,needScroll:!0}},"update-elapsed-time":t=>{if(t.activityStartTime===null)return t;const e=Date.now()-t.activityStartTime;return{...t,elapsedMs:e}},"toggle-log-details":(t,e)=>Pa(t,e),"start-edit-message":(t,e)=>({...ya(t,e.messageId,e.text),needScroll:!1}),"cancel-edit-message":t=>ba(t),"update-edit-text":(t,e)=>wa(t,e.target.value),"toggle-tool-output":(t,e)=>{const n=t.messages.map(r=>r.id===e?{...r,isToolOutputExpanded:!r.isToolOutputExpanded}:r);return{...t,messages:n}},"show-delete-message-confirm":(t,e)=>xa(t,e.messageId,e.backendMessageId,e.messageText,e.userEntered),"hide-delete-message-confirm":t=>ka(t),"delete-message-confirmed":async t=>{if(!t.messageToDelete)return t;const{id:e,messageId:n,chatId:r}=t.messageToDelete;try{const s=await z.deleteMessage(t.worldName,n,r);if(!s.success)return{...t,error:`Failed to delete message: ${s.failedAgents?.map(c=>c.error).join(", ")||"Unknown error"}`,messageToDelete:null};const o=await z.getWorld(t.worldName);let a=[];const i=Array.isArray(o.agents)?o.agents:o.agents&&typeof o.agents.values=="function"?Array.from(o.agents.values()):Object.values(o.agents||{});for(const c of i){c.spriteIndex=i.indexOf(c)%9,c.messageCount=0;for(const d of c.memory||[])if(d.chatId===r){c.messageCount++;const h=ms(d,c.name);a.push(h)}}return a=fs(a,i),{...t,world:o,messages:a,messageToDelete:null,needScroll:!0}}catch(s){return{...t,error:s.message||"Failed to delete message",messageToDelete:null}}},"save-edit-message":async function*(t,e){const n=t.editingText?.trim();if(!n)return;const r=t.messages.find(h=>h.id===e);if(!r){yield{...t,error:"Message not found",editingMessageId:null,editingText:""};return}const s=String(r.text||"").trim();if(n===s)return;if(!r.messageId){yield{...t,error:"Cannot edit message: missing message ID. Message may not be saved yet.",editingMessageId:null,editingText:""};return}const o=r.chatId||t.currentChat?.id;if(!o){yield{...t,error:"Cannot edit message: no active chat session",editingMessageId:null,editingText:""};return}const a={messageId:r.messageId,chatId:o,newContent:n,timestamp:Date.now(),worldName:t.worldName};try{localStorage.setItem("agent-world-edit-backup",JSON.stringify(a))}catch(h){console.warn("Failed to save edit backup to localStorage:",h)}const i=t.messages.findIndex(h=>h.id===e),c=i>=0?t.messages.slice(0,i):t.messages,d={...t,messages:c,editingMessageId:null,editingText:"",isSending:!0,needScroll:!1,lastUserMessageText:n};yield d;try{await qa(t.worldName,r.messageId,n,o,{awaitCompletion:!1});try{localStorage.removeItem("agent-world-edit-backup")}catch(h){console.warn("Failed to clear edit backup from localStorage:",h)}yield{...d,isSending:!1,error:null}}catch(h){let y=h.message||"Failed to edit message";h.message?.includes("423")||h.message?.includes("WORLD_LOCKED")?y="Cannot edit message: world is currently processing. Please try again in a moment.":h.message?.includes("404")?y="Message not found in agent memories. It may have been already deleted.":h.message?.includes("400")&&(y="Invalid message: only user messages can be edited."),yield{...t,isSending:!1,editingMessageId:null,editingText:"",error:y}}},"chat-history-show-delete-confirm":(t,e)=>va(t,e),"chat-history-hide-modals":t=>Sa(t),"delete-agent":async(t,e)=>Ea(t,e.agent,t.worldName),"export-world-markdown":async(t,e)=>Ra(t,e.worldName),"view-world-markdown":async(t,e)=>$a(t,e.worldName),"create-new-chat":async function*(t){try{if(yield _r(t),!(await z.newChat(t.worldName)).success){yield Ut(t,"Failed to create new chat");return}l.run("initWorld",t.worldName)}catch(e){yield Ut(t,e.message||"Failed to create new chat")}},"load-chat-from-history":async function*(t,e){try{t.debounceFrameId!==null&&cancelAnimationFrame(t.debounceFrameId),t.elapsedIntervalId!==null&&clearInterval(t.elapsedIntervalId);const n={...t,pendingStreamUpdates:new Map,debounceFrameId:null,activeTools:[],isBusy:!1,elapsedMs:0,activityStartTime:null,elapsedIntervalId:null,hitlPromptQueue:[],submittingHitlRequestId:null};yield _r(n),(await z.setChat(t.worldName,e)).success||(yield n);const s=Mr(t.worldName,e);l.route(s),history.pushState(null,"",s)}catch(n){yield Ut(t,n.message||"Failed to load chat from history")}},"delete-chat-from-history":async function*(t,e){try{yield Aa(t),await z.deleteChat(t.worldName,e.chatId);const n=Mr(t.worldName);l.route(n),history.pushState(null,"",n)}catch(n){yield Ut(t,n.message||"Failed to delete chat",!0)}},"clear-agent-messages":async(t,e)=>Ia(t,e.agent,t.worldName),"clear-world-messages":async t=>_a(t,t.worldName)};function yi(t,e){const n=String(e||"").trim().toLowerCase();if(!n)return!1;const r=String(t?.id||"").trim().toLowerCase(),s=String(t?.name||"").trim().toLowerCase();return n===r||n===s}class bi extends Me{state={worldName:"World",world:null,messages:[],userInput:"",loading:!0,error:null,messagesLoading:!1,isSending:!1,isStopping:!1,isWaiting:!1,selectedSettingsTarget:"chat",selectedAgent:null,activeAgent:null,showAgentEdit:!1,agentEditMode:"create",selectedAgentForEdit:null,showWorldEdit:!1,worldEditMode:"edit",selectedWorldForEdit:null,chatToDelete:null,connectionStatus:"disconnected",needScroll:!1,currentChat:null,editingMessageId:null,editingText:"",messageToDelete:null,activeAgentFilters:[],agentActivities:{},pendingStreamUpdates:new Map,debounceFrameId:null,activeTools:[],isBusy:!1,elapsedMs:0,activityStartTime:null,elapsedIntervalId:null,hitlPromptQueue:[],submittingHitlRequestId:null};view=e=>{const n=e.hitlPromptQueue?.length?e.hitlPromptQueue[0]:null;return e.error?l.h("div",{className:"world-container flex flex-col h-screen"},l.h("div",{className:"world-columns flex flex-1 overflow-hidden"},l.h("div",{className:"chat-column flex flex-col flex-1"},l.h("div",{className:"agents-section"},l.h("div",{className:"agents-row flex items-center gap-4 px-4 py-2"},l.h("div",{className:"text-text-secondary"},"Error"))),l.h("div",{className:"error-state flex items-center justify-center flex-1 p-4"},l.h("div",{className:"text-center"},l.h("p",{className:"text-lg text-text-primary mb-4"},"Error: ",e.error),l.h("button",{className:"btn btn-primary px-6 py-3",$onclick:["/World",e.worldName]},"Retry")))),l.h("div",{className:"settings-column w-96"},l.h("div",{className:"settings-section p-4"},l.h("div",{className:"settings-row flex gap-2"},l.h("button",{className:"world-settings-btn",title:"World Settings"},l.h("span",{className:"world-gear-icon"},"⚙"))))))):l.h("div",{className:"world-container flex flex-col h-screen"},l.h("div",{className:"world-columns flex flex-1 overflow-hidden"},l.h("div",{className:"chat-column flex flex-col flex-1"},l.h("div",{className:"agents-section"},l.h("div",{className:"agents-row agents-row-with-back flex items-center gap-4 px-4 py-2"},l.h("div",{className:"back-button-container"},l.h("a",{href:"/"},l.h("button",{className:"back-button flex items-center justify-center",title:"Back to Worlds"},l.h("span",{className:"world-back-icon"},"←")))),l.h("div",{className:"agents-list-container flex-1"},e.world?.agents?.length?l.h("div",{className:"agents-list flex flex-wrap gap-6 justify-center items-center"},e.world?.agents.map((r,s)=>{const o=e.selectedSettingsTarget==="agent"&&e.selectedAgent?.id===r.id,a=e.activeAgentFilters.includes(r.id),i=yi(r,e.world?.mainAgent);return l.h("div",{key:`agent-${r.id||s}`,className:`agent-item ${o?"selected":""} ${i?"main-agent":""} flex flex-col items-center gap-1 px-4 cursor-pointer`,$onclick:["open-agent-edit",r]},l.h("div",{className:"agent-sprite-container relative"},l.h("div",{className:`agent-sprite sprite-${r.spriteIndex} w-16 h-16`}),i?l.h("div",{className:"main-agent-badge absolute",title:"Main agent"},"MAIN"):null,l.h("div",{className:`message-badge ${a?"active":""} absolute`,$onclick:["toggle-agent-filter",r.id]},r.messageCount)),l.h("div",{className:"agent-name text-sm text-center"},r.name))})):l.h("div",{className:"no-agents text-text-secondary"},"No agents in this world:",l.h("span",null," ",jt(`<a href="#" onclick="app.run('open-agent-create')">Create Agent</a>`)))))),l.h(oa,{worldName:e.worldName,messages:e.messages,rawMessages:e.rawMessages,userInput:e.userInput,messagesLoading:e.messagesLoading,isSending:e.isSending,isWaiting:e.isWaiting,needScroll:e.needScroll,activeAgent:e.activeAgent,agents:e.world?.agents||[],selectedAgent:e.selectedSettingsTarget==="agent"?e.selectedAgent:null,currentChat:e.currentChat?.name,currentChatId:e.currentChat?.id||null,editingMessageId:e.editingMessageId,editingText:e.editingText,agentFilters:e.activeAgentFilters,isBusy:e.isBusy||e.isWaiting,elapsedMs:e.elapsedMs,activeTools:e.activeTools,isStopping:e.isStopping,activeHitlPrompt:n,submittingHitlRequestId:e.submittingHitlRequestId})),l.h("div",{className:"settings-column w-96"},l.h("div",{className:"settings-section p-4"},l.h("div",{className:"settings-row flex gap-2"},l.h("button",{className:"world-settings-btn",title:"Create New Agent",$onclick:"open-agent-create"},l.h("span",{className:"world-gear-icon"},"+")),l.h("button",{className:"world-settings-btn",title:"World Settings",$onclick:"open-world-edit",style:{marginLeft:"8px"}},l.h("span",{className:"world-gear-icon"},"⚙")),l.h("button",{className:"world-settings-btn",$onclick:["export-world-markdown",{worldName:e.world?.name}],title:"Export world to markdown file",style:{marginLeft:"8px"}},l.h("span",{className:"world-gear-icon"},"↓")),l.h("button",{className:"world-settings-btn",$onclick:["view-world-markdown",{worldName:e.world?.name}],title:"View world markdown in new tab",style:{marginLeft:"4px"}},l.h("span",{className:"world-gear-icon"},"🗎")))),l.h(aa,{world:e.world}))),e.showAgentEdit&&l.h(ua,{agent:e.selectedAgentForEdit,mode:e.agentEditMode,worldName:e.worldName,parentComponent:this}),e.showWorldEdit&&l.h(Qr,{world:e.selectedWorldForEdit,mode:e.worldEditMode,parentComponent:this}),e.chatToDelete&&l.h("div",{className:"modal-overlay fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",$onclick:"chat-history-hide-modals"},l.h("div",{className:"modal-content chat-history-modal bg-white rounded-lg p-6 max-w-md",onclick:r=>r.stopPropagation()},l.h("button",{className:"modal-close-btn absolute top-4 right-4 text-2xl",$onclick:"chat-history-hide-modals",title:"Close"},"×"),l.h("h3",{className:"text-xl font-bold mb-4"},"Delete Chat"),l.h("p",{className:"delete-confirmation-text mb-2"},"Are you sure you want to delete chat ",l.h("span",{className:"delete-confirmation-name font-bold"},'"',e.chatToDelete.name,'"'),"?"),l.h("p",{className:"warning delete-confirmation-warning text-system mb-4"},"⚠️ This action cannot be undone."),l.h("div",{className:"form-actions flex gap-2 justify-end"},l.h("button",{className:"btn-danger px-4 py-2 rounded",$onclick:["delete-chat-from-history",{chatId:e.chatToDelete.id}]},"Delete Chat"),l.h("button",{className:"btn-secondary px-4 py-2 rounded",$onclick:"chat-history-hide-modals"},"Cancel")))),e.messageToDelete&&l.h("div",{className:"modal-overlay fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",$onclick:"hide-delete-message-confirm"},l.h("div",{className:"modal-content chat-history-modal bg-white rounded-lg p-6 max-w-md",onclick:r=>r.stopPropagation()},l.h("button",{className:"modal-close-btn absolute top-4 right-4 text-2xl",$onclick:"hide-delete-message-confirm",title:"Close"},"×"),l.h("h3",{className:"text-xl font-bold mb-4"},"Delete Message"),l.h("p",{className:"delete-confirmation-text mb-2"},"Are you sure you want to delete this message?"),l.h("p",{className:"warning delete-confirmation-warning text-system mb-4"},"⚠️ This action will delete the message and all messages after it. This cannot be undone."),l.h("div",{className:"form-actions flex gap-2 justify-end"},l.h("button",{className:"btn-danger px-4 py-2 rounded",$onclick:"delete-message-confirmed"},"Delete Message"),l.h("button",{className:"btn-secondary px-4 py-2 rounded",$onclick:"hide-delete-message-confirm"},"Cancel")))))};is_global_event=()=>!0;unload=()=>{this.state.debounceFrameId!==null&&cancelAnimationFrame(this.state.debounceFrameId),this.state.elapsedIntervalId!==null&&clearInterval(this.state.elapsedIntervalId)};update={...fi,"open-agent-create":e=>({...e,showAgentEdit:!0,agentEditMode:"create",selectedAgentForEdit:null}),"open-agent-edit":(e,n)=>({...e,showAgentEdit:!0,agentEditMode:"edit",selectedAgentForEdit:n}),"open-agent-delete":(e,n)=>({...e,showAgentEdit:!0,agentEditMode:"delete",selectedAgentForEdit:n}),"close-agent-edit":e=>({...e,showAgentEdit:!1}),"open-world-edit":e=>({...e,showWorldEdit:!0,worldEditMode:"edit",selectedWorldForEdit:e.world}),"close-world-edit":e=>({...e,showWorldEdit:!1}),"agent-saved":e=>{location.reload()},"agent-deleted":e=>{location.reload()},"toggle-agent-filter":(e,n,r)=>{r?.stopPropagation();const s=e.activeAgentFilters||[],o=s.includes(n);return{...e,activeAgentFilters:o?s.filter(a=>a!==n):[...s,n]}}}}class wi extends Me{state="Settings";view=e=>l.h("div",null,l.h("h1",null,e));update={"/Settings":e=>e}}l.render("#root",l.h(xo,null));l.addComponents("#pages",{"/":Ho,"/World":bi,"/Settings":wi});