Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
app-host.html rebuilt (locked-down Docker) for the merged page tools
milind-soni1f228ab60080
diff --git a/shared/app-frame/app-host.html b/shared/app-frame/app-host.htmlindex 441e07ce82..06a7e67356 100644--- a/shared/app-frame/app-host.html+++ b/shared/app-frame/app-host.html@@ -1,4 +1,4 @@-<!-- mausbot app-host v1 sha256:24cc00f4da963d9e1e19375d3668c6425a685ec2757b5740cab0fcc9bf2cc944 -->+<!-- mausbot app-host v1 sha256:592d0f25c47a29120396dd0992cced9e69149ac4c252ff5dcd3a940f934ed62f --><!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">@@ -6,5 +6,5 @@<style>html,body{margin:0;padding:0;background:transparent;overflow:hidden}iframe{display:block;width:100%;border:0;background:transparent}</style></head><body><script id="mausbot-app-host">(()=>{var U="2026-01-26";var T={htmlBytes:256*1024,title:80,fallback:1500,fallbackExcerpt:600,heightMin:80,heightMax:720,messageText:4e3,contextText:4e3,doneText:300,mcpHtmlBytes:2*1024*1024,rpcArgumentsBytes:64*1024,rpcResourceBytes:8*1024*1024,messagesPerHour:20,rpcPerMinute:60,pageQueryRows:5e3,pageQueryBytes:1e6,pageQuerySqlChars:2e4,pageQueryMs:1e4,pageStateKeyChars:200,pageStateValueBytes:64*1024,pageStateBytes:256*1024,pageStateKeys:200,pageConnectors:8,pageConnectorTools:24,pageConnectorArgsBytes:64*1024,pageConnectorResultBytes:512*1024,pageConnectorMs:6e4,pageConnectorErrorChars:1e3,pageConnectorCallsPerMinute:30,connectorCallsPerMinute:60};var E="In a room, pages, apps and widgets are view-only: they cannot send messages or tell a bot what anyone sees.";function N(e){let t=0;for(let r=0;r<e.length;r+=1){let a=e.charCodeAt(r);if(a<128)t+=1;else if(a<2048)t+=2;else if(a>=55296&&a<=56319&&r+1<e.length){let l=e.charCodeAt(r+1);l>=56320&&l<=57343?(t+=4,r+=1):t+=3}else t+=3}return t}var $=["tools/call","tools/list","resources/read","resources/list"],W=["mausbot/data/query","mausbot/state/get","mausbot/state/set","mausbot/state/keys","mausbot/connectors/call","mausbot/connectors/list"];function j(e){return e==="mausbot/data/query"?"data":e.startsWith("mausbot/connectors/")?"connectors":"state"}var L=-32601,M=-32602,f=-32e3;var m={messageBytes:1e6,minHeight:48,defaultHeight:160,maxHeight:720,linkChars:2048,teardownMs:1e3,engagedTouchMs:1e4,contextCoalesceMs:1e3,logsPerMinute:50,rates:{message:[[3e3,1],[6e5,10]],openLink:[[2e3,1]],rpc:[[1e4,10],[6e5,120]]}};function se(e){let t=J(e);return{...e.can.openLinks?{openLinks:{}}:{},logging:{},...e.can.modelContext?{updateModelContext:{text:{},structuredContent:{}}}:{},...e.can.message?{message:{text:{}}}:{},...t&&e.can.serverTools?{serverTools:{}}:{},...t&&e.can.serverResources?{serverResources:{}}:{},sandbox:{permissions:{},csp:{connectDomains:[...e.network.connect],resourceDomains:[...e.network.resources]}}}}function J(e){return!!e.tool}function C(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function z(e){return typeof e=="string"&&e.length<=200||typeof e=="number"&&Number.isFinite(e)}function G(e){let t;try{t=JSON.stringify(e)}catch{return null}return t===void 0?null:t.length*3<=m.messageBytes?t.length:N(t)}function ie(e){if(!C(e)||e.jsonrpc!=="2.0")return null;let t=G(e);return t===null||t>m.messageBytes||e.params!==void 0&&!C(e.params)?null:typeof e.method=="string"?!e.method||e.method.length>200||"id"in e&&!z(e.id)?null:e:e.method!==void 0||!z(e.id)?null:"result"in e||C(e.error)&&typeof e.error.code=="number"&&typeof e.error.message=="string"?e:null}function B(e,t){let r=[],a=Math.max(...e.map(([l])=>l));return{take(){let l=t();for(;r.length&&l-r[0]>=a;)r.shift();for(let[g,d]of e)if(r.filter(R=>l-R<g).length>=d)return!1;return r.push(l),!0}}}function H(e){return C(e)&&typeof e.code=="number"&&Number.isInteger(e.code)?{code:e.code,message:typeof e.message=="string"&&e.message?e.message:"The host refused this."}:{code:f,message:e instanceof Error&&e.message?e.message:"The host could not do that."}}function ae(e){if(typeof e!="string"||!e||e.length>m.linkChars)return null;let t;try{t=new URL(e)}catch{return null}return t.protocol!=="http:"&&t.protocol!=="https:"||t.username||t.password?null:t.href.length<=m.linkChars?t.href:null}function le(e,t){return e==="connectors"?t?"In a room, a page cannot call connected apps.":'This page declared no connector tools: show it with uses naming each tool, e.g. ["gmail:GMAIL_FETCH_EMAILS"].':t?"In a room, a page cannot read its bot's data or keep state.":`This page did not declare "${e}": show it with uses: ["${e}"] to ${e==="data"?"read its bot's data":"keep state"}.`}function V(e,t){let r=e.tool,a=e.name??e.connector??e.server;if(typeof r!="string"||!r||r.length>128||typeof a!="string"||!a||a.length>68)return null;let l=a.trim().toLowerCase();return typeof e.server=="string"||l.startsWith("mcp:")?{server:l.replace(/^mcp:/,""),tool:r}:typeof e.connector=="string"?{connector:l,tool:r}:!t.some(d=>"connector"in d&&d.connector===l)&&t.some(d=>"server"in d&&d.server===l)?{server:l,tool:r}:{connector:l,tool:r}}function pe(e,t){return e.find(r=>("server"in t?"server"in r&&r.server===t.server:"connector"in r&&r.connector===t.connector)&&r.tools.includes(t.tool))??null}function ue(e){let t="server"in e?`mcp:${e.server}:${e.tool}`:`${e.connector}:${e.tool}`;return`This page did not declare ${e.tool}: list "${t}" in show_html uses to call it.`}function de(e,t){let r=a=>typeof a=="string"&&a.length>0&&a.length<=T.pageStateKeyChars;switch(e){case"mausbot/data/query":return typeof t.sql!="string"||!t.sql.trim()||t.sql.length>T.pageQuerySqlChars?`mausbot.data.query needs one SELECT of at most ${T.pageQuerySqlChars} characters.`:t.params===void 0||Array.isArray(t.params)||C(t.params)?null:"mausbot.data.query params: a list for ? or $1, or an object for $name.";case"mausbot/state/get":case"mausbot/state/set":return r(t.key)?null:`A state key is text of 1 to ${T.pageStateKeyChars} characters.`;case"mausbot/state/keys":case"mausbot/connectors/list":return null;case"mausbot/connectors/call":{if(!V(t,[]))return"mausbot.connectors.call needs (connector or server, tool name, arguments object).";if(t.arguments!==void 0&&!C(t.arguments))return"mausbot.connectors.call arguments: one object.";let a=G(t.arguments??{});return a===null||a>T.pageConnectorArgsBytes?`mausbot.connectors.call arguments: at most ${T.pageConnectorArgsBytes} bytes of JSON.`:null}}}function ce(e,t,r,a){return e==="mausbot/connectors/list"?{}:r?{...r,arguments:C(t.arguments)?t.arguments:{},engaged:a()}:t}function ge(e){if(!e||e.role!=="user"||!Array.isArray(e.content)||e.content.length===0)return null;let t=[];for(let a of e.content){if(!C(a)||a.type!=="text"||typeof a.text!="string")return null;t.push(a.text)}let r=t.join(`-`).trim();return r&&r.length<=T.messageText?r:null}function K(e){let{doc:t,adapter:r}=e,a=J(t),l=e.timers??{set:(n,p)=>setTimeout(n,p),clear:n=>clearTimeout(n)},g=()=>r.now(),d={...e.hostContext,...a&&t.tool?{toolInfo:{tool:t.tool}}:{}},R=null,S=!1,y=!1,k=!1,I=!1,O=0,w=new Map,b={message:B(m.rates.message,g),openLink:B(m.rates.openLink,g),rpc:B(m.rates.rpc,g),log:B([[6e4,m.logsPerMinute]],g)},A=null,o=null,u=-1/0,h=n=>{if(!k)try{r.post(n)}catch{}},v=(n,p)=>h({jsonrpc:"2.0",id:n,result:p}),i=(n,p,s)=>h({jsonrpc:"2.0",id:n,error:{code:p,message:s}}),q=()=>{let n=e.limits?.maxHeight,p=d.containerDimensions?.maxHeight,s=typeof n=="number"&&n>0?n:typeof p=="number"&&p>0?p:m.maxHeight;return Math.max(m.minHeight,s)},F=()=>{if(o=null,k||!A)return;let n=A;A=null,u=g(),Promise.resolve().then(()=>r.setContext(n)).catch(()=>{})},Y=async()=>{if(o===null||!A)return;l.clear(o),o=null;let n=A;A=null,u=g();try{await r.setContext(n)}catch{}},X=()=>{if(a&&!I&&(I=!0,h({jsonrpc:"2.0",method:"ui/notifications/tool-input",params:{arguments:t.toolInput??{}}}),h({jsonrpc:"2.0",method:"ui/notifications/tool-result",params:t.toolResult??{content:[]}})),R){let n=R;R=null,h({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:n})}},ee=async(n,p,s)=>{if(!a)return i(n,L,"Method not found");if(!(p.startsWith("tools/")?t.can.serverTools:t.can.serverResources))return i(n,f,t.room?E:t.blocked?.text??"This app cannot reach its server right now.");if(p==="tools/call"&&(typeof s.name!="string"||!s.name||s.arguments!==void 0&&!C(s.arguments)))return i(n,M,"tools/call needs {name, arguments?}.");if(p==="resources/read"&&typeof s.uri!="string")return i(n,M,"resources/read needs {uri}.");if(!b.rpc.take())return i(n,f,"Too many calls from this app. Wait a moment.");try{let x=await r.callRpc(p,s);v(n,x??{})}catch(x){let P=H(x);i(n,P.code,P.message)}},te=async(n,p,s)=>{if(a)return i(n,L,"Method not found");let c=j(p),x=c==="connectors"?t.can.connectors??[]:[];if(c==="connectors"?!x.length:!t.can[c])return i(n,f,le(c,!!t.room));let P=de(p,s);if(P)return i(n,M,P);let _=p==="mausbot/connectors/call"?V(s,x):null;if(_&&!pe(x,_))return i(n,f,ue(_));if(!b.rpc.take())return i(n,f,"Too many calls from this page. Wait a moment.");try{v(n,await r.callRpc(p,ce(p,s,_,()=>r.engaged()))??{})}catch(oe){let D=H(oe);i(n,D.code,D.message)}},ne=async(n,p,s)=>{if(p==="ui/initialize")return S=!0,v(n,{protocolVersion:U,hostInfo:{name:"mausbot",version:e.hostVersion},hostCapabilities:se(t),hostContext:d});if(y)switch(p){case"ping":return v(n,{});case"ui/request-display-mode":return v(n,{mode:"inline"});case"ui/open-link":{if(!t.can.openLinks)return i(n,f,"This app cannot open links here.");if(!r.engaged())return i(n,f,"Links open only after the person clicks in the app.");let c=ae(s?.url);if(!c)return i(n,M,"Only http and https links of at most 2,048 characters, without a user name or password, can be opened.");if(!b.openLink.take())return i(n,f,"Too many links from this app. Wait a moment.");try{return await r.openLink(c),v(n,{})}catch(x){return i(n,f,H(x).message)}}case"ui/message":{if(!t.can.message)return i(n,f,t.room?E:"This app cannot send messages here.");if(!r.engaged())return i(n,f,"Messages are sent only after the person clicks in the app.");let c=ge(s);if(c===null)return i(n,M,`Only text messages of 1 to ${T.messageText} characters can be sent.`);if(!b.message.take())return i(n,f,"Too many messages from this app. Wait a moment.");try{return await Y(),await r.sendMessage(c),v(n,{})}catch(x){return i(n,f,H(x).message)}}case"ui/update-model-context":{if(!t.can.modelContext)return i(n,f,t.room?E:"This app cannot update the model's context here.");if(s?.content!==void 0&&!Array.isArray(s.content)||s?.structuredContent!==void 0&&!C(s.structuredContent))return i(n,M,"ui/update-model-context takes {content?, structuredContent?}.");if(A={...Array.isArray(s?.content)?{content:s.content}:{},...C(s?.structuredContent)?{structuredContent:s.structuredContent}:{}},o===null){let c=u+m.contextCoalesceMs-g();c<=0?F():o=l.set(F,c)}return v(n,{})}default:return $.includes(p)?ee(n,p,s??{}):W.includes(p)?te(n,p,s??{}):i(n,L,"Method not found")}},re=(n,p)=>{if(n==="ui/notifications/initialized"){if(!S||y)return;y=!0,X();return}if(y)switch(n){case"ui/notifications/size-changed":{let s=p?.height;if(typeof s!="number"||!Number.isFinite(s))return;r.resize(Math.round(Math.min(q(),Math.max(m.minHeight,s))));return}case"notifications/message":e.log&&b.log.take()&&e.log(p);return;case"ui/notifications/request-teardown":r.teardownRequested();return;default:}};return{get initialized(){return y},handleMessage(n){if(k)return;let p=e.source();if(p==null||n.source!==p)return;let s=ie(n.data);if(!s)return;if("method"in s){"id"in s?ne(s.id,s.method,s.params):re(s.method,s.params);return}let c=w.get(s.id);c&&(w.delete(s.id),c(s))},contextChanged(n){k||(d={...d,...n},y?h({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:n}):S&&(R={...R,...n}))},teardown(){return k||!y?Promise.resolve():new Promise(n=>{let p=`host:${++O}`,s=!1,c=()=>{s||(s=!0,w.delete(p),l.clear(x),n())},x=l.set(c,m.teardownMs);w.set(p,c),h({jsonrpc:"2.0",id:p,method:"ui/resource-teardown",params:{}})})},dispose(){k=!0,o!==null&&l.clear(o),o=null;for(let n of w.values())n({jsonrpc:"2.0",id:"",result:{}});w.clear()}}}var Q=1;function me(e){let r=e.webkit?.messageHandlers?.appHost;if(r&&typeof r.postMessage=="function")return{send:l=>r.postMessage(l)};let a=e.appHost;return a&&typeof a.postMessage=="function"?{send:l=>a.postMessage(JSON.stringify(l)),listen:l=>{a.onmessage=g=>{if(typeof g.data!="string")return;let d;try{d=JSON.parse(g.data)}catch{return}d&&typeof d=="object"&&d.v===Q&&l(d)}}}:null}function fe(e,t){let r=t??me(e);if(!r)return null;let a=e.document,l=null,g=null,d=0,R=!1,S=0,y=new Map,k=o=>{try{r.send(o)}catch{}},I=(o,u)=>new Promise((h,v)=>{let i=`c${++S}`;y.set(i,{resolve:h,reject:v}),k({v:1,type:"call",callId:i,op:o,params:u})}),O=()=>{for(let o of y.values())o.reject({code:-32e3,message:"This app was closed."});y.clear()};e.addEventListener("message",o=>{l&&(l.handleMessage({source:o.source,data:o.data}),!R&&l.initialized&&(R=!0,k({v:1,type:"initialized"})))});let w=()=>{l?.dispose(),l=null,g?.remove(),g=null,R=!1,O()},b={load(o){if(!o||o.v!==Q||!o.doc||typeof o.doc.srcdoc!="string")return;w(),typeof o.engagedAt=="number"&&(d=o.engagedAt);let u=a.createElement("iframe");u.setAttribute("sandbox","allow-scripts allow-forms"),u.setAttribute("referrerpolicy","no-referrer"),u.setAttribute("title","App");let h=Math.max(m.minHeight,Math.round(o.limits?.height??m.defaultHeight));u.style.height=`${h}px`,l=K({doc:o.doc,hostContext:o.hostContext??{},hostVersion:o.hostVersion??"phone",...o.limits?.maxHeight?{limits:{maxHeight:o.limits.maxHeight}}:{},source:()=>u.contentWindow,adapter:{post:i=>u.contentWindow?.postMessage(i,"*"),callRpc:(i,q)=>I("rpc",{method:i,params:q}),sendMessage:async i=>{await I("message",{text:i})},openLink:async i=>{await I("open-link",{url:i})},setContext:async i=>{await I("context",{...i})},resize:i=>{u.style.height=`${i}px`,k({v:1,type:"size",height:i})},engaged:()=>Date.now()-d<=m.engagedTouchMs,teardownRequested:()=>k({v:1,type:"teardown-request"}),now:()=>Date.now()}}),g=u,u.srcdoc=o.doc.srcdoc,a.body.appendChild(u)},contextChanged(o){l?.contextChanged(o??{})},engaged(o){typeof o=="number"&&Number.isFinite(o)&&(d=Math.max(d,o))},async teardown(){l&&await l.teardown(),w(),k({v:1,type:"torn-down"})},reply(o,u){let h=y.get(o);h&&(y.delete(o),u&&"error"in u&&u.error?h.reject(u.error):h.resolve(u&&"result"in u?u.result:void 0))}};r.listen?.(o=>{switch(o.call){case"load":return b.load(o.args[0]);case"contextChanged":return b.contextChanged(o.args[0]);case"engaged":return b.engaged(o.args[0]);case"teardown":return void b.teardown();case"reply":return b.reply(o.args[0],o.args[1])}});let A=e;return A.appHost&&typeof A.appHost.postMessage=="function"||(A.appHost=b),A.mausbotAppHost=b,k({v:1,type:"ready"}),b}function Z(){typeof window<"u"&&fe(window)}Z();})();</script>+`).trim();return r&&r.length<=T.messageText?r:null}function K(e){let{doc:t,adapter:r}=e,a=J(t),l=e.timers??{set:(n,p)=>setTimeout(n,p),clear:n=>clearTimeout(n)},g=()=>r.now(),d={...e.hostContext,...a&&t.tool?{toolInfo:{tool:t.tool}}:{}},R=null,S=!1,y=!1,k=!1,I=!1,O=0,w=new Map,b={message:B(m.rates.message,g),openLink:B(m.rates.openLink,g),rpc:B(m.rates.rpc,g),log:B([[6e4,m.logsPerMinute]],g)},A=null,o=null,u=-1/0,h=n=>{if(!k)try{r.post(n)}catch{}},v=(n,p)=>h({jsonrpc:"2.0",id:n,result:p}),i=(n,p,s)=>h({jsonrpc:"2.0",id:n,error:{code:p,message:s}}),F=()=>{let n=e.limits?.maxHeight,p=d.containerDimensions?.maxHeight,s=typeof n=="number"&&n>0?n:typeof p=="number"&&p>0?p:m.maxHeight;return Math.max(m.minHeight,s)},q=()=>{if(o=null,k||!A)return;let n=A;A=null,u=g(),Promise.resolve().then(()=>r.setContext(n)).catch(()=>{})},Y=async()=>{if(o===null||!A)return;l.clear(o),o=null;let n=A;A=null,u=g();try{await r.setContext(n)}catch{}},X=()=>{if(a&&!I&&(I=!0,h({jsonrpc:"2.0",method:"ui/notifications/tool-input",params:{arguments:t.toolInput??{}}}),h({jsonrpc:"2.0",method:"ui/notifications/tool-result",params:t.toolResult??{content:[]}})),R){let n=R;R=null,h({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:n})}},ee=async(n,p,s)=>{if(!a)return i(n,L,"Method not found");if(!(p.startsWith("tools/")?t.can.serverTools:t.can.serverResources))return i(n,f,t.room?E:t.blocked?.text??"This app cannot reach its server right now.");if(p==="tools/call"&&(typeof s.name!="string"||!s.name||s.arguments!==void 0&&!C(s.arguments)))return i(n,M,"tools/call needs {name, arguments?}.");if(p==="resources/read"&&typeof s.uri!="string")return i(n,M,"resources/read needs {uri}.");if(!b.rpc.take())return i(n,f,"Too many calls from this app. Wait a moment.");try{let x=await r.callRpc(p,s);v(n,x??{})}catch(x){let P=H(x);i(n,P.code,P.message)}},te=async(n,p,s)=>{if(a)return i(n,L,"Method not found");let c=j(p),x=c==="connectors"?t.can.connectors??[]:[];if(c==="connectors"?!x.length:!t.can[c])return i(n,f,le(c,!!t.room));let P=de(p,s);if(P)return i(n,M,P);let _=p==="mausbot/connectors/call"?V(s,x):null;if(_&&!pe(x,_))return i(n,f,ue(_));if(!b.rpc.take())return i(n,f,"Too many calls from this page. Wait a moment.");try{v(n,await r.callRpc(p,ce(p,s,_,()=>r.engaged()))??{})}catch(oe){let D=H(oe);i(n,D.code,D.message)}},ne=async(n,p,s)=>{if(p==="ui/initialize")return S=!0,v(n,{protocolVersion:U,hostInfo:{name:"mausbot",version:e.hostVersion},hostCapabilities:se(t),hostContext:d});if(y)switch(p){case"ping":return v(n,{});case"ui/request-display-mode":return v(n,{mode:"inline"});case"ui/open-link":{if(!t.can.openLinks)return i(n,f,"This app cannot open links here.");if(!r.engaged())return i(n,f,"Links open only after the person clicks in the app.");let c=ae(s?.url);if(!c)return i(n,M,"Only http and https links of at most 2,048 characters, without a user name or password, can be opened.");if(!b.openLink.take())return i(n,f,"Too many links from this app. Wait a moment.");try{return await r.openLink(c),v(n,{})}catch(x){return i(n,f,H(x).message)}}case"ui/message":{if(!t.can.message)return i(n,f,t.room?E:"This app cannot send messages here.");if(!r.engaged())return i(n,f,"Messages are sent only after the person clicks in the app.");let c=ge(s);if(c===null)return i(n,M,`Only text messages of 1 to ${T.messageText} characters can be sent.`);if(!b.message.take())return i(n,f,"Too many messages from this app. Wait a moment.");try{return await Y(),await r.sendMessage(c),v(n,{})}catch(x){return i(n,f,H(x).message)}}case"ui/update-model-context":{if(!t.can.modelContext)return i(n,f,t.room?E:"This app cannot update the model's context here.");if(s?.content!==void 0&&!Array.isArray(s.content)||s?.structuredContent!==void 0&&!C(s.structuredContent))return i(n,M,"ui/update-model-context takes {content?, structuredContent?}.");if(A={...Array.isArray(s?.content)?{content:s.content}:{},...C(s?.structuredContent)?{structuredContent:s.structuredContent}:{}},o===null){let c=u+m.contextCoalesceMs-g();c<=0?q():o=l.set(q,c)}return v(n,{})}default:return $.includes(p)?ee(n,p,s??{}):W.includes(p)?te(n,p,s??{}):i(n,L,"Method not found")}},re=(n,p)=>{if(n==="ui/notifications/initialized"){if(!S||y)return;y=!0,X();return}if(y)switch(n){case"ui/notifications/size-changed":{let s=p?.height;if(typeof s!="number"||!Number.isFinite(s))return;r.resize(Math.round(Math.min(F(),Math.max(m.minHeight,s))));return}case"notifications/message":e.log&&b.log.take()&&e.log(p);return;case"ui/notifications/request-teardown":r.teardownRequested();return;default:}};return{get initialized(){return y},handleMessage(n){if(k)return;let p=e.source();if(p==null||n.source!==p)return;let s=ie(n.data);if(!s)return;if("method"in s){"id"in s?ne(s.id,s.method,s.params):re(s.method,s.params);return}let c=w.get(s.id);c&&(w.delete(s.id),c(s))},contextChanged(n){k||(d={...d,...n},y?h({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:n}):S&&(R={...R,...n}))},teardown(){return k||!y?Promise.resolve():new Promise(n=>{let p=`host:${++O}`,s=!1,c=()=>{s||(s=!0,w.delete(p),l.clear(x),n())},x=l.set(c,m.teardownMs);w.set(p,c),h({jsonrpc:"2.0",id:p,method:"ui/resource-teardown",params:{}})})},dispose(){k=!0,o!==null&&l.clear(o),o=null;for(let n of w.values())n({jsonrpc:"2.0",id:"",result:{}});w.clear()}}}var Q=1;function me(e){let r=e.webkit?.messageHandlers?.appHost;if(r&&typeof r.postMessage=="function")return{send:l=>r.postMessage(l)};let a=e.appHost;return a&&typeof a.postMessage=="function"?{send:l=>a.postMessage(JSON.stringify(l)),listen:l=>{a.onmessage=g=>{if(typeof g.data!="string")return;let d;try{d=JSON.parse(g.data)}catch{return}d&&typeof d=="object"&&d.v===Q&&l(d)}}}:null}function fe(e,t){let r=t??me(e);if(!r)return null;let a=e.document,l=null,g=null,d=0,R=!1,S=0,y=new Map,k=o=>{try{r.send(o)}catch{}},I=(o,u)=>new Promise((h,v)=>{let i=`c${++S}`;y.set(i,{resolve:h,reject:v}),k({v:1,type:"call",callId:i,op:o,params:u})}),O=()=>{for(let o of y.values())o.reject({code:-32e3,message:"This app was closed."});y.clear()};e.addEventListener("message",o=>{l&&(l.handleMessage({source:o.source,data:o.data}),!R&&l.initialized&&(R=!0,k({v:1,type:"initialized"})))});let w=()=>{l?.dispose(),l=null,g?.remove(),g=null,R=!1,O()},b={load(o){if(!o||o.v!==Q||!o.doc||typeof o.doc.srcdoc!="string")return;w(),typeof o.engagedAt=="number"&&(d=o.engagedAt);let u=a.createElement("iframe");u.setAttribute("sandbox","allow-scripts allow-forms"),u.setAttribute("referrerpolicy","no-referrer"),u.setAttribute("title","App");let h=Math.max(m.minHeight,Math.round(o.limits?.height??m.defaultHeight));u.style.height=`${h}px`,l=K({doc:o.doc,hostContext:o.hostContext??{},hostVersion:o.hostVersion??"phone",...o.limits?.maxHeight?{limits:{maxHeight:o.limits.maxHeight}}:{},source:()=>u.contentWindow,adapter:{post:i=>u.contentWindow?.postMessage(i,"*"),callRpc:(i,F)=>I("rpc",{method:i,params:F}),sendMessage:async i=>{await I("message",{text:i})},openLink:async i=>{await I("open-link",{url:i})},setContext:async i=>{await I("context",{...i})},resize:i=>{u.style.height=`${i}px`,k({v:1,type:"size",height:i})},engaged:()=>Date.now()-d<=m.engagedTouchMs,teardownRequested:()=>k({v:1,type:"teardown-request"}),now:()=>Date.now()}}),g=u,u.srcdoc=o.doc.srcdoc,a.body.appendChild(u)},contextChanged(o){l?.contextChanged(o??{})},engaged(o){typeof o=="number"&&Number.isFinite(o)&&(d=Math.max(d,o))},async teardown(){l&&await l.teardown(),w(),k({v:1,type:"torn-down"})},reply(o,u){let h=y.get(o);h&&(y.delete(o),u&&"error"in u&&u.error?h.reject(u.error):h.resolve(u&&"result"in u?u.result:void 0))}};r.listen?.(o=>{switch(o.call){case"load":return b.load(o.args[0]);case"contextChanged":return b.contextChanged(o.args[0]);case"engaged":return b.engaged(o.args[0]);case"teardown":return void b.teardown();case"reply":return b.reply(o.args[0],o.args[1])}});let A=e;return A.appHost&&typeof A.appHost.postMessage=="function"||(A.appHost=b),A.mausbotAppHost=b,k({v:1,type:"ready"}),b}function Z(){typeof window<"u"&&fe(window)}Z();})();</script></body></html>