Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Bot pages can read their bot's data and keep state when they declare it (#7657)
Milind Sonife523aca350f
diff --git a/packages/phone-protocol/src/app-rpc.ts b/packages/phone-protocol/src/app-rpc.tsindex 3d447f8743..e218992c23 100644--- a/packages/phone-protocol/src/app-rpc.ts+++ b/packages/phone-protocol/src/app-rpc.ts@@ -17,6 +17,12 @@ export type JsonRpcMessage =export const APP_RPC_METHODS = ["tools/call", "tools/list", "resources/read", "resources/list"] as const;export type AppRpcMethod = (typeof APP_RPC_METHODS)[number];+/** What a bot's page may ask its own server for, each only when the page declared it (show_html `uses`):+ * `mausbot/data/query` {sql, params?} → {columns, rows, truncated}; `mausbot/state/get` {key} → {value?};+ * `mausbot/state/set` {key, value?} (no value removes the key) → {}; `mausbot/state/keys` {} → {keys}. */+export const PAGE_RPC_METHODS = ["mausbot/data/query", "mausbot/state/get", "mausbot/state/set", "mausbot/state/keys"] as const;+export type PageRpcMethod = (typeof PAGE_RPC_METHODS)[number];+export const RPC_METHOD_NOT_FOUND = -32601;export const RPC_INVALID_PARAMS = -32602;export const RPC_HOST_REFUSED = -32000;diff --git a/packages/phone-protocol/src/app.ts b/packages/phone-protocol/src/app.tsindex b16e4c0a5c..b00d4b7bd6 100644--- a/packages/phone-protocol/src/app.ts+++ b/packages/phone-protocol/src/app.ts@@ -30,8 +30,23 @@ export const APP_LIMITS = {messagesPerHour: 20,/** rpc calls per app row per minute. */rpcPerMinute: 60,+ /** mausbot.data.query: rows and JSON bytes of rows one answer holds, the SQL's length, and its wall clock. */+ pageQueryRows: 5_000,+ pageQueryBytes: 1_000_000,+ pageQuerySqlChars: 20_000,+ pageQueryMs: 10_000,+ /** mausbot.state: a key's characters, one value's JSON bytes, all of a page's values, and its keys. */+ pageStateKeyChars: 200,+ pageStateValueBytes: 64 * 1024,+ pageStateBytes: 256 * 1024,+ pageStateKeys: 200,} as const;+/** What a bot's page may ask the host for beyond the bridge's basics, declared with show_html `uses`: `data`, read-only+ * SQL on its bot's database; `state`, a small store of its own that its later versions keep. */+export const APP_USES = ["data", "state"] as const;+export type AppUse = (typeof APP_USES)[number];+/** Versions of one bot page kept for stepping back, the current one included. */export const APP_PAGE_VERSIONS = 10;@@ -139,6 +154,9 @@ export interface AppCan {message: boolean;openLinks: boolean;modelContext: boolean;+ /** A bot's page that declared `data` or `state` (show_html `uses`), outside a room. */+ data?: boolean;+ state?: boolean;}export interface AppToolDefinition {@@ -197,6 +215,7 @@ export interface ShowHtmlInput {frameless?: boolean;/** Reload the page in place whenever a file in its folder changes; only with `path`. */live?: boolean;+ uses?: AppUse[];}export interface UpdateHtmlInput {@@ -209,6 +228,8 @@ export interface UpdateHtmlInput {frameless?: boolean;/** Turn reloading on folder changes on (only with `path`) or off; kept as it was when omitted. */live?: boolean;+ /** Kept as the page's current version declared when omitted. */+ uses?: AppUse[];}export type AppInputResult<T> = { ok: true; value: T } | { ok: false; error: string };@@ -298,6 +319,26 @@ function checkLive(value: unknown, path: string | undefined): AppInputResult<booreturn { ok: true, value };}+const USES_HELP = 'uses: a list of "data" and "state", e.g. ["data", "state"].';++/** A list of names; a string holding one name, several separated by commas, or a JSON list is read as that list. */+function checkUses(value: unknown): AppInputResult<AppUse[] | undefined> {+ if (value === undefined || value === null) return { ok: true, value: undefined };+ let list: unknown = value;+ if (typeof list === "string") {+ const text = list.trim();+ try { list = text.startsWith("[") ? JSON.parse(text) : text.split(","); } catch { return { ok: false, error: USES_HELP }; }+ }+ if (!Array.isArray(list)) return { ok: false, error: USES_HELP };+ const uses: AppUse[] = [];+ for (const item of list) {+ const name = typeof item === "string" ? item.trim().toLowerCase() : "";+ if (!(APP_USES as readonly string[]).includes(name)) return { ok: false, error: USES_HELP };+ if (!uses.includes(name as AppUse)) uses.push(name as AppUse);+ }+ return { ok: true, value: uses };+}+export function parseShowHtmlInput(input: unknown): AppInputResult<ShowHtmlInput> {if (!isRecord(input)) return { ok: false, error: "show_html needs {html, jsx or path, title, height?, fallback_text?}." };const page = checkPage(input);@@ -311,6 +352,9 @@ export function parseShowHtmlInput(input: unknown): AppInputResult<ShowHtmlInputconst live = checkLive(input.live, out.path);if (!live.ok) return live;if (live.value) out.live = true;+ const uses = checkUses(input.uses);+ if (!uses.ok) return uses;+ if (uses.value?.length) out.uses = uses.value;if (input.height !== undefined && input.height !== null) {if (typeof input.height !== "number" || !Number.isFinite(input.height)) return { ok: false, error: "height: must be a number of pixels, 80 to 720." };out.height = Math.round(Math.min(APP_LIMITS.heightMax, Math.max(APP_LIMITS.heightMin, input.height)));@@ -338,6 +382,9 @@ export function parseUpdateHtmlInput(input: unknown): AppInputResult<UpdateHtmlIconst live = checkLive(input.live, out.path);if (!live.ok) return live;if (live.value !== undefined) out.live = live.value;+ const uses = checkUses(input.uses);+ if (!uses.ok) return uses;+ if (uses.value !== undefined) out.uses = uses.value;if (input.title !== undefined && input.title !== null) {const title = checkTitle(input.title);if (!title.ok) return title;diff --git a/server/app-docs.ts b/server/app-docs.tsindex 5fbcf28285..c1c1c14517 100644--- a/server/app-docs.ts+++ b/server/app-docs.ts@@ -5,7 +5,7 @@ import { createHash, randomBytes } from "node:crypto";import { mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";import { join } from "node:path";-import type { AppNetwork, AppSource, AppToolDefinition, AppToolResult } from "../shared/app.ts";+import type { AppNetwork, AppSource, AppToolDefinition, AppToolResult, AppUse } from "../shared/app.ts";import type { PageVideo } from "./pages/bundle.ts";export const APP_DOCS_MAX_BYTES = 512 * 1024 * 1024;@@ -24,6 +24,8 @@ export interface AppDocData {files?: Record<string, string>;/** Videos that stay on disk, by path in the folder. They take no room in this store. */videos?: Record<string, PageVideo>;+ /** What a bot's page declared it uses (show_html `uses`). */+ uses?: AppUse[];tool?: AppToolDefinition;toolInput?: Record<string, unknown>;toolResult?: AppToolResult;diff --git a/server/app-state.ts b/server/app-state.tsnew file mode 100644index 0000000000..adbad2f601--- /dev/null+++ b/server/app-state.ts@@ -0,0 +1,106 @@+// What bot pages keep for themselves (mausbot.state), under DATA_DIR/app-state/<threadId>/<messageId>.json. A page's+// versions are one row, so they share one file; the file goes with the row.+import { randomBytes } from "node:crypto";+import { mkdirSync, readdirSync, readFileSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs";+import { join } from "node:path";++import { APP_LIMITS, utf8Bytes } from "../shared/app.ts";++const ID = /^[\w-]{1,128}$/;++interface StateFile {+ v: 1;+ values: Record<string, unknown>;+}++export type AppStateResult<T> = { ok: true; value: T } | { ok: false; status: 400 | 404 | 413; error: string };++export class AppStates {+ private readonly dir: string;++ constructor(dir: string) {+ this.dir = dir;+ }++ private file(threadId: string, messageId: string): string | null {+ return ID.test(threadId) && ID.test(messageId) ? join(this.dir, threadId, `${messageId}.json`) : null;+ }++ private read(file: string): Record<string, unknown> {+ try {+ const parsed = JSON.parse(readFileSync(file, "utf8")) as StateFile;+ return parsed && parsed.v === 1 && parsed.values && typeof parsed.values === "object" && !Array.isArray(parsed.values) ? parsed.values : {};+ } catch {+ return {};+ }+ }++ get(threadId: string, messageId: string, key: string): AppStateResult<unknown> {+ const file = this.file(threadId, messageId);+ if (!file) return { ok: false, status: 404, error: "That page is not in this conversation." };+ const values = this.read(file);+ return { ok: true, value: Object.hasOwn(values, key) ? values[key] : undefined };+ }++ keys(threadId: string, messageId: string): AppStateResult<string[]> {+ const file = this.file(threadId, messageId);+ if (!file) return { ok: false, status: 404, error: "That page is not in this conversation." };+ return { ok: true, value: Object.keys(this.read(file)) };+ }++ /** `value` undefined removes the key. */+ set(threadId: string, messageId: string, key: string, value: unknown): AppStateResult<null> {+ const file = this.file(threadId, messageId);+ if (!file) return { ok: false, status: 404, error: "That page is not in this conversation." };+ if (!key || key.length > APP_LIMITS.pageStateKeyChars) return { ok: false, status: 400, error: `A state key is text of 1 to ${APP_LIMITS.pageStateKeyChars} characters.` };+ const values = this.read(file);+ if (value === undefined) {+ if (!Object.hasOwn(values, key)) return { ok: true, value: null };+ delete values[key];+ } else {+ let text: string | undefined;+ try { text = JSON.stringify(value); } catch { text = undefined; }+ if (text === undefined) return { ok: false, status: 400, error: "A state value is anything JSON can hold." };+ if (utf8Bytes(text) > APP_LIMITS.pageStateValueBytes) {+ return { ok: false, status: 413, error: `A state value is at most ${APP_LIMITS.pageStateValueBytes} bytes as JSON.` };+ }+ if (!Object.hasOwn(values, key) && Object.keys(values).length >= APP_LIMITS.pageStateKeys) {+ return { ok: false, status: 413, error: `A page keeps at most ${APP_LIMITS.pageStateKeys} keys; remove one first.` };+ }+ values[key] = JSON.parse(text) as unknown;+ }+ const body = JSON.stringify({ v: 1, values } satisfies StateFile);+ if (utf8Bytes(body) > APP_LIMITS.pageStateBytes) {+ return { ok: false, status: 413, error: `A page keeps at most ${APP_LIMITS.pageStateBytes} bytes of state; remove something first.` };+ }+ if (Object.keys(values).length === 0) {+ try { unlinkSync(file); } catch { /* never written */ }+ return { ok: true, value: null };+ }+ mkdirSync(join(this.dir, threadId), { recursive: true, mode: 0o700 });+ const temp = `${file}.${randomBytes(6).toString("hex")}.tmp`;+ writeFileSync(temp, body, { mode: 0o600 });+ renameSync(temp, file);+ return { ok: true, value: null };+ }++ /** Removes the state of every page whose row is gone; how many files went. */+ sweep(rowExists: (threadId: string, messageId: string) => boolean): number {+ let removed = 0;+ let threads: string[];+ try { threads = readdirSync(this.dir); } catch { return 0; }+ for (const threadId of threads) {+ const folder = join(this.dir, threadId);+ let names: string[];+ try { names = readdirSync(folder); } catch { continue; }+ let left = names.length;+ for (const name of names) {+ const messageId = name.endsWith(".json") ? name.slice(0, -".json".length) : "";+ if (!name.endsWith(".tmp") && ID.test(threadId) && ID.test(messageId) && rowExists(threadId, messageId)) continue;+ try { unlinkSync(join(folder, name)); removed += 1; left -= 1; } catch { /* gone meanwhile */ }+ }+ if (left === 0) { try { rmdirSync(folder); } catch { /* written meanwhile */ } }+ }+ return removed;+ }+}diff --git a/server/chat-apps.ts b/server/chat-apps.tsindex 482ba0a65d..c0e7c9a29e 100644--- a/server/chat-apps.ts+++ b/server/chat-apps.ts@@ -2,12 +2,13 @@ import type { IncomingMessage, ServerResponse } from "node:http";import {APP_LIMITS, APP_PAGE_VERSIONS, appBlockedText, htmlFallbackText, oneLine, parseShowHtmlInput, parseUpdateHtmlInput, utf8Bytes,- type AppCan, type AppDocument, type AppPayload,+ type AppCan, type AppDocument, type AppPayload, type AppUse,} from "../shared/app.ts";import { BOT_HTML_NETWORK } from "../shared/app-frame/csp.ts";import { botHtmlDocument, mcpAppDocument, publishedBotHtml, ROOM_CAN } from "../shared/app-frame/document.ts";import { jsxPublishedHtml } from "../shared/app-frame/jsx-page.ts";import { APP_DOCS_SWEEP_GRACE_MS, AppDocs, type AppDocData, type AppDocPut } from "./app-docs.ts";+import { AppStates } from "./app-state.ts";import { speakerIn, type AgentCardResult, type AgentCardStore } from "./chat-widgets.ts";import { compileJsxPage } from "./jsx-compile.ts";import { appDocRefs } from "./message-db.ts";@@ -24,6 +25,7 @@ const NOT_A_PAGE = "That app came from an MCP server, not from show_html; it canexport interface ChatAppsStore extends AgentCardStore {onChange?(listener: (change: StoreChange) => void): () => void;+ botByThread?(threadId: string): unknown;}function isRecord(value: unknown): value is Record<string, unknown> {@@ -47,7 +49,7 @@ function scrubbed(html: string, title: string): { html: string; title: string; m}/** A folder page also carries the files beside its index.html and where they were read. */-type PageText = { html: string; format?: "jsx"; files?: PageFile[]; folder?: string; videos?: AppDocData["videos"] };+type PageText = { html: string; format?: "jsx"; files?: PageFile[]; folder?: string; videos?: AppDocData["videos"]; uses?: AppUse[] };type MadePage = { ok: true; page: PageText; title: string; masked: boolean; leftOut?: string };/** The page's text, scrubbed; a jsx page is transpiled first, so one that cannot run is refused with where. */@@ -87,7 +89,8 @@ async function folderPage(path: string, title: string, folders: BotFolders): Pro}function storePage(docs: AppDocs, page: PageText): AppDocPut {- const data = { ...(page.format ? { format: page.format } : {}), ...(page.folder ? { folder: page.folder } : {}), ...(page.videos ? { videos: page.videos } : {}) };+ const data = { ...(page.format ? { format: page.format } : {}), ...(page.folder ? { folder: page.folder } : {}), ...(page.videos ? { videos: page.videos } : {}),+ ...(page.uses?.length ? { uses: page.uses } : {}) };return docs.put({ source: "html", html: page.html, ...(Object.keys(data).length ? { data } : {}), ...(page.files ? { files: page.files } : {}) });}@@ -127,10 +130,11 @@ export function createAppCard(args: {function placePage(args: { store: AgentCardStore; docs: AppDocs; bot: { id: string; name: string; color: MausColor }; threadId: string; authored?(messageId: string): void },- value: { appId?: string; height?: number; fallbackText?: string; frameless?: boolean; live?: boolean },- made: MadePage,+ value: { appId?: string; height?: number; fallbackText?: string; frameless?: boolean; live?: boolean; uses?: AppUse[] },+ given: MadePage,): AgentCardResult {const { store, docs, bot, threadId } = args;+ const made = value.uses === undefined ? given : { ...given, page: { ...given.page, uses: value.uses } };const { page } = made;if (value.appId === undefined) {const stored = storePage(docs, page);@@ -162,7 +166,8 @@ function replacePage(store: Pick<AgentCardStore, "patchMessage">, docs: AppDocs, threadId: string, existing: Message & { app: AppPayload }, made: MadePage,options: { frameless?: boolean; live?: boolean } = {},): Message | null {- const { page } = made;+ // A version that says nothing about `uses` (a live folder's reload, a replacement without it) keeps what the page declared.+ const page = made.page.uses !== undefined ? made.page : { ...made.page, uses: docs.read(existing.app.doc)?.data?.uses };const stored = storePage(docs, page);const border = options.frameless === undefined ? existing.app.border : !options.frameless;// Only a page from a folder can stay live; a page sent as html or jsx stops being live.@@ -230,7 +235,8 @@ export function appDocument(args: {const files = stored.data?.folder && args.files? `${args.files.origin}${args.files.folder({ threadId: args.threadId, messageId: row.id, doc: version.doc })}` : undefined;return botHtmlDocument({ messageId: row.id, rev, html: stored.html, title: row.app.title,- ...(stored.data?.format === "jsx" ? { format: "jsx" as const } : {}), ...(files ? { files } : {}), ...(room ? { room } : {}) });+ ...(stored.data?.format === "jsx" ? { format: "jsx" as const } : {}), ...(files ? { files } : {}), ...(room ? { room } : {}),+ ...(stored.data?.uses?.length ? { uses: stored.data.uses } : {}) });}if (!stored.data?.tool) return null;const access: ReturnType<McpAppAccess> = room ? { can: ROOM_CAN } : (args.mcpAccess ?? MCP_READ_ONLY)(row, args.threadId);@@ -453,6 +459,12 @@ export function rowRate(limit: number, windowMs: number): { take(key: string, noexport interface ChatApps {readonly docs: AppDocs;+ /** Each bot page's own small store (mausbot.state), by conversation and row: every version of a page shares it. */+ readonly states: AppStates;+ /** What the current version of a bot's page declared it uses; none for an MCP app or a missing row. */+ declaredUses(threadId: string, messageId: string): AppUse[];+ /** True while the workspace is being backed up or restored: a page's state waits. */+ paused(): boolean;createAppCard(args: {bot: { id: string; name: string; color: MausColor }; threadId: string; input: Record<string, unknown>; authored?(messageId: string): void; folders?: BotFolders;}): AgentCardResult | Promise<AgentCardResult>;@@ -495,12 +507,19 @@ export function createChatApps(deps: {liveRoots?(threadId: string, botId: string | undefined): readonly string[] | null;}): ChatApps {const docs = new AppDocs(`${deps.dataDir}/app-docs`, deps.maxBytes ? { maxBytes: deps.maxBytes } : {});+ const states = new AppStates(`${deps.dataDir}/app-state`);const references = deps.references ?? appDocRefs;const sweep = () => {- try { return docs.sweep(references()); } catch (error) {+ let removed = 0;+ try { removed += docs.sweep(references()); } catch (error) {console.error("chat apps: document sweep failed", error);- return 0;}+ // A conversation that is gone is never read: reading one would bring it back into the store.+ const known = (threadId: string) => Boolean(deps.store.groupByThread(threadId) || deps.store.botByThread?.(threadId));+ try { removed += states.sweep((threadId, messageId) => known(threadId) && Boolean(appRow(deps.store, threadId, messageId))); } catch (error) {+ console.error("chat apps: page state sweep failed", error);+ }+ return removed;};let pending: ReturnType<typeof setTimeout> | null = null;let pendingAt = Infinity;@@ -600,6 +619,12 @@ export function createChatApps(deps: {liveTimer?.unref?.();const apps: ChatApps = {docs,+ states,+ declaredUses: (threadId, messageId) => {+ const row = appRow(deps.store, threadId, messageId);+ return row?.app.source === "html" && row.app.doc ? docs.read(row.app.doc)?.data?.uses ?? [] : [];+ },+ paused: () => deps.paused?.() ?? false,createAppCard: (args) => {const result = createAppCard({ ...args, store: deps.store, docs });return result instanceof Promise ? result.then((done) => watchIfLive(args.threadId, done)) : watchIfLive(args.threadId, result);diff --git a/server/data/engine.ts b/server/data/engine.tsindex 0f01b79bb0..26cafe3206 100644--- a/server/data/engine.ts+++ b/server/data/engine.ts@@ -12,6 +12,7 @@ import { boxCpus } from "../box-cpus.ts";import { boxMemory } from "../box-memory.ts";import { DATA_DIR } from "../config.ts";import { tableIdentifierParts } from "./identifiers.ts";+import { preparePageQuery } from "./page-query.ts";import {DataFailure,type BotDatabase,@@ -335,17 +336,20 @@ class BotDb implements BotDatabase {const instance = await binding.DuckDBInstance.create(join(folder, DATA_DB_FILE), settings);let bot: DuckDB.DuckDBConnection | undefined;let panel: DuckDB.DuckDBConnection | undefined;+ let page: DuckDB.DuckDBConnection | undefined;try {bot = await instance.connect();panel = await instance.connect();+ page = await instance.connect();// A real schema: temp tables would be invisible to the panel's connection.await bot.run(`CREATE SCHEMA IF NOT EXISTS ${DATA_RESULTS_SCHEMA}`);const keywords = await bot.runAndReadAll("SELECT keyword_name FROM duckdb_keywords() WHERE keyword_category = 'reserved'");const reserved = new Set(keywords.getRowsJson().map((row) => String(row[0]).toLowerCase()));- return { binding, instance, lanes: { bot: new Lane(bot), panel: new Lane(panel) }, reserved };+ return { binding, instance, lanes: { bot: new Lane(bot), panel: new Lane(panel), page: new Lane(page) }, reserved };} catch (error) {bot?.closeSync();panel?.closeSync();+ page?.closeSync();instance.closeSync();throw error;}@@ -415,6 +419,27 @@ class BotDb implements BotDatabase {return this.statement(options.connection, sql, options, (open, conn) => this.read(open, conn, sql, maxRows));}+ async pageQuery(sql: string, params: unknown[] | Record<string, unknown> | undefined, options: { maxRows: number; timeoutMs: number; signal?: AbortSignal }): Promise<RunResult> {+ return this.statement("page", sql, options, async (open, conn) => {+ const started = performance.now();+ // A transaction a cancelled query left open ends before the next one begins.+ await conn.run("ROLLBACK").catch(() => undefined);+ await conn.run("BEGIN TRANSACTION READ ONLY");+ try {+ const prepared = await preparePageQuery(open.binding, conn, sql, params);+ const result = await prepared.stream();+ const rows: Cell[][] = [];+ for (let chunk = await result.fetchChunk(); chunk && chunk.rowCount > 0 && rows.length <= options.maxRows; chunk = await result.fetchChunk()) {+ rows.push(...this.cells(open.binding, chunk));+ }+ const kept = rows.slice(0, options.maxRows);+ return { columns: this.resultColumns(result), rows: kept, rowCount: kept.length, truncated: rows.length > options.maxRows, elapsedMs: Math.round(performance.now() - started) };+ } finally {+ await conn.run("ROLLBACK").catch(() => undefined);+ }+ });+ }+/** A first-time INSTALL is a download, so extensions load as their own step, off the statement's timeout. */private async loadExtensions(options: RunOptions): Promise<void> {const extensions = options.extensions ?? [];diff --git a/server/data/page-query.test.ts b/server/data/page-query.test.tsnew file mode 100644index 0000000000..bde12290b0--- /dev/null+++ b/server/data/page-query.test.ts@@ -0,0 +1,132 @@+// A bot's page reading its bot's database through real DuckDB: one SELECT on the bot's own tables, never a write, a file+// or a URL.+import { mkdtempSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { tmpdir } from "node:os";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import { DATA_RESULTS_SCHEMA } from "../../shared/data-surface.ts";+import { createDataEngine } from "./engine.ts";+import { DataFailure, type BotDatabase, type DataEngine } from "./types.ts";++const root = mkdtempSync(join(tmpdir(), "omb-page-query-"));+const csv = join(root, "secret.csv");+writeFileSync(csv, "token\nhunter2\n");+let engine: DataEngine;+let db: BotDatabase;+const LIMITS = { maxRows: 100, timeoutMs: 5_000 };++beforeAll(async () => {+ engine = createDataEngine({ botFolder: (botId) => join(root, "bots", botId), dataDir: join(root, "data") });+ db = await engine.forBot("scout");+ for (const sql of [+ "CREATE TABLE sales AS SELECT i AS id, ['north', 'south'][1 + i % 2] AS region, (i * 10)::BIGINT AS amount, (i / 4)::DECIMAL(10, 2) AS share FROM range(1, 301) t(i)",+ "CREATE VIEW north AS SELECT * FROM sales WHERE region = 'north'",+ `CREATE TABLE ${DATA_RESULTS_SCHEMA}.r1 AS SELECT 1 AS one`,+ "CREATE SEQUENCE ticket",+ "CREATE MACRO bump() AS nextval('ticket')",+ ]) await db.run(sql, { connection: "bot" });+});++afterAll(async () => {+ await engine.closeAll();+});++async function refused(sql: string, params?: unknown[] | Record<string, unknown>): Promise<DataFailure> {+ try {+ await db.pageQuery(sql, params, LIMITS);+ } catch (error) {+ if (error instanceof DataFailure) return error;+ throw error;+ }+ throw new Error(`ran: ${sql}`);+}++const salesCount = async () => (await db.run("SELECT count(*) FROM sales", { connection: "bot" })).rows[0]![0];++describe("pageQuery", () => {+ it("reads the bot's tables, views and results, with positional and named parameters", async () => {+ const top = await db.pageQuery("SELECT region, sum(amount) AS total FROM sales WHERE id <= ? GROUP BY region ORDER BY region", [10], LIMITS);+ expect(top.columns.map((column) => column.name)).toEqual(["region", "total"]);+ expect(top.rows).toEqual([["north", "300"], ["south", "250"]]);+ expect(top.truncated).toBe(false);+ expect((await db.pageQuery("SELECT count(*) AS n FROM north WHERE amount > $min", { min: 2_000 }, LIMITS)).rows).toEqual([["50"]]);+ expect((await db.pageQuery(`FROM ${DATA_RESULTS_SCHEMA}.r1`, undefined, LIMITS)).rows).toEqual([[1]]);+ expect((await db.pageQuery("WITH recent AS (SELECT * FROM sales WHERE id > 295) SELECT count(*) FROM recent, range(2)", undefined, LIMITS)).rows).toEqual([["10"]]);+ expect((await db.pageQuery("SELECT 1 AS a;", undefined, LIMITS)).rows).toEqual([[1]]);+ expect((await db.pageQuery("WITH RECURSIVE t(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM t WHERE n < 3), u AS (SELECT n FROM t) SELECT sum(n) FROM u", undefined, LIMITS)).rows).toEqual([["6"]]);+ });++ it("stops at maxRows and says the rest was left out", async () => {+ const result = await db.pageQuery("SELECT id FROM sales ORDER BY id", undefined, { maxRows: 7, timeoutMs: 5_000 });+ expect(result.rows).toHaveLength(7);+ expect(result.truncated).toBe(true);+ });++ it("refuses every statement but a SELECT, before it runs", async () => {+ for (const sql of [+ "INSERT INTO sales VALUES (999, 'x', 1, 1)",+ "UPDATE sales SET amount = 0",+ "DELETE FROM sales",+ "WITH gone AS (SELECT 1) DELETE FROM sales",+ "CREATE TABLE copy AS SELECT * FROM sales",+ "DROP TABLE sales",+ `ATTACH '${join(root, "other.duckdb")}' AS other`,+ `COPY sales TO '${join(root, "out.csv")}'`,+ "INSTALL httpfs",+ "LOAD httpfs",+ "SET threads = 1",+ "PRAGMA version",+ "CALL pragma_version()",+ "EXPLAIN SELECT 1",+ "DESCRIBE sales",+ "SELECT 1; DROP TABLE sales",+ "SELECT 1; SELECT 2",+ ]) {+ const failure = await refused(sql);+ expect(failure.error.code, sql).toBe("write_refused");+ }+ expect(await salesCount()).toBe("300");+ });++ it("refuses files, URLs, other databases and settings, without opening the file", async () => {+ for (const sql of [+ `SELECT * FROM read_csv('${csv}')`,+ `SELECT * FROM '${csv}'`,+ `SELECT (SELECT count(*) FROM read_text('${csv}')) AS n`,+ `SELECT * FROM glob('${root}/*')`,+ "SELECT * FROM query('SELECT 1')",+ "SELECT * FROM read_parquet('https://example.com/x.parquet')",+ "SELECT * FROM duckdb_settings()",+ "SELECT current_setting('temp_directory')",+ "SELECT nextval('ticket')",+ "SELECT * FROM information_schema.tables",+ "SELECT * FROM other.main.sales",+ "SELECT * FROM missing_table",+ // A CTE named like a file covers only its own scope, and only a plain name counts as one.+ `SELECT * FROM (WITH "${csv}" AS (SELECT 1) SELECT * FROM "${csv}")`,+ `SELECT * FROM (WITH x AS (SELECT 1) SELECT * FROM x), "${csv}"`,+ "WITH duckdb_databases AS (SELECT * FROM duckdb_databases) SELECT * FROM duckdb_databases",+ "WITH a AS (SELECT * FROM duckdb_databases), duckdb_databases AS (SELECT 1) SELECT * FROM a",+ "WITH RECURSIVE duckdb_databases AS (SELECT * FROM duckdb_databases UNION ALL SELECT 1) SELECT 1",+ ]) {+ const failure = await refused(sql);+ expect(failure.error.code, sql).toBe("write_refused");+ expect(failure.error.message, sql).not.toContain("hunter2");+ }+ });++ it("runs read-only: a macro that would write is stopped by DuckDB itself", async () => {+ const failure = await refused("SELECT bump()");+ expect(failure.error.code).toBe("sql_error");+ expect(failure.error.message).toMatch(/read-only/);+ expect((await db.run("SELECT currval('ticket')", { connection: "bot" }).catch(() => null))?.rows ?? null).toBeNull();+ });++ it("stops a query at its time limit and the next one runs", async () => {+ const failure = await db.pageQuery("SELECT count(*) FROM range(100000000) x, range(100000000) y", undefined, { maxRows: 1, timeoutMs: 300 }).catch((error: unknown) => error);+ expect(failure).toBeInstanceOf(DataFailure);+ expect((failure as DataFailure).error.code).toBe("timeout");+ expect((await db.pageQuery("SELECT count(*) FROM sales", undefined, LIMITS)).rows).toEqual([["300"]]);+ }, 30_000);+});diff --git a/server/data/page-query.ts b/server/data/page-query.tsnew file mode 100644index 0000000000..ceaf7a30a3--- /dev/null+++ b/server/data/page-query.ts@@ -0,0 +1,116 @@+// A bot's page reads its bot's database through mausbot.data.query. The instance is shared with the bot's own tools, which+// load files and URLs, so its external access stays on; what keeps a page's SQL away from files, the network and+// writes is this gate, every step of it judged by DuckDB itself, never by reading the text:+//+// 1. DuckDB splits the text: exactly one statement.+// 2. DuckDB's own parser serializes it (json_serialize_sql serializes only a SELECT) and the tree is walked before+// anything binds (binding a file reader already opens the file): table functions only from PURE_TABLE_FUNCTIONS,+// every table a table or view of this database (or, by a plain name, a CTE the reference can see: an earlier one, or+// itself from a recursive one's recursive side), so neither a file path nor a built-in view can pass as one,+// and no function from SETTINGS_FUNCTIONS.+// 3. DuckDB prepares it and names its type: SELECT only.+// 4. It runs inside a read-only transaction, which DuckDB refuses to write the database file from.+//+// Security: views and macros the bot made run as the bot wrote them, so one the bot made over a file reads that file.+import type * as DuckDB from "@duckdb/node-api";++import { DATA_RESULTS_SCHEMA } from "../../shared/data-surface.ts";+import { DataFailure } from "./types.ts";++export type PageQueryParams = unknown[] | Record<string, unknown>;++const PURE_TABLE_FUNCTIONS = new Set(["range", "generate_series", "unnest"]);+const SETTINGS_FUNCTIONS = new Set(["current_setting", "write_log", "nextval", "setseed", "getvariable"]);+const READABLE_SCHEMAS = new Set(["main", DATA_RESULTS_SCHEMA]);+const PLAIN_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;+const TABLE_REFS = new Set(["BASE_TABLE", "SUBQUERY", "JOIN", "EXPRESSION_LIST", "TABLE_FUNCTION", "EMPTY", "EMPTY_FROM", "PIVOT"]);++export const PAGE_QUERY_HINT = "A page runs one SELECT on its bot's own tables and views.";++const refuse = (message: string, sql: string) => new DataFailure({ code: "write_refused", message, sql, hint: PAGE_QUERY_HINT });++function isRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);+}++type Catalog = { tables: Set<string>; unqualified: Set<string> };++async function catalogOf(conn: DuckDB.DuckDBConnection): Promise<Catalog> {+ const reader = await conn.runAndReadAll(+ "SELECT schema_name, table_name FROM duckdb_tables() WHERE database_name = current_database() AND NOT internal " ++ "UNION ALL SELECT schema_name, view_name FROM duckdb_views() WHERE database_name = current_database() AND NOT internal");+ const tables = new Set<string>();+ const unqualified = new Set<string>();+ for (const [schema, name] of reader.getRowsJson() as Array<[string, string]>) {+ const schemaName = String(schema).toLowerCase();+ if (!READABLE_SCHEMAS.has(schemaName)) continue;+ tables.add(`${schemaName}.${String(name).toLowerCase()}`);+ if (schemaName === "main") unqualified.add(String(name).toLowerCase());+ }+ return { tables, unqualified };+}++/** Throws write_refused at the first thing in the parsed tree a page may not reach. */+export function checkPageTree(tree: unknown, catalog: Catalog, database: string, sql: string): void {+ const visit = (node: unknown, ctes: ReadonlySet<string>): void => {+ if (Array.isArray(node)) { for (const item of node) visit(item, ctes); return; }+ if (!isRecord(node)) return;+ const map = isRecord(node.cte_map) && Array.isArray(node.cte_map.map) ? node.cte_map.map : [];+ // A CTE's body sees the CTEs before it, and itself only from the recursive side of a recursive one; the query sees all.+ let scope = new Set(ctes);+ for (const entry of map) {+ const name = isRecord(entry) && typeof entry.key === "string" && PLAIN_NAME.test(entry.key) ? entry.key.toLowerCase() : null;+ const body = isRecord(entry) && isRecord(entry.value) && isRecord(entry.value.query) ? entry.value.query.node : undefined;+ if (isRecord(body) && body.type === "RECURSIVE_CTE_NODE" && name) {+ const own = new Set(scope).add(name);+ for (const [key, value] of Object.entries(body)) visit(value, key === "left" ? scope : own);+ } else visit(entry, scope);+ if (name) scope = new Set(scope).add(name);+ }+ if (node.class === "FUNCTION" && typeof node.function_name === "string" && SETTINGS_FUNCTIONS.has(node.function_name.toLowerCase())) {+ throw refuse(`${node.function_name}() cannot run from a page.`, sql);+ }+ const tableRef = typeof node.type === "string" && node.class === undefined && "alias" in node && "sample" in node;+ if (tableRef) {+ const type = node.type as string;+ if (!TABLE_REFS.has(type)) throw refuse(`A page cannot read ${type.toLowerCase().replace(/_/g, " ")}.`, sql);+ if (type === "TABLE_FUNCTION") {+ const name = isRecord(node.function) && typeof node.function.function_name === "string" ? node.function.function_name : "";+ if (!PURE_TABLE_FUNCTIONS.has(name.toLowerCase())) throw refuse(`${name || "That table function"}() cannot run from a page: files, URLs and settings stay out of its reach.`, sql);+ }+ if (type === "BASE_TABLE") checkTable(node, scope);+ }+ for (const [key, value] of Object.entries(node)) if (key !== "cte_map") visit(value, scope);+ };+ const checkTable = (node: Record<string, unknown>, ctes: ReadonlySet<string>) => {+ const name = String(node.table_name ?? "").toLowerCase();+ const schema = String(node.schema_name ?? "").toLowerCase();+ const catalogName = String(node.catalog_name ?? "").toLowerCase();+ const shown = [catalogName, schema, name].filter(Boolean).join(".");+ if (catalogName && catalogName !== database.toLowerCase()) throw refuse(`${shown} is not in this bot's database.`, sql);+ if (!schema) {+ if (ctes.has(name) || catalog.unqualified.has(name)) return;+ } else if (catalog.tables.has(`${schema}.${name}`)) return;+ throw refuse(`${shown} is not a table or view in this bot's database.`, sql);+ };+ visit(tree, new Set());+}++/** The prepared statement of a page's query, once it has passed every step but the transaction. */+export async function preparePageQuery(binding: typeof DuckDB, conn: DuckDB.DuckDBConnection, sql: string, params: PageQueryParams | undefined): Promise<DuckDB.DuckDBPreparedStatement> {+ const extracted = await conn.extractStatements(sql);+ if (extracted.count !== 1) throw refuse("One statement per query.", sql);+ const parsed = await conn.runAndReadAll("SELECT json_serialize_sql($1::VARCHAR), current_database()", [sql]);+ const [text, database] = parsed.getRowsJson()[0] as [string, string];+ let tree: unknown;+ try { tree = JSON.parse(text); } catch { throw refuse("DuckDB could not read that query.", sql); }+ if (!isRecord(tree) || tree.error === true) {+ const why = isRecord(tree) && typeof tree.error_message === "string" ? tree.error_message : "";+ throw /only select/i.test(why) ? refuse("Only a SELECT can run from a page.", sql) : new DataFailure({ code: "sql_error", message: why || "DuckDB could not read that query.", sql });+ }+ checkPageTree(tree.statements, await catalogOf(conn), String(database), sql);+ const prepared = await extracted.prepare(0);+ if (prepared.statementType !== binding.StatementType.SELECT) throw refuse("Only a SELECT can run from a page.", sql);+ if (params !== undefined) prepared.bind(params as DuckDB.DuckDBValue[] | Record<string, DuckDB.DuckDBValue>);+ return prepared;+}diff --git a/server/data/types.ts b/server/data/types.tsindex aec4c5ff2d..71d9db3c92 100644--- a/server/data/types.ts+++ b/server/data/types.ts@@ -20,7 +20,8 @@ export class DataFailure extends Error {}}-export type DataConnection = "bot" | "panel";+/** `page`: bot pages' read-only queries, on their own connection so they never wait behind the bot or the panel. */+export type DataConnection = "bot" | "panel" | "page";export type DataExtension = "httpfs" | "excel" | "azure" | "postgres" | "mysql" | "sqlite";export interface RunOptions {@@ -56,6 +57,9 @@ export interface DescribeResult {export interface BotDatabase {readonly botId: string;run(sql: string, options: RunOptions): Promise<RunResult>;+ /** One SELECT from a bot's page, judged by page-query.ts and run read-only on the page connection; at most `maxRows`+ * rows, `truncated` when there were more. `rowCount` is the rows returned. */+ pageQuery(sql: string, params: unknown[] | Record<string, unknown> | undefined, options: { maxRows: number; timeoutMs: number; signal?: AbortSignal }): Promise<RunResult>;materialise(sql: string, name: string, options: RunOptions): Promise<MaterialiseResult>;/** A missing table is not an error. */dropResult(name: string, connection?: DataConnection): Promise<void>;diff --git a/server/drivers/agents-app-tools.ts b/server/drivers/agents-app-tools.tsindex ee1065c79b..d04938d18d 100644--- a/server/drivers/agents-app-tools.ts+++ b/server/drivers/agents-app-tools.ts@@ -2,7 +2,7 @@ export const APP_TOOL_DEFINITIONS = [{name: "show_html",description:- "Show a small self-contained web page in this chat, where the person can point at a part to change: a mini app, a game, a chart, a calculator, a report. Forms and choices go in show_widget, plain data in a markdown table. Send `html` (a document or a fragment, with inline style and script), `jsx`, one React component file with a default export (it can import react, lucide-react icons, echarts, and Chart and useTheme from \"mausbot\", and style with Tailwind classes), or `path`, a folder in your working folder with index.html and its files (up to 5 MB). It runs in a locked sandbox: no network requests, storage, popups or form posts; scripts, styles and fonts load only from cdnjs.cloudflare.com, cdn.jsdelivr.net, unpkg.com and Google Fonts, images only as data: URLs or from those; embed the data. Theme: --color-text-primary, --color-background-primary, --color-border-primary, --font-sans. In the page, mausbot.send(text) puts text in their message box after they click in it, mausbot.open(url) opens a link, mausbot.setContext(text) tells you what they see. At most 256 KB. Call again with its app_id to replace it; it reloads. Never put secrets in it. In rooms everyone sees it, view-only. For a data dashboard, follow the data-dashboards skill. Asked for a claude.ai Artifact? Those need Claude's own claude.ai sign-in and are not available to bots here: say so in one line, then make it with this tool, or publish_page for a public link.",+ "Show a small self-contained web page in this chat, where the person can point at a part to change: a mini app, a game, a chart, a calculator, a report. Forms and choices go in show_widget, plain data in a markdown table. Send `html` (a document or a fragment, with inline style and script), `jsx`, one React component file with a default export (it can import react, lucide-react icons, echarts, and Chart and useTheme from \"mausbot\", and style with Tailwind classes), or `path`, a folder in your working folder with index.html and its files (up to 5 MB). It runs in a locked sandbox: no network requests, storage, popups or form posts; scripts, styles and fonts load only from cdnjs.cloudflare.com, cdn.jsdelivr.net, unpkg.com and Google Fonts, images only as data: URLs or from those; embed the data. Theme: --color-text-primary, --color-background-primary, --color-border-primary, --font-sans. In the page, mausbot.send(text) puts text in their message box after they click in it, mausbot.open(url) opens a link, mausbot.setContext(text) tells you what they see. uses [\"data\"]: mausbot.data.query(sql) SELECTs your Data tables; \"state\": mausbot.state.get/set. At most 256 KB. Call again with its app_id to replace it; it reloads. Never put secrets in it. In rooms everyone sees it, view-only. For a data dashboard, follow the data-dashboards skill. Asked for a claude.ai Artifact? Those need Claude's own claude.ai sign-in and are not available to bots here: say so in one line, then make it with this tool, or publish_page for a public link.",inputSchema: {type: "object",additionalProperties: false,@@ -15,6 +15,7 @@ export const APP_TOOL_DEFINITIONS = [fallback_text: { type: "string", description: "Optional plain text for clients without pages." },frameless: { type: "boolean", description: "true drops the card frame; a replacement keeps its frame unless given." },live: { type: "boolean", description: "With path: true reloads it when its folder changes." },+ uses: { type: "array", items: { type: "string", enum: ["data", "state"] } },app_id: { type: "string", description: "Only to replace a page you showed." },},},diff --git a/server/drivers/agents-call-cards.ts b/server/drivers/agents-call-cards.tsindex fc5340be4d..acd6250a7c 100644--- a/server/drivers/agents-call-cards.ts+++ b/server/drivers/agents-call-cards.ts@@ -21,14 +21,16 @@ async function callAppTool(name: "show_html" | "update_html", args: Json, contexconst page = parsed.value.jsx !== undefined ? { jsx: args.jsx } : parsed.value.path !== undefined ? { path: args.path } : { html: args.html };const frameless = parsed.value.frameless !== undefined ? { frameless: parsed.value.frameless } : {};const live = parsed.value.live !== undefined ? { live: parsed.value.live } : {};+ const uses = parsed.value.uses !== undefined ? { uses: parsed.value.uses } : {};const body = updating- ? { tool: name, app_id: args.app_id, ...page, ...(typeof args.title === "string" ? { title: args.title } : {}), ...frameless, ...live }+ ? { tool: name, app_id: args.app_id, ...page, ...(typeof args.title === "string" ? { title: args.title } : {}), ...frameless, ...live, ...uses }: {tool: name, ...page, title: args.title,...(typeof args.height === "number" ? { height: args.height } : {}),...(typeof args.fallback_text === "string" ? { fallback_text: args.fallback_text } : {}),...frameless,...live,+ ...uses,};const answer = await context.client.apiResponse(CARD_ROUTE, { method: "POST", body: JSON.stringify(body) });if (!answer.ok) return { text: String(answer.body.error ?? (updating ? "Could not update that page." : "Could not show that page.")), isError: true };diff --git a/server/drivers/agents-catalog-goldens/antigravity-cli.tools-list.json b/server/drivers/agents-catalog-goldens/antigravity-cli.tools-list.jsonindex 103e71295e..988330cce1 100644--- a/server/drivers/agents-catalog-goldens/antigravity-cli.tools-list.json+++ b/server/drivers/agents-catalog-goldens/antigravity-cli.tools-list.json@@ -462,6 +462,16 @@"live": {"type": "boolean"},+ "uses": {+ "type": "array",+ "items": {+ "type": "string",+ "enum": [+ "data",+ "state"+ ]+ }+ },"app_id": {"type": "string"}diff --git a/server/drivers/agents-catalog-goldens/full.tools-list.json b/server/drivers/agents-catalog-goldens/full.tools-list.jsonindex 5dabf785ba..a6a6b85bd7 100644--- a/server/drivers/agents-catalog-goldens/full.tools-list.json+++ b/server/drivers/agents-catalog-goldens/full.tools-list.json@@ -630,7 +630,7 @@},{"name": "show_html",- "description": "Show a small self-contained web page in this chat, where the person can point at a part to change: a mini app, a game, a chart, a calculator, a report. Forms and choices go in show_widget, plain data in a markdown table. Send `html` (a document or a fragment, with inline style and script), `jsx`, one React component file with a default export (it can import react, lucide-react icons, echarts, and Chart and useTheme from \"mausbot\", and style with Tailwind classes), or `path`, a folder in your working folder with index.html and its files (up to 5 MB). It runs in a locked sandbox: no network requests, storage, popups or form posts; scripts, styles and fonts load only from cdnjs.cloudflare.com, cdn.jsdelivr.net, unpkg.com and Google Fonts, images only as data: URLs or from those; embed the data. Theme: --color-text-primary, --color-background-primary, --color-border-primary, --font-sans. In the page, mausbot.send(text) puts text in their message box after they click in it, mausbot.open(url) opens a link, mausbot.setContext(text) tells you what they see. At most 256 KB. Call again with its app_id to replace it; it reloads. Never put secrets in it. In rooms everyone sees it, view-only. For a data dashboard, follow the data-dashboards skill. Asked for a claude.ai Artifact? Those need Claude's own claude.ai sign-in and are not available to bots here: say so in one line, then make it with this tool, or publish_page for a public link.",+ "description": "Show a small self-contained web page in this chat, where the person can point at a part to change: a mini app, a game, a chart, a calculator, a report. Forms and choices go in show_widget, plain data in a markdown table. Send `html` (a document or a fragment, with inline style and script), `jsx`, one React component file with a default export (it can import react, lucide-react icons, echarts, and Chart and useTheme from \"mausbot\", and style with Tailwind classes), or `path`, a folder in your working folder with index.html and its files (up to 5 MB). It runs in a locked sandbox: no network requests, storage, popups or form posts; scripts, styles and fonts load only from cdnjs.cloudflare.com, cdn.jsdelivr.net, unpkg.com and Google Fonts, images only as data: URLs or from those; embed the data. Theme: --color-text-primary, --color-background-primary, --color-border-primary, --font-sans. In the page, mausbot.send(text) puts text in their message box after they click in it, mausbot.open(url) opens a link, mausbot.setContext(text) tells you what they see. uses [\"data\"]: mausbot.data.query(sql) SELECTs your Data tables; \"state\": mausbot.state.get/set. At most 256 KB. Call again with its app_id to replace it; it reloads. Never put secrets in it. In rooms everyone sees it, view-only. For a data dashboard, follow the data-dashboards skill. Asked for a claude.ai Artifact? Those need Claude's own claude.ai sign-in and are not available to bots here: say so in one line, then make it with this tool, or publish_page for a public link.","inputSchema": {"type": "object","additionalProperties": false,@@ -665,6 +665,16 @@"type": "boolean","description": "With path: true reloads it when its folder changes."},+ "uses": {+ "type": "array",+ "items": {+ "type": "string",+ "enum": [+ "data",+ "state"+ ]+ }+ },"app_id": {"type": "string","description": "Only to replace a page you showed."diff --git a/server/drivers/agents-catalog-goldens/profiles.json b/server/drivers/agents-catalog-goldens/profiles.jsonindex d3c6ea0837..1ac7673b4e 100644--- a/server/drivers/agents-catalog-goldens/profiles.json+++ b/server/drivers/agents-catalog-goldens/profiles.json@@ -1,7 +1,7 @@{"default": {- "bytes": 62476,- "sha256": "126a596b1b8d5a32dea63a254267ad0b047fd0012482966a5317982f65f5c7c4",+ "bytes": 62651,+ "sha256": "f971ff532c8ca9aa0e45102c2cf471a98bcf707fa14b1bef0046bf01d96786ab","tools": ["tool_result_read","list_room_targets",@@ -62,8 +62,8 @@]},"voice": {- "bytes": 63257,- "sha256": "205e6301de59fa008a6166eae7b3424de60d82df7787b6ae188cb747e690f2b1",+ "bytes": 63432,+ "sha256": "efb91749198708eba5984a96b8fdf633ca3671bc0f704946cd7357425c4f22c6","tools": ["tool_result_read","list_room_targets",@@ -125,8 +125,8 @@]},"shared": {- "bytes": 64741,- "sha256": "c00a652e2b324b17676443d46923046aec74db874c2a3f2e619d5585b1b7456c",+ "bytes": 64916,+ "sha256": "dbe76b09cf20c884f131ad458aa9d9780fad7dc332d27cede960ff6cf9e18303","tools": ["tool_result_read","list_shared_computers",@@ -189,8 +189,8 @@]},"shared+voice": {- "bytes": 65522,- "sha256": "d4589e9d7316612378d1ee852f8e4f22dabffacfa2bed23d8fb7301c852459f4",+ "bytes": 65697,+ "sha256": "ea25d09d3cf93096968028ae0f37bff887ed8ff92b0e128562dbb0249627fb80","tools": ["tool_result_read","list_shared_computers",@@ -254,8 +254,8 @@]},"skills": {- "bytes": 64899,- "sha256": "537ad85115aa4966f95cb0a607d0c3095a677e65257d0ba85d99990acbcc519d",+ "bytes": 65074,+ "sha256": "54e4a92acdb910bbc43396c36c094d4cd16e289da4f418bbe45d6c29d09df933","tools": ["tool_result_read","list_room_targets",@@ -318,8 +318,8 @@]},"skills+voice": {- "bytes": 65680,- "sha256": "b0f7647220b8896c547cbb51284cc51d798945d64d1f7f361bcb805d5b3439e5",+ "bytes": 65855,+ "sha256": "5498058e312314b1772d013480875bdf52296224260a14d74a0593d051739daa","tools": ["tool_result_read","list_room_targets",@@ -383,8 +383,8 @@]},"skills+shared": {- "bytes": 67164,- "sha256": "64b0214728f2d2d7476b5e9ee7eed6452adb2c4c35cc4cc30f062422be182ee6",+ "bytes": 67339,+ "sha256": "51cf792084549e844dd06744a95010345af90835e5a64ceb987144636632705b","tools": ["tool_result_read","list_shared_computers",@@ -449,8 +449,8 @@]},"skills+shared+voice": {- "bytes": 67945,- "sha256": "3074a197562a4a64831e4ec884e663f56c974841815170fa13bd136a0fc1791b",+ "bytes": 68120,+ "sha256": "10be6b1febc86237827a0ef8f8540fb236b7ae8ebba1bbd7a38d33405a82a8ab","tools": ["tool_result_read","list_shared_computers",@@ -516,8 +516,8 @@]},"non-chief": {- "bytes": 53928,- "sha256": "d8dce83d662870c1b0d95a60773d01b53b3d4c5edad567d54bbaf6f83824c26c",+ "bytes": 54103,+ "sha256": "0ed8d4c15b6c6add25ab3417ea2ab389ad24dcbb0cbb64c1d49aa6396c896e39","tools": ["tool_result_read","list_room_targets",@@ -571,8 +571,8 @@]},"voice+non-chief": {- "bytes": 54709,- "sha256": "08cd5b86396c2a790cd75433ee9993bf0c56da73538f5d7c69d8511ab4e29b85",+ "bytes": 54884,+ "sha256": "c1d78a1c9e32629115737b1f33a6d44048f474f7664598daaa4d486b17d001ac","tools": ["tool_result_read","list_room_targets",@@ -627,8 +627,8 @@]},"shared+non-chief": {- "bytes": 56193,- "sha256": "3695d48baebfcb72b3cf9894e44240a881ff2a2b5ab51f3177f47c8a71271261",+ "bytes": 56368,+ "sha256": "32500585206c0ae2ba15c77291dadf4d98bb99e330ed90a174d32327e29c8e43","tools": ["tool_result_read","list_shared_computers",@@ -684,8 +684,8 @@]},"shared+voice+non-chief": {- "bytes": 56974,- "sha256": "9485bcba42d21675ee7f239775da7b510786e7ddfed122684d34bfc8eedc9348",+ "bytes": 57149,+ "sha256": "d6782c327006a88fb2c248e243a5aee1b6139ae364f8afeb92e2a18555bd271f","tools": ["tool_result_read","list_shared_computers",@@ -742,8 +742,8 @@]},"skills+non-chief": {- "bytes": 56351,- "sha256": "ba30109b2196c33165500b0ddb2c69f4ce532cffe6b1987300b51547cfcde299",+ "bytes": 56526,+ "sha256": "ab2653d9cadba76e774cfb86cc7f5ae5e735ed318573b431784f3e52d5e5fb05","tools": ["tool_result_read","list_room_targets",@@ -799,8 +799,8 @@]},"skills+voice+non-chief": {- "bytes": 57132,- "sha256": "ca1b7ce48622dcfde56dbdfea6fc749b6cfa32aa4e993f9b0d72ea303bb49289",+ "bytes": 57307,+ "sha256": "e0168ea0d4edd367fc59f420b1fdab9c31c0135e9eb196512c5c6576d5dab6eb","tools": ["tool_result_read","list_room_targets",@@ -857,8 +857,8 @@]},"skills+shared+non-chief": {- "bytes": 58616,- "sha256": "c62fd9c0c17d3598d03a751722bb605298d7cfac84febcbc9d8579ef153f788b",+ "bytes": 58791,+ "sha256": "0c116b2aa7f9d3ffb0d2a5f5412f78ed13d9563eeffcdbb49472b64855b0ce55","tools": ["tool_result_read","list_shared_computers",@@ -916,8 +916,8 @@]},"skills+shared+voice+non-chief": {- "bytes": 59397,- "sha256": "5b89185a3b057d065817ef0729286d1e1f88848bd00500bf3aa84782e61af324",+ "bytes": 59572,+ "sha256": "053bca11a6a464e9e9fdad21d18fbbecb5246b91ea5e2633a1fa0bb129cd6244","tools": ["tool_result_read","list_shared_computers",@@ -976,8 +976,8 @@]},"skills+shared+voice+cloud-home": {- "bytes": 67701,- "sha256": "b9dd39969837e0f3954a4c95a19fc3d9cfb568971cd49a63fd18d38430bc4168",+ "bytes": 67876,+ "sha256": "ef1d1466191ae299bde944c5e4ac8dba1554399420e0a65386d298c3e9d57230","tools": ["tool_result_read","list_shared_computers",@@ -1043,8 +1043,8 @@]},"skills+shared+voice+non-chief+cloud-home": {- "bytes": 59153,- "sha256": "03d416aefc52dc6c24cc31da911a75eecc3639fadfee11ced36b8be8b8e3db0d",+ "bytes": 59328,+ "sha256": "647dbc8b64bc00b900b7a2b2cc18fe390ee6f833a99f538316ecf75fbed203ba","tools": ["tool_result_read","list_shared_computers",@@ -1103,8 +1103,8 @@]},"skills+shared+voice+x": {- "bytes": 71784,- "sha256": "c638f7c08a7c7460b3fc7a28d0ce65bac8a8cdf7bc49229855c1752f4d0bd5d7",+ "bytes": 71959,+ "sha256": "8372e4e93c8cdf0558d4d660194e6e797c0a6ef0787b847e15c15432b06ee734","tools": ["tool_result_read","list_shared_computers",@@ -1174,8 +1174,8 @@]},"skills+shared+voice+x+team": {- "bytes": 71784,- "sha256": "c638f7c08a7c7460b3fc7a28d0ce65bac8a8cdf7bc49229855c1752f4d0bd5d7",+ "bytes": 71959,+ "sha256": "8372e4e93c8cdf0558d4d660194e6e797c0a6ef0787b847e15c15432b06ee734","tools": ["tool_result_read","list_shared_computers",@@ -1245,8 +1245,8 @@]},"skills+shared+voice+x+team+images": {- "bytes": 73731,- "sha256": "bdd56be3301bace5e0901f6c6a9341e1f367e9b163c09b7604c8d24c151afe7d",+ "bytes": 73906,+ "sha256": "b88de7b45bb16b52f239028edb46125dda5e9a6e3c52451e9d66e274df31e7b6","tools": ["tool_result_read","list_shared_computers",@@ -1318,8 +1318,8 @@]},"default+legacy-switches": {- "bytes": 62476,- "sha256": "126a596b1b8d5a32dea63a254267ad0b047fd0012482966a5317982f65f5c7c4",+ "bytes": 62651,+ "sha256": "f971ff532c8ca9aa0e45102c2cf471a98bcf707fa14b1bef0046bf01d96786ab","tools": ["tool_result_read","list_room_targets",@@ -1380,8 +1380,8 @@]},"default+mausbot": {- "bytes": 63127,- "sha256": "876a011dc3c033564b9003ce1a810adf44e4ae4b13c2544382c122839f0b73db",+ "bytes": 63302,+ "sha256": "60b615dd716b9c2771976356b1dbd50d391daa4b38cb2ad6a0b6778aa427db3b","tools": ["tool_result_read","list_room_targets",@@ -1444,8 +1444,8 @@]},"skills+shared+voice+mausbot": {- "bytes": 68596,- "sha256": "b8fc55bcf5140d2b0656eff43ca4ebf9dbe9e38f59804c8a194ec0cb32ebd379",+ "bytes": 68771,+ "sha256": "a66ea038d92ac7d2561946c00db620cf1d95375a04f1edbd73359f7ead254725","tools": ["tool_result_read","list_shared_computers",@@ -1513,8 +1513,8 @@]},"default+no-computer-pick": {- "bytes": 61264,- "sha256": "0499346554393181c7c9553641d6dc135915662b68fbf40c9155c16f1f2db002",+ "bytes": 61439,+ "sha256": "ab0ff49c1e84c985c12814c904674ffb1522622ca1b1c3ca697051281fb8f133","tools": ["tool_result_read","list_room_targets",@@ -1574,8 +1574,8 @@]},"default+room": {- "bytes": 57272,- "sha256": "cf5f5e0507878ab7ef5bc72ea41013f0b6cb628714c6b8abc6083284a3cdd15e",+ "bytes": 57447,+ "sha256": "543f229ff9b5d322bbc458e65eebcae1d576d1a60c3baf46c13421c0a5b5a855","tools": ["tool_result_read","list_room_targets",@@ -1628,8 +1628,8 @@]},"non-chief+room": {- "bytes": 48724,- "sha256": "81350def78ee9e48aefd0b404b846036521d5c2697816a9e8ba70c1247697a1c",+ "bytes": 48899,+ "sha256": "21cfd9b34601859a8673c3463d94cb0d69cbd082a4484e4e3d5aaff2bf7d29ac","tools": ["tool_result_read","list_room_targets",@@ -1675,8 +1675,8 @@]},"default+images": {- "bytes": 64423,- "sha256": "821f650af2e106140c515b2137c81ce7fb576f4802238dcfeb7901302fa403b8",+ "bytes": 64598,+ "sha256": "83f78d6ceff824e2fd0be03b0e38f11f67c9cde51d6aee24fe033e9018781fca","tools": ["tool_result_read","list_room_targets",@@ -1739,8 +1739,8 @@]},"skills+shared+voice+x+team+images+hosting": {- "bytes": 75655,- "sha256": "b04ee6f79fbf040833880a425b6eba38d7954865ea8752988bfe2e4968715126",+ "bytes": 75830,+ "sha256": "cdf18449a80b38b102349a3fb62d39aeb8e6366fd20e86604c35fab426369977","tools": ["tool_result_read","list_shared_computers",@@ -1814,8 +1814,8 @@]},"default+hosting": {- "bytes": 64400,- "sha256": "4668b4efdbaf17c3ba6d44554afacda1ec02a76c60e86f13aede4781c423a64a",+ "bytes": 64575,+ "sha256": "b0b0eba268fdd815ded8006553c9dee21b0ee0869d42d11b615615c8a71a1683","tools": ["tool_result_read","list_room_targets",@@ -1878,8 +1878,8 @@]},"skills+shared+voice+x+team+board": {- "bytes": 73839,- "sha256": "794697b0f9682077899708e76dcbc75b4bed4588ffbba55371b68853168f06e1",+ "bytes": 74014,+ "sha256": "a73df664fd385920e40d7963206b254b4c9199feedfe95bfdb21a6e67aa5c1ae","tools": ["tool_result_read","list_shared_computers",@@ -1952,8 +1952,8 @@]},"default+room+board": {- "bytes": 59327,- "sha256": "c028972269f98e3f689cf138a5de55e94580beeaeda42f038f17366d8a9ee1e8",+ "bytes": 59502,+ "sha256": "8fc54d373404b531552b6f32b96830db205c78b25d9ba90b76ac521d847a4138","tools": ["tool_result_read","list_room_targets",diff --git a/server/drivers/agents-catalog-wire.test.ts b/server/drivers/agents-catalog-wire.test.tsindex a838ed4e10..d3f19396cb 100644--- a/server/drivers/agents-catalog-wire.test.ts+++ b/server/drivers/agents-catalog-wire.test.ts@@ -99,16 +99,16 @@ const BUDGET_BASELINE: Record<string, number> = {"skills+voice": 64611,"skills+shared": 66095,"skills+shared+voice": 66876,- "non-chief": 52961,- "voice+non-chief": 53742,- "shared+non-chief": 55226,- "shared+voice+non-chief": 56007,- "skills+non-chief": 55282,- "skills+voice+non-chief": 56063,- "skills+shared+non-chief": 57547,- "skills+shared+voice+non-chief": 58328,+ "non-chief": 53136,+ "voice+non-chief": 53917,+ "shared+non-chief": 55401,+ "shared+voice+non-chief": 56182,+ "skills+non-chief": 55457,+ "skills+voice+non-chief": 56238,+ "skills+shared+non-chief": 57722,+ "skills+shared+voice+non-chief": 58503,"skills+shared+voice+cloud-home": 66632,- "skills+shared+voice+non-chief+cloud-home": 58084,+ "skills+shared+voice+non-chief+cloud-home": 58259,"default+legacy-switches": 61509,"default+mausbot": 62160,"skills+shared+voice+mausbot": 67527,diff --git a/server/index.ts b/server/index.tsindex c08a610ce3..fa77714ebb 100644--- a/server/index.ts+++ b/server/index.ts@@ -11938,7 +11938,7 @@ ROUTES.push(createBotMessageRoutes({}));const liveRoots = (threadId: string, botId: string | undefined) => { const bot = botId ? store.bot(botId) : store.botByThread(threadId); return bot ? messageFileRootsForThread(bot.id, threadId).filter((root) => root !== ATTACHMENTS_DIR) : null; }; const chatApps = createChatApps({ store, dataDir: DATA_DIR, liveRows: liveAppRows, liveRoots, paused: () => workspaceMaintenance.active || moveFreeze.frozen() });const chatAppsMcp = createChatAppsMcp({ store, apps: chatApps, dataDir: DATA_DIR, keys: mcpKeys, storedServers: () => cfg.mcpServers ?? {}, mountedServers: (bot) => teamConnections.engineMcp(bot), personMcp: teamConnections.personMcp, probeAs: (server) => mcpServersHost.probeAs(server), oauth: mcpOAuth });-ROUTES.push(createChatAppRoutes({ store, apps: chatApps, threadRefusal: cloudThreadRefusal, mcpRpc: chatAppsMcp.rpc, threadVisible: (auth, threadId) => (auth.kind !== "session" || sessions.isLive(auth.session.id)) && visibleTo(viewerFor(auth)).thread(threadId) }));+ROUTES.push(createChatAppRoutes({ store, apps: chatApps, threadRefusal: cloudThreadRefusal, mcpRpc: chatAppsMcp.rpc, data: dataEngine, dataOff: (botId) => serverTurnedOff(store.bot(botId)?.toolsOff, "data"), threadVisible: (auth, threadId) => (auth.kind !== "session" || sessions.isLive(auth.session.id)) && visibleTo(viewerFor(auth)).thread(threadId) }));const roomReactionNotes = createRoomReactionNotes({ store }), { react } = createReactions({store, noted: roomReactionNotes.noted, inboxAnswer: (input) => teamMessages.reactedIn(input.auth, input.threadId, input.target.id, input.answer, { sendId: input.sendId, sender: messageSender(input.auth) }), reply: (input) => personReplies.deliver({ ...input, about: "message" }),answerCard: (input) => respondToCard({ ...input, via: "reaction" }), withdraw: personReplies.withdraw,diff --git a/server/routes/bot-page-rpc.test.ts b/server/routes/bot-page-rpc.test.tsnew file mode 100644index 0000000000..0ff8d2cc92--- /dev/null+++ b/server/routes/bot-page-rpc.test.ts@@ -0,0 +1,238 @@+// A bot's page reading its bot's data and keeping state through its rpc route, against a real DuckDB database.+import { existsSync, mkdtempSync, rmSync } from "node:fs";+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { APP_LIMITS } from "../../shared/app.ts";+import { createChatApps, type ChatApps } from "../chat-apps.ts";+import { DATA_DIR } from "../config.ts";+import type { ModelSelection } from "../contracts.ts";+import { createDataEngine } from "../data/engine.ts";+import { json, readBody } from "../harness/http.ts";+import type { RequestAuth } from "../request-auth.ts";+import { Store } from "../store.ts";+import { AppStates } from "../app-state.ts";+import { pageRows } from "./bot-page-rpc.ts";+import { createChatAppRoutes, type ChatAppRouteDeps } from "./chat-apps.ts";+import { dispatchRoutes } from "./table.ts";++const sonnet: ModelSelection = { instanceId: "claude", model: "claude-sonnet-5" };+const servers: Server[] = [];+const apps: ChatApps[] = [];+const root = mkdtempSync(join(tmpdir(), "omb-page-rpc-"));+const engine = createDataEngine({ botFolder: (botId) => join(root, "bots", botId), dataDir: join(root, "data") });++beforeEach(() => rmSync(DATA_DIR, { recursive: true, force: true }));+afterEach(async () => {+ for (const app of apps.splice(0)) app.close();+ await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));+});+afterAll(async () => { await engine.closeAll(); });++async function fixture(options: { dataOff?: boolean; paused?: () => boolean; threadVisible?: ChatAppRouteDeps["threadVisible"] } = {}) {+ const store = new Store(() => sonnet);+ const bot = store.createBot({ name: "Scout" });+ const other = store.createBot({ name: "Other" });+ const chatApps = createChatApps({ store, dataDir: DATA_DIR, sweeps: false, ...(options.paused ? { paused: options.paused } : {}) });+ apps.push(chatApps);+ const routes = [createChatAppRoutes({ store, apps: chatApps, data: engine, dataOff: () => options.dataOff === true,+ ...(options.threadVisible ? { threadVisible: options.threadVisible } : {}) })];+ const server = createServer(async (req, res) => {+ const url = new URL(req.url ?? "/", "http://localhost");+ // A test names a paired person with x-session; otherwise the request is the owner's, on this computer.+ const person = req.headers["x-session"];+ const auth = (typeof person === "string"+ ? { kind: "session", session: { id: person, email: `${person}@example.com` }, via: "bearer", scopes: ["client"] }+ : { kind: "loopback", scopes: ["admin", "client"] }) as RequestAuth;+ try {+ if (!await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody })) json(res, 404, { from: "inline routes" });+ } catch (error) {+ json(res, 500, { error: error instanceof Error ? error.message : String(error) });+ }+ });+ servers.push(server);+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+ const db = await engine.forBot(bot.id);+ await db.run("CREATE OR REPLACE TABLE sales AS SELECT i AS id, ['north', 'south'][1 + i % 2] AS region, (i * 10)::BIGINT AS amount FROM range(1, 301) t(i)", { connection: "bot" });+ const show = (input: Record<string, unknown>, who = bot, threadId = bot.threadId) => {+ const result = chatApps.createAppCard({ bot: who, threadId, input: { tool: "show_html", html: "<p>Dash</p>", title: "Dash", ...input } });+ if (result instanceof Promise || !result.ok) throw new Error("not shown");+ return result.messageId;+ };+ const rpc = async (id: string, method: string, params?: unknown, who = bot, threadId = bot.threadId, session?: string) => {+ const response = await fetch(`${base}/api/bots/${who.id}/apps/${id}/rpc`, {+ method: "POST", headers: { "content-type": "application/json", ...(session ? { "x-session": session } : {}) }, body: JSON.stringify({ threadId, method, ...(params === undefined ? {} : { params }) }),+ });+ return { status: response.status, body: await response.json() as Record<string, any> };+ };+ return { store, bot, other, chatApps, show, rpc };+}++describe("mausbot.data.query on the rpc route", () => {+ it("answers a page that declared data with its bot's rows, as objects with numbers", async () => {+ const { show, rpc } = await fixture();+ const id = show({ uses: ["data"] });+ const answer = await rpc(id, "mausbot/data/query", { sql: "SELECT region, sum(amount) AS total, count(*) AS n FROM sales WHERE id <= ? GROUP BY 1 ORDER BY 1", params: [4] });+ expect(answer).toEqual({ status: 200, body: {+ columns: [{ name: "region", type: "VARCHAR" }, { name: "total", type: "HUGEINT" }, { name: "n", type: "BIGINT" }],+ rows: [{ region: "north", total: 60, n: 2 }, { region: "south", total: 40, n: 2 }],+ truncated: false,+ } });+ });++ it("refuses writes, files and anything but one SELECT, and the table is unchanged", async () => {+ const { bot, show, rpc } = await fixture();+ const id = show({ uses: ["data"] });+ for (const sql of [+ "INSERT INTO sales VALUES (999, 'x', 1)", "UPDATE sales SET amount = 0", "DELETE FROM sales", "CREATE TABLE t AS SELECT 1", "DROP TABLE sales",+ `ATTACH '${join(root, "x.duckdb")}' AS x`, `COPY sales TO '${join(root, "out.csv")}'`, "INSTALL httpfs", "LOAD httpfs", "SELECT 1; DELETE FROM sales",+ "SELECT * FROM read_csv('/etc/hosts')",+ ]) {+ const answer = await rpc(id, "mausbot/data/query", { sql });+ expect(answer.status, sql).toBe(409);+ expect(answer.body.error.message, sql).toContain("A page runs one SELECT on its bot's own tables and views.");+ }+ expect(existsSync(join(root, "out.csv"))).toBe(false);+ const count = await (await engine.forBot(bot.id)).run("SELECT count(*) FROM sales", { connection: "bot" });+ expect(count.rows).toEqual([["300"]]);+ });++ it("truncates at the row and byte caps", async () => {+ const { show, rpc } = await fixture();+ const id = show({ uses: ["data"] });+ const many = await rpc(id, "mausbot/data/query", { sql: `SELECT range AS n FROM range(${APP_LIMITS.pageQueryRows + 10})` });+ expect(many.body.rows).toHaveLength(APP_LIMITS.pageQueryRows);+ expect(many.body.truncated).toBe(true);+ const wide = await rpc(id, "mausbot/data/query", { sql: "SELECT repeat('x', 1500) AS s FROM range(1000)" });+ expect(wide.body.truncated).toBe(true);+ expect(Buffer.byteLength(JSON.stringify(wide.body.rows))).toBeLessThanOrEqual(APP_LIMITS.pageQueryBytes);+ expect(wide.body.rows.length).toBeGreaterThan(0);+ });++ it("is refused to a page that did not declare it, an MCP app, another bot or conversation, a room, and a bot with Data off", async () => {+ const { store, bot, other, show, rpc } = await fixture();+ const plain = show({});+ expect(await rpc(plain, "mausbot/data/query", { sql: "SELECT 1" })).toEqual({ status: 409, body: { error: { code: -32000, message: 'This page did not declare "data": show it with uses: ["data"] to read its bot\'s data.' } } });+ const id = show({ uses: ["data"] });+ expect((await rpc(id, "mausbot/data/query", { sql: "SELECT 1" }, other, other.threadId)).status).toBe(404);+ expect((await rpc(id, "mausbot/data/query", { sql: "SELECT 1" }, other, bot.threadId)).status).toBe(404);+ const second = store.createTask(bot.id)!;+ expect((await rpc(id, "mausbot/data/query", { sql: "SELECT 1" }, bot, second.threadId)).status).toBe(404);+ // Another bot's page reads its own database, never this bot's.+ const theirs = show({ uses: ["data"] }, other, other.threadId);+ expect((await rpc(theirs, "mausbot/data/query", { sql: "SELECT count(*) FROM sales" }, other, other.threadId)).status).toBe(409);+ const room = store.createGroup("Launch", [bot.id, other.id]);+ const inRoom = show({ uses: ["data"] }, bot, room.threadId);+ for (const method of ["mausbot/data/query", "mausbot/state/keys"]) {+ expect(await rpc(inRoom, method, { sql: "SELECT 1" }, bot, room.threadId))+ .toEqual({ status: 409, body: { error: { code: -32000, message: "In a room, a page cannot read its bot's data or keep state." } } });+ }+ let paused = true;+ const waiting = await fixture({ paused: () => paused });+ expect((await waiting.rpc(waiting.show({ uses: ["data"] }), "mausbot/data/query", { sql: "SELECT 1" })).status).toBe(503);+ paused = false;+ const off = await fixture({ dataOff: true });+ expect((await off.rpc(off.show({ uses: ["data"] }), "mausbot/data/query", { sql: "SELECT 1" })).body.error.message).toContain("Data is switched off");+ });++ it("is refused to a person who cannot see the conversation, for data and state alike; the owner still reads it", async () => {+ const visible = vi.fn((auth: RequestAuth) => auth.kind !== "session" || auth.session.id !== "outsider");+ const { show, rpc, bot } = await fixture({ threadVisible: visible });+ const id = show({ uses: ["data", "state"] });+ const calls: Array<[string, Record<string, unknown>]> = [+ ["mausbot/data/query", { sql: "SELECT count(*) AS n FROM sales" }], ["mausbot/state/get", { key: "a" }],+ ["mausbot/state/set", { key: "a", value: 1 }], ["mausbot/state/keys", {}],+ ];+ for (const [method, params] of calls) {+ expect(await rpc(id, method, params, bot, bot.threadId, "outsider"), method).toEqual({ status: 404, body: { error: "no such conversation" } });+ }+ expect((await rpc(id, "mausbot/state/keys")).body).toEqual({ keys: [] });+ expect((await rpc(id, "mausbot/data/query", { sql: "SELECT count(*) AS n FROM sales" })).body.rows).toEqual([{ n: 300 }]);+ expect((await rpc(id, "mausbot/state/get", { key: "a" }, bot, bot.threadId, "member")).status).toBe(200);+ });++ it("holds a page to the rpc rate", async () => {+ const { show, rpc } = await fixture();+ const id = show({ uses: ["state"] });+ for (let i = 0; i < APP_LIMITS.rpcPerMinute; i++) expect((await rpc(id, "mausbot/state/keys")).status).toBe(200);+ expect((await rpc(id, "mausbot/state/keys")).status).toBe(429);+ });+});++describe("mausbot.state on the rpc route", () => {+ it("keeps values for the page, across its versions, until it stops declaring state", async () => {+ const { show, rpc, chatApps, bot } = await fixture();+ const id = show({ uses: ["state"] });+ expect(await rpc(id, "mausbot/state/get", { key: "filter" })).toEqual({ status: 200, body: {} });+ expect(await rpc(id, "mausbot/state/set", { key: "filter", value: { region: "north" } })).toEqual({ status: 200, body: {} });+ expect(await rpc(id, "mausbot/state/get", { key: "filter" })).toEqual({ status: 200, body: { value: { region: "north" } } });+ expect(await rpc(id, "mausbot/state/keys")).toEqual({ status: 200, body: { keys: ["filter"] } });+ // A new version without `uses` keeps what the page declared, and its state.+ const replaced = chatApps.createAppCard({ bot, threadId: bot.threadId, input: { tool: "update_html", app_id: id, html: "<p>Dash 2</p>" } });+ expect(replaced).toMatchObject({ ok: true, messageId: id });+ expect(chatApps.declaredUses(bot.threadId, id)).toEqual(["state"]);+ expect((await rpc(id, "mausbot/state/get", { key: "filter" })).body).toEqual({ value: { region: "north" } });+ // Setting without a value removes the key.+ expect((await rpc(id, "mausbot/state/set", { key: "filter" })).status).toBe(200);+ expect((await rpc(id, "mausbot/state/keys")).body).toEqual({ keys: [] });+ chatApps.createAppCard({ bot, threadId: bot.threadId, input: { tool: "update_html", app_id: id, html: "<p>Dash 3</p>", uses: [] } });+ expect((await rpc(id, "mausbot/state/keys")).status).toBe(409);+ });++ it("holds the caps and waits while the workspace is paused", async () => {+ let paused = false;+ const { show, rpc } = await fixture({ paused: () => paused });+ const id = show({ uses: ["state"] });+ expect((await rpc(id, "mausbot/state/set", { key: "k".repeat(APP_LIMITS.pageStateKeyChars + 1), value: 1 })).status).toBe(400);+ expect((await rpc(id, "mausbot/state/set", { key: "big", value: "x".repeat(APP_LIMITS.pageStateValueBytes) })).status).toBe(413);+ paused = true;+ expect((await rpc(id, "mausbot/state/set", { key: "a", value: 1 })).status).toBe(503);+ expect((await rpc(id, "mausbot/state/get", { key: "a" })).status).toBe(200);+ paused = false;+ expect((await rpc(id, "mausbot/state/set", { key: "a", value: 1 })).status).toBe(200);+ });+});++describe("AppStates", () => {+ it("caps a page's keys and bytes, and the sweep removes the state of rows that are gone", () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-app-state-"));+ const states = new AppStates(dir);+ for (let i = 0; i < APP_LIMITS.pageStateKeys; i++) expect(states.set("t1", "m1", `k${i}`, i).ok).toBe(true);+ expect(states.set("t1", "m1", "one-more", 1)).toMatchObject({ ok: false, status: 413 });+ expect(states.set("t1", "m1", "k0", "replaced").ok).toBe(true);+ const chunk = "x".repeat(APP_LIMITS.pageStateValueBytes - 10);+ const fill = new AppStates(mkdtempSync(join(tmpdir(), "omb-app-state-")));+ let refused = false;+ for (let i = 0; i < 10 && !refused; i++) refused = !fill.set("t", "m", `v${i}`, chunk).ok;+ expect(refused).toBe(true);+ expect(states.set("t2", "m2", "a", 1).ok).toBe(true);+ expect(states.set("../x", "m", "a", 1)).toMatchObject({ ok: false, status: 404 });+ expect(states.sweep((threadId) => threadId === "t1")).toBe(1);+ expect(states.keys("t2", "m2")).toEqual({ ok: true, value: [] });+ expect(states.keys("t1", "m1").ok && (states.keys("t1", "m1") as { value: string[] }).value.length).toBe(APP_LIMITS.pageStateKeys);+ expect(existsSync(join(dir, "t2"))).toBe(false);+ });++ it("goes with its conversation in the chat apps' sweep", async () => {+ const { store, bot, show, rpc, chatApps } = await fixture();+ const second = store.createTask(bot.id)!;+ const id = show({ uses: ["state"] }, bot, second.threadId);+ expect((await rpc(id, "mausbot/state/set", { key: "a", value: 1 }, bot, second.threadId)).status).toBe(200);+ chatApps.sweep();+ expect(chatApps.states.keys(second.threadId, id)).toEqual({ ok: true, value: ["a"] });+ store.deleteTask(bot.id, second.threadId);+ chatApps.sweep();+ expect(chatApps.states.keys(second.threadId, id)).toEqual({ ok: true, value: [] });+ });+});++describe("pageRows", () => {+ it("keeps every column of a repeated name, and numbers that do not fit as text", () => {+ expect(pageRows({ columns: [{ name: "a", type: "BIGINT" }, { name: "a", type: "DECIMAL(4,1)" }, { name: "b", type: "HUGEINT" }], rows: [["1", "2.5", "123456789012345678901"]] }))+ .toEqual({ columns: [{ name: "a", type: "BIGINT" }, { name: "a_2", type: "DECIMAL(4,1)" }, { name: "b", type: "HUGEINT" }], rows: [{ a: 1, a_2: 2.5, b: "123456789012345678901" }] });+ });+});diff --git a/server/routes/bot-page-rpc.ts b/server/routes/bot-page-rpc.tsnew file mode 100644index 0000000000..9e9ffe2aa0--- /dev/null+++ b/server/routes/bot-page-rpc.ts@@ -0,0 +1,113 @@+// mausbot.data and mausbot.state for a bot's own page, on its rpc route once the route has checked the bot, the+// conversation and the row. Each answers only for what the page's current version declared (show_html `uses`).+import { APP_LIMITS, type AppUse } from "../../shared/app.ts";+import { pageUseRefusal, RPC_HOST_REFUSED, RPC_INVALID_PARAMS, type PageRpcMethod } from "../../shared/app-frame/bridge.ts";+import type { ChatApps } from "../chat-apps.ts";+import { boundRows } from "../data/tools.ts";+import { DataFailure, type DataEngine, type RunResult } from "../data/types.ts";++export interface PageRpcDeps {+ apps: Pick<ChatApps, "declaredUses" | "states" | "paused">;+ data?: Pick<DataEngine, "unavailable" | "forBot">;+ /** True when the person switched this bot's Data tools off. */+ dataOff?(botId: string): boolean;+}++export interface PageRpcAnswer {+ status: number;+ body: Record<string, unknown>;+}++const PAUSED = "This page waits while this computer is backed up. Try again in a moment.";+const answer = (body: Record<string, unknown>): PageRpcAnswer => ({ status: 200, body });+const refuse = (status: number, message: string, code = RPC_HOST_REFUSED): PageRpcAnswer => ({ status, body: { error: { code, message } } });++function isRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);+}++const INTEGER_TYPE = /^(?:U?TINYINT|U?SMALLINT|U?INTEGER|U?BIGINT|U?HUGEINT)$/;++/** Rows as objects by column name, with whole numbers and decimals as JS numbers where they fit. A repeated column name+ * gets `_2`, `_3`… so no cell is lost. */+export function pageRows(result: Pick<RunResult, "columns" | "rows">): { columns: Array<{ name: string; type: string }>; rows: Array<Record<string, unknown>> } {+ const seen = new Map<string, number>();+ const columns = result.columns.map((column) => {+ const count = (seen.get(column.name) ?? 0) + 1;+ seen.set(column.name, count);+ return { name: count === 1 ? column.name : `${column.name}_${count}`, type: column.type };+ });+ const numeric = columns.map((column) => INTEGER_TYPE.test(column.type) ? "integer" : column.type.startsWith("DECIMAL") ? "decimal" : null);+ const rows = result.rows.map((row) => {+ const out: Record<string, unknown> = {};+ columns.forEach((column, index) => {+ const cell = row[index] ?? null;+ const kind = numeric[index];+ if (typeof cell === "string" && kind) {+ const value = Number(cell);+ out[column.name] = Number.isFinite(value) && (kind === "decimal" || Number.isSafeInteger(value)) ? value : cell;+ } else out[column.name] = cell;+ });+ return out;+ });+ return { columns, rows };+}++async function query(deps: PageRpcDeps, botId: string, params: Record<string, unknown>): Promise<PageRpcAnswer> {+ if (!deps.data) return refuse(503, "This page cannot read data on this computer.");+ if (deps.apps.paused()) return refuse(503, PAUSED);+ if (deps.dataOff?.(botId)) return refuse(409, "Data is switched off for this bot, so its pages cannot read it.");+ const unavailable = deps.data.unavailable();+ if (unavailable !== null) return refuse(503, unavailable);+ const sql = params.sql;+ if (typeof sql !== "string" || !sql.trim() || sql.length > APP_LIMITS.pageQuerySqlChars) {+ return refuse(400, `mausbot.data.query needs one SELECT of at most ${APP_LIMITS.pageQuerySqlChars} characters.`, RPC_INVALID_PARAMS);+ }+ const given = params.params;+ if (given !== undefined && !Array.isArray(given) && !isRecord(given)) {+ return refuse(400, "mausbot.data.query params: a list for ? or $1, or an object for $name.", RPC_INVALID_PARAMS);+ }+ try {+ const database = await deps.data.forBot(botId);+ const result = await database.pageQuery(sql, given, { maxRows: APP_LIMITS.pageQueryRows, timeoutMs: APP_LIMITS.pageQueryMs });+ const bounded = boundRows(result.rows, APP_LIMITS.pageQueryRows, APP_LIMITS.pageQueryBytes);+ const shaped = pageRows({ columns: result.columns, rows: bounded.rows });+ let rows = shaped.rows;+ let truncated = result.truncated || bounded.truncated;+ // Rows as objects repeat their column names: the cap holds for what is sent.+ while (rows.length && Buffer.byteLength(JSON.stringify(rows)) > APP_LIMITS.pageQueryBytes) {+ rows = rows.slice(0, rows.length - Math.max(1, Math.ceil(rows.length / 10)));+ truncated = true;+ }+ return answer({ columns: shaped.columns, rows, truncated });+ } catch (error) {+ if (!(error instanceof DataFailure)) throw error;+ const { code, message, hint } = error.error;+ const status = code === "write_refused" ? 409 : code === "timeout" || code === "engine_unavailable" ? 503 : 422;+ const text = code === "timeout" ? `The query ran past ${APP_LIMITS.pageQueryMs / 1000} seconds. Aggregate or filter first.` : message;+ return refuse(status, hint && code === "write_refused" ? `${text} ${hint}` : text);+ }+}++export async function pageRpc(deps: PageRpcDeps, call: { botId: string; threadId: string; messageId: string; method: PageRpcMethod; params: Record<string, unknown> }): Promise<PageRpcAnswer> {+ const use: AppUse = call.method === "mausbot/data/query" ? "data" : "state";+ if (!deps.apps.declaredUses(call.threadId, call.messageId).includes(use)) return refuse(409, pageUseRefusal(use, false));+ if (call.method === "mausbot/data/query") return query(deps, call.botId, call.params);+ const { states } = deps.apps;+ const key = call.params.key;+ const keyed = typeof key === "string" && key.length > 0 && key.length <= APP_LIMITS.pageStateKeyChars;+ if (call.method !== "mausbot/state/keys" && !keyed) {+ return refuse(400, `A state key is text of 1 to ${APP_LIMITS.pageStateKeyChars} characters.`, RPC_INVALID_PARAMS);+ }+ if (call.method === "mausbot/state/keys") {+ const keys = states.keys(call.threadId, call.messageId);+ return keys.ok ? answer({ keys: keys.value }) : refuse(keys.status, keys.error);+ }+ if (call.method === "mausbot/state/get") {+ const got = states.get(call.threadId, call.messageId, key as string);+ return got.ok ? answer(got.value === undefined ? {} : { value: got.value }) : refuse(got.status, got.error);+ }+ if (deps.apps.paused()) return refuse(503, PAUSED);+ const set = states.set(call.threadId, call.messageId, key as string, call.params.value);+ return set.ok ? answer({}) : refuse(set.status, set.error, set.status === 400 ? RPC_INVALID_PARAMS : RPC_HOST_REFUSED);+}diff --git a/server/routes/chat-apps.ts b/server/routes/chat-apps.tsindex 2a88280d19..55ac2e1c0c 100644--- a/server/routes/chat-apps.ts+++ b/server/routes/chat-apps.ts@@ -1,11 +1,13 @@import { APP_LIMITS, ROOM_VIEW_ONLY, type AppPayload } from "../../shared/app.ts";-import { APP_RPC_METHODS, type AppRpcMethod } from "../../shared/app-frame/bridge.ts";+import { APP_RPC_METHODS, PAGE_RPC_METHODS, pageUseRefusal, RPC_HOST_REFUSED, type AppRpcMethod, type PageRpcMethod } from "../../shared/app-frame/bridge.ts";import { webOrigin } from "../../shared/app-frame/csp.ts";import { appRow, createChatApps, rowRate, type ChatApps } from "../chat-apps.ts";+import type { DataEngine } from "../data/types.ts";import { messageFileDisposition } from "../message-file.ts";import type { RequestAuth } from "../request-auth.ts";import type { BotRecord, Message, Store } from "../store.ts";import { refusalBody, userError } from "../user-errors.ts";+import { pageRpc } from "./bot-page-rpc.ts";import { PASS, type RouteHandler } from "./table.ts";export { createChatApps };@@ -35,6 +37,10 @@ export interface ChatAppRouteDeps {* page they load, so leaving a room, or losing sight of its bot, closes its pages to them. */threadVisible?(auth: RequestAuth, threadId: string): boolean;mcpRpc?(request: McpRpcRequest): Promise<McpRpcAnswer>;+ /** The bots' databases, which a bot's page that declared `data` reads. */+ data?: Pick<DataEngine, "unavailable" | "forBot">;+ /** True when the person switched this bot's Data tools off. */+ dataOff?(botId: string): boolean;}const DOCUMENT = /^\/api\/threads\/([\w-]+)\/messages\/([\w-]+)\/app(\/download)?$/;@@ -47,6 +53,7 @@ function isRecord(value: unknown): value is Record<string, unknown> {export function createChatAppRoutes(deps: ChatAppRouteDeps): RouteHandler {const { store, apps } = deps;const contextRate = rowRate(120, 60_000);+ const pageRate = rowRate(APP_LIMITS.rpcPerMinute, 60_000);return async ({ req, res, url, path, method, auth, json, readBody }) => {let m = DOCUMENT.exec(path);@@ -96,12 +103,21 @@ export function createChatAppRoutes(deps: ChatAppRouteDeps): RouteHandler {const threadId = body.threadId;const bot = store.bot(botId);if (!bot) return json(res, 404, { error: "no such bot" });- if (store.groupByThread(threadId)) return json(res, 409, { error: ROOM_VIEW_ONLY });+ // A bot page's own data and state calls; an MCP app's row never makes one.+ const pageCall = (row: { app: AppPayload } | undefined) => action === "rpc" && row?.app.source === "html" && typeof body.method === "string" &&+ (PAGE_RPC_METHODS as readonly string[]).includes(body.method);+ if (store.groupByThread(threadId)) {+ return json(res, 409, pageCall(appRow(store, threadId, messageId))+ ? { error: { code: RPC_HOST_REFUSED, message: pageUseRefusal("data", true) } } : { error: ROOM_VIEW_ONLY });+ }if (!store.taskByThread(bot.id, threadId)) return json(res, 404, { error: "no such conversation" });const refused = deps.threadRefusal?.(auth, threadId);if (refused) return json(res, 403, { error: refused });const row = appRow(store, threadId, messageId);if (!row || (row.from && row.from.botId !== bot.id)) return json(res, 404, { error: "That app is not in this conversation." });+ const pageMethod = pageCall(row);+ // A page's data and state are a read of the conversation: only for whoever may see it.+ if (pageMethod && deps.threadVisible && !deps.threadVisible(auth, threadId)) return json(res, 404, { error: "no such conversation" });if (action === "context") {if (!contextRate.take(`${threadId}:${row.id}`)) return json(res, 429, { error: "Too many context updates from this app." });@@ -109,6 +125,14 @@ export function createChatAppRoutes(deps: ChatAppRouteDeps): RouteHandler {return result.ok ? json(res, 200, { ok: true }) : json(res, result.status, { error: result.error });}+ if (pageMethod) {+ if (body.params !== undefined && !isRecord(body.params)) return json(res, 400, { error: "params must be an object" });+ if (!pageRate.take(`${threadId}:${row.id}`)) return json(res, 429, { error: { code: -32000, message: "Too many calls from this page. Wait a moment." } });+ const answer = await pageRpc({ apps, ...(deps.data ? { data: deps.data } : {}), ...(deps.dataOff ? { dataOff: deps.dataOff } : {}) }, {+ botId: bot.id, threadId, messageId: row.id, method: body.method as PageRpcMethod, params: isRecord(body.params) ? body.params : {},+ });+ return json(res, answer.status, answer.body);+ }if (row.app.source !== "mcp") return json(res, 404, { error: "That app has no server to call." });if (typeof body.method !== "string" || !(APP_RPC_METHODS as readonly string[]).includes(body.method)) {return json(res, 400, { error: `method must be one of ${APP_RPC_METHODS.join(", ")}` });diff --git a/server/testing/fake-data-database.ts b/server/testing/fake-data-database.tsindex 531aef2e98..ed6c0addb2 100644--- a/server/testing/fake-data-database.ts+++ b/server/testing/fake-data-database.ts@@ -57,6 +57,14 @@ export class FakeDataDatabase implements BotDatabase {return table ? this.tables.get(table[1]!) : undefined;}+ async pageQuery(sql: string, _params: unknown, options: { maxRows: number; timeoutMs: number; signal?: AbortSignal }): Promise<RunResult> {+ this.calls.push({ method: "pageQuery", sql, connection: "page", maxRows: options.maxRows });+ await this.settle(options);+ const { columns, rows } = this.take();+ const kept = rows.slice(0, options.maxRows);+ return { columns, rows: kept, rowCount: kept.length, truncated: kept.length < rows.length, elapsedMs: 1 };+ }+async run(sql: string, options: RunOptions): Promise<RunResult> {this.calls.push({ method: "run", sql, connection: options.connection, maxRows: options.maxRows });await this.settle(options);diff --git a/shared/app-frame/app-host.html b/shared/app-frame/app-host.htmlindex 62abfe266c..3a5880a3e2 100644--- a/shared/app-frame/app-host.html+++ b/shared/app-frame/app-host.html@@ -1,10 +1,10 @@-<!-- mausbot app-host v1 sha256:77ffbb379886c92991db4d92d8638215c54818cef02c9a6993c5dcd454808068 -->+<!-- mausbot app-host v1 sha256:b2cb1ac587a54f7761c87052234c219d47e0249dd38b6e015eb7b212d392c22e --><!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 N="2026-01-26";var j={htmlBytes:262144,title:80,fallback:1500,fallbackExcerpt:600,heightMin:80,heightMax:720,messageText:4e3,contextText:4e3,doneText:300,mcpHtmlBytes:2097152,rpcArgumentsBytes:65536,rpcResourceBytes:8388608,messagesPerHour:20,rpcPerMinute:60};var _="In a room, pages, apps and widgets are view-only: they cannot send messages or tell a bot what anyone sees.";function D(e){let n=0;for(let s=0;s<e.length;s+=1){let c=e.charCodeAt(s);if(c<128)n+=1;else if(c<2048)n+=2;else if(c>=55296&&c<=56319&&s+1<e.length){let a=e.charCodeAt(s+1);a>=56320&&a<=57343?(n+=4,s+=1):n+=3}else n+=3}return n}var B=["tools/call","tools/list","resources/read","resources/list"];var d={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 X(e){let n=F(e);return{...e.can.openLinks?{openLinks:{}}:{},logging:{},...e.can.modelContext?{updateModelContext:{text:{},structuredContent:{}}}:{},...e.can.message?{message:{text:{}}}:{},...n&&e.can.serverTools?{serverTools:{}}:{},...n&&e.can.serverResources?{serverResources:{}}:{},sandbox:{permissions:{},csp:{connectDomains:[...e.network.connect],resourceDomains:[...e.network.resources]}}}}function F(e){return!!e.tool}function M(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function $(e){return typeof e=="string"&&e.length<=200||typeof e=="number"&&Number.isFinite(e)}function Z(e){let n;try{n=JSON.stringify(e)}catch{return null}return n===void 0?null:n.length*3<=d.messageBytes?n.length:D(n)}function Q(e){if(!M(e)||e.jsonrpc!=="2.0")return null;let n=Z(e);return n===null||n>d.messageBytes||e.params!==void 0&&!M(e.params)?null:typeof e.method=="string"?!e.method||e.method.length>200||"id"in e&&!$(e.id)?null:e:e.method!==void 0||!$(e.id)?null:"result"in e||M(e.error)&&typeof e.error.code=="number"&&typeof e.error.message=="string"?e:null}function T(e,n){let s=[],c=Math.max(...e.map(([a])=>a));return{take(){let a=n();for(;s.length&&a-s[0]>=c;)s.shift();for(let[f,u]of e)if(s.filter(A=>a-A<f).length>=u)return!1;return s.push(a),!0}}}function O(e){return M(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:-32e3,message:e instanceof Error&&e.message?e.message:"The host could not do that."}}function ee(e){if(typeof e!="string"||!e||e.length>d.linkChars)return null;let n;try{n=new URL(e)}catch{return null}return n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password?null:n.href.length<=d.linkChars?n.href:null}function te(e){if(!e||e.role!=="user"||!Array.isArray(e.content)||e.content.length===0)return null;let n=[];for(let c of e.content){if(!M(c)||c.type!=="text"||typeof c.text!="string")return null;n.push(c.text)}let s=n.join(`-`).trim();return s&&s.length<=j.messageText?s:null}function z(e){let{doc:n,adapter:s}=e,c=F(n),a=e.timers??{set:(t,l)=>setTimeout(t,l),clear:t=>clearTimeout(t)},f=()=>s.now(),u={...e.hostContext,...c&&n.tool?{toolInfo:{tool:n.tool}}:{}},A=null,C=!1,h=!1,x=!1,H=!1,P=0,R=new Map,k={message:T(d.rates.message,f),openLink:T(d.rates.openLink,f),rpc:T(d.rates.rpc,f),log:T([[6e4,d.logsPerMinute]],f)},b=null,r=null,p=-1/0,g=t=>{if(!x)try{s.post(t)}catch{}},w=(t,l)=>g({jsonrpc:"2.0",id:t,result:l}),i=(t,l,o)=>g({jsonrpc:"2.0",id:t,error:{code:l,message:o}}),S=()=>{let t=e.limits?.maxHeight,l=u.containerDimensions?.maxHeight,o=typeof t=="number"&&t>0?t:typeof l=="number"&&l>0?l:d.maxHeight;return Math.max(d.minHeight,o)},E=()=>{if(r=null,x||!b)return;let t=b;b=null,p=f(),Promise.resolve().then(()=>s.setContext(t)).catch(()=>{})},q=async()=>{if(r===null||!b)return;a.clear(r),r=null;let t=b;b=null,p=f();try{await s.setContext(t)}catch{}},W=()=>{if(c&&!H&&(H=!0,g({jsonrpc:"2.0",method:"ui/notifications/tool-input",params:{arguments:n.toolInput??{}}}),g({jsonrpc:"2.0",method:"ui/notifications/tool-result",params:n.toolResult??{content:[]}})),A){let t=A;A=null,g({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:t})}},Y=async(t,l,o)=>{if(!c)return i(t,-32601,"Method not found");if(!(l.startsWith("tools/")?n.can.serverTools:n.can.serverResources))return i(t,-32e3,n.room?_:n.blocked?.text??"This app cannot reach its server right now.");if(l==="tools/call"&&(typeof o.name!="string"||!o.name||o.arguments!==void 0&&!M(o.arguments)))return i(t,-32602,"tools/call needs {name, arguments?}.");if(l==="resources/read"&&typeof o.uri!="string")return i(t,-32602,"resources/read needs {uri}.");if(!k.rpc.take())return i(t,-32e3,"Too many calls from this app. Wait a moment.");try{let v=await s.callRpc(l,o);w(t,v??{})}catch(v){let L=O(v);i(t,L.code,L.message)}},G=async(t,l,o)=>{if(l==="ui/initialize")return C=!0,w(t,{protocolVersion:N,hostInfo:{name:"mausbot",version:e.hostVersion},hostCapabilities:X(n),hostContext:u});if(h)switch(l){case"ping":return w(t,{});case"ui/request-display-mode":return w(t,{mode:"inline"});case"ui/open-link":{if(!n.can.openLinks)return i(t,-32e3,"This app cannot open links here.");if(!s.engaged())return i(t,-32e3,"Links open only after the person clicks in the app.");let m=ee(o?.url);if(!m)return i(t,-32602,"Only http and https links of at most 2,048 characters, without a user name or password, can be opened.");if(!k.openLink.take())return i(t,-32e3,"Too many links from this app. Wait a moment.");try{return await s.openLink(m),w(t,{})}catch(v){return i(t,-32e3,O(v).message)}}case"ui/message":{if(!n.can.message)return i(t,-32e3,n.room?_:"This app cannot send messages here.");if(!s.engaged())return i(t,-32e3,"Messages are sent only after the person clicks in the app.");let m=te(o);if(m===null)return i(t,-32602,`Only text messages of 1 to ${j.messageText} characters can be sent.`);if(!k.message.take())return i(t,-32e3,"Too many messages from this app. Wait a moment.");try{return await q(),await s.sendMessage(m),w(t,{})}catch(v){return i(t,-32e3,O(v).message)}}case"ui/update-model-context":{if(!n.can.modelContext)return i(t,-32e3,n.room?_:"This app cannot update the model's context here.");if(o?.content!==void 0&&!Array.isArray(o.content)||o?.structuredContent!==void 0&&!M(o.structuredContent))return i(t,-32602,"ui/update-model-context takes {content?, structuredContent?}.");if(b={...Array.isArray(o?.content)?{content:o.content}:{},...M(o?.structuredContent)?{structuredContent:o.structuredContent}:{}},r===null){let m=p+d.contextCoalesceMs-f();m<=0?E():r=a.set(E,m)}return w(t,{})}default:return B.includes(l)?Y(t,l,o??{}):i(t,-32601,"Method not found")}},K=(t,l)=>{if(t==="ui/notifications/initialized"){if(!C||h)return;h=!0,W();return}if(h)switch(t){case"ui/notifications/size-changed":{let o=l?.height;if(typeof o!="number"||!Number.isFinite(o))return;s.resize(Math.round(Math.min(S(),Math.max(d.minHeight,o))));return}case"notifications/message":e.log&&k.log.take()&&e.log(l);return;case"ui/notifications/request-teardown":s.teardownRequested();return;default:}};return{get initialized(){return h},handleMessage(t){if(x)return;let l=e.source();if(l==null||t.source!==l)return;let o=Q(t.data);if(!o)return;if("method"in o){"id"in o?G(o.id,o.method,o.params):K(o.method,o.params);return}let m=R.get(o.id);m&&(R.delete(o.id),m(o))},contextChanged(t){x||(u={...u,...t},h?g({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:t}):C&&(A={...A,...t}))},teardown(){return x||!h?Promise.resolve():new Promise(t=>{let l=`host:${++P}`,o=!1,m=()=>{o||(o=!0,R.delete(l),a.clear(v),t())},v=a.set(m,d.teardownMs);R.set(l,m),g({jsonrpc:"2.0",id:l,method:"ui/resource-teardown",params:{}})})},dispose(){x=!0,r!==null&&a.clear(r),r=null;for(let t of R.values())t({jsonrpc:"2.0",id:"",result:{}});R.clear()}}}var U=1;function ne(e){let s=e.webkit?.messageHandlers?.appHost;if(s&&typeof s.postMessage=="function")return{send:a=>s.postMessage(a)};let c=e.appHost;return c&&typeof c.postMessage=="function"?{send:a=>c.postMessage(JSON.stringify(a)),listen:a=>{c.onmessage=f=>{if(typeof f.data!="string")return;let u;try{u=JSON.parse(f.data)}catch{return}u&&typeof u=="object"&&u.v===U&&a(u)}}}:null}function re(e,n){let s=n??ne(e);if(!s)return null;let c=e.document,a=null,f=null,u=0,A=!1,C=0,h=new Map,x=r=>{try{s.send(r)}catch{}},H=(r,p)=>new Promise((g,w)=>{let i=`c${++C}`;h.set(i,{resolve:g,reject:w}),x({v:1,type:"call",callId:i,op:r,params:p})}),P=()=>{for(let r of h.values())r.reject({code:-32e3,message:"This app was closed."});h.clear()};e.addEventListener("message",r=>{a&&(a.handleMessage({source:r.source,data:r.data}),!A&&a.initialized&&(A=!0,x({v:1,type:"initialized"})))});let R=()=>{a?.dispose(),a=null,f?.remove(),f=null,A=!1,P()},k={load(r){if(!r||r.v!==U||!r.doc||typeof r.doc.srcdoc!="string")return;R(),typeof r.engagedAt=="number"&&(u=r.engagedAt);let p=c.createElement("iframe");p.setAttribute("sandbox","allow-scripts allow-forms"),p.setAttribute("referrerpolicy","no-referrer"),p.setAttribute("title","App");let g=Math.max(d.minHeight,Math.round(r.limits?.height??d.defaultHeight));p.style.height=`${g}px`,a=z({doc:r.doc,hostContext:r.hostContext??{},hostVersion:r.hostVersion??"phone",...r.limits?.maxHeight?{limits:{maxHeight:r.limits.maxHeight}}:{},source:()=>p.contentWindow,adapter:{post:i=>p.contentWindow?.postMessage(i,"*"),callRpc:(i,S)=>H("rpc",{method:i,params:S}),sendMessage:async i=>{await H("message",{text:i})},openLink:async i=>{await H("open-link",{url:i})},setContext:async i=>{await H("context",{...i})},resize:i=>{p.style.height=`${i}px`,x({v:1,type:"size",height:i})},engaged:()=>Date.now()-u<=d.engagedTouchMs,teardownRequested:()=>x({v:1,type:"teardown-request"}),now:()=>Date.now()}}),f=p,p.srcdoc=r.doc.srcdoc,c.body.appendChild(p)},contextChanged(r){a?.contextChanged(r??{})},engaged(r){typeof r=="number"&&Number.isFinite(r)&&(u=Math.max(u,r))},async teardown(){a&&await a.teardown(),R(),x({v:1,type:"torn-down"})},reply(r,p){let g=h.get(r);g&&(h.delete(r),p&&"error"in p&&p.error?g.reject(p.error):g.resolve(p&&"result"in p?p.result:void 0))}};s.listen?.(r=>{switch(r.call){case"load":return k.load(r.args[0]);case"contextChanged":return k.contextChanged(r.args[0]);case"engaged":return k.engaged(r.args[0]);case"teardown":return void k.teardown();case"reply":return k.reply(r.args[0],r.args[1])}});let b=e;return b.appHost&&typeof b.appHost.postMessage=="function"||(b.appHost=k),b.mausbotAppHost=k,x({v:1,type:"ready"}),k}function V(){typeof window<"u"&&re(window)}V();})();</script>+<script id="mausbot-app-host">(()=>{var B="2026-01-26";var H={htmlBytes:262144,title:80,fallback:1500,fallbackExcerpt:600,heightMin:80,heightMax:720,messageText:4e3,contextText:4e3,doneText:300,mcpHtmlBytes:2097152,rpcArgumentsBytes:65536,rpcResourceBytes:8388608,messagesPerHour:20,rpcPerMinute:60,pageQueryRows:5e3,pageQueryBytes:1e6,pageQuerySqlChars:2e4,pageQueryMs:1e4,pageStateKeyChars:200,pageStateValueBytes:65536,pageStateBytes:262144,pageStateKeys:200};var I="In a room, pages, apps and widgets are view-only: they cannot send messages or tell a bot what anyone sees.";function $(e){let n=0;for(let i=0;i<e.length;i+=1){let p=e.charCodeAt(i);if(p<128)n+=1;else if(p<2048)n+=2;else if(p>=55296&&p<=56319&&i+1<e.length){let l=e.charCodeAt(i+1);l>=56320&&l<=57343?(n+=4,i+=1):n+=3}else n+=3}return n}var J=["tools/call","tools/list","resources/read","resources/list"],U=["mausbot/data/query","mausbot/state/get","mausbot/state/set","mausbot/state/keys"];var f={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 ee(e){let n=F(e);return{...e.can.openLinks?{openLinks:{}}:{},logging:{},...e.can.modelContext?{updateModelContext:{text:{},structuredContent:{}}}:{},...e.can.message?{message:{text:{}}}:{},...n&&e.can.serverTools?{serverTools:{}}:{},...n&&e.can.serverResources?{serverResources:{}}:{},sandbox:{permissions:{},csp:{connectDomains:[...e.network.connect],resourceDomains:[...e.network.resources]}}}}function F(e){return!!e.tool}function M(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function q(e){return typeof e=="string"&&e.length<=200||typeof e=="number"&&Number.isFinite(e)}function te(e){let n;try{n=JSON.stringify(e)}catch{return null}return n===void 0?null:n.length*3<=f.messageBytes?n.length:$(n)}function ne(e){if(!M(e)||e.jsonrpc!=="2.0")return null;let n=te(e);return n===null||n>f.messageBytes||e.params!==void 0&&!M(e.params)?null:typeof e.method=="string"?!e.method||e.method.length>200||"id"in e&&!q(e.id)?null:e:e.method!==void 0||!q(e.id)?null:"result"in e||M(e.error)&&typeof e.error.code=="number"&&typeof e.error.message=="string"?e:null}function S(e,n){let i=[],p=Math.max(...e.map(([l])=>l));return{take(){let l=n();for(;i.length&&l-i[0]>=p;)i.shift();for(let[g,d]of e)if(i.filter(w=>l-w<g).length>=d)return!1;return i.push(l),!0}}}function E(e){return M(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:-32e3,message:e instanceof Error&&e.message?e.message:"The host could not do that."}}function re(e){if(typeof e!="string"||!e||e.length>f.linkChars)return null;let n;try{n=new URL(e)}catch{return null}return n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password?null:n.href.length<=f.linkChars?n.href:null}function oe(e,n){return n?"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 se(e,n){let i=p=>typeof p=="string"&&p.length>0&&p.length<=H.pageStateKeyChars;switch(e){case"mausbot/data/query":return typeof n.sql!="string"||!n.sql.trim()||n.sql.length>H.pageQuerySqlChars?`mausbot.data.query needs one SELECT of at most ${H.pageQuerySqlChars} characters.`:n.params===void 0||Array.isArray(n.params)||M(n.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 i(n.key)?null:`A state key is text of 1 to ${H.pageStateKeyChars} characters.`;case"mausbot/state/keys":return null}}function ie(e){if(!e||e.role!=="user"||!Array.isArray(e.content)||e.content.length===0)return null;let n=[];for(let p of e.content){if(!M(p)||p.type!=="text"||typeof p.text!="string")return null;n.push(p.text)}let i=n.join(`+`).trim();return i&&i.length<=H.messageText?i:null}function z(e){let{doc:n,adapter:i}=e,p=F(n),l=e.timers??{set:(t,a)=>setTimeout(t,a),clear:t=>clearTimeout(t)},g=()=>i.now(),d={...e.hostContext,...p&&n.tool?{toolInfo:{tool:n.tool}}:{}},w=null,P=!1,y=!1,k=!1,C=!1,O=0,v=new Map,h={message:S(f.rates.message,g),openLink:S(f.rates.openLink,g),rpc:S(f.rates.rpc,g),log:S([[6e4,f.logsPerMinute]],g)},b=null,r=null,u=-1/0,m=t=>{if(!k)try{i.post(t)}catch{}},R=(t,a)=>m({jsonrpc:"2.0",id:t,result:a}),s=(t,a,o)=>m({jsonrpc:"2.0",id:t,error:{code:a,message:o}}),j=()=>{let t=e.limits?.maxHeight,a=d.containerDimensions?.maxHeight,o=typeof t=="number"&&t>0?t:typeof a=="number"&&a>0?a:f.maxHeight;return Math.max(f.minHeight,o)},N=()=>{if(r=null,k||!b)return;let t=b;b=null,u=g(),Promise.resolve().then(()=>i.setContext(t)).catch(()=>{})},Q=async()=>{if(r===null||!b)return;l.clear(r),r=null;let t=b;b=null,u=g();try{await i.setContext(t)}catch{}},K=()=>{if(p&&!C&&(C=!0,m({jsonrpc:"2.0",method:"ui/notifications/tool-input",params:{arguments:n.toolInput??{}}}),m({jsonrpc:"2.0",method:"ui/notifications/tool-result",params:n.toolResult??{content:[]}})),w){let t=w;w=null,m({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:t})}},G=async(t,a,o)=>{if(!p)return s(t,-32601,"Method not found");if(!(a.startsWith("tools/")?n.can.serverTools:n.can.serverResources))return s(t,-32e3,n.room?I:n.blocked?.text??"This app cannot reach its server right now.");if(a==="tools/call"&&(typeof o.name!="string"||!o.name||o.arguments!==void 0&&!M(o.arguments)))return s(t,-32602,"tools/call needs {name, arguments?}.");if(a==="resources/read"&&typeof o.uri!="string")return s(t,-32602,"resources/read needs {uri}.");if(!h.rpc.take())return s(t,-32e3,"Too many calls from this app. Wait a moment.");try{let A=await i.callRpc(a,o);R(t,A??{})}catch(A){let T=E(A);s(t,T.code,T.message)}},Y=async(t,a,o)=>{if(p)return s(t,-32601,"Method not found");let c=a==="mausbot/data/query"?"data":"state";if(!n.can[c])return s(t,-32e3,oe(c,!!n.room));let A=se(a,o);if(A)return s(t,-32602,A);if(!h.rpc.take())return s(t,-32e3,"Too many calls from this page. Wait a moment.");try{R(t,await i.callRpc(a,o)??{})}catch(T){let D=E(T);s(t,D.code,D.message)}},X=async(t,a,o)=>{if(a==="ui/initialize")return P=!0,R(t,{protocolVersion:B,hostInfo:{name:"mausbot",version:e.hostVersion},hostCapabilities:ee(n),hostContext:d});if(y)switch(a){case"ping":return R(t,{});case"ui/request-display-mode":return R(t,{mode:"inline"});case"ui/open-link":{if(!n.can.openLinks)return s(t,-32e3,"This app cannot open links here.");if(!i.engaged())return s(t,-32e3,"Links open only after the person clicks in the app.");let c=re(o?.url);if(!c)return s(t,-32602,"Only http and https links of at most 2,048 characters, without a user name or password, can be opened.");if(!h.openLink.take())return s(t,-32e3,"Too many links from this app. Wait a moment.");try{return await i.openLink(c),R(t,{})}catch(A){return s(t,-32e3,E(A).message)}}case"ui/message":{if(!n.can.message)return s(t,-32e3,n.room?I:"This app cannot send messages here.");if(!i.engaged())return s(t,-32e3,"Messages are sent only after the person clicks in the app.");let c=ie(o);if(c===null)return s(t,-32602,`Only text messages of 1 to ${H.messageText} characters can be sent.`);if(!h.message.take())return s(t,-32e3,"Too many messages from this app. Wait a moment.");try{return await Q(),await i.sendMessage(c),R(t,{})}catch(A){return s(t,-32e3,E(A).message)}}case"ui/update-model-context":{if(!n.can.modelContext)return s(t,-32e3,n.room?I:"This app cannot update the model's context here.");if(o?.content!==void 0&&!Array.isArray(o.content)||o?.structuredContent!==void 0&&!M(o.structuredContent))return s(t,-32602,"ui/update-model-context takes {content?, structuredContent?}.");if(b={...Array.isArray(o?.content)?{content:o.content}:{},...M(o?.structuredContent)?{structuredContent:o.structuredContent}:{}},r===null){let c=u+f.contextCoalesceMs-g();c<=0?N():r=l.set(N,c)}return R(t,{})}default:return J.includes(a)?G(t,a,o??{}):U.includes(a)?Y(t,a,o??{}):s(t,-32601,"Method not found")}},Z=(t,a)=>{if(t==="ui/notifications/initialized"){if(!P||y)return;y=!0,K();return}if(y)switch(t){case"ui/notifications/size-changed":{let o=a?.height;if(typeof o!="number"||!Number.isFinite(o))return;i.resize(Math.round(Math.min(j(),Math.max(f.minHeight,o))));return}case"notifications/message":e.log&&h.log.take()&&e.log(a);return;case"ui/notifications/request-teardown":i.teardownRequested();return;default:}};return{get initialized(){return y},handleMessage(t){if(k)return;let a=e.source();if(a==null||t.source!==a)return;let o=ne(t.data);if(!o)return;if("method"in o){"id"in o?X(o.id,o.method,o.params):Z(o.method,o.params);return}let c=v.get(o.id);c&&(v.delete(o.id),c(o))},contextChanged(t){k||(d={...d,...t},y?m({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:t}):P&&(w={...w,...t}))},teardown(){return k||!y?Promise.resolve():new Promise(t=>{let a=`host:${++O}`,o=!1,c=()=>{o||(o=!0,v.delete(a),l.clear(A),t())},A=l.set(c,f.teardownMs);v.set(a,c),m({jsonrpc:"2.0",id:a,method:"ui/resource-teardown",params:{}})})},dispose(){k=!0,r!==null&&l.clear(r),r=null;for(let t of v.values())t({jsonrpc:"2.0",id:"",result:{}});v.clear()}}}var V=1;function ae(e){let i=e.webkit?.messageHandlers?.appHost;if(i&&typeof i.postMessage=="function")return{send:l=>i.postMessage(l)};let p=e.appHost;return p&&typeof p.postMessage=="function"?{send:l=>p.postMessage(JSON.stringify(l)),listen:l=>{p.onmessage=g=>{if(typeof g.data!="string")return;let d;try{d=JSON.parse(g.data)}catch{return}d&&typeof d=="object"&&d.v===V&&l(d)}}}:null}function le(e,n){let i=n??ae(e);if(!i)return null;let p=e.document,l=null,g=null,d=0,w=!1,P=0,y=new Map,k=r=>{try{i.send(r)}catch{}},C=(r,u)=>new Promise((m,R)=>{let s=`c${++P}`;y.set(s,{resolve:m,reject:R}),k({v:1,type:"call",callId:s,op:r,params:u})}),O=()=>{for(let r of y.values())r.reject({code:-32e3,message:"This app was closed."});y.clear()};e.addEventListener("message",r=>{l&&(l.handleMessage({source:r.source,data:r.data}),!w&&l.initialized&&(w=!0,k({v:1,type:"initialized"})))});let v=()=>{l?.dispose(),l=null,g?.remove(),g=null,w=!1,O()},h={load(r){if(!r||r.v!==V||!r.doc||typeof r.doc.srcdoc!="string")return;v(),typeof r.engagedAt=="number"&&(d=r.engagedAt);let u=p.createElement("iframe");u.setAttribute("sandbox","allow-scripts allow-forms"),u.setAttribute("referrerpolicy","no-referrer"),u.setAttribute("title","App");let m=Math.max(f.minHeight,Math.round(r.limits?.height??f.defaultHeight));u.style.height=`${m}px`,l=z({doc:r.doc,hostContext:r.hostContext??{},hostVersion:r.hostVersion??"phone",...r.limits?.maxHeight?{limits:{maxHeight:r.limits.maxHeight}}:{},source:()=>u.contentWindow,adapter:{post:s=>u.contentWindow?.postMessage(s,"*"),callRpc:(s,j)=>C("rpc",{method:s,params:j}),sendMessage:async s=>{await C("message",{text:s})},openLink:async s=>{await C("open-link",{url:s})},setContext:async s=>{await C("context",{...s})},resize:s=>{u.style.height=`${s}px`,k({v:1,type:"size",height:s})},engaged:()=>Date.now()-d<=f.engagedTouchMs,teardownRequested:()=>k({v:1,type:"teardown-request"}),now:()=>Date.now()}}),g=u,u.srcdoc=r.doc.srcdoc,p.body.appendChild(u)},contextChanged(r){l?.contextChanged(r??{})},engaged(r){typeof r=="number"&&Number.isFinite(r)&&(d=Math.max(d,r))},async teardown(){l&&await l.teardown(),v(),k({v:1,type:"torn-down"})},reply(r,u){let m=y.get(r);m&&(y.delete(r),u&&"error"in u&&u.error?m.reject(u.error):m.resolve(u&&"result"in u?u.result:void 0))}};i.listen?.(r=>{switch(r.call){case"load":return h.load(r.args[0]);case"contextChanged":return h.contextChanged(r.args[0]);case"engaged":return h.engaged(r.args[0]);case"teardown":return void h.teardown();case"reply":return h.reply(r.args[0],r.args[1])}});let b=e;return b.appHost&&typeof b.appHost.postMessage=="function"||(b.appHost=h),b.mausbotAppHost=h,k({v:1,type:"ready"}),h}function W(){typeof window<"u"&&le(window)}W();})();</script></body></html>diff --git a/shared/app-frame/bridge.test.ts b/shared/app-frame/bridge.test.tsindex 4ac5d86712..287cd8e5f7 100644--- a/shared/app-frame/bridge.test.ts+++ b/shared/app-frame/bridge.test.ts@@ -456,3 +456,61 @@ describe("hostCapabilitiesFor", () => {expect(capabilities.sandbox).toEqual({ permissions: {}, csp: { connectDomains: BOT_HTML_NETWORK.connect, resourceDomains: BOT_HTML_NETWORK.resources } });});});++describe("a bot page's data and state", () => {+ const declared = (can: Partial<AppDocument["can"]>, over: Partial<AppDocument> = {}): AppDocument => ({ ...botDoc(), can: { ...botDoc().can, ...can }, ...over });++ it("refuses what the page did not declare, naming the missing declaration", async () => {+ const h = harness(declared({ state: true }));+ await h.connect();+ const query = await h.request("mausbot/data/query", { sql: "SELECT 1" });+ expect(query?.error).toEqual({ code: RPC_HOST_REFUSED, message: 'This page did not declare "data": show it with uses: ["data"] to read its bot\'s data.' });+ expect(h.calls.rpc).toEqual([]);+ const other = harness(declared({ data: true }));+ await other.connect();+ expect((await other.request("mausbot/state/set", { key: "k", value: 1 }))?.error?.message).toContain('did not declare "state"');+ expect(other.calls.rpc).toEqual([]);+ });++ it("forwards declared calls with no click first, and hands back the host's answer", async () => {+ const h = harness(declared({ data: true, state: true }));+ h.setEngaged(false);+ h.answerRpc(async (method) => (method === "mausbot/data/query" ? { columns: [], rows: [{ n: 1 }], truncated: false } : {}));+ await h.connect();+ expect((await h.request("mausbot/data/query", { sql: "SELECT 1 AS n", params: [1] }))?.result).toEqual({ columns: [], rows: [{ n: 1 }], truncated: false });+ expect((await h.request("mausbot/state/set", { key: "filter", value: { region: "north" } }))?.result).toEqual({});+ expect((await h.request("mausbot/state/keys"))?.result).toEqual({});+ expect(h.calls.rpc.map((call) => call.method)).toEqual(["mausbot/data/query", "mausbot/state/set", "mausbot/state/keys"]);+ });++ it("checks the params before the host is asked", async () => {+ const h = harness(declared({ data: true, state: true }));+ await h.connect();+ expect((await h.request("mausbot/data/query", {}))?.error?.code).toBe(RPC_INVALID_PARAMS);+ expect((await h.request("mausbot/data/query", { sql: "SELECT 1", params: "1" }))?.error?.code).toBe(RPC_INVALID_PARAMS);+ expect((await h.request("mausbot/state/get", { key: "" }))?.error?.code).toBe(RPC_INVALID_PARAMS);+ expect((await h.request("mausbot/state/get", { key: "k".repeat(201) }))?.error?.code).toBe(RPC_INVALID_PARAMS);+ expect(h.calls.rpc).toEqual([]);+ });++ it("gives a room's page and an MCP app none of it", async () => {+ const room = harness(declared({ data: false, state: false }, { room: true }));+ await room.connect();+ expect((await room.request("mausbot/data/query", { sql: "SELECT 1" }))?.error?.message).toBe("In a room, a page cannot read its bot's data or keep state.");+ const mcp = harness(mcpDoc({ can: { ...mcpDoc().can, data: true, state: true } }));+ await mcp.connect();+ expect((await mcp.request("mausbot/state/keys"))?.error?.code).toBe(RPC_METHOD_NOT_FOUND);+ expect(room.calls.rpc).toEqual([]);+ expect(mcp.calls.rpc).toEqual([]);+ });++ it("shares the page's rpc rate", async () => {+ const h = harness(declared({ data: true }));+ await h.connect();+ const [[windowMs, max]] = APP_FRAME_LIMITS.rates.rpc;+ for (let i = 0; i < max!; i++) expect((await h.request("mausbot/data/query", { sql: "SELECT 1" }))?.error).toBeUndefined();+ expect((await h.request("mausbot/data/query", { sql: "SELECT 1" }))?.error?.message).toBe("Too many calls from this page. Wait a moment.");+ await h.advance(windowMs!);+ expect((await h.request("mausbot/data/query", { sql: "SELECT 1" }))?.error).toBeUndefined();+ });+});diff --git a/shared/app-frame/bridge.ts b/shared/app-frame/bridge.tsindex aef7da12b5..7df7bca7a1 100644--- a/shared/app-frame/bridge.ts+++ b/shared/app-frame/bridge.ts@@ -4,10 +4,12 @@import { APP_LIMITS, APP_PROTOCOL_VERSION, ROOM_VIEW_ONLY, utf8Bytes, type AppDocument } from "../app.ts";import {APP_RPC_METHODS,+ PAGE_RPC_METHODS,RPC_HOST_REFUSED,RPC_INVALID_PARAMS,RPC_METHOD_NOT_FOUND,type AppRpcMethod,+ type PageRpcMethod,type JsonRpcError,type JsonRpcId,type JsonRpcMessage,@@ -60,7 +62,7 @@ export interface AppContextUpdate {export interface AppBridgeAdapter {post(message: JsonRpcMessage): void;/** Resolves with the JSON-RPC `result`; rejects with { code, message }. */- callRpc(method: AppRpcMethod, params: Record<string, unknown>): Promise<unknown>;+ callRpc(method: AppRpcMethod | PageRpcMethod, params: Record<string, unknown>): Promise<unknown>;sendMessage(text: string): Promise<void>;openLink(url: string): Promise<void> | void;setContext(update: AppContextUpdate): Promise<void> | void;@@ -177,6 +179,29 @@ export function openableLink(value: unknown): string | null {return url.href.length <= APP_FRAME_LIMITS.linkChars ? url.href : null;}+/** Why a bot's page may not make a call it did not declare, or makes in a room. */+export function pageUseRefusal(use: "data" | "state", room: boolean): string {+ if (room) return "In a room, a page cannot read its bot's data or keep state.";+ return `This page did not declare "${use}": show it with uses: ["${use}"] to ${use === "data" ? "read its bot's data" : "keep state"}.`;+}++/** The params a page's own call needs, or what is wrong with them. */+function pageParamsProblem(method: PageRpcMethod, params: Record<string, unknown>): string | null {+ const key = (value: unknown) => typeof value === "string" && value.length > 0 && value.length <= APP_LIMITS.pageStateKeyChars;+ switch (method) {+ case "mausbot/data/query":+ if (typeof params.sql !== "string" || !params.sql.trim() || params.sql.length > APP_LIMITS.pageQuerySqlChars) {+ return `mausbot.data.query needs one SELECT of at most ${APP_LIMITS.pageQuerySqlChars} characters.`;+ }+ return params.params === undefined || Array.isArray(params.params) || isRecord(params.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 key(params.key) ? null : `A state key is text of 1 to ${APP_LIMITS.pageStateKeyChars} characters.`;+ case "mausbot/state/keys":+ return null;+ }+}+function messageText(params: Record<string, unknown> | undefined): string | null {if (!params || params.role !== "user" || !Array.isArray(params.content) || params.content.length === 0) return null;const texts: string[] = [];@@ -286,6 +311,22 @@ export function createAppBridge(options: AppBridgeOptions): AppBridge {}};+ // A page's reads and saves need no click: a dashboard loads its data, and remembers its filters, on its own.+ const onPageRpc = async (id: JsonRpcId, method: PageRpcMethod, params: Record<string, unknown>) => {+ if (mcp) return fail(id, RPC_METHOD_NOT_FOUND, "Method not found");+ const use = method === "mausbot/data/query" ? "data" : "state";+ if (!doc.can[use]) return fail(id, RPC_HOST_REFUSED, pageUseRefusal(use, Boolean(doc.room)));+ const problem = pageParamsProblem(method, params);+ if (problem) return fail(id, RPC_INVALID_PARAMS, problem);+ if (!rates.rpc.take()) return fail(id, RPC_HOST_REFUSED, "Too many calls from this page. Wait a moment.");+ try {+ respond(id, (await adapter.callRpc(method, params)) ?? {});+ } catch (error) {+ const failure = rpcErrorFrom(error);+ fail(id, failure.code, failure.message);+ }+ };+const onRequest = async (id: JsonRpcId, method: string, params: Record<string, unknown> | undefined) => {if (method === "ui/initialize") {answeredInitialize = true;@@ -348,6 +389,7 @@ export function createAppBridge(options: AppBridgeOptions): AppBridge {}default:if ((APP_RPC_METHODS as readonly string[]).includes(method)) return onRpc(id, method as AppRpcMethod, params ?? {});+ if ((PAGE_RPC_METHODS as readonly string[]).includes(method)) return onPageRpc(id, method as PageRpcMethod, params ?? {});return fail(id, RPC_METHOD_NOT_FOUND, "Method not found");}};diff --git a/shared/app-frame/document.test.ts b/shared/app-frame/document.test.tsindex b6d99ccec5..df7ef72819 100644--- a/shared/app-frame/document.test.ts+++ b/shared/app-frame/document.test.ts@@ -1,8 +1,8 @@import { describe, expect, it } from "vitest";import { BOT_HTML_CSP, mcpAppCsp } from "./csp.ts";-import { botHtmlDocument, buildSrcdoc, CSP_META_PREFIX, mcpAppDocument, stripDocumentPreamble } from "./document.ts";-import { APP_HELPER_SOURCE, APP_ROOM_HELPER_SOURCE, APP_THEME_STYLE } from "./helper.ts";+import { botHtmlDocument, buildSrcdoc, CSP_META_PREFIX, mcpAppDocument, publishedBotHtml, stripDocumentPreamble } from "./document.ts";+import { APP_HELPER_SOURCE, APP_ROOM_HELPER_SOURCE, APP_THEME_STYLE, PUBLISHED_PAGE_NO_BOT } from "./helper.ts";import { APP_POINT_SOURCE } from "./point.ts";const CSP = "default-src 'none'";@@ -92,3 +92,25 @@ describe("documents", () => {expect(doc).toMatchObject({ tool: { name: "create_view" }, toolInput: { a: 1 }, network });});});++describe("a bot page's declared uses", () => {+ it("become the page's can, and a room's page gets none of them", () => {+ expect(botHtmlDocument({ messageId: "m", rev: 0, html: "<p>x</p>" }).can).toEqual({ serverTools: false, serverResources: false, message: true, openLinks: true, modelContext: true });+ expect(botHtmlDocument({ messageId: "m", rev: 0, html: "<p>x</p>", uses: ["data"] }).can).toMatchObject({ data: true });+ expect(botHtmlDocument({ messageId: "m", rev: 0, html: "<p>x</p>", uses: ["data"] }).can.state).toBeUndefined();+ expect(botHtmlDocument({ messageId: "m", rev: 0, html: "<p>x</p>", uses: ["data", "state"] }).can).toMatchObject({ data: true, state: true });+ const room = botHtmlDocument({ messageId: "m", rev: 0, html: "<p>x</p>", uses: ["data", "state"], room: true }).can;+ expect(room.data).toBeUndefined();+ expect(room.state).toBeUndefined();+ });++ it("are refused with a plain reason on a published page", async () => {+ const html = publishedBotHtml("<p>x</p>");+ const script = /<script>(.*?)<\/script>/.exec(html)![1]!;+ const window: Record<string, unknown> = { matchMedia: () => ({ matches: false }), open: () => null };+ new Function("window", "matchMedia", script)(window, window.matchMedia);+ const mausbot = window.mausbot as { data: { query(): Promise<unknown> }; state: { set(): Promise<unknown> } };+ await expect(mausbot.data.query()).rejects.toThrow(PUBLISHED_PAGE_NO_BOT);+ await expect(mausbot.state.set()).rejects.toThrow(PUBLISHED_PAGE_NO_BOT);+ });+});diff --git a/shared/app-frame/document.ts b/shared/app-frame/document.tsindex d13b7d8e66..febb3978b0 100644--- a/shared/app-frame/document.ts+++ b/shared/app-frame/document.ts@@ -1,9 +1,9 @@// No byte of app content precedes the CSP meta. A leading BOM, whitespace, comments, bogus comments// (`<?xml …?>`, `<![CDATA[…]>`) and the app's own doctype are stripped first; the rest follows the meta,// which already sits in the head the parser opened for it.-import type { AppCan, AppDocument, AppToolDefinition, AppToolResult } from "../app.ts";+import type { AppCan, AppDocument, AppToolDefinition, AppToolResult, AppUse } from "../app.ts";import { BOT_HTML_CSP, BOT_HTML_NETWORK, folderPageCsp, folderPageNetwork, mcpAppCsp } from "./csp.ts";-import { APP_HELPER_SOURCE, APP_ROOM_HELPER_SOURCE, APP_THEME_STYLE } from "./helper.ts";+import { APP_HELPER_SOURCE, APP_ROOM_HELPER_SOURCE, APP_THEME_STYLE, PUBLISHED_PAGE_NO_BOT } from "./helper.ts";import { jsxPageHtml } from "./jsx-page.ts";import { APP_POINT_SOURCE } from "./point.ts";@@ -39,10 +39,13 @@ export function buildSrcdoc(input: { html: string; csp: string; botHelper?: boolreturn `${head}${base}${helper}${stripDocumentPreamble(input.html)}`;}-/** `window.mausbot` on a published page, where no chat answers it: send and setContext do nothing, open opens a tab. */-const PUBLISHED_MAUSBOT = "window.mausbot={theme:matchMedia(\"(prefers-color-scheme: dark)\").matches?\"dark\":\"light\"," ++/** `window.mausbot` on a published page, where no chat answers it: send and setContext do nothing, open opens a tab, and+ * data and state reject. */+const PUBLISHED_MAUSBOT = "(function(){var no=function(){return Promise.reject(new Error(" + JSON.stringify(PUBLISHED_PAGE_NO_BOT) + "))};" ++ "window.mausbot={theme:matchMedia(\"(prefers-color-scheme: dark)\").matches?\"dark\":\"light\"," +"send:function(){return Promise.resolve()},setContext:function(){return Promise.resolve()}," +- "open:function(u){window.open(String(u),\"_blank\",\"noopener\");return Promise.resolve()}};";+ "open:function(u){window.open(String(u),\"_blank\",\"noopener\");return Promise.resolve()}," ++ "data:{query:no},state:{get:no,set:no,keys:no}};})();";/** A bot's HTML page as a published page serves it: the theme colours the chat would give it, and a quiet mausbot. */export function publishedBotHtml(html: string): string {@@ -54,8 +57,11 @@ export const BOT_HTML_CAN: AppCan = { serverTools: false, serverResources: falseexport const ROOM_CAN: AppCan = { serverTools: false, serverResources: false, message: false, openLinks: true, modelContext: false };/** `format: "jsx"`: `html` is a React component file, served inside the page shell. `files`: a folder page, whose- * other files load from that folder URL (the token route's, ending in "/"). */-export function botHtmlDocument(input: { messageId: string; rev: number; html: string; format?: "jsx"; title?: string; files?: string; room?: boolean }): AppDocument {+ * other files load from that folder URL (the token route's, ending in "/"). `uses`: what the page declared; a room's+ * page gets none of it. */+export function botHtmlDocument(input: {+ messageId: string; rev: number; html: string; format?: "jsx"; title?: string; files?: string; room?: boolean; uses?: readonly AppUse[];+}): AppDocument {const html = input.format === "jsx" ? jsxPageHtml({ title: input.title ?? "Page", source: input.html }) : input.html;const csp = input.files ? folderPageCsp(input.files) : BOT_HTML_CSP;const network = input.files ? folderPageNetwork(input.files) : BOT_HTML_NETWORK;@@ -66,11 +72,15 @@ export function botHtmlDocument(input: { messageId: string; rev: number; html: ssrcdoc: buildSrcdoc({ html, csp, botHelper: true, room: input.room === true, ...(input.files ? { base: input.files } : {}) }),csp,network: { connect: [...network.connect], resources: [...network.resources] },- can: { ...(input.room ? ROOM_CAN : BOT_HTML_CAN) },+ can: input.room ? { ...ROOM_CAN } : declaredCan(input.uses ?? []),...(input.room ? { room: true as const } : {}),};}+function declaredCan(uses: readonly AppUse[]): AppCan {+ return { ...BOT_HTML_CAN, ...(uses.includes("data") ? { data: true } : {}), ...(uses.includes("state") ? { state: true } : {}) };+}+export function mcpAppDocument(input: {messageId: string;rev: number;diff --git a/shared/app-frame/helper.test.ts b/shared/app-frame/helper.test.tsindex 4ab54f9a59..ba9d2b97cd 100644--- a/shared/app-frame/helper.test.ts+++ b/shared/app-frame/helper.test.ts@@ -24,7 +24,9 @@ interface Scene {under?: Array<{ position?: "absolute" | "fixed"; width: number | "window"; height: number | "window"; freed?: number }>;}-function boot(engaged = true, options: { scene?: Scene; start?: number; loaded?: boolean; room?: boolean } = {}) {+function boot(engaged = true, options: {+ scene?: Scene; start?: number; loaded?: boolean; room?: boolean; can?: Partial<AppDocument["can"]>; rpc?: (method: string, params: Record<string, unknown>) => Promise<unknown>;+} = {}) {const room = options.room === true;const page = new Window();pages.push(page);@@ -85,13 +87,13 @@ function boot(engaged = true, options: { scene?: Scene; start?: number; loaded?:}const seen = { messages: [] as string[], links: [] as string[], contexts: [] as unknown[], heights: [] as number[], selections: [] as unknown[] };bridge = createAppBridge({- doc: room ? { ...DOC, can: { ...ROOM_CAN }, room: true } : DOC,+ doc: room ? { ...DOC, can: { ...ROOM_CAN }, room: true } : { ...DOC, can: { ...DOC.can, ...options.can } },hostContext: { theme: "dark", styles: { variables: { "--color-text-primary": "#fafafa", "not-a-variable": "x" } } },source: () => frame,hostVersion: "1",adapter: {post: (message) => (frame.postMessage as (data: unknown) => void)(message),- callRpc: async () => ({}),+ callRpc: async (method, params) => (options.rpc ? options.rpc(method, params) : {}),sendMessage: async (text) => { seen.messages.push(text); },openLink: (url) => { seen.links.push(url); },setContext: (update) => { seen.contexts.push(update); },@@ -125,6 +127,8 @@ function boot(engaged = true, options: { scene?: Scene; start?: number; loaded?:},mausbot: () => frame.mausbot as {send(text: string): Promise<void>; open(url: string): Promise<void>; setContext(text: string): Promise<void>; theme: string; room: boolean;+ data: { query(sql: string, params?: unknown): Promise<unknown> };+ state: { get(key: string): Promise<unknown>; set(key: string, value?: unknown): Promise<void>; keys(): Promise<string[]> };},};}@@ -166,6 +170,35 @@ describe("the bot-page helper", () => {expect(page.seen.contexts[0]).toEqual({ content: [{ type: "text", text: "Looking at March" }] });});+ it("reads data and keeps state through the bridge when the page declared them, with no click", async () => {+ const asked: Array<[string, Record<string, unknown>]> = [];+ const saved: Record<string, unknown> = {};+ const page = boot(false, {+ can: { data: true, state: true },+ rpc: async (method, params) => {+ asked.push([method, params]);+ if (method === "mausbot/data/query") return { columns: [{ name: "n", type: "INTEGER" }], rows: [{ n: 1 }], truncated: false };+ if (method === "mausbot/state/set") { if ("value" in params) saved[params.key as string] = params.value; else delete saved[params.key as string]; return {}; }+ if (method === "mausbot/state/get") return params.key as string in saved ? { value: saved[params.key as string] } : {};+ return { keys: Object.keys(saved) };+ },+ });+ expect(await page.mausbot().data.query("SELECT ? AS n", [1])).toEqual({ columns: [{ name: "n", type: "INTEGER" }], rows: [{ n: 1 }], truncated: false });+ await page.mausbot().state.set("filter", { region: "north" });+ expect(await page.mausbot().state.get("filter")).toEqual({ region: "north" });+ expect(await page.mausbot().state.keys()).toEqual(["filter"]);+ await page.mausbot().state.set("filter");+ expect(await page.mausbot().state.get("filter")).toBeUndefined();+ expect(asked[0]).toEqual(["mausbot/data/query", { sql: "SELECT ? AS n", params: [1] }]);+ expect(asked[4]).toEqual(["mausbot/state/set", { key: "filter" }]);+ });++ it("rejects data and state with the reason when the page did not declare them", async () => {+ const page = boot();+ await expect(page.mausbot().data.query("SELECT 1")).rejects.toThrow('This page did not declare "data"');+ await expect(page.mausbot().state.keys()).rejects.toThrow('This page did not declare "state"');+ });+it("in a room, says so, and its send and setContext resolve without asking the host; a page that asks anyway is refused", async () => {const page = boot(true, { room: true });expect(page.mausbot().room).toBe(true);diff --git a/shared/app-frame/helper.ts b/shared/app-frame/helper.tsindex 4ccfcb705c..630149d76c 100644--- a/shared/app-frame/helper.ts+++ b/shared/app-frame/helper.ts@@ -7,8 +7,12 @@// setContext(text): Promise<void>, // ui/update-model-context// theme: "light" | "dark",// room: boolean, // shown in a room: send and setContext resolve and do nothing+// data: { query(sql, params?): Promise<{ columns, rows, truncated }> }, // mausbot/data/query+// state: { get(key): Promise<value | undefined>, set(key, value?): Promise<void>, keys(): Promise<string[]> },// }//+// data and state answer only for a page shown with show_html `uses` naming them; otherwise they reject with the reason.+//// Outside a room it also reports the person's text selection (mausbot/notifications/selection), so the host can// offer to cite it in the chat's composer. Everywhere it reports whether the page, as rendered, opens with a heading// (mausbot/notifications/heading), so the host's card knows whether to put the page's title above it.@@ -29,6 +33,9 @@ export const APP_THEME_STYLE = ["--font-mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}",].join("");+/** What a published page's data and state calls reject with: no bot answers there. */+export const PUBLISHED_PAGE_NO_BOT = "This page is published: it cannot read the bot's data or keep state. Embed the data in the page instead.";+/** The page's text selection, read by the desktop host beside the bridge: { text, left, bottom }, or { text: "" } once gone. */export const APP_SELECTION_METHOD = "mausbot/notifications/selection";/** One past the longest quote a chat citation holds, so the host can say a longer selection is too long. */@@ -305,6 +312,25 @@ const helperSource = (room: boolean) => `(function () {return request("ui/update-model-context", { content: [{ type: "text", text: String(text) }] });}).then(function () {});};+ var call = function (method, params) {+ return ready.then(function () { return request(method, params); });+ };+ api.data = {+ query: function (sql, params) {+ return call("mausbot/data/query", params === undefined ? { sql: String(sql) } : { sql: String(sql), params: params });+ }+ };+ api.state = {+ get: function (key) {+ return call("mausbot/state/get", { key: String(key) }).then(function (result) { return result ? result.value : undefined; });+ },+ set: function (key, value) {+ return call("mausbot/state/set", value === undefined ? { key: String(key) } : { key: String(key), value: value }).then(function () {});+ },+ keys: function () {+ return call("mausbot/state/keys", {}).then(function (result) { return result && Array.isArray(result.keys) ? result.keys : []; });+ }+ };Object.defineProperty(window, "mausbot", { value: api, enumerable: true });})();`;diff --git a/shared/app-frame/host-page.ts b/shared/app-frame/host-page.tsindex b8631fd2d1..9036346771 100644--- a/shared/app-frame/host-page.ts+++ b/shared/app-frame/host-page.ts@@ -33,7 +33,7 @@// every message came from the main frame of this page's origin, and the app// frame's opaque origin cannot reach this page's globals.import type { AppDocument } from "../app.ts";-import { APP_FRAME_LIMITS, createAppBridge, type AppBridge, type AppContextUpdate, type AppHostContext, type AppRpcMethod } from "./bridge.ts";+import { APP_FRAME_LIMITS, createAppBridge, type AppBridge, type AppContextUpdate, type AppHostContext, type AppRpcMethod, type PageRpcMethod } from "./bridge.ts";export const APP_HOST_PROTOCOL_VERSION = 1;@@ -171,7 +171,7 @@ export function startAppHostPage(win: Window, given?: AppHostTransport): AppHostsource: () => element.contentWindow,adapter: {post: (message) => element.contentWindow?.postMessage(message, "*"),- callRpc: (method: AppRpcMethod, params) => call("rpc", { method, params }),+ callRpc: (method: AppRpcMethod | PageRpcMethod, params) => call("rpc", { method, params }),sendMessage: async (text) => { await call("message", { text }); },openLink: async (url) => { await call("open-link", { url }); },setContext: async (update: AppContextUpdate) => { await call("context", { ...update }); },diff --git a/shared/app-frame/jsx-page.ts b/shared/app-frame/jsx-page.tsindex 65224359ed..206bd90fe6 100644--- a/shared/app-frame/jsx-page.ts+++ b/shared/app-frame/jsx-page.ts@@ -2,7 +2,7 @@// pinned and come from cdn.jsdelivr.net, which a bot page's CSP already allows, through one import map; nothing is// bundled into the app. In a chat frame the shell transpiles the file itself with Sucrase; a published page carries// the server's transpiled code instead and loads no compiler.-import { APP_THEME_STYLE } from "./helper.ts";+import { APP_THEME_STYLE, PUBLISHED_PAGE_NO_BOT } from "./helper.ts";/** Exact versions, each at least two weeks old when pinned; `sucrase` matches the server's own dependency. */export const JSX_PAGE_LIBRARIES = {@@ -17,7 +17,7 @@ export const JSX_PAGE_LIBRARIES = {const NPM = "https://cdn.jsdelivr.net/npm";const REACT = `${NPM}/react@${JSX_PAGE_LIBRARIES.react}/+esm`;-/** What a page's file may import. `mausbot` is the shell's own: Chart, useTheme, send, open and setContext. */+/** What a page's file may import. `mausbot` is the shell's own: Chart, useTheme, send, open, setContext, data and state. */export const JSX_PAGE_IMPORTS: Readonly<Record<string, string>> = {react: REACT,"react/jsx-runtime": `${NPM}/react@${JSX_PAGE_LIBRARIES.react}/jsx-runtime/+esm`,@@ -158,11 +158,18 @@ export const JSX_RUNTIME_SOURCE = `(function (env) {style: Object.assign({ width: "100%", height: props.height || 320 }, props.style) });};var bridge = function () { return win.mausbot && typeof win.mausbot.send === "function" ? win.mausbot : null; };+ var unpublished = function () { return Promise.reject(new Error(${JSON.stringify(PUBLISHED_PAGE_NO_BOT)})); };return {__esModule: true, Chart: Chart, useTheme: useTheme,send: function (text) { return bridge() ? bridge().send(text) : Promise.resolve(); },open: function (url) { if (bridge()) return bridge().open(url); win.open(url, "_blank", "noopener"); return Promise.resolve(); },- setContext: function (text) { return bridge() ? bridge().setContext(text) : Promise.resolve(); }+ setContext: function (text) { return bridge() ? bridge().setContext(text) : Promise.resolve(); },+ data: { query: function (sql, params) { return bridge() ? bridge().data.query(sql, params) : unpublished(); } },+ state: {+ get: function (key) { return bridge() ? bridge().state.get(key) : unpublished(); },+ set: function (key, value) { return bridge() ? bridge().state.set(key, value) : unpublished(); },+ keys: function () { return bridge() ? bridge().state.keys() : unpublished(); }+ }};};var compile = function () {diff --git a/shared/app.test.ts b/shared/app.test.tsindex d42d7cfed0..4431f763fc 100644--- a/shared/app.test.ts+++ b/shared/app.test.ts@@ -120,3 +120,19 @@ describe("htmlVisibleText numeric character references", () => {expect(htmlVisibleText("😀")).toBe("😀");});});++describe("show_html uses", () => {+ it("reads a list of data and state, and the shapes models send for one", () => {+ expect(parseShowHtmlInput({ html: "<p>x</p>", title: "t", uses: ["data", "state", "data"] })).toMatchObject({ ok: true, value: { uses: ["data", "state"] } });+ expect(parseShowHtmlInput({ html: "<p>x</p>", title: "t", uses: "data" })).toMatchObject({ ok: true, value: { uses: ["data"] } });+ expect(parseShowHtmlInput({ html: "<p>x</p>", title: "t", uses: '["State"]' })).toMatchObject({ ok: true, value: { uses: ["state"] } });+ expect(parseShowHtmlInput({ html: "<p>x</p>", title: "t", uses: [] }).ok && "uses" in (parseShowHtmlInput({ html: "<p>x</p>", title: "t", uses: [] }) as { value: object }).value).toBe(false);+ expect(parseShowHtmlInput({ html: "<p>x</p>", title: "t", uses: ["network"] })).toEqual({ ok: false, error: 'uses: a list of "data" and "state", e.g. ["data", "state"].' });+ expect(parseShowHtmlInput({ html: "<p>x</p>", title: "t", uses: [{ name: "data" }] }).ok).toBe(false);+ });++ it("keeps a replacement's uses as given, and leaves them out when not given", () => {+ expect(parseUpdateHtmlInput({ app_id: "m1", html: "<p>x</p>", uses: [] })).toMatchObject({ ok: true, value: { uses: [] } });+ expect(parseUpdateHtmlInput({ app_id: "m1", html: "<p>x</p>" }).ok && "uses" in (parseUpdateHtmlInput({ app_id: "m1", html: "<p>x</p>" }) as { value: object }).value).toBe(false);+ });+});diff --git a/skills/data-dashboards/SKILL.md b/skills/data-dashboards/SKILL.mdindex 287f6b6512..925b39b1c1 100644--- a/skills/data-dashboards/SKILL.md+++ b/skills/data-dashboards/SKILL.md@@ -15,12 +15,38 @@ that with `show_html` and the page's `app_id`; the same card refreshes.| The person wants | Build ||---|---|| A quick answer or one chart | No page. Use the Data tools (`data_sql`, `data_show`) or a markdown table. |+| A dashboard here on data in your database | A chat page shown with `uses: ["data"]` that reads it with `mausbot.data.query` (below). It shows the data as it is when the page opens: nothing to export or embed. || A small summary to look at here | A chat page (`show_html`) with pre-aggregated rows embedded as CSV. |-| To explore bigger data, or a link to share | Query with the Data tools, export the slice with `data_export` (`format: "parquet"`) into a folder beside `index.html`, show the folder in the chat with `show_html` `path`, and `publish_page` it when the person wants a link: the same card gains it. |+| A link to share, or data not in your database | Query with the Data tools, export the slice with `data_export` (`format: "parquet"`) into a folder beside `index.html`, show the folder in the chat with `show_html` `path`, and `publish_page` it when the person wants a link: the same card gains it. || "Keep it up to date", "live" | The folder page with `live: true` on `show_html` (and on `publish_page` for a link), plus a schedule (`trigger`, `action=create`, `when=schedule`) whose instructions only re-run the export into the same folder and set `CONFIG.updated`. A live chat card reloads within seconds of the folder changing; a live link is published again by itself (at most once a minute) and open copies reload. Without `live`, the schedule must publish the same folder again; the same path keeps the same link. |Publish only when the person wants others to open it (share, send to someone, post) or asks to publish; a page just for them stays in the chat. A published page is public to anyone with its link, so say so: never put secrets, personal details or rows they didn't ask to share in it.+## Live data in a chat page++Show the page with `uses: ["data"]` (and `"state"` to remember the person's filters, as this example does) and query+your Data tables from it. Every query is one `SELECT` on your own tables and views, read-only: no files, URLs or writes, at most 5,000 rows+and 1 MB an answer, 10 seconds each, about 10 calls in 10 seconds. Aggregate in SQL and load the page in a few+queries. Rows come as objects; whole numbers and decimals as numbers, dates as text.++```html+<select id="region"><option>All</option><option>north</option></select><ul id="out">Loading…</ul>+<script>+const pick = document.getElementById("region");+async function draw() {+ const { rows } = await mausbot.data.query("SELECT product, sum(revenue) AS revenue FROM sales WHERE $r = 'All' OR region = $r GROUP BY 1 ORDER BY 2 DESC LIMIT 10", { r: pick.value });+ document.getElementById("out").innerHTML = rows.map((row) => `<li>${row.product}: ${row.revenue}</li>`).join("");+ mausbot.state.set("region", pick.value);+}+mausbot.state.get("region").then((saved) => { if (saved) pick.value = saved; draw(); });+pick.onchange = draw;+</script>+```++Pass values only as parameters (`?`, `$1` or `$name`), never pasted into the SQL. `mausbot.state.get(key)`,+`set(key, value)` (no value removes it) and `keys()` keep up to 256 KB for this page; its later versions keep it. A+published page cannot reach your database: for a link, use the template's Parquet route below.+## Start from the template`dashboard.html` sits next to this guide, in the folder named by this skill's `root`. It is tested in the chat@@ -105,7 +131,8 @@ Cut cards rather than adding a fifth chart.- `lucide-react` icons: `import { Check, ArrowRight } from "lucide-react"`, sized with `size={16}`.- `echarts` (6.1), or `import { Chart, useTheme } from "mausbot"`: `<Chart option={…} height={280} label="…" />`follows the light or dark theme; `useTheme()` returns `"light"` or `"dark"`.-- `mausbot` also has `send(text)`, `open(url)` and `setContext(text)`, as in the tool's description.+- `mausbot` also has `send(text)`, `open(url)` and `setContext(text)`, as in the tool's description, and `data` and+ `state` when the page declares them (see "Live data in a chat page").- Tailwind classes (4.3) need no import. `dark:` follows the chat's theme.TypeScript types are fine. A file that doesn't read, or imports anything else, comes back as an error with theline: fix it and send the whole file again. Errors while it runs show on the page and reach you with the next message.diff --git a/src/components/app/app-api.ts b/src/components/app/app-api.tsindex ae3b2a7c17..fd62073bfc 100644--- a/src/components/app/app-api.ts+++ b/src/components/app/app-api.ts@@ -2,7 +2,7 @@ import { t } from "@/lib/i18n";import { api, ApiError } from "@/state/store";import type { AppBlockedReason, AppDocument } from "../../../shared/app";import type { PublishedPageCard } from "../../../shared/published-page";-import { RPC_HOST_REFUSED, type AppContextUpdate, type AppRpcMethod, type JsonRpcError } from "../../../shared/app-frame/bridge";+import { RPC_HOST_REFUSED, type AppContextUpdate, type AppRpcMethod, type JsonRpcError, type PageRpcMethod } from "../../../shared/app-frame/bridge";import { randomUuid } from "@/lib/random-uuid";export function appDocumentPath(threadId: string, messageId: string): string {@@ -84,7 +84,7 @@ export async function callAppRpc(args: {botId: string;threadId: string;messageId: string;- method: AppRpcMethod;+ method: AppRpcMethod | PageRpcMethod;params: Record<string, unknown>;}): Promise<AppRpcOutcome> {try {