Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep a bot Local VM desktop running through idle
skygunnerbf5351f81976
diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 689615916d..d08e0477d4 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -1385,7 +1385,10 @@ grant desktop control.Managed VPS desktops stop after 480 idle minutes by default. Set`vpsIdle.timeoutMinutes` in `config.json` to a whole number from 5 to 1440.-Private desktops have their own `localVm.idleTimeoutMinutes` setting.+Private desktops have their own `localVm.idleTimeoutMinutes` setting. With+`localVm.mode: "per-bot"`, a bot's own `localVm.keepDesktopRunning: true`+keeps its desktop up through idle; it still counts toward `localVm.maxInstances`+and the setting is cleared when the bot is deleted.An open Local VM viewer keeps that VM's idle timer active. Remote VPS viewersshare a tunnel; it closes 30 seconds after the last viewer leaves, allowingdiff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.tsindex ac5a800392..60aa98e45b 100644--- a/packages/phone-protocol/src/wire.ts+++ b/packages/phone-protocol/src/wire.ts@@ -353,7 +353,7 @@ export interface WireBot extends DefaultBotFields, BotAccessFields {/** The coordinator for this bot's sidebar section. */chiefOfStaff?: boolean;/** Owner-selected additional teams this Chief may coordinate. */- managedSections?: string[];+ managedSections?: string[]; /** When `keepDesktopRunning` is true, this bot's Local VM desktop is never stopped by the idle timer. */ localVm?: { keepDesktopRunning?: boolean };/** Team Cloud only: the lowercased email of the member who created the bot (or moved it in). */createdBy?: string;/** Team Cloud only: the lowercased email of the member the bot reports to, whose inbox its questions, approvals,diff --git a/screenshots/issue-4982/after-768-daylight.png b/screenshots/issue-4982/after-768-daylight.pngnew file mode 100644index 0000000000..b54bf64940Binary files /dev/null and b/screenshots/issue-4982/after-768-daylight.png differdiff --git a/screenshots/issue-4982/after-768-midnight.png b/screenshots/issue-4982/after-768-midnight.pngnew file mode 100644index 0000000000..d535438715Binary files /dev/null and b/screenshots/issue-4982/after-768-midnight.png differdiff --git a/screenshots/issue-4982/before-768-daylight.png b/screenshots/issue-4982/before-768-daylight.pngnew file mode 100644index 0000000000..cb22981036Binary files /dev/null and b/screenshots/issue-4982/before-768-daylight.png differdiff --git a/screenshots/issue-4982/before-768-midnight.png b/screenshots/issue-4982/before-768-midnight.pngnew file mode 100644index 0000000000..a57f6159e9Binary files /dev/null and b/screenshots/issue-4982/before-768-midnight.png differdiff --git a/server/container-computer.ts b/server/container-computer.tsindex b72081f431..def8957d1a 100644--- a/server/container-computer.ts+++ b/server/container-computer.ts@@ -87,13 +87,12 @@ export interface LocalVmTarget {workspaceDir: string;viewerPort: number | null;label: string;+ /** The bot this per-bot desktop belongs to; absent for shared and pool targets. */ botId?: string;}export const SHARED_LOCAL_VM_TARGET: LocalVmTarget = {- key: "shared",- containerName: CONTAINER,- workspaceDir: VM_WORKSPACE_DIR,- viewerPort: HOST_VIEWER_PORT,+ key: "shared", containerName: CONTAINER,+ workspaceDir: VM_WORKSPACE_DIR, viewerPort: HOST_VIEWER_PORT,label: "shared",};@@ -107,6 +106,7 @@ export function perBotLocalVmTarget(botId: string): LocalVmTarget {workspaceDir: join(DATA_DIR, "vm-homes", short),viewerPort: null,label: digest,+ botId,};}diff --git a/server/index.ts b/server/index.tsindex 2d5930c9d1..4156aeafa8 100644--- a/server/index.ts+++ b/server/index.ts@@ -427,7 +427,7 @@ import { createComputerAsksHost } from "./host/computer-asks-host.ts";import { discoverExistingPerBotLocalVms, localVmInventoryEntry } from "./local-vm-inventory.ts";import { createLocalVmUpdater, LOCAL_VM_UPDATING_PROBLEM, recoverLocalVms, VPS_OUTDATED_HINT, vpsDesktopOutdated, withoutHostWhileUpdating } from "./desktop-updates.ts";import { keepInstalledAppsBeforeRemove } from "./local-vm-profiles.ts";-import { localVmStopReason, recordLocalVmIdleStop } from "./local-vm-stop-reason.ts";+import { localVmStopReason, recordLocalVmIdleStop } from "./local-vm-stop-reason.ts"; import { stopIdleLocalVm } from "./local-vm-idle-stop.ts";import { ComputerIdleTimer } from "./computer-idle.ts";import { CLOUD_COMPUTER_DID_NOT_START, CLOUD_COMPUTER_START_BUDGET_MS, CLOUD_COMPUTER_STARTING, createCloudComputerPower, type CloudComputerReadyHooks } from "./host/cloud-computer-power.ts"; import { usedByAnotherBot } from "./host/cloud-computer-users.ts"; import { ownCloudComputer, resetBotCloudComputer } from "./host/cloud-computer-reset.ts"; import { createCloudComputerResetAsks, noOwnCloudComputer } from "./host/cloud-computer-reset-asks.ts";import { LocalVmLease, LocalVmLeasePool } from "./local-vm-lease.ts";@@ -6183,15 +6183,15 @@ function localVmIdleFor(target: LocalVmTarget): ComputerIdleTimer {if (idle) return idle;idle = new ComputerIdleTimer(localVmIdleMs(),- () => localVmImageBusy || localVmLifecycleBusy.has(target.key) || localVmActiveThreads.has(target.key) || sharedVm.heldOnTarget(target),+ () => Boolean(target.botId && store.bot(target.botId)?.localVm?.keepDesktopRunning) || localVmImageBusy || localVmLifecycleBusy.has(target.key) || localVmActiveThreads.has(target.key) || sharedVm.heldOnTarget(target),async () => {localVmLifecycleBusy.add(target.key);try {- const status = await containerComputerStatus(undefined, undefined, target);- if (status.container === "running" && status.managed) {- const stopped = await containerComputerAction("stop", undefined, undefined, target);- recordLocalVmIdleStop(target.key, stopped.stopped_at);- }+ return await stopIdleLocalVm({+ keepRunning: () => Boolean(target.botId && store.bot(target.botId)?.localVm?.keepDesktopRunning),+ status: () => containerComputerStatus(undefined, undefined, target), stop: () => containerComputerAction("stop", undefined, undefined, target),+ record: (stoppedAt) => recordLocalVmIdleStop(target.key, stoppedAt),+ });} finally {localVmLifecycleBusy.delete(target.key);}diff --git a/server/local-vm-idle-stop.test.ts b/server/local-vm-idle-stop.test.tsnew file mode 100644index 0000000000..55f9a0bf61--- /dev/null+++ b/server/local-vm-idle-stop.test.ts@@ -0,0 +1,50 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { ComputerIdleTimer } from "./computer-idle.ts";+import { perBotLocalVmTarget } from "./container-computer.ts";+import { stopIdleLocalVm } from "./local-vm-idle-stop.ts";++afterEach(() => vi.useRealTimers());++describe("stopping an idle private desktop", () => {+ it("keeps one bot's desktop running and resumes its idle timer after turning the setting off", async () => {+ vi.useFakeTimers();+ const first = perBotLocalVmTarget("coordinator");+ const second = perBotLocalVmTarget("worker");+ const preferences = new Map([[first.botId, true], [second.botId, false]]);+ const stopped: string[] = [];+ const timer = (target: typeof first) => {+ const keepRunning = () => preferences.get(target.botId) === true;+ return new ComputerIdleTimer(1_000, keepRunning, () => stopIdleLocalVm({+ keepRunning,+ status: async () => ({ container: "running", managed: true }),+ stop: async () => { stopped.push(target.botId!); return {}; },+ record: () => {},+ }));+ };+ const coordinator = timer(first), worker = timer(second);+ coordinator.touch(); worker.touch();+ await vi.advanceTimersByTimeAsync(2_000);+ expect(stopped).toEqual(["worker"]);+ preferences.set(first.botId, false);+ await vi.advanceTimersByTimeAsync(1_100);+ expect(stopped).toEqual(["worker", "coordinator"]);+ coordinator.cancel(); worker.cancel();+ });++ it("checks the bot's current preference after awaiting desktop status", async () => {+ let keepRunning = false;+ let finishStatus!: (status: { container: string; managed: boolean }) => void;+ const status = new Promise<{ container: string; managed: boolean }>((resolve) => { finishStatus = resolve; });+ const stop = vi.fn(async () => ({ stopped_at: "now" }));+ const record = vi.fn();+ const pending = stopIdleLocalVm({ keepRunning: () => keepRunning, status: () => status, stop, record });+ keepRunning = true;+ finishStatus({ container: "running", managed: true });+ expect(await pending).toBe("busy");+ expect(stop).not.toHaveBeenCalled();+ keepRunning = false;+ await stopIdleLocalVm({ keepRunning: () => keepRunning, status: async () => ({ container: "running", managed: true }), stop, record });+ expect(stop).toHaveBeenCalledOnce();+ expect(record).toHaveBeenCalledWith("now");+ });+});diff --git a/server/local-vm-idle-stop.ts b/server/local-vm-idle-stop.tsnew file mode 100644index 0000000000..557d03ad99--- /dev/null+++ b/server/local-vm-idle-stop.ts@@ -0,0 +1,13 @@+export async function stopIdleLocalVm(deps: {+ keepRunning(): boolean;+ status(): Promise<{ container: string; managed: boolean }>;+ stop(): Promise<{ stopped_at?: string | null }>;+ record(stoppedAt: string | null | undefined): void;+}): Promise<void | "busy"> {+ const status = await deps.status();+ if (deps.keepRunning()) return "busy";+ if (status.container === "running" && status.managed) {+ const stopped = await deps.stop();+ deps.record(stopped.stopped_at);+ }+}diff --git a/server/local-vm-settings.ts b/server/local-vm-settings.tsindex 7317c0cf47..280ecac2f7 100644--- a/server/local-vm-settings.ts+++ b/server/local-vm-settings.ts@@ -41,6 +41,10 @@ export const localVmConfigSchema = z.object({cpus: z.number().int().min(MIN_DESKTOP_CPUS).max(MAX_DESKTOP_CPUS).optional(),});+export const perBotLocalVmConfigSchema = z.object({+ keepDesktopRunning: z.boolean().optional(),+});+export function localVmMode(cfg: AppConfig): "shared" | "per-bot" | "pool" {return cfg.localVm?.mode ?? DEFAULT_LOCAL_VM_MODE;}diff --git a/server/routes/bot-patch.test.ts b/server/routes/bot-patch.test.tsindex 9e06fba33d..7473479ac6 100644--- a/server/routes/bot-patch.test.ts+++ b/server/routes/bot-patch.test.ts@@ -342,6 +342,23 @@ describe("PATCH /api/bots/:id toolsOff", () => {});});+describe("PATCH /api/bots/:id localVm", () => {+ it("stores keepDesktopRunning, clears it with null, and refuses a malformed value", async () => {+ const { store, bot, patch } = fixture();+ expect((await patch(bot.id, { localVm: { keepDesktopRunning: true } })).status).toBe(200);+ expect(store.bot(bot.id)?.localVm).toEqual({ keepDesktopRunning: true });+ const other = store.createBot({ name: "Echo" });+ expect(store.bot(other.id)?.localVm).toBeUndefined();+ expect((await patch(bot.id, { localVm: { keepDesktopRunning: false } })).status).toBe(200);+ expect(store.bot(bot.id)?.localVm).toEqual({ keepDesktopRunning: false });+ expect((await patch(bot.id, { localVm: null })).status).toBe(200);+ expect(store.bot(bot.id)?.localVm).toBeUndefined();+ const refused = await patch(bot.id, { localVm: { keepDesktopRunning: "yes" } });+ expect(refused.status).toBe(400);+ expect(refused.body.error).toBe("localVm must be { keepDesktopRunning?: boolean }");+ });+});+describe("PATCH /api/bots/:id liveVoice", () => {it.each(["nuri", "juni", "flitz", "brise", "sillage", "nira", "harema", "shida", "noeul"])("saves %s as the bot's Live call voice", async (liveVoice) => {const { store, bot, patch } = fixture();diff --git a/server/routes/bot-patch.ts b/server/routes/bot-patch.tsindex 9a664d9b27..bf3f8a14f0 100644--- a/server/routes/bot-patch.ts+++ b/server/routes/bot-patch.ts@@ -22,6 +22,7 @@ import type { CacheKeepWarm } from "../cache-keepwarm.ts";import { cloudBackendChangeError, vpsBotAliasChangeError, vpsLeftBehindNotice, VPS_BOT_ALIAS_CHANGE_ERROR, VPS_BOT_ALIAS_LIFECYCLE_ERROR, VPS_BOT_ALIAS_RESOURCES_ERROR } from "../cloud-backend.ts";import * as composio from "../composio.ts";import { isValidSshAlias, type AppConfig } from "../config.ts";+import { perBotLocalVmConfigSchema } from "../local-vm-settings.ts";import type { ModelSelection } from "../contracts.ts";import type { createApprovalModeSupport } from "../harness-capabilities.ts";import type { ProviderRegistry } from "../harness/registry.ts";@@ -460,6 +461,17 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {if (body.chiefOfStaff !== undefined && typeof body.chiefOfStaff !== "boolean") {return json(res, 400, { error: "chiefOfStaff must be true or false" });}+ if (body.localVm !== undefined) {+ if (body.localVm === null) {+ patch.localVm = undefined;+ } else if (typeof body.localVm === "object" && body.localVm !== null) {+ const parsed = perBotLocalVmConfigSchema.safeParse(body.localVm);+ if (!parsed.success) return json(res, 400, { error: "localVm must be { keepDesktopRunning?: boolean }" });+ patch.localVm = parsed.data;+ } else {+ return json(res, 400, { error: "localVm must be an object or null" });+ }+ }if (body.cloudBackend !== undefined) {const backendError = cloudBackendChangeError(Boolean(existingBot?.busy), activeVpsThreads.has(m[1]));if (backendError) return json(res, 409, { error: backendError });diff --git a/shared/app-frame/app-host.html b/shared/app-frame/app-host.htmlindex 4863df20c9..c97f875078 100644--- a/shared/app-frame/app-host.html+++ b/shared/app-frame/app-host.html@@ -1,10 +1,10 @@-<!-- mausbot app-host v1 sha256:5a7eda35e9359dca4a7a4556663a65439a861c8c7e976cbfef77ec34274f25ac -->+<!-- mausbot app-host v1 sha256:788bd71c2286b1a5975a6a486068c11e34d08130be264f22c21cfcf78a1a977c --><!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"><meta name="color-scheme" content="light dark"><title>App</title><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 v(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(!v(e)||e.jsonrpc!=="2.0")return null;let t=G(e);return t===null||t>m.messageBytes||e.params!==void 0&&!v(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||v(e.error)&&typeof e.error.code=="number"&&typeof e.error.message=="string"?e:null}function H(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 B(e){return v(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)||v(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&&!v(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:v(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(!v(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:H(m.rates.message,g),openLink:H(m.rates.openLink,g),rpc:H(m.rates.rpc,g),log:H([[6e4,m.logsPerMinute]],g)},A=null,o=null,u=-1/0,h=n=>{if(!k)try{r.post(n)}catch{}},C=(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&&!v(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);C(n,x??{})}catch(x){let P=B(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{C(n,await r.callRpc(p,ce(p,s,_,()=>r.engaged()))??{})}catch(oe){let D=B(oe);i(n,D.code,D.message)}},ne=async(n,p,s)=>{if(p==="ui/initialize")return S=!0,C(n,{protocolVersion:U,hostInfo:{name:"mausbot",version:e.hostVersion},hostCapabilities:se(t),hostContext:d});if(y)switch(p){case"ping":return C(n,{});case"ui/request-display-mode":return C(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),C(n,{})}catch(x){return i(n,f,B(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),C(n,{})}catch(x){return i(n,f,B(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&&!v(s.structuredContent))return i(n,M,"ui/update-model-context takes {content?, structuredContent?}.");if(A={...Array.isArray(s?.content)?{content:s.content}:{},...v(s?.structuredContent)?{structuredContent:s.structuredContent}:{}},o===null){let c=u+m.contextCoalesceMs-g();c<=0?F():o=l.set(F,c)}return C(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,C)=>{let i=`c${++S}`;y.set(i,{resolve:h,reject:C}),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>+<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 v(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(!v(e)||e.jsonrpc!=="2.0")return null;let t=G(e);return t===null||t>m.messageBytes||e.params!==void 0&&!v(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||v(e.error)&&typeof e.error.code=="number"&&typeof e.error.message=="string"?e:null}function H(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,c]of e)if(r.filter(R=>l-R<g).length>=c)return!1;return r.push(l),!0}}}function B(e){return v(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(c=>"connector"in c&&c.connector===l)&&t.some(c=>"server"in c&&c.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 ce(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)||v(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&&!v(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 de(e,t,r,a){return e==="mausbot/connectors/list"?{}:r?{...r,arguments:v(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(!v(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(),c={...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:H(m.rates.message,g),openLink:H(m.rates.openLink,g),rpc:H(m.rates.rpc,g),log:H([[6e4,m.logsPerMinute]],g)},A=null,o=null,u=-1/0,h=n=>{if(!k)try{r.post(n)}catch{}},C=(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=c.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&&!v(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);C(n,x??{})}catch(x){let P=B(x);i(n,P.code,P.message)}},te=async(n,p,s)=>{if(a)return i(n,L,"Method not found");let d=j(p),x=d==="connectors"?t.can.connectors??[]:[];if(d==="connectors"?!x.length:!t.can[d])return i(n,f,le(d,!!t.room));let P=ce(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{C(n,await r.callRpc(p,de(p,s,_,()=>r.engaged()))??{})}catch(oe){let D=B(oe);i(n,D.code,D.message)}},ne=async(n,p,s)=>{if(p==="ui/initialize")return S=!0,C(n,{protocolVersion:U,hostInfo:{name:"mausbot",version:e.hostVersion},hostCapabilities:se(t),hostContext:c});if(y)switch(p){case"ping":return C(n,{});case"ui/request-display-mode":return C(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 d=ae(s?.url);if(!d)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(d),C(n,{})}catch(x){return i(n,f,B(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 d=ge(s);if(d===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(d),C(n,{})}catch(x){return i(n,f,B(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&&!v(s.structuredContent))return i(n,M,"ui/update-model-context takes {content?, structuredContent?}.");if(A={...Array.isArray(s?.content)?{content:s.content}:{},...v(s?.structuredContent)?{structuredContent:s.structuredContent}:{}},o===null){let d=u+m.contextCoalesceMs-g();d<=0?F():o=l.set(F,d)}return C(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 d=w.get(s.id);d&&(w.delete(s.id),d(s))},contextChanged(n){k||(c={...c,...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,d=()=>{s||(s=!0,w.delete(p),l.clear(x),n())},x=l.set(d,m.teardownMs);w.set(p,d),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 c;try{c=JSON.parse(g.data)}catch{return}c&&typeof c=="object"&&c.v===Q&&l(c)}}}:null}function fe(e,t){let r=t??me(e);if(!r)return null;let a=e.document,l=null,g=null,c=0,R=!1,S=0,y=new Map,k=o=>{try{r.send(o)}catch{}},I=(o,u)=>new Promise((h,C)=>{let i=`c${++S}`;y.set(i,{resolve:h,reject:C}),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"&&(c=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()-c<=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)&&(c=Math.max(c,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>diff --git a/src/components/BotSettingsDialog.simple.test.ts b/src/components/BotSettingsDialog.simple.test.tsindex dd784cc1ca..f836839105 100644--- a/src/components/BotSettingsDialog.simple.test.ts+++ b/src/components/BotSettingsDialog.simple.test.ts@@ -422,6 +422,15 @@ describe("the bot panel in Simple mode", () => {expect(shown(panel(makeBot(), "access"))).toEqual({ tab: "computer", page: undefined });});+ it("shows Keep this bot's desktop always running only for per-bot desktops", () => {+ fixture.advanced = true;+ fixture.storeState = { settingsOpen: true, botSettingsSection: "identity", botSettingsExpandAccordion: true, config: { localVm: { mode: "per-bot" } } };+ expect(dialog(makeBot()).html).toContain("Keep this bot's desktop always running");+ fresh();+ fixture.storeState = { ...fixture.storeState, config: { localVm: { mode: "shared" } } };+ expect(dialog(makeBot()).html).not.toContain("Keep this bot's desktop always running");+ });+it("shows no switch on any tab, and on Bot settings only Notifications and Bot API's: memory, upkeep, browser, record steps and Work until done live elsewhere", () => {const bot = makeBot();expect(switches(panel(bot).html)).toBe(0);diff --git a/src/components/bot-settings/IdentitySection.tsx b/src/components/bot-settings/IdentitySection.tsxindex 719dac80b2..6fab2a2b8a 100644--- a/src/components/bot-settings/IdentitySection.tsx+++ b/src/components/bot-settings/IdentitySection.tsx@@ -16,6 +16,7 @@ import { ProposalStatus } from "./ProposalStatus";import { randomBotName } from "@/lib/random-bot-name";import { intlLocale, t } from "@/lib/i18n";import { useStoreRef } from "@/state/store-ref";+import { useStoreSelector } from "@/state/store-select";export type IdentityPart = "avatar" | "provenance" | "name" | "title" | "blurb";@@ -38,6 +39,7 @@ export function IdentitySection({const { draft } = useBotEditor();const store = useStoreRef();const shows = (part: IdentityPart) => !parts || parts.includes(part);+ const perBotDesktop = useStoreSelector((state) => state.config?.localVm?.mode === "per-bot");return (<div className="flex flex-col gap-4">@@ -109,6 +111,19 @@ export function IdentitySection({</div></div>}+ {shows("name") && perBotDesktop && <Field label={t("botSettings.identity.keepDesktopRunning")}>+ <label className="flex items-center gap-2 cursor-pointer">+ <input+ type="checkbox"+ checked={bot.localVm?.keepDesktopRunning === true}+ onChange={(e) => patch({ localVm: { keepDesktopRunning: e.target.checked } })}+ className="size-4 rounded border-hairline/40 text-accent focus-visible:ring-2 focus-visible:ring-accent/60"+ />+ <span className="text-[13px] text-ink">{t("botSettings.identity.keepDesktopRunningLabel")}</span>+ </label>+ <p className="mt-1 text-[12px] text-ink-secondary">{t("botSettings.identity.keepDesktopRunningHelp")}</p>+ </Field>}+<DefaultBotHideRow bot={bot} />{instructionsOpen && <BotInstructionsDialog bot={bot} inline={draft} onClose={() => setInstructionsOpen(false)} />}</div>diff --git a/src/components/bot-settings/useBotSettingsDerived.ts b/src/components/bot-settings/useBotSettingsDerived.tsindex 4c2ef3455d..fcce47a14c 100644--- a/src/components/bot-settings/useBotSettingsDerived.ts+++ b/src/components/bot-settings/useBotSettingsDerived.ts@@ -49,6 +49,7 @@ export type BotPatch = Partial<| "recordBrowserSteps"| "mcpServers"| "modelSelection"+ | "localVm">> & {computer?: Bot["computer"] | null;diff --git a/src/locales/en.json b/src/locales/en.jsonindex cf38252006..039500d110 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -4871,6 +4871,9 @@"botSettings.identity.viewFull": "View full","botSettings.identity.blurbPlaceholder": "One line on what this bot is for","botSettings.identity.blurbHelp": "Shown in rosters, on the phone, and to other bots. Standing instructions belong in Soul, which has room for a full document.",+ "botSettings.identity.keepDesktopRunning": "Local VM",+ "botSettings.identity.keepDesktopRunningLabel": "Keep this bot's desktop always running",+ "botSettings.identity.keepDesktopRunningHelp": "When on, this bot's Local VM desktop is never stopped by the idle timer. Other bots still stop after the shared idle timeout. Counts toward the per-bot desktop limit.","botSettings.soul.description": "Who this bot is and the rules it never breaks. Always in its context.","botSettings.visibility.subtitle": "Choose who sees this bot, its conversations, the rooms it is in and its files. Admins always can.","botSettings.visibility.everyone": "Everyone who can sign in",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 0dd3959498..40cdc81e9f 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -4515,6 +4515,9 @@"botSettings.identity.viewFull": "Ver completo","botSettings.identity.blurbPlaceholder": "Diga em uma linha para que serve este bot","botSettings.identity.blurbHelp": "Aparece nas listas, no celular e para outros bots. As instruções permanentes ficam em Essência, onde cabe um documento completo.",+ "botSettings.identity.keepDesktopRunning": "VM local",+ "botSettings.identity.keepDesktopRunningLabel": "Manter a área de trabalho deste bot sempre ativa",+ "botSettings.identity.keepDesktopRunningHelp": "Quando ativada, a área de trabalho da VM local deste bot permanece ativa durante a inatividade. As áreas de trabalho dos outros bots continuam sendo encerradas após o tempo limite de inatividade. Esta área de trabalho conta para o limite de áreas de trabalho por bot.","botSettings.soul.description": "Quem este bot é e quais regras nunca quebra. Tudo isso fica sempre no contexto.","botSettings.visibility.subtitle": "Escolha quem vê este bot, as conversas e os arquivos dele e os grupos em que ele está. Os admins sempre podem ver tudo isso.","botSettings.visibility.everyone": "Todos que podem entrar",diff --git a/src/state/store.tsx b/src/state/store.tsxindex 7d97bc8cdb..8baf416c4b 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -319,7 +319,7 @@ export interface Bot extends DefaultBotFields, Pick<WireBot, "mascotFaceColor" |section?: string;pinnedMessageId?: string;chiefOfStaff?: boolean;- managedSections?: string[];+ managedSections?: string[]; localVm?: { keepDesktopRunning?: boolean };createdBy?: string; reportsTo?: string;composio?: boolean;connectorTools?: Record<string, ConnectorToolGrant>;