agent-world 0.12.0 → 0.12.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -4
- package/bin/agent-world-cli.js +41 -0
- package/bin/agent-world-server.js +40 -0
- package/bin/agent-world.js +53 -0
- package/dist/cli/index.js +4 -4
- package/dist/core/activity-tracker.d.ts +0 -1
- package/dist/core/activity-tracker.js +0 -1
- package/dist/core/anthropic-direct.d.ts +0 -1
- package/dist/core/anthropic-direct.js +0 -1
- package/dist/core/chat-constants.d.ts +0 -1
- package/dist/core/chat-constants.js +0 -1
- package/dist/core/create-agent-tool.d.ts +0 -1
- package/dist/core/create-agent-tool.js +0 -1
- package/dist/core/events/index.d.ts +0 -1
- package/dist/core/events/index.js +0 -1
- package/dist/core/events/memory-manager.d.ts +0 -1
- package/dist/core/events/memory-manager.js +0 -1
- package/dist/core/events/mention-logic.d.ts +0 -1
- package/dist/core/events/mention-logic.js +0 -1
- package/dist/core/events/orchestrator.d.ts +0 -1
- package/dist/core/events/orchestrator.js +0 -1
- package/dist/core/events/persistence.d.ts +0 -1
- package/dist/core/events/persistence.js +0 -1
- package/dist/core/events/publishers.d.ts +0 -1
- package/dist/core/events/publishers.js +0 -1
- package/dist/core/events/subscribers.d.ts +0 -1
- package/dist/core/events/subscribers.js +0 -1
- package/dist/core/events/tool-bridge-logging.d.ts +0 -1
- package/dist/core/events/tool-bridge-logging.js +0 -1
- package/dist/core/events-metadata.d.ts +0 -1
- package/dist/core/events-metadata.js +0 -1
- package/dist/core/export.d.ts +0 -1
- package/dist/core/export.js +0 -1
- package/dist/core/file-tools.d.ts +0 -1
- package/dist/core/file-tools.js +0 -1
- package/dist/core/google-direct.d.ts +0 -1
- package/dist/core/google-direct.js +0 -1
- package/dist/core/hitl.d.ts +0 -1
- package/dist/core/hitl.js +0 -1
- package/dist/core/index.d.ts +0 -1
- package/dist/core/index.js +0 -1
- package/dist/core/llm-config.d.ts +0 -1
- package/dist/core/llm-config.js +0 -1
- package/dist/core/llm-manager.d.ts +0 -1
- package/dist/core/llm-manager.js +0 -1
- package/dist/core/load-skill-tool.d.ts +0 -1
- package/dist/core/load-skill-tool.js +0 -1
- package/dist/core/logger.d.ts +0 -1
- package/dist/core/logger.js +0 -1
- package/dist/core/managers.d.ts +0 -1
- package/dist/core/managers.js +0 -1
- package/dist/core/mcp-server-registry.d.ts +0 -1
- package/dist/core/mcp-server-registry.js +0 -1
- package/dist/core/message-prep.d.ts +0 -1
- package/dist/core/message-prep.js +0 -1
- package/dist/core/message-processing-control.d.ts +0 -1
- package/dist/core/message-processing-control.js +0 -1
- package/dist/core/openai-direct.d.ts +0 -1
- package/dist/core/openai-direct.js +0 -1
- package/dist/core/shell-cmd-tool.d.ts +0 -1
- package/dist/core/shell-cmd-tool.js +0 -1
- package/dist/core/shell-process-registry.d.ts +0 -1
- package/dist/core/shell-process-registry.js +0 -1
- package/dist/core/skill-registry.d.ts +0 -1
- package/dist/core/skill-registry.js +0 -1
- package/dist/core/skill-settings.d.ts +0 -1
- package/dist/core/skill-settings.js +0 -1
- package/dist/core/storage/agent-storage.d.ts +0 -1
- package/dist/core/storage/agent-storage.js +0 -1
- package/dist/core/storage/eventStorage/fileEventStorage.d.ts +0 -1
- package/dist/core/storage/eventStorage/fileEventStorage.js +0 -1
- package/dist/core/storage/eventStorage/index.d.ts +0 -1
- package/dist/core/storage/eventStorage/index.js +0 -1
- package/dist/core/storage/eventStorage/memoryEventStorage.d.ts +0 -1
- package/dist/core/storage/eventStorage/memoryEventStorage.js +0 -1
- package/dist/core/storage/eventStorage/sqliteEventStorage.d.ts +0 -1
- package/dist/core/storage/eventStorage/sqliteEventStorage.js +0 -1
- package/dist/core/storage/eventStorage/types.d.ts +0 -1
- package/dist/core/storage/eventStorage/types.js +0 -1
- package/dist/core/storage/eventStorage/validation.d.ts +0 -1
- package/dist/core/storage/eventStorage/validation.js +0 -1
- package/dist/core/storage/memory-storage.d.ts +0 -1
- package/dist/core/storage/memory-storage.js +0 -1
- package/dist/core/storage/migration-runner.d.ts +0 -1
- package/dist/core/storage/migration-runner.d.ts.map +1 -1
- package/dist/core/storage/migration-runner.js +4 -11
- package/dist/core/storage/migration-runner.js.map +1 -1
- package/dist/core/storage/sqlite-schema.d.ts +0 -1
- package/dist/core/storage/sqlite-schema.js +0 -1
- package/dist/core/storage/sqlite-storage.d.ts +0 -1
- package/dist/core/storage/sqlite-storage.js +0 -1
- package/dist/core/storage/storage-factory.d.ts +0 -1
- package/dist/core/storage/storage-factory.js +0 -1
- package/dist/core/storage/validation.d.ts +0 -1
- package/dist/core/storage/validation.js +0 -1
- package/dist/core/storage/world-storage.d.ts +0 -1
- package/dist/core/storage/world-storage.js +0 -1
- package/dist/core/subscription.d.ts +0 -1
- package/dist/core/subscription.js +0 -1
- package/dist/core/tool-utils.d.ts +0 -1
- package/dist/core/tool-utils.js +0 -1
- package/dist/core/types.d.ts +0 -1
- package/dist/core/types.js +0 -1
- package/dist/core/utils.d.ts +0 -1
- package/dist/core/utils.js +0 -1
- package/dist/public/assets/index-BO20H4xt.js +96 -0
- package/dist/public/assets/{index-C9kPXL6G.css → index-ETY7W5_S.css} +1 -1
- package/dist/public/index.html +2 -2
- package/dist/server/api.js +29 -1
- package/dist/server/index.js +4 -4
- package/dist/server/sse-handler.d.ts +2 -1
- package/dist/server/sse-handler.js +10 -1
- package/migrations/0000_init_base_schema.sql +129 -0
- package/migrations/0001_add_chat_id.sql +12 -0
- package/migrations/0002_add_llm_config.sql +9 -0
- package/migrations/0003_add_current_chat_id.sql +8 -0
- package/migrations/0004_add_mcp_config.sql +8 -0
- package/migrations/0005_add_message_id.sql +12 -0
- package/migrations/0006_add_reply_to_message_id.sql +12 -0
- package/migrations/0007_create_world_chats.sql +35 -0
- package/migrations/0008_create_events_table.sql +78 -0
- package/migrations/0009_add_event_sequences.sql +40 -0
- package/migrations/0010_add_tool_call_fields.sql +27 -0
- package/migrations/0011_add_event_metadata_indexes.sql +79 -0
- package/migrations/0012_add_tool_role.sql +78 -0
- package/migrations/0013_add_world_variables.sql +7 -0
- package/migrations/0014_add_main_agent_and_auto_reply.sql +10 -0
- package/package.json +5 -5
- package/dist/public/assets/index-DOQEHGWt.js +0 -96
|
@@ -1,96 +0,0 @@
|
|
|
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 Lr="3.38.0",Ss=`AppRun-${Lr}`;class $r{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 As=Ss;let Ot;const tt=typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};tt.app&&tt._AppRunVersions?Ot=tt.app:(Ot=new $r,tt.app=Ot,tt._AppRunVersions=As);const M=Ot;function _e(t){return t?.target instanceof HTMLElement?t.target:null}function Ts(t,e=document){try{return e.querySelector(t)}catch(n){return console.warn(`Invalid selector: ${t}`,n),null}}function Es(t){try{return document.getElementById(t)}catch(e){return console.warn(`Error getting element by id: ${t}`,e),null}}const Dr=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},Ns=(t,e)=>{let n=t;for(const r of e){if(n==null)return;n=n[r]}return n},Is=(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},Me=(t,e)=>{if(!e)return t.state||"";const n=Dr(e),r=Ns(t.state,n);return r!==void 0?r:""},Re=(t,e,n)=>{if(!e){t.setState(n);return}const r=Dr(e),s=t.state||{},o=Is(s,r,n);t.setState(o)},Cs=(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):M.run(t,o);else if(typeof s=="string")e[t]=o=>r.run?r.run(s,o):M.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):M.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=Me(r,o),e.onclick=a=>{const i=_e(a);i&&Re(r,o||i.name,i.checked)};break;case"radio":e.checked=Me(r,o)===e.value,e.onclick=a=>{const i=_e(a);i&&Re(r,o||i.name,i.value)};break;case"number":case"range":e.value=Me(r,o),e.oninput=a=>{const i=_e(a);i&&Re(r,o||i.name,Number(i.value))};break;default:e.value=Me(r,o),e.oninput=a=>{const i=_e(a);i&&Re(r,o||i.name,i.value)}}else n==="select"?(e.value=Me(r,o),e.onchange=a=>{const i=_e(a);i&&!i.multiple&&Re(r,o||i.name,i.value)}):n==="option"?(e.selected=Me(r,o),e.onclick=a=>{const i=_e(a);i&&Re(r,o||i.name,i.selected)}):n==="textarea"&&(e.innerHTML=Me(r,o),e.oninput=a=>{const i=_e(a);i&&Re(r,o||i.name,i.value)})}else M.run("$",{key:t,tag:n,props:e,component:r})},Ft=(t,e)=>{if(Array.isArray(t))return t.map(n=>Ft(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("$")&&(Cs(a,s,r,e),delete s[a])}),o&&Ft(o,e),t}};class ft{constructor(e,n,r){this.normal=n,this.property=e,r&&(this.space=r)}}ft.prototype.normal={};ft.prototype.property={};ft.prototype.space=void 0;function Or(t,e){const n={},r={};for(const s of t)Object.assign(n,s.property),Object.assign(r,s.normal);return new ft(n,r,e)}function bn(t){return t.toLowerCase()}class se{constructor(e,n){this.attribute=n,this.property=e}}se.prototype.attribute="";se.prototype.booleanish=!1;se.prototype.boolean=!1;se.prototype.commaOrSpaceSeparated=!1;se.prototype.commaSeparated=!1;se.prototype.defined=!1;se.prototype.mustUseProperty=!1;se.prototype.number=!1;se.prototype.overloadedBoolean=!1;se.prototype.property="";se.prototype.spaceSeparated=!1;se.prototype.space=void 0;let _s=0;const v=De(),z=De(),wn=De(),g=De(),R=De(),Ge=De(),le=De();function De(){return 2**++_s}const xn=Object.freeze(Object.defineProperty({__proto__:null,boolean:v,booleanish:z,commaOrSpaceSeparated:le,commaSeparated:Ge,number:g,overloadedBoolean:wn,spaceSeparated:R},Symbol.toStringTag,{value:"Module"})),cn=Object.keys(xn);class Rn extends se{constructor(e,n,r,s){let o=-1;if(super(e,n),rr(this,"space",s),typeof r=="number")for(;++o<cn.length;){const a=cn[o];rr(this,cn[o],(r&xn[a])===xn[a])}}}Rn.prototype.defined=!0;function rr(t,e,n){n&&(t[e]=n)}function Ve(t){const e={},n={};for(const[r,s]of Object.entries(t.properties)){const o=new Rn(r,t.transform(t.attributes||{},r),s,t.space);t.mustUseProperty&&t.mustUseProperty.includes(r)&&(o.mustUseProperty=!0),e[r]=o,n[bn(r)]=r,n[bn(o.attribute)]=r}return new ft(e,n,t.space)}const Pr=Ve({properties:{ariaActiveDescendant:null,ariaAtomic:z,ariaAutoComplete:null,ariaBusy:z,ariaChecked:z,ariaColCount:g,ariaColIndex:g,ariaColSpan:g,ariaControls:R,ariaCurrent:null,ariaDescribedBy:R,ariaDetails:null,ariaDisabled:z,ariaDropEffect:R,ariaErrorMessage:null,ariaExpanded:z,ariaFlowTo:R,ariaGrabbed:z,ariaHasPopup:null,ariaHidden:z,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:R,ariaLevel:g,ariaLive:null,ariaModal:z,ariaMultiLine:z,ariaMultiSelectable:z,ariaOrientation:null,ariaOwns:R,ariaPlaceholder:null,ariaPosInSet:g,ariaPressed:z,ariaReadOnly:z,ariaRelevant:null,ariaRequired:z,ariaRoleDescription:R,ariaRowCount:g,ariaRowIndex:g,ariaRowSpan:g,ariaSelected:z,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 Wr(t,e){return e in t?t[e]:e}function Ur(t,e){return Wr(t,e.toLowerCase())}const Ms=Ve({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Ge,acceptCharset:R,accessKey:R,action:null,allow:null,allowFullScreen:v,allowPaymentRequest:v,allowUserMedia:v,alt:null,as:null,async:v,autoCapitalize:null,autoComplete:R,autoFocus:v,autoPlay:v,blocking:R,capture:null,charSet:null,checked:v,cite:null,className:R,cols:g,colSpan:null,content:null,contentEditable:z,controls:v,controlsList:R,coords:g|Ge,crossOrigin:null,data:null,dateTime:null,decoding:null,default:v,defer:v,dir:null,dirName:null,disabled:v,download:wn,draggable:z,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:v,formTarget:null,headers:R,height:g,hidden:wn,high:g,href:null,hrefLang:null,htmlFor:R,httpEquiv:R,id:null,imageSizes:null,imageSrcSet:null,inert:v,inputMode:null,integrity:null,is:null,isMap:v,itemId:null,itemProp:R,itemRef:R,itemScope:v,itemType:R,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:R,placeholder:null,playsInline:v,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:v,referrerPolicy:null,rel:R,required:v,reversed:v,rows:g,rowSpan:g,sandbox:R,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:z,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:z,width:g,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:R,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:z,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:Ur}),Rs=Ve({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:le,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:R,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:Ge,g2:Ge,glyphName:Ge,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:le,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:R,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:g,pointsAtY:g,pointsAtZ:g,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:le,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:le,rev:le,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:le,requiredFeatures:le,requiredFonts:le,requiredFormats:le,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:le,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:le,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:le,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:Wr}),Fr=Ve({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()}}),zr=Ve({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Ur}),Hr=Ve({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(t,e){return"xml:"+e.slice(3).toLowerCase()}}),Ls=/[A-Z]/g,sr=/-[a-z]/g,$s=/^data[-\w.:]+$/i;function Ds(t,e){const n=bn(e);let r=e,s=se;if(n in t.normal)return t.property[t.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&$s.test(e)){if(e.charAt(4)==="-"){const o=e.slice(5).replace(sr,Ps);r="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=e.slice(4);if(!sr.test(o)){let a=o.replace(Ls,Os);a.charAt(0)!=="-"&&(a="-"+a),e="data"+a}}s=Rn}return new s(r,e)}function Os(t){return"-"+t.toLowerCase()}function Ps(t){return t.charAt(1).toUpperCase()}const Ws=Or([Pr,Ms,Fr,zr,Hr],"html"),Us=Or([Pr,Rs,Fr,zr,Hr],"svg"),or="_props",lr=new Map;function Fs(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 zs(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 Hs(t,e){const n=`${t}:${e}`;let r=lr.get(n);return r===void 0&&(r=Ds(e?Us:Ws,t)||null,lr.set(n,r)),r}function Bs(t,e,n){const r=zs(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){qs(n)?t.setAttribute(e,e):t.removeAttribute(e)}function _t(t,e,n){try{t[e]=n}catch{Pt(t,e,n,!1)}}function Pt(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 qs(t){return t==null||t===!1||t===""?!1:t===!0?!0:typeof t=="string"?t.toLowerCase()!=="false"&&t!=="0":!!t}function Gs(t,e,n,r){if(Vs(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-")){Bs(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=Hs(e,r);s?s.boolean||s.overloadedBoolean?ar(t,s.attribute,n):s.mustUseProperty&&!r?_t(t,s.property,n):Pt(t,s.attribute,n,r):e.startsWith("aria-")||e==="role"?Pt(t,e,n,r):e in t||t[e]!==void 0?_t(t,e,n):Pt(t,e,n,r)}function Vs(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 Ys(t){return/^[a-zA-Z_:][\w\-:.]*$/.test(t)&&!t.includes("<")&&!t.includes(">")&&!t.includes('"')&&!t.includes("'")}function Ln(t,e,n){const r=t[or]||{},s=Fs(r,e);t[or]=e||{},Xs(t,s,e,n)}function Xs(t,e,n,r){for(const s in e)Ys(s)&&Gs(t,s,e[s],r);e&&typeof e.ref=="function"&&window.requestAnimationFrame(()=>e.ref(t))}function Zs(t,...e){return Br(e)}function Br(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 pt={};let ir=0;const Ks=500,Qs=1e3;function Js(){if(!(Object.keys(pt).length<=Qs))for(const[t,e]of Object.entries(pt))e.isConnected||delete pt[t]}function eo(t,e,...n){const r=Br(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 to=(t,e,n={})=>{if(e==null||e===!1)return;const r=typeof t=="string"&&t?document.getElementById(t)||document.querySelector(t):t;e=Ft(e,n),no(r,e,n)};function no(t,e,n={}){if(e==null||e===!1||(e=Wt(e,n),!t))return;const r=t.nodeName==="SVG";Array.isArray(e)?kn(t,e,r):kn(t,[e],r)}function ro(t,e){const n=t.nodeName,r=`${e.tag||""}`;return n.toUpperCase()===r.toUpperCase()}function un(t,e,n){if(n=n||e.tag==="svg",!ro(t,e)){t.parentNode.replaceChild(Ht(e,n),t);return}kn(t,e.children,n),Ln(t,e.props,n)}function kn(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],h=t.childNodes[i];if(typeof c=="string")h.textContent!==c&&(h.nodeType===3?h.nodeValue=c:t.replaceChild(vn(c),h));else if(c instanceof HTMLElement||c instanceof SVGElement)t.insertBefore(c,h);else{const d=c.props&&c.props.key;if(d)if(h.key===d)un(t.childNodes[i],c,n);else{const y=pt[d];y?(t.insertBefore(y,h),un(t.childNodes[i],c,n)):t.replaceChild(Ht(c,n),h)}else un(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(Ht(e[c],n));t.appendChild(i)}}const zt=t=>{const e=document.createElement("section");return e.insertAdjacentHTML("afterbegin",t),Array.from(e.children)};function vn(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 Ht(t,e){if(t instanceof HTMLElement||t instanceof SVGElement)return t;if(typeof t=="string")return vn(t);if(!t.tag||typeof t.tag=="function")return vn(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 Ln(n,t.props,e),t.children&&t.children.forEach(r=>n.appendChild(Ht(r,e))),t.props&&t.props.key!==void 0&&(n.key=t.props.key,pt[t.props.key]=n,++ir>=Ks&&(Js(),ir=0)),n}function so(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 h=e.__componentCache[a];if(!h||!(h instanceof r)||!h.element){const d=document.createElement(c);h=e.__componentCache[a]=new r({...s,children:o}).mount(d,{render:!0})}else h.renderState(h.state);if(h.mounted){const d=h.mounted(s,o,h.state);typeof d<"u"&&h.setState(d)}return Ln(h.element,s,!1),h.element}function Wt(t,e,n=0){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(s=>Wt(s,e,n++));let r=t;if(t&&typeof t.tag=="function"&&Object.getPrototypeOf(t.tag).__isAppRunComponent&&(r=so(t,e,n)),r&&Array.isArray(r.children)){const s=r.props?._component;if(s){let o=0;r.children=r.children.map(a=>Wt(a,s,o++))}else r.children=r.children.map(o=>Wt(o,e,n++))}return r}const oo=(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 h=c.toLowerCase();return h!==c&&(i[h]=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,oo(e,n))},Sn={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 lo(t,e={}){return function(n,r){const s=t?t.toString():r;Sn.defineMetadata(`apprun-update:${s}`,{name:s,key:r,options:e},n)}}function ao(t,e){return function(r){return jr(t,r,e),r}}const cr=t=>t,V=M;class Le{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?Es(this.element)||Ts(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=Ft(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 $r,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||{};Sn.getMetadataKeys(this).forEach(r=>{if(r.startsWith("apprun-update:")){const s=Sn.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)})}}Le.__isAppRunComponent=!0;function io(t){return t?t.startsWith("#/")?t.substring(2).split("/"):t.startsWith("#")||t.startsWith("/")?t.substring(1).split("/"):t.split("/"):[]}function co(t){return!t||t==="/"||t==="#"||t==="#/"?t:t.endsWith("/")?t.slice(0,-1):t}function uo(t){const e=t.filter(Boolean);e.length>11&&console.warn(`Deep route hierarchy detected: ${e.join("/")} (${e.length} levels)`)}function ho(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 po(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 go(t,e){for(let n=0;n<t.length;n++){const r=t[n],s=M.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=M.find("#");if(t&&t.length>0){M.run("#"),M.run(Ee,"#");return}const e=M.find("/");if(e&&e.length>0){M.run("/"),M.run(Ee,"/");return}const n=M.find("#/");if(n&&n.length>0){M.run("#/"),M.run(Ee,"#/");return}console.warn("No subscribers for event: "),M.run(mt,""),M.run(Ee,"")}function mo(t){if(!t){ur();return}t=co(t);const e=M.basePath;e&&(t=ho(t,e));const n=io(t);uo(n);let r;t.startsWith("#/")?r="hash-slash":t.startsWith("#")?r="hash":t.startsWith("/")?r="path":r="non-prefixed";const s=po(n,r),o=go(s,n);if(o)fo(o.eventName,...o.parameters);else if(s.length>0){const a=s[s.length-1];console.warn(`No subscribers for event: ${a}`),M.run(mt,t),M.run(Ee,t)}else ur()}const fo=(t,...e)=>{if(!t||t===Ee||t===mt)return;const n=M.find(t);!n||n.length===0?(console.warn(`No subscribers for event: ${t}`),M.run(mt,t,...e)):M.run(t,...e),M.run(Ee,t,...e)},Ee="//",mt="///",qe=t=>{M.lastUrl!==t&&(M.lastUrl=t,mo(t))};function dr(t){return t&&typeof t=="object"&&typeof t.mount=="function"}function An(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 qr(t){return typeof t=="function"&&!An(t)}async function yo(t,e=3){let n=t,r=0;for(;qr(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 bo=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(An(r)){const s=new r,o={route:n};s.mount(t,o);continue}if(qr(r)){let s=await yo(r);if(dr(s)){const o={route:n};s.mount(t,o);continue}if(An(s)){const o=new s,a={route:n};o.mount(t,a);continue}M.on(n,(...o)=>{const a=r(...o);if(typeof t=="string"&&(t=document.querySelector(t),!t)){console.error(`Element not found: ${t}`);return}return M.render(t,a)});continue}console.error("Invalid component: component must be a class, instance, or function that returns a class/instance")}},l=M;if(!l.start){l.version=Lr,l.h=l.createElement=eo,l.render=to,l.Fragment=Zs,l.webComponent=jr,l.safeHTML=zt,l.start=(e,n,r,s,o)=>{const a={render:!0,global_event:!0,...o},i=new Le(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(Ee,t),l.on(mt,t),l.route=qe,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",()=>qe(location.hash)),window.addEventListener("popstate",()=>qe(location.pathname)),n?!e&&qe(location.hash):(!e&&(()=>{const r=l.basePath||"";let s=location.pathname;r&&s.startsWith(r)&&(s=s.substring(r.length),s.startsWith("/")||(s="/"+s)),qe(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),qe(o.pathname)}}))}),typeof window=="object"){const e=window;e.Component=Le,e._React=e.React,e.React=l,e.on=lo,e.customElement=ao,e.safeHTML=zt}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=bo}const wo=()=>l.h("div",{id:"main",className:"w-full min-h-screen"},l.h("div",{id:"pages"})),xo="/api";async function W(t,e={}){const n=`${xo}${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 ko(){return(await W("/worlds")).json()}async function vo(t){if(!t)throw new Error("World name is required");return(await W(`/worlds/${encodeURIComponent(t)}`)).json()}async function So(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 W("/worlds",{method:"POST",body:JSON.stringify(e)})).json()}async function Ao(t,e){if(!t||!e)throw new Error("World name and update data are required");return(await W(`/worlds/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(e)})).json()}async function To(t){if(!t)throw new Error("World name is required");await W(`/worlds/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Eo(t,e){if(!t||!e)throw new Error("World name and agent data are required");return(await W(`/worlds/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(e)})).json()}async function No(t,e,n){if(!t||!e||!n)throw new Error("World name, agent name, and update data are required");return(await W(`/worlds/${encodeURIComponent(t)}/agents/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})).json()}async function Io(t,e){if(!t||!e)throw new Error("World name and agent name are required");await W(`/worlds/${encodeURIComponent(t)}/agents/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Co(t,e){if(!t||!e)throw new Error("World name and agent name are required");await W(`/worlds/${encodeURIComponent(t)}/agents/${encodeURIComponent(e)}/memory`,{method:"DELETE"})}async function _o(t){if(!t)throw new Error("World name is required");const e=await W(`/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 Mo(t){if(!t)throw new Error("World name is required");return(await W(`/worlds/${encodeURIComponent(t)}/export`)).text()}async function Ro(t,e){return await(await W(`/worlds/${encodeURIComponent(t)}/setChat/${encodeURIComponent(e)}`,{method:"POST"})).json()}async function Lo(t,e){if(!t||!e)throw new Error("World name and chat ID are required");await W(`/worlds/${encodeURIComponent(t)}/chats/${encodeURIComponent(e)}`,{method:"DELETE"})}async function $o(t){if(!t)throw new Error("World name is required");return await(await W(`/worlds/${encodeURIComponent(t)}/chats`,{method:"POST"})).json()}async function Do(t,e,n){if(!t||!e||!n)throw new Error("World name, message ID, and chat ID are required");return(await W(`/worlds/${encodeURIComponent(t)}/messages/${encodeURIComponent(e)}`,{method:"DELETE",body:JSON.stringify({chatId:n})})).json()}async function Oo(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 W(`/worlds/${encodeURIComponent(t)}/messages/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify({chatId:r,newContent:n,stream:!1})})).json()}async function Po(t,e,n,r){if(!t||!e||!n)throw new Error("World name, request ID, and option ID are required");return(await W(`/worlds/${encodeURIComponent(t)}/hitl/respond`,{method:"POST",body:JSON.stringify({requestId:e,optionId:n,chatId:r??null})})).json()}async function Wo(t,e,n="human"){if(!t||!e?.trim())throw new Error("World name and non-empty message are required");return W(`/worlds/${encodeURIComponent(t)}/messages`,{method:"POST",body:JSON.stringify({message:e,sender:n})})}async function Uo(t,e){if(!t||!e)throw new Error("World name and chat ID are required");return(await W(`/worlds/${encodeURIComponent(t)}/messages/stop`,{method:"POST",body:JSON.stringify({chatId:e})})).json()}const H={apiRequest:W,getWorlds:ko,getWorld:vo,createWorld:So,updateWorld:Ao,deleteWorld:To,exportWorldToMarkdown:_o,getWorldMarkdown:Mo,createAgent:Eo,updateAgent:No,deleteAgent:Io,clearAgentMemory:Co,setChat:Ro,deleteChat:Lo,newChat:$o,deleteMessage:Do,editMessage:Oo,respondHitlOption:Po,stopMessageProcessing:Uo,sendMessage:Wo};function Gt(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 Gr(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 Fo=t=>({mode:t.mode||"create",world:{...Vr(),...t.world||{}},parentComponent:t.parentComponent,loading:!1,error:null,errorDetails:null}),Vr=()=>({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 H.createWorld(t.world):await H.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=Gt(e);yield{...t,loading:!1,error:n.message,errorDetails:n.details||null}}},pr=async function*(t){yield{...t,loading:!0,error:null};try{await H.deleteWorld(t.world.name),yield{...t,loading:!1,successMessage:"World deleted successfully!"},setTimeout(()=>{location.reload()},2e3)}catch(e){const n=Gt(e);yield{...t,loading:!1,error:n.message,errorDetails:n.details||null}}},nt=t=>{t?.parentComponent&&typeof t.parentComponent.run=="function"?t.parentComponent.run("close-world-edit"):l.run("close-world-edit")};class Yr extends Le{mounted=e=>Fo(e);state={mode:"create",world:Vr(),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:nt,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:nt,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"},Gr(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:nt,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:nt,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:nt,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 zo extends Le{state=async()=>{try{return{worlds:await H.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(Yr,{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 re(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 rt(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 $n(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Oe=$n();function Xr(t){Oe=t}var gt={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(J.caret,"$1"),n=n.replace(s,a),r},getRegex:()=>new RegExp(n,e)};return r}var Ho=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),J={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")},Bo=/^(?:[ \t]*(?:\n|$))+/,jo=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,qo=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,yt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Go=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Dn=/(?:[*+-]|\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,Dn).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(),Vo=I(Zr).replace(/bull/g,Dn).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(),On=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Yo=/^[^\n]+/,Pn=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Xo=I(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Pn).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Zo=I(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Dn).getRegex(),Vt="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",Wn=/<!--(?:-?>|[\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",Wn).replace("tag",Vt).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Qr=I(On).replace("hr",yt).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",Vt).getRegex(),Qo=I(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Qr).getRegex(),Un={blockquote:Qo,code:jo,def:Xo,fences:qo,heading:Go,hr:yt,html:Ko,lheading:Kr,list:Zo,newline:Bo,paragraph:Qr,table:gt,text:Yo},gr=I("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",yt).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",Vt).getRegex(),Jo={...Un,lheading:Vo,table:gr,paragraph:I(On).replace("hr",yt).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",Vt).getRegex()},el={...Un,html:I(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Wn).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:gt,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:I(On).replace("hr",yt).replace("heading",` *#{1,6} *[^
|
|
2
|
-
]`).replace("lheading",Kr).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},tl=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,nl=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Jr=/^( {2,}|\\)\n(?!\s*$)/,rl=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Yt=/[\p{P}\p{S}]/u,Fn=/[\s\p{P}\p{S}]/u,es=/[^\s\p{P}\p{S}]/u,sl=I(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Fn).getRegex(),ts=/(?!~)[\p{P}\p{S}]/u,ol=/(?!~)[\s\p{P}\p{S}]/u,ll=/(?:[^\s\p{P}\p{S}]|~)/u,al=I(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Ho?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),ns=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,il=I(ns,"u").replace(/punct/g,Yt).getRegex(),cl=I(ns,"u").replace(/punct/g,ts).getRegex(),rs="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",ul=I(rs,"gu").replace(/notPunctSpace/g,es).replace(/punctSpace/g,Fn).replace(/punct/g,Yt).getRegex(),dl=I(rs,"gu").replace(/notPunctSpace/g,ll).replace(/punctSpace/g,ol).replace(/punct/g,ts).getRegex(),hl=I("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,es).replace(/punctSpace/g,Fn).replace(/punct/g,Yt).getRegex(),pl=I(/\\(punct)/,"gu").replace(/punct/g,Yt).getRegex(),gl=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(),ml=I(Wn).replace("(?:-->|$)","-->").getRegex(),fl=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",ml).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Bt=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,yl=I(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",Bt).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ss=I(/^!?\[(label)\]\[(ref)\]/).replace("label",Bt).replace("ref",Pn).getRegex(),os=I(/^!?\[(ref)\](?:\[\])?/).replace("ref",Pn).getRegex(),bl=I("reflink|nolink(?!\\()","g").replace("reflink",ss).replace("nolink",os).getRegex(),mr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,zn={_backpedal:gt,anyPunctuation:pl,autolink:gl,blockSkip:al,br:Jr,code:nl,del:gt,emStrongLDelim:il,emStrongRDelimAst:ul,emStrongRDelimUnd:hl,escape:tl,link:yl,nolink:os,punctuation:sl,reflink:ss,reflinkSearch:bl,tag:fl,text:rl,url:gt},wl={...zn,link:I(/^!?\[(label)\]\((.*?)\)/).replace("label",Bt).getRegex(),reflink:I(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Bt).getRegex()},Tn={...zn,emStrongRDelimAst:dl,emStrongLDelim:cl,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()},xl={...Tn,br:I(Jr).replace("{2,}","*").getRegex(),text:I(Tn.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Mt={normal:Un,gfm:Jo,pedantic:el},st={normal:zn,gfm:Tn,breaks:xl,pedantic:wl},kl={"&":"&","<":"<",">":">",'"':""","'":"'"},fr=t=>kl[t];function ke(t,e){if(e){if(J.escapeTest.test(t))return t.replace(J.escapeReplace,fr)}else if(J.escapeTestNoEncode.test(t))return t.replace(J.escapeReplaceNoEncode,fr);return t}function yr(t){try{t=encodeURI(t).replace(J.percentDecode,"%")}catch{return null}return t}function br(t,e){let n=t.replace(J.findPipe,(o,a,i)=>{let c=!1,h=a;for(;--h>=0&&i[h]==="\\";)c=!c;return c?"|":" |"}),r=n.split(J.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(J.slashPipe,"|");return r}function ot(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 vl(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 Sl(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 jt=class{options;rules;lexer;constructor(t){this.options=t||Oe}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:ot(n,`
|
|
5
|
-
`)}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let n=e[0],r=Sl(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=ot(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:ot(e[0],`
|
|
6
|
-
`)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=ot(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 h=i.join(`
|
|
9
|
-
`),d=h.replace(this.rules.other.blockquoteSetextReplace,`
|
|
10
|
-
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}
|
|
11
|
-
${h}`:h,s=s?`${s}
|
|
12
|
-
${d}`:d;let y=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(d,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,h="",d="";if(!(e=o.exec(t))||this.rules.block.hr.test(t))break;h=e[0],t=t.substring(h.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,d=y.trimStart()):S?b=e[1].length+1:(b=e[2].search(this.rules.other.nonSpaceChar),b=b>4?1:b,d=y.slice(b),b+=e[1].length),S&&this.rules.other.blankLine.test(k)&&(h+=k+`
|
|
20
|
-
`,t=t.substring(k.length+1),c=!0),!c){let E=this.rules.other.nextBulletRegex(b),Z=this.rules.other.hrRegex(b),q=this.rules.other.fencesBeginRegex(b),D=this.rules.other.headingBeginRegex(b),he=this.rules.other.htmlBeginRegex(b);for(;t;){let O=t.split(`
|
|
21
|
-
`,1)[0],oe;if(k=O,this.options.pedantic?(k=k.replace(this.rules.other.listReplaceNesting," "),oe=k):oe=k.replace(this.rules.other.tabCharGlobal," "),q.test(k)||D.test(k)||he.test(k)||E.test(k)||Z.test(k))break;if(oe.search(this.rules.other.nonSpaceChar)>=b||!k.trim())d+=`
|
|
22
|
-
`+oe.slice(b);else{if(S||y.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||q.test(y)||D.test(y)||Z.test(y))break;d+=`
|
|
23
|
-
`+k}!S&&!k.trim()&&(S=!0),h+=O+`
|
|
24
|
-
`,t=t.substring(O.length+1),y=oe.slice(b)}}s.loose||(a?s.loose=!0:this.rules.other.doubleBlankLine.test(h)&&(a=!0)),s.items.push({type:"list_item",raw:h,task:!!this.options.gfm&&this.rules.other.listIsTask.test(d),loose:!1,text:d,tokens:[]}),s.raw+=h}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 d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}}let h=this.rules.other.listTaskCheckbox.exec(c.raw);if(h){let d={type:"checkbox",raw:h[0]+" ",checked:h[0]!=="[ ]"};c.checked=d.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=d.raw+c.tokens[0].raw,c.tokens[0].text=d.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(d)):c.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):c.tokens.unshift(d)}}if(!s.loose){let h=c.tokens.filter(y=>y.type==="space"),d=h.length>0&&h.some(y=>this.rules.other.anyLine.test(y.raw));s.loose=d}}if(s.loose)for(let c of s.items){c.loose=!0;for(let h of c.tokens)h.type==="text"&&(h.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=ot(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=vl(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,h=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(h.lastIndex=0,e=e.slice(-1*t.length+s);(r=h.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 d=[...r[0]][0].length,y=t.slice(0,s+r.index+d+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}}}},ue=class En{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Oe,this.options.tokenizer=this.options.tokenizer||new jt,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:J,block:Mt.normal,inline:st.normal};this.options.pedantic?(n.block=Mt.pedantic,n.inline=st.pedantic):this.options.gfm&&(n.block=Mt.gfm,this.options.breaks?n.inline=st.breaks:n.inline=st.gfm),this.tokenizer.rules=n}static get rules(){return{block:Mt,inline:st}}static lex(e,n){return new En(n).lex(e)}static lexInline(e,n){return new En(n).inlineTokens(e)}lex(e){e=e.replace(J.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(J.tabCharGlobal," ").replace(J.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(h=>{c=h.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(d=>(c=d.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 d=n.at(-1);c.type==="text"&&d?.type==="text"?(d.raw+=c.raw,d.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 h=e;if(this.options.extensions?.startInline){let d=1/0,y=e.slice(1),k;this.options.extensions.startInline.forEach(S=>{k=S.call({lexer:this},y),typeof k=="number"&&k>=0&&(d=Math.min(d,k))}),d<1/0&&d>=0&&(h=e.substring(0,d+1))}if(c=this.tokenizer.inlineText(h)){e=e.substring(c.raw.length),c.raw.slice(-1)!=="_"&&(i=c.raw.slice(-1)),a=!0;let d=n.at(-1);d?.type==="text"?(d.raw+=c.raw,d.text+=c.text):n.push(c);continue}if(e){let d="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(d);break}else throw new Error(d)}}return n}},qt=class{options;parser;constructor(t){this.options=t||Oe}space(t){return""}code({text:t,lang:e,escaped:n}){let r=(e||"").match(J.notSpaceStart)?.[0],s=t.replace(J.endingNewline,"")+`
|
|
41
|
-
`;return r?'<pre><code class="language-'+ke(r)+'">'+(n?s:ke(s,!0))+`</code></pre>
|
|
42
|
-
`:"<pre><code>"+(n?s:ke(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>${ke(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="'+ke(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 ke(n);t=s;let o=`<img src="${t}" alt="${n}"`;return e&&(o+=` title="${ke(e)}"`),o+=">",o}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:ke(t.text)}},Hn=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}},de=class Nn{options;renderer;textRenderer;constructor(e){this.options=e||Oe,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 Hn}static parse(e,n){return new Nn(n).parse(e)}static parseInline(e,n){return new Nn(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}},ht=class{options;block;constructor(t){this.options=t||Oe}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?ue.lex:ue.lexInline}provideParser(){return this.block?de.parse:de.parseInline}},Al=class{defaults=$n();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=de;Renderer=qt;TextRenderer=Hn;Lexer=ue;Tokenizer=jt;Hooks=ht;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]=(...h)=>{let d=i.apply(s,h);return d===!1&&(d=c.apply(s,h)),d||""}}r.renderer=s}if(n.tokenizer){let s=this.defaults.tokenizer||new jt(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]=(...h)=>{let d=i.apply(s,h);return d===!1&&(d=c.apply(s,h)),d}}r.tokenizer=s}if(n.hooks){let s=this.defaults.hooks||new ht;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];ht.passThroughHooks.has(o)?s[a]=h=>{if(this.defaults.async&&ht.passThroughHooksRespectAsync.has(o))return(async()=>{let y=await i.call(s,h);return c.call(s,y)})();let d=i.call(s,h);return c.call(s,d)}:s[a]=(...h)=>{if(this.defaults.async)return(async()=>{let y=await i.apply(s,h);return y===!1&&(y=await c.apply(s,h)),y})();let d=i.apply(s,h);return d===!1&&(d=c.apply(s,h)),d}}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 ue.lex(t,e??this.defaults)}parser(t,e){return de.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?ue.lex:ue.lexInline)(a,s),c=s.hooks?await s.hooks.processAllTokens(i):i;s.walkTokens&&await Promise.all(this.walkTokens(c,s.walkTokens));let h=await(s.hooks?await s.hooks.provideParser():t?de.parse:de.parseInline)(c,s);return s.hooks?await s.hooks.postprocess(h):h})().catch(o);try{s.hooks&&(e=s.hooks.preprocess(e));let a=(s.hooks?s.hooks.provideLexer():t?ue.lex:ue.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?de.parse:de.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>"+ke(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},$e=new Al;function C(t,e){return $e.parse(t,e)}C.options=C.setOptions=function(t){return $e.setOptions(t),C.defaults=$e.defaults,Xr(C.defaults),C};C.getDefaults=$n;C.defaults=Oe;C.use=function(...t){return $e.use(...t),C.defaults=$e.defaults,Xr(C.defaults),C};C.walkTokens=function(t,e){return $e.walkTokens(t,e)};C.parseInline=$e.parseInline;C.Parser=de;C.parser=de.parse;C.Renderer=qt;C.TextRenderer=Hn;C.Lexer=ue;C.lexer=ue.lex;C.Tokenizer=jt;C.Hooks=ht;C.parse=C;C.options;C.setOptions;C.use;C.walkTokens;C.parseInline;de.parse;ue.lex;const{entries:ls,setPrototypeOf:xr,isFrozen:Tl,getPrototypeOf:El,getOwnPropertyDescriptor:Nl}=Object;let{freeze:ee,seal:ie,create:In}=Object,{apply:Cn,construct:_n}=typeof Reflect<"u"&&Reflect;ee||(ee=function(e){return e});ie||(ie=function(e){return e});Cn||(Cn=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)});_n||(_n=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 Rt=te(Array.prototype.forEach),Il=te(Array.prototype.lastIndexOf),kr=te(Array.prototype.pop),lt=te(Array.prototype.push),Cl=te(Array.prototype.splice),Ut=te(String.prototype.toLowerCase),dn=te(String.prototype.toString),hn=te(String.prototype.match),at=te(String.prototype.replace),_l=te(String.prototype.indexOf),Ml=te(String.prototype.trim),ce=te(Object.prototype.hasOwnProperty),Q=te(RegExp.prototype.test),it=Rl(TypeError);function te(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 Cn(t,e,r)}}function Rl(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return _n(t,n)}}function A(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ut;xr&&xr(t,null);let r=e.length;for(;r--;){let s=e[r];if(typeof s=="string"){const o=n(s);o!==s&&(Tl(e)||(e[r]=o),s=o)}t[s]=!0}return t}function Ll(t){for(let e=0;e<t.length;e++)ce(t,e)||(t[e]=null);return t}function ge(t){const e=In(null);for(const[n,r]of ls(t))ce(t,n)&&(Array.isArray(r)?e[n]=Ll(r):r&&typeof r=="object"&&r.constructor===Object?e[n]=ge(r):e[n]=r);return e}function ct(t,e){for(;t!==null;){const r=Nl(t,e);if(r){if(r.get)return te(r.get);if(typeof r.value=="function")return te(r.value)}t=El(t)}function n(){return null}return n}const vr=ee(["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"]),pn=ee(["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"]),gn=ee(["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"]),$l=ee(["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"]),mn=ee(["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"]),Dl=ee(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Sr=ee(["#text"]),Ar=ee(["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"]),fn=ee(["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=ee(["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"]),Lt=ee(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Ol=ie(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Pl=ie(/<%[\w\W]*|[\w\W]*%>/gm),Wl=ie(/\$\{[\w\W]*/gm),Ul=ie(/^data-[\-\w.\u00B7-\uFFFF]+$/),Fl=ie(/^aria-[\-\w]+$/),as=ie(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),zl=ie(/^(?:\w+script|data):/i),Hl=ie(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),is=ie(/^html$/i),Bl=ie(/^[a-z][.\w]*(-[.\w]+)+$/i);var Er=Object.freeze({__proto__:null,ARIA_ATTR:Fl,ATTR_WHITESPACE:Hl,CUSTOM_ELEMENT:Bl,DATA_ATTR:Ul,DOCTYPE_NAME:is,ERB_EXPR:Pl,IS_ALLOWED_URI:as,IS_SCRIPT_OR_DATA:zl,MUSTACHE_EXPR:Ol,TMPLIT_EXPR:Wl});const ut={element:1,text:3,progressingInstruction:7,comment:8,document:9},jl=function(){return typeof window>"u"?null:window},ql=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 cs(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:jl();const e=w=>cs(w);if(e.version="3.3.1",e.removed=[],!t||!t.document||t.document.nodeType!==ut.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:h,NamedNodeMap:d=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:y,DOMParser:k,trustedTypes:S}=t,b=c.prototype,E=ct(b,"cloneNode"),Z=ct(b,"remove"),q=ct(b,"nextSibling"),D=ct(b,"childNodes"),he=ct(b,"parentNode");if(typeof a=="function"){const w=n.createElement("template");w.content&&w.content.ownerDocument&&(n=w.content.ownerDocument)}let O,oe="";const{implementation:Pe,createNodeIterator:Xt,createDocumentFragment:Zt,getElementsByTagName:Kt}=n,{importNode:Qt}=r;let P=Nr();e.isSupported=typeof ls=="function"&&typeof he=="function"&&Pe&&Pe.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:me,ERB_EXPR:Ye,TMPLIT_EXPR:Xe,DATA_ATTR:Jt,ARIA_ATTR:bt,IS_SCRIPT_OR_DATA:ve,ATTR_WHITESPACE:wt,CUSTOM_ELEMENT:en}=Er;let{IS_ALLOWED_URI:xt}=Er,p=null;const N=A({},[...vr,...pn,...gn,...mn,...Sr]);let x=null;const _=A({},[...Ar,...fn,...Tr,...Lt]);let T=Object.seal(In(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}})),ae=null,We=null;const Se=Object.seal(In(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let kt=!0,Ne=!0,vt=!1,St=!0,Ae=!1,Ue=!0,fe=!1,Ze=!1,Ke=!1,Te=!1,Fe=!1,ze=!1,Qe=!0,At=!1;const Tt="user-content-";let Je=!0,Ie=!1,B={},L=null;const ye=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 tn=null;const Bn=A({},["audio","video","img","source","image","track"]);let nn=null;const jn=A({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Et="http://www.w3.org/1998/Math/MathML",Nt="http://www.w3.org/2000/svg",be="http://www.w3.org/1999/xhtml";let He=be,rn=!1,sn=null;const fs=A({},[Et,Nt,be],dn);let It=A({},["mi","mo","mn","ms","mtext"]),Ct=A({},["annotation-xml"]);const ys=A({},["title","style","font","a","script"]);let et=null;const bs=["application/xhtml+xml","text/html"],ws="text/html";let j=null,Be=null;const xs=n.createElement("form"),qn=function(u){return u instanceof RegExp||u instanceof Function},on=function(){let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Be&&Be===u)){if((!u||typeof u!="object")&&(u={}),u=ge(u),et=bs.indexOf(u.PARSER_MEDIA_TYPE)===-1?ws:u.PARSER_MEDIA_TYPE,j=et==="application/xhtml+xml"?dn:Ut,p=ce(u,"ALLOWED_TAGS")?A({},u.ALLOWED_TAGS,j):N,x=ce(u,"ALLOWED_ATTR")?A({},u.ALLOWED_ATTR,j):_,sn=ce(u,"ALLOWED_NAMESPACES")?A({},u.ALLOWED_NAMESPACES,dn):fs,nn=ce(u,"ADD_URI_SAFE_ATTR")?A(ge(jn),u.ADD_URI_SAFE_ATTR,j):jn,tn=ce(u,"ADD_DATA_URI_TAGS")?A(ge(Bn),u.ADD_DATA_URI_TAGS,j):Bn,L=ce(u,"FORBID_CONTENTS")?A({},u.FORBID_CONTENTS,j):ye,ae=ce(u,"FORBID_TAGS")?A({},u.FORBID_TAGS,j):ge({}),We=ce(u,"FORBID_ATTR")?A({},u.FORBID_ATTR,j):ge({}),B=ce(u,"USE_PROFILES")?u.USE_PROFILES:!1,kt=u.ALLOW_ARIA_ATTR!==!1,Ne=u.ALLOW_DATA_ATTR!==!1,vt=u.ALLOW_UNKNOWN_PROTOCOLS||!1,St=u.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Ae=u.SAFE_FOR_TEMPLATES||!1,Ue=u.SAFE_FOR_XML!==!1,fe=u.WHOLE_DOCUMENT||!1,Te=u.RETURN_DOM||!1,Fe=u.RETURN_DOM_FRAGMENT||!1,ze=u.RETURN_TRUSTED_TYPE||!1,Ke=u.FORCE_BODY||!1,Qe=u.SANITIZE_DOM!==!1,At=u.SANITIZE_NAMED_PROPS||!1,Je=u.KEEP_CONTENT!==!1,Ie=u.IN_PLACE||!1,xt=u.ALLOWED_URI_REGEXP||as,He=u.NAMESPACE||be,It=u.MATHML_TEXT_INTEGRATION_POINTS||It,Ct=u.HTML_INTEGRATION_POINTS||Ct,T=u.CUSTOM_ELEMENT_HANDLING||{},u.CUSTOM_ELEMENT_HANDLING&&qn(u.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(T.tagNameCheck=u.CUSTOM_ELEMENT_HANDLING.tagNameCheck),u.CUSTOM_ELEMENT_HANDLING&&qn(u.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(T.attributeNameCheck=u.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),u.CUSTOM_ELEMENT_HANDLING&&typeof u.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(T.allowCustomizedBuiltInElements=u.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Ae&&(Ne=!1),Fe&&(Te=!0),B&&(p=A({},Sr),x=[],B.html===!0&&(A(p,vr),A(x,Ar)),B.svg===!0&&(A(p,pn),A(x,fn),A(x,Lt)),B.svgFilters===!0&&(A(p,gn),A(x,fn),A(x,Lt)),B.mathMl===!0&&(A(p,mn),A(x,Tr),A(x,Lt))),u.ADD_TAGS&&(typeof u.ADD_TAGS=="function"?Se.tagCheck=u.ADD_TAGS:(p===N&&(p=ge(p)),A(p,u.ADD_TAGS,j))),u.ADD_ATTR&&(typeof u.ADD_ATTR=="function"?Se.attributeCheck=u.ADD_ATTR:(x===_&&(x=ge(x)),A(x,u.ADD_ATTR,j))),u.ADD_URI_SAFE_ATTR&&A(nn,u.ADD_URI_SAFE_ATTR,j),u.FORBID_CONTENTS&&(L===ye&&(L=ge(L)),A(L,u.FORBID_CONTENTS,j)),u.ADD_FORBID_CONTENTS&&(L===ye&&(L=ge(L)),A(L,u.ADD_FORBID_CONTENTS,j)),Je&&(p["#text"]=!0),fe&&A(p,["html","head","body"]),p.table&&(A(p,["tbody"]),delete ae.tbody),u.TRUSTED_TYPES_POLICY){if(typeof u.TRUSTED_TYPES_POLICY.createHTML!="function")throw it('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof u.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw it('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');O=u.TRUSTED_TYPES_POLICY,oe=O.createHTML("")}else O===void 0&&(O=ql(S,s)),O!==null&&typeof oe=="string"&&(oe=O.createHTML(""));ee&&ee(u),Be=u}},Gn=A({},[...pn,...gn,...$l]),Vn=A({},[...mn,...Dl]),ks=function(u){let m=he(u);(!m||!m.tagName)&&(m={namespaceURI:He,tagName:"template"});const f=Ut(u.tagName),$=Ut(m.tagName);return sn[u.namespaceURI]?u.namespaceURI===Nt?m.namespaceURI===be?f==="svg":m.namespaceURI===Et?f==="svg"&&($==="annotation-xml"||It[$]):!!Gn[f]:u.namespaceURI===Et?m.namespaceURI===be?f==="math":m.namespaceURI===Nt?f==="math"&&Ct[$]:!!Vn[f]:u.namespaceURI===be?m.namespaceURI===Nt&&!Ct[$]||m.namespaceURI===Et&&!It[$]?!1:!Vn[f]&&(ys[f]||!Gn[f]):!!(et==="application/xhtml+xml"&&sn[u.namespaceURI]):!1},pe=function(u){lt(e.removed,{element:u});try{he(u).removeChild(u)}catch{Z(u)}},Ce=function(u,m){try{lt(e.removed,{attribute:m.getAttributeNode(u),from:m})}catch{lt(e.removed,{attribute:null,from:m})}if(m.removeAttribute(u),u==="is")if(Te||Fe)try{pe(m)}catch{}else try{m.setAttribute(u,"")}catch{}},Yn=function(u){let m=null,f=null;if(Ke)u="<remove></remove>"+u;else{const U=hn(u,/^[\r\n\t ]+/);f=U&&U[0]}et==="application/xhtml+xml"&&He===be&&(u='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+u+"</body></html>");const $=O?O.createHTML(u):u;if(He===be)try{m=new k().parseFromString($,et)}catch{}if(!m||!m.documentElement){m=Pe.createDocument(He,"template",null);try{m.documentElement.innerHTML=rn?oe:$}catch{}}const K=m.body||m.documentElement;return u&&f&&K.insertBefore(n.createTextNode(f),K.childNodes[0]||null),He===be?Kt.call(m,fe?"html":"body")[0]:fe?m.documentElement:K},Xn=function(u){return Xt.call(u.ownerDocument||u,u,h.SHOW_ELEMENT|h.SHOW_COMMENT|h.SHOW_TEXT|h.SHOW_PROCESSING_INSTRUCTION|h.SHOW_CDATA_SECTION,null)},ln=function(u){return u instanceof y&&(typeof u.nodeName!="string"||typeof u.textContent!="string"||typeof u.removeChild!="function"||!(u.attributes instanceof d)||typeof u.removeAttribute!="function"||typeof u.setAttribute!="function"||typeof u.namespaceURI!="string"||typeof u.insertBefore!="function"||typeof u.hasChildNodes!="function")},Zn=function(u){return typeof i=="function"&&u instanceof i};function we(w,u,m){Rt(w,f=>{f.call(e,u,m,Be)})}const Kn=function(u){let m=null;if(we(P.beforeSanitizeElements,u,null),ln(u))return pe(u),!0;const f=j(u.nodeName);if(we(P.uponSanitizeElement,u,{tagName:f,allowedTags:p}),Ue&&u.hasChildNodes()&&!Zn(u.firstElementChild)&&Q(/<[/\w!]/g,u.innerHTML)&&Q(/<[/\w!]/g,u.textContent)||u.nodeType===ut.progressingInstruction||Ue&&u.nodeType===ut.comment&&Q(/<[/\w]/g,u.data))return pe(u),!0;if(!(Se.tagCheck instanceof Function&&Se.tagCheck(f))&&(!p[f]||ae[f])){if(!ae[f]&&Jn(f)&&(T.tagNameCheck instanceof RegExp&&Q(T.tagNameCheck,f)||T.tagNameCheck instanceof Function&&T.tagNameCheck(f)))return!1;if(Je&&!L[f]){const $=he(u)||u.parentNode,K=D(u)||u.childNodes;if(K&&$){const U=K.length;for(let ne=U-1;ne>=0;--ne){const xe=E(K[ne],!0);xe.__removalCount=(u.__removalCount||0)+1,$.insertBefore(xe,q(u))}}}return pe(u),!0}return u instanceof c&&!ks(u)||(f==="noscript"||f==="noembed"||f==="noframes")&&Q(/<\/no(script|embed|frames)/i,u.innerHTML)?(pe(u),!0):(Ae&&u.nodeType===ut.text&&(m=u.textContent,Rt([me,Ye,Xe],$=>{m=at(m,$," ")}),u.textContent!==m&&(lt(e.removed,{element:u.cloneNode()}),u.textContent=m)),we(P.afterSanitizeElements,u,null),!1)},Qn=function(u,m,f){if(Qe&&(m==="id"||m==="name")&&(f in n||f in xs))return!1;if(!(Ne&&!We[m]&&Q(Jt,m))){if(!(kt&&Q(bt,m))){if(!(Se.attributeCheck instanceof Function&&Se.attributeCheck(m,u))){if(!x[m]||We[m]){if(!(Jn(u)&&(T.tagNameCheck instanceof RegExp&&Q(T.tagNameCheck,u)||T.tagNameCheck instanceof Function&&T.tagNameCheck(u))&&(T.attributeNameCheck instanceof RegExp&&Q(T.attributeNameCheck,m)||T.attributeNameCheck instanceof Function&&T.attributeNameCheck(m,u))||m==="is"&&T.allowCustomizedBuiltInElements&&(T.tagNameCheck instanceof RegExp&&Q(T.tagNameCheck,f)||T.tagNameCheck instanceof Function&&T.tagNameCheck(f))))return!1}else if(!nn[m]){if(!Q(xt,at(f,wt,""))){if(!((m==="src"||m==="xlink:href"||m==="href")&&u!=="script"&&_l(f,"data:")===0&&tn[u])){if(!(vt&&!Q(ve,at(f,wt,"")))){if(f)return!1}}}}}}}return!0},Jn=function(u){return u!=="annotation-xml"&&hn(u,en)},er=function(u){we(P.beforeSanitizeAttributes,u,null);const{attributes:m}=u;if(!m||ln(u))return;const f={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:x,forceKeepAttr:void 0};let $=m.length;for(;$--;){const K=m[$],{name:U,namespaceURI:ne,value:xe}=K,je=j(U),an=xe;let G=U==="value"?an:Ml(an);if(f.attrName=je,f.attrValue=G,f.keepAttr=!0,f.forceKeepAttr=void 0,we(P.uponSanitizeAttribute,u,f),G=f.attrValue,At&&(je==="id"||je==="name")&&(Ce(U,u),G=Tt+G),Ue&&Q(/((--!?|])>)|<\/(style|title|textarea)/i,G)){Ce(U,u);continue}if(je==="attributename"&&hn(G,"href")){Ce(U,u);continue}if(f.forceKeepAttr)continue;if(!f.keepAttr){Ce(U,u);continue}if(!St&&Q(/\/>/i,G)){Ce(U,u);continue}Ae&&Rt([me,Ye,Xe],nr=>{G=at(G,nr," ")});const tr=j(u.nodeName);if(!Qn(tr,je,G)){Ce(U,u);continue}if(O&&typeof S=="object"&&typeof S.getAttributeType=="function"&&!ne)switch(S.getAttributeType(tr,je)){case"TrustedHTML":{G=O.createHTML(G);break}case"TrustedScriptURL":{G=O.createScriptURL(G);break}}if(G!==an)try{ne?u.setAttributeNS(ne,U,G):u.setAttribute(U,G),ln(u)?pe(u):kr(e.removed)}catch{Ce(U,u)}}we(P.afterSanitizeAttributes,u,null)},vs=function w(u){let m=null;const f=Xn(u);for(we(P.beforeSanitizeShadowDOM,u,null);m=f.nextNode();)we(P.uponSanitizeShadowNode,m,null),Kn(m),er(m),m.content instanceof o&&w(m.content);we(P.afterSanitizeShadowDOM,u,null)};return e.sanitize=function(w){let u=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},m=null,f=null,$=null,K=null;if(rn=!w,rn&&(w="<!-->"),typeof w!="string"&&!Zn(w))if(typeof w.toString=="function"){if(w=w.toString(),typeof w!="string")throw it("dirty is not a string, aborting")}else throw it("toString is not a function");if(!e.isSupported)return w;if(Ze||on(u),e.removed=[],typeof w=="string"&&(Ie=!1),Ie){if(w.nodeName){const xe=j(w.nodeName);if(!p[xe]||ae[xe])throw it("root node is forbidden and cannot be sanitized in-place")}}else if(w instanceof i)m=Yn("<!---->"),f=m.ownerDocument.importNode(w,!0),f.nodeType===ut.element&&f.nodeName==="BODY"||f.nodeName==="HTML"?m=f:m.appendChild(f);else{if(!Te&&!Ae&&!fe&&w.indexOf("<")===-1)return O&&ze?O.createHTML(w):w;if(m=Yn(w),!m)return Te?null:ze?oe:""}m&&Ke&&pe(m.firstChild);const U=Xn(Ie?w:m);for(;$=U.nextNode();)Kn($),er($),$.content instanceof o&&vs($.content);if(Ie)return w;if(Te){if(Fe)for(K=Zt.call(m.ownerDocument);m.firstChild;)K.appendChild(m.firstChild);else K=m;return(x.shadowroot||x.shadowrootmode)&&(K=Qt.call(r,K,!0)),K}let ne=fe?m.outerHTML:m.innerHTML;return fe&&p["!doctype"]&&m.ownerDocument&&m.ownerDocument.doctype&&m.ownerDocument.doctype.name&&Q(is,m.ownerDocument.doctype.name)&&(ne="<!DOCTYPE "+m.ownerDocument.doctype.name+`>
|
|
60
|
-
`+ne),Ae&&Rt([me,Ye,Xe],xe=>{ne=at(ne,xe," ")}),O&&ze?O.createHTML(ne):ne},e.setConfig=function(){let w=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};on(w),Ze=!0},e.clearConfig=function(){Be=null,Ze=!1},e.isValidAttribute=function(w,u,m){Be||on({});const f=j(w),$=j(u);return Qn(f,$,m)},e.addHook=function(w,u){typeof u=="function"&<(P[w],u)},e.removeHook=function(w,u){if(u!==void 0){const m=Il(P[w],u);return m===-1?void 0:Cl(P[w],m,1)[0]}return kr(P[w])},e.removeHooks=function(w){P[w]=[]},e.removeAllHooks=function(){P=Nr()},e}var $t=cs();const Gl=typeof window<"u"&&$t&&$t.default?$t.default:$t;C.setOptions({gfm:!0,breaks:!0});const Vl=["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"],Yl={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 us(t){if(!t||typeof t!="string")return"";try{const e=C(t);return Gl.sanitize(e,{ALLOWED_TAGS:Vl,ALLOWED_ATTR:Yl,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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}}function ds(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(ds(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"},zt(us(t.text||"")))}function Ql(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 Jl(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 ea(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"},Jl(e)))}function ta(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 na=!1,yn=4;function ra(t){const{currentChatId:e,isWaiting:n,isBusy:r,isStopping:s,isSending:o,userInput:a}=t,i=!!e&&(n||r),c=i?s:!a.trim()||o||n||s;return{canStopCurrentSession:i,actionButtonDisabled:c,actionButtonClass:i?"send-button stop-button":"send-button",actionButtonText:i?s?"Stopping...":"Stop":o?"Sending...":"Send"}}function sa(t){const{worldName:e,messages:n=[],rawMessages:r=[],userInput:s="",messagesLoading:o,isSending:a,isWaiting:i,needScroll:c=!1,activeAgent:h,agents:d=[],currentChat:y,currentChatId:k=null,editingMessageId:S=null,editingText:b="",agentFilters:E=[],isBusy:Z=!1,elapsedMs:q=0,isStopping:D=!1}=t,O=!i?"Type your message...":"Waiting for agents...",oe=a||i||D,{canStopCurrentSession:Pe,actionButtonDisabled:Xt,actionButtonClass:Zt,actionButtonText:Kt}=ra({currentChatId:k,isWaiting:i,isBusy:Z,isStopping:D,isSending:a,userInput:s}),Qt=h?.name?.trim()||d[0]?.name?.trim()||"Agent",P=new Map,me=new Map;for(const p of d){const N=re(p.name),x=re(p.id);P.set(N,p.spriteIndex),me.set(x,p.spriteIndex)}const Ye=d.filter(p=>p.name!==h?.name).map(p=>({name:p.name,spriteIndex:p.spriteIndex})),Xe=p=>{const N=re(p.sender),x=re(p.fromAgentId);return N!==x&&!p.isStreaming},Jt=p=>{const N=re(p.fromAgentId||"");if(N){const T=d.find(ae=>re(ae.id)===N);if(T)return T.autoReply===!1}const x=re(p.sender||"");return x?d.find(T=>re(T.id)===x||re(T.name)===x)?.autoReply===!1:!1},bt=(p,N)=>{if(!p.replyToMessageId)return null;const x=N.find(ae=>ae.messageId===p.replyToMessageId);return x?rt(x.sender)===Y.HUMAN?"HUMAN":x.sender:null},ve=E.length>0?(()=>{const p=r.filter(_=>rt(_.sender)===Y.HUMAN?!0:_.ownerAgentId&&E.includes(_.ownerAgentId)),N=new Map,x=[];for(const _ of p)rt(_.sender)===Y.HUMAN&&_.messageId?N.has(_.messageId)||(N.set(_.messageId,_),x.push(_)):x.push(_);return x})():n,wt=p=>{if(p.isToolEvent&&!p.isToolStreaming)return!0;try{const N=p.text.trim(),x=N.startsWith("@")?N.substring(N.indexOf(",")+1).trim():N;if(x.startsWith("{")&&x.endsWith("}")){const _=JSON.parse(x);if(_.__type==="tool_result"&&_.tool_call_id)return!0}}catch{}return!1},en=(p,N)=>p===Y.HUMAN||N?"message-row-left":"message-row-right",xt=p=>{const N=rt(p.sender);if(N===Y.HUMAN||N===Y.SYSTEM||N===Y.WORLD)return yn;const x=re(p.sender||""),_=re(p.fromAgentId||"");return P.has(x)?P.get(x):me.has(x)?me.get(x):me.has(_)?me.get(_):P.has(_)?P.get(_):yn};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(ta,{activeAgent:h?{name:h.name,spriteIndex:h.spriteIndex}:null,queuedAgents:Ye}),l.h(Ql,{isBusy:Z||!1}),(Z||q&&q>0)&&l.h(ea,{elapsedMs:q||0})),l.h("div",{className:"chat-container"},l.h("div",{className:"conversation-area",ref:(p,N)=>{p&&c&&requestAnimationFrame(()=>{p.scrollTop=p.scrollHeight,N&&(N.needScroll=!1)})}},o?l.h("div",{className:"loading-messages"},"Loading messages..."):ve.length===0?l.h("div",{className:"no-messages"},"No messages yet. Start a conversation!"):ve.map((p,N)=>{if(wt(p))return null;if(p.logEvent){const L=!!p.isLogExpanded;let ye=null;if(p.logEvent.data!==void 0)try{ye=JSON.stringify(p.logEvent.data,null,2)}catch{ye=String(p.logEvent.data)}return l.h("div",{key:p.id||"log-"+N,className:"message log-message"},l.h("button",{type:"button",className:"log-header","aria-expanded":L,$onclick:["toggle-log-details",p.id||`log-${N}`]},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"},L?"▲":"▼")),L&&l.h("pre",{className:"log-details"},ye??"No additional details"))}if(p.worldEvent)return null;const x=rt(p.sender),_=Xe(p),T=p.type==="user"||p.type==="human",ae=()=>{if(!p.replyToMessageId)return!1;const L=ve.find(ye=>ye.messageId===p.replyToMessageId);return L?L.sender===p.fromAgentId:!1},We=T&&p.replyToMessageId&&ae(),Se=!!p.replyToMessageId,kt=p.messageId?ve.some(L=>L.replyToMessageId===p.messageId):!1,Ne=T&&x===Y.AGENT&&_&&!p.isStreaming&&(Se?!We:!kt);if(Ne)return null;const vt=x===Y.HUMAN?"user-message":"agent-message",St=x===Y.SYSTEM?"system-message":"",Ae=_&&!Ne&&x!==Y.HUMAN?"cross-agent-message":"",Ue=Ne?"memory-only-message":"",fe=ds(p)?"tool-message":"",Ze=`message ${vt} ${St} ${Ae} ${Ue} ${fe}`.trim(),Ke=en(x,_),Te=x===Y.HUMAN,Fe=xt(p),ze=x===Y.HUMAN?"HUMAN":p.sender||"Agent",Qe=x===Y.HUMAN,At=S===p.id,Tt=b.trim(),Je=String(p.text||"").trim(),Ie=!!Tt&&Tt!==Je;let B="";if(Qe)B="From: HUMAN",p.seenByAgents&&p.seenByAgents.length>0&&(B+=`
|
|
61
|
-
To: ${p.seenByAgents.join(", ")}`);else if(x===Y.AGENT)if(Jt(p))B=p.sender;else if(We){const L=bt(p,ve);L?B=`Agent: ${p.sender} (reply to ${L})`:B=`Agent: ${p.sender} (reply)`}else if(p.type==="assistant"||p.type==="agent"){const L=bt(p,ve);L?B=`Agent: ${p.sender} (reply to ${L})`:B=`Agent: ${p.sender} (reply)`}else _&&T?B=`Agent: ${p.sender} (message from ${p.fromAgentId||p.sender})`:B=`Agent: ${p.sender}`;else Y.SYSTEM,B=p.sender;return l.h("div",{key:p.id||"msg-"+N,className:`message-row ${Ke}`},l.h("div",{className:"message-avatar-container",title:ze},l.h("div",{className:Te?"message-avatar message-avatar-empty":`message-avatar agent-sprite sprite-${Fe}`})),l.h("div",{className:Ze},l.h("div",{className:"message-sender",style:{whiteSpace:"pre-line"}},B),At?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:!Ie},"Update"),l.h("button",{className:"btn-secondary",$onclick:"cancel-edit-message"},"Cancel"))):l.h(l.Fragment,null,Kl(p),Qe&&!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-${h?.spriteIndex??0}`}),l.h("span",null,"responding ..."))),p.hasError&&l.h("div",{className:"error-indicator"},"Error: ",p.errorMessage),na))}),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,Qt," is working...")))))),l.h("div",{className:"input-area"},l.h("div",{className:"input-container"},l.h("input",{type:"text",className:"message-input",placeholder:O,value:s||"",$oninput:"update-input",$onkeypress:"key-press",disabled:oe}),l.h("button",{className:Zt,$onclick:Pe?"stop-message-processing":"send-message",disabled:Xt,title:Pe?"Stop processing":"Send message"},Kt)))))}function oa(t){const{world:e}=t,n=e&&e.agents&&e.agents.length>0,r=e?.chats||[],s=e?.currentChatId??null;return l.h("fieldset",{className:"settings-fieldset"},l.h("legend",null,"Chat History"),l.h("div",{className:"chat-history-header centered"},l.h("button",{className:"new-chat-btn",$onclick:"create-new-chat",title:n?"Create new chat session":"Create an agent first to enable new chats",disabled:!n},"✚ New Chat")),l.h("div",{className:"chat-history-container"},r.length===0?l.h("div",{className:"no-chats"},l.h("p",null,"No chat history entries found."),l.h("p",null,"Start a conversation with agents to auto-save chats.")):l.h("ul",{className:"chat-list simplified-chat-list"},r.map(o=>{const a=s===o.id;return l.h("li",{key:o.id,$onclick:["load-chat-from-history",o.id],className:`chat-item simplified-chat-item chat-list-li${a?" current":""}`},l.h("span",{className:`chat-title clickable chat-list-title${a?" current":""}`,title:o.name},o.name),l.h("button",{className:"chat-close-btn chat-list-close-btn",$onclick:["chat-history-show-delete-confirm",o],title:"Delete chat"},"×"))}))))}const la=t=>({mode:t.mode||"create",worldName:t.worldName,agent:t.agent||hs,parentComponent:t.parentComponent,loading:!1,error:null,errorDetails:null}),hs={name:"",description:"",autoReply:!0,provider:"ollama",model:"llama3.2:3b",temperature:.7,maxTokens:2048,systemPrompt:"You are a helpful assistant."};function aa(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=aa(t.agent);t.mode==="create"?await H.createAgent(t.worldName,e):await H.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=Gt(e);yield{...t,loading:!1,error:n.message,errorDetails:n.details||null}}},Cr=async function*(t){yield{...t,loading:!0,error:null};try{await H.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=Gt(e);yield{...t,loading:!1,error:n.message,errorDetails:n.details||null}}},dt=t=>{t?.parentComponent&&typeof t.parentComponent.run=="function"?t.parentComponent.run("close-agent-edit"):l.run("close-agent-edit")};class ia extends Le{mounted=e=>la(e);state={mode:"create",worldName:"",agent:hs,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:dt,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:dt,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"},Gr(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("label",{htmlFor:"agent-auto-reply"},"Auto Reply"),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("span",{className:"form-help-text"},"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:dt,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:dt,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:dt,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 ca(t,e){return{...t,userInput:e}}function ua(t,e){return t==="Enter"&&!!e?.trim()}function da(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 ha(t,e){return{...t,messages:[...t.messages||[],e],userInput:"",isSending:!0,needScroll:!0}}function pa(t){return{...t,isSending:!1}}function ga(t,e){return{...t,isSending:!1,isWaiting:!1,error:e}}function ma(t,e,n){return{...t,editingMessageId:e,editingText:n}}function fa(t){return{...t,editingMessageId:null,editingText:""}}function ya(t,e){return{...t,editingText:e}}function ba(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 wa(t){return{...t,messageToDelete:null}}function xa(t,e){return{...t,chatToDelete:e}}function ka(t){return{...t,chatToDelete:null}}function _r(t){return{...t,loading:!0}}function va(t){return{...t,loading:!0,chatToDelete:null}}function Dt(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 Sa(t,e,n){try{await H.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 Aa(t,e,n){const r={agents:t.world?.agents??[],messages:t.messages||[],selectedAgent:t.selectedAgent,selectedSettingsTarget:t.selectedSettingsTarget},s=await Sa(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 Ta(t,e,n){try{await H.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 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}:{...t,error:s.error||null}}async function Na(t,e){try{await Promise.all(t.agents.map(s=>H.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 Ia(t,e){const n={agents:t.world?.agents??[],messages:t.messages||[],selectedAgent:t.selectedAgent,selectedSettingsTarget:t.selectedSettingsTarget},r=await Na(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 Ca(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 _a(t,e){const n=await Ca(e);return n.success?t:{...t,error:n.error||null}}async function Ma(t){try{const e=await H.getWorldMarkdown(t),n=us(e),r=La(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 Ra(t,e){const n=await Ma(e);return n.success?t:{...t,error:n.error||null}}function La(t,e){return`<!DOCTYPE html>
|
|
62
|
-
<html lang="en">
|
|
63
|
-
<head>
|
|
64
|
-
<meta charset="UTF-8">
|
|
65
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
66
|
-
<title>World Export: ${e}</title>
|
|
67
|
-
<style>
|
|
68
|
-
body {
|
|
69
|
-
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
|
70
|
-
max-width: 800px;
|
|
71
|
-
margin: 0 auto;
|
|
72
|
-
padding: 20px;
|
|
73
|
-
line-height: 1.6;
|
|
74
|
-
color: #333;
|
|
75
|
-
}
|
|
76
|
-
h1, h2, h3 { color: #2c3e50; }
|
|
77
|
-
h1 { border-bottom: 2px solid #3498db; padding-bottom: 10px; }
|
|
78
|
-
h2 { border-bottom: 1px solid #bdc3c7; padding-bottom: 5px; }
|
|
79
|
-
code {
|
|
80
|
-
background: #f8f9fa;
|
|
81
|
-
padding: 2px 4px;
|
|
82
|
-
border-radius: 3px;
|
|
83
|
-
font-family: 'Monaco', 'Consolas', monospace;
|
|
84
|
-
}
|
|
85
|
-
pre { background: #f8f9fa; padding: 15px; border-radius: 5px; overflow-x: auto; }
|
|
86
|
-
pre code { background: none; padding: 0; }
|
|
87
|
-
ul { padding-left: 20px; }
|
|
88
|
-
li { margin-bottom: 5px; }
|
|
89
|
-
hr { border: none; height: 1px; background: #bdc3c7; margin: 30px 0; }
|
|
90
|
-
strong { color: #2c3e50; }
|
|
91
|
-
</style>
|
|
92
|
-
</head>
|
|
93
|
-
<body>${t}</body>
|
|
94
|
-
</html>`}function $a(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 Da(t,e){const n={messages:t.messages,needScroll:t.needScroll},r=$a(n,e);return r.success?{...t,messages:r.changes.messages,needScroll:r.changes.needScroll}:t}function Oa(t){const e=t&&typeof t=="object"?t:null,n=e&&typeof e.content=="object"?e.content:null;if(!n||String(n.eventType||"").trim()!=="hitl-option-request")return null;const r=String(n.requestId||"").trim();if(!r)return null;const s=Array.isArray(n.options)?n.options.map(i=>{const c=i&&typeof i=="object"?i:null;return{id:String(c?.id||"").trim(),label:String(c?.label||"").trim(),description:c?.description?String(c.description):void 0}}).filter(i=>i.id.length>0&&i.label.length>0):[];if(s.length===0)return null;const o=String(n.defaultOptionId||"").trim(),a=s.some(i=>i.id===o)?o:s.find(i=>i.id==="no")?.id||s[0].id;return{requestId:r,chatId:e?.chatId?String(e.chatId):null,title:String(n.title||"Approval required").trim()||"Approval required",message:String(n.message||"").trim(),options:s,defaultOptionId:a}}function Pa(t,e){const n=Array.isArray(t)?t:[];return n.some(r=>r.requestId===e.requestId)?n:[...n,e]}function Wa(t,e){return(Array.isArray(t)?t:[]).filter(r=>r.requestId!==e)}function Rr(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 Ua(t,e){const n=String(e||"").trim();if(n&&Rr(t,n))return n;const r=String(t?.currentChatId||"").trim();return r&&Rr(t,r)?r:null}const X=(t,e)=>{l.run(t,e)};let F={activeMessages:new Map,currentWorldName:null};const Fa=t=>{if(!(!t||typeof t!="object"))switch(t.type){case"sse":za(t.data);break;case"system":X("handleSystemEvent",t.data);break;case"message":X("handleMessageEvent",t.data);break;case"error":X("handleError",{message:t.message||"SSE error"});break;case"world":X("handleWorldActivity",t.data??t.payload??t);break}},za=t=>{const e=t;if(!e)return;const n=e.messageId,r=e.agentName;switch(e.type){case"start":F.activeMessages.set(n,{content:"",sender:r,messageId:n,isStreaming:!0}),X("handleStreamStart",{messageId:n,sender:r,worldName:e.worldName||F.currentWorldName});break;case"chunk":const s=F.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;X("handleStreamChunk",{messageId:n,sender:r,content:i,isAccumulated:e.accumulatedContent!==void 0,worldName:e.worldName||F.currentWorldName,tool_calls:c})}break;case"tool-start":e.toolExecution||console.warn("tool-start event missing toolExecution:",{eventData:e,messageId:n,agentName:r}),X("handleToolStart",{messageId:n,sender:r,toolExecution:e.toolExecution,worldName:e.worldName||F.currentWorldName});break;case"tool-progress":X("handleToolProgress",{messageId:n,sender:r,toolExecution:e.toolExecution,worldName:e.worldName||F.currentWorldName});break;case"tool-result":e.toolExecution||console.warn("tool-result event missing toolExecution:",{eventData:e,messageId:n,agentName:r}),X("handleToolResult",{messageId:n,sender:r,toolExecution:e.toolExecution,worldName:e.worldName||F.currentWorldName});break;case"tool-error":e.toolExecution||console.warn("tool-error event missing toolExecution:",{eventData:e,messageId:n,agentName:r}),X("handleToolError",{messageId:n,sender:r,toolExecution:e.toolExecution,worldName:e.worldName||F.currentWorldName});break;case"tool-stream":const o=F.activeMessages.get(n);if(o){const i=e.accumulatedContent!==void 0?e.accumulatedContent:o.content+(e.content||"");o.content=i,X("handleToolStream",{messageId:n,agentName:r,content:i,stream:e.stream||"stdout",accumulatedContent:i,worldName:e.worldName||F.currentWorldName}),console.log("[tool-stream] Accumulated output:",{messageId:n,stream:e.stream,chunkLength:e.content?.length,totalLength:i.length})}else F.activeMessages.set(n,{content:e.content||"",sender:r,messageId:n,isStreaming:!0}),X("handleToolStream",{messageId:n,agentName:r,content:e.content||"",stream:e.stream||"stdout",accumulatedContent:e.content||"",worldName:e.worldName||F.currentWorldName}),console.log("[tool-stream] Started new stream:",{messageId:n,stream:e.stream,contentLength:e.content?.length});break;case"end":const a=F.activeMessages.get(n);if(a){const i=e.finalContent!==void 0?e.finalContent:a.content;X("handleStreamEnd",{messageId:n,sender:r,content:i,worldName:e.worldName||F.currentWorldName}),F.activeMessages.delete(n)}break;case"error":X("handleStreamError",{messageId:n,sender:r,error:e.error||"Streaming error",worldName:e.worldName||F.currentWorldName}),F.activeMessages.delete(n);break;case"log":X("handleLogEvent",{messageId:e.messageId,logEvent:e.logEvent,worldName:e.worldName||F.currentWorldName});break}};async function Ha(t,e,n,r,s,o){let a="HUMAN",i,c,h=r,d=s,y=o;if(typeof n=="string"?a=n:n===void 0?a="HUMAN":(a=n.sender??"HUMAN",i=n.chatId,c=n.historyMessages,h=n.onMessage??h,d=n.onError??d,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),ps(t,`/worlds/${encodeURIComponent(t)}/messages`,{method:"POST",requestPayload:k,onMessage:h,onError:d,onComplete:y})}async function Ba(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 ps(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 ps(t,e,n){F.currentWorldName=t;const s=(await W(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,h=null;const d=n.awaitCompletion?new Promise((S,b)=>{c=S,h=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(`
|
|
95
|
-
`);a=E.pop()||"";for(const Z of E)if(!(Z.trim()===""||!Z.startsWith("data: ")))try{const q=Z.slice(6).trim();if(q==="")continue;const D=JSON.parse(q);if(n.awaitCompletion&&D.type==="error"){const he=new Error(D.message||"Failed to edit message");n.onError?.(he),h?.(he),y();return}Fa(D),n.onMessage?.(D),D.type==="complete"&&(n.onComplete?.(D.payload||D),c?.())}catch(q){console.error("Error parsing SSE data:",q);const D={message:"Failed to parse SSE data"};X("handleError",D),n.onError?.(new Error(D.message)),h?.(new Error(D.message))}}}catch(S){console.error("SSE stream error:",S);const b={message:S.message||"SSE stream error"};X("handleError",b),n.onError?.(S),h?.(S)}finally{y()}})(),d&&await d,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}},qa=(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}},Ga=(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}},Va=(t,e)=>{const{messageId:n,sender:r,error:s}=e,a=t.activeStreamMessageId??n;let i=!1;const c=(t.messages||[]).map(d=>d.isStreaming&&(d.messageId===a||!n&&d.sender===r&&d.type==="agent-stream")?(i=!0,{...d,isStreaming:!1,hasError:!0,errorMessage:s}):d),h=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:h,activeStreamMessageId:void 0,isWaiting:!1}},Ya=(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||F.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}},Qa=(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}},Ja=(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"})},gs=(t,e)=>{const n=re(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 d=t.createdAt?new Date(t.createdAt).getTime():Date.now(),y=(t.content||"").substring(0,20).replace(/\s/g,"");t.messageId=`fallback-${d}-${y.substring(0,10)}`}const a=s&&(n!=="human"&&n!=="user");let i,c;a?(i=re(e),c=n):(i=n,c=t.agentId||(s?void 0:e));const h=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:re(e),role:t.role,tool_calls:h.tool_calls||h.toolCalls,tool_call_id:h.tool_call_id||h.toolCallId}},ms=(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 h=o.type==="agent"||o.type==="assistant"?0:o.type==="user"||o.type==="human"?1:2,d=a.type==="agent"||a.type==="assistant"?0:a.type==="user"||a.type==="human"?1:2;return h-d})},ei=t=>{if(t.debounceFrameId!==null)return t;const e=requestAnimationFrame(()=>{l.run("flush-stream-updates")});return{...t,debounceFrameId:e}},ti=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}},ni=t=>(t.elapsedIntervalId!==null&&clearInterval(t.elapsedIntervalId),{...t,elapsedIntervalId:null,activityStartTime:null,elapsedMs:0}),ri=t=>t.activeTools.length>0||t.pendingStreamUpdates.size>0,si=(t,e)=>Va(t,e),oi=(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=ti(n)),n},li=(t,e)=>Za(t,e),ai=(t,e)=>{let n=Ka(t,e);const r=e.messageId;n={...n,activeTools:n.activeTools.filter(o=>o.toolUseId!==r)};const s=ri(n);return n={...n,isBusy:s},!s&&n.elapsedIntervalId!==null&&(n=ni(n)),n},ii=(t,e)=>Qa(t,e),ci=(t,e)=>{const{messageId:n,content:r}=e,s=new Map(t.pendingStreamUpdates);s.set(n,r||"");let o={...t,pendingStreamUpdates:s};return o=ei(o),o=qa(o,e),o},ui=(t,e)=>Ja(t,e),di=(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*Mn(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 H.getWorld(r);if(!s)throw new Error("World not found: "+r);n=Ua(s,n)||void 0,s.currentChatId!==n&&n&&await H.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 h of c.memory||[])if(h.chatId===n){c.messageCount++;const d=gs(h,c.name);o.push(d)}}const i=ms([...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 hi=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 h=i.currentChat?.id||i.world?.currentChatId||void 0,d=Mn(i,i.worldName,h);for await(const y of d)return{...i,...y}}const c=Oa(e);return c?{...i,hitlPromptQueue:Pa(i.hitlPromptQueue||[],c)}:i},pi=(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 h={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},d=t.messages||[],y=(o||"").toLowerCase();if((y==="human"||y==="user")&&n.messageId){const b=d.findIndex(E=>E.messageId===n.messageId||E.userEntered&&E.text===h.text);if(b!==-1){if(d[b].messageId===n.messageId)return t;const Z=d.map((q,D)=>D===b?{...q,messageId:n.messageId,chatId:n.chatId??q.chatId,createdAt:n.createdAt||q.createdAt,userEntered:!1,seenByAgents:a?[a]:[]}:q);return{...t,messages:Z}}}const S=d.findIndex(b=>b?.isStreaming&&(b.sender||"").toLowerCase()===y);if(S!==-1){const b=d.map((E,Z)=>Z!==S?E:{...E,...h,id:h.id,isStreaming:!1,messageId:h.messageId??E.messageId}).filter(E=>!!E&&!E.userEntered);return{...t,messages:b}}return t.messages=d.filter(b=>!b.userEntered&&!(b.isStreaming&&(b.sender||"").toLowerCase()===y)),t.messages.push(h),{...t}},gi=(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}},mi={initWorld:Mn,"/World":Mn,"update-input":(t,e)=>ca(t,e.target.value),"key-press":(t,e)=>{ua(e.key,t.userInput)&&l.run("send-message")},"send-message":async t=>{const e=da(t.userInput,t.worldName);if(!e)return t;const r={...ha(t,e.message),lastUserMessageText:e.text};try{return await Ha(t.worldName,e.text,{sender:"HUMAN",chatId:t.currentChat?.id||t.world?.currentChatId||void 0}),pa(r)}catch(s){return ga(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 H.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:ci,handleStreamEnd:Ga,handleStreamError:si,handleLogEvent:Ya,handleMessageEvent:pi,handleSystemEvent:hi,"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 H.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}yield{...t,submittingHitlRequestId:null,hitlPromptQueue:Wa(t.hitlPromptQueue||[],n)}}catch(o){yield{...t,submittingHitlRequestId:null,error:o?.message||"Failed to submit HITL response."}}},handleError:gi,handleToolError:ii,handleToolStart:oi,handleToolProgress:li,handleToolResult:ai,handleToolStream:ui,handleWorldActivity:(t,e)=>di(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)=>Da(t,e),"start-edit-message":(t,e)=>({...ma(t,e.messageId,e.text),needScroll:!1}),"cancel-edit-message":t=>fa(t),"update-edit-text":(t,e)=>ya(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)=>ba(t,e.messageId,e.backendMessageId,e.messageText,e.userEntered),"hide-delete-message-confirm":t=>wa(t),"delete-message-confirmed":async t=>{if(!t.messageToDelete)return t;const{id:e,messageId:n,chatId:r}=t.messageToDelete;try{const s=await H.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 H.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 h of c.memory||[])if(h.chatId===r){c.messageCount++;const d=gs(h,c.name);a.push(d)}}return a=ms(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(d=>d.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(d){console.warn("Failed to save edit backup to localStorage:",d)}const i=t.messages.findIndex(d=>d.id===e),c=i>=0?t.messages.slice(0,i):t.messages,h={...t,messages:c,editingMessageId:null,editingText:"",isSending:!0,needScroll:!1,lastUserMessageText:n};yield h;try{await Ba(t.worldName,r.messageId,n,o,{awaitCompletion:!1});try{localStorage.removeItem("agent-world-edit-backup")}catch(d){console.warn("Failed to clear edit backup from localStorage:",d)}yield{...h,isSending:!1,error:null}}catch(d){let y=d.message||"Failed to edit message";d.message?.includes("423")||d.message?.includes("WORLD_LOCKED")?y="Cannot edit message: world is currently processing. Please try again in a moment.":d.message?.includes("404")?y="Message not found in agent memories. It may have been already deleted.":d.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)=>xa(t,e),"chat-history-hide-modals":t=>ka(t),"delete-agent":async(t,e)=>Aa(t,e.agent,t.worldName),"export-world-markdown":async(t,e)=>_a(t,e.worldName),"view-world-markdown":async(t,e)=>Ra(t,e.worldName),"create-new-chat":async function*(t){try{if(yield _r(t),!(await H.newChat(t.worldName)).success){yield Dt(t,"Failed to create new chat");return}l.run("initWorld",t.worldName)}catch(e){yield Dt(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 H.setChat(t.worldName,e)).success||(yield n);const s=Mr(t.worldName,e);l.route(s),history.pushState(null,"",s)}catch(n){yield Dt(t,n.message||"Failed to load chat from history")}},"delete-chat-from-history":async function*(t,e){try{yield va(t),await H.deleteChat(t.worldName,e.chatId);const n=Mr(t.worldName);l.route(n),history.pushState(null,"",n)}catch(n){yield Dt(t,n.message||"Failed to delete chat",!0)}},"clear-agent-messages":async(t,e)=>Ea(t,e.agent,t.worldName),"clear-world-messages":async t=>Ia(t,t.worldName)};class fi extends Le{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);return l.h("div",{key:`agent-${r.id||s}`,className:`agent-item ${o?"selected":""} 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`}),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," ",zt(`<a href="#" onclick="app.run('open-agent-create')">Create Agent</a>`)))))),l.h(sa,{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})),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(oa,{world:e.world}))),e.showAgentEdit&&l.h(ia,{agent:e.selectedAgentForEdit,mode:e.agentEditMode,worldName:e.worldName,parentComponent:this}),e.showWorldEdit&&l.h(Yr,{world:e.selectedWorldForEdit,mode:e.worldEditMode,parentComponent:this}),n&&l.h("div",{className:"modal-overlay fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"},l.h("div",{className:"modal-content chat-history-modal bg-white rounded-lg p-6 max-w-md",onclick:r=>r.stopPropagation()},l.h("h3",{className:"text-xl font-bold mb-4"},n.title||"Approval required"),l.h("p",{className:"delete-confirmation-text whitespace-pre-wrap mb-4"},(n.message||"Please choose an option to continue.").replace(/\n\s*\n+/g,`
|
|
96
|
-
`)),l.h("div",{className:"form-actions flex gap-2 justify-end flex-nowrap overflow-x-auto pb-1"},n.options.map(r=>{const s=e.submittingHitlRequestId===n.requestId;return l.h("button",{key:r.id,className:"btn-secondary px-4 py-2 rounded shrink-0",disabled:s,$onclick:["respond-hitl-option",{requestId:n.requestId,optionId:r.id,chatId:n.chatId}]},l.h("div",{className:"font-bold"},r.label))})))),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={...mi,"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]}}}}l.render("#root",l.h(wo,null));l.addComponents("#pages",{"/":zo,"/World":fi});
|