Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(data): resolve temporary relations on their owning connection
Afloat1127bba5c555
diff --git a/server/data/engine.ts b/server/data/engine.tsindex 0c4d596b24..4aaa6dc660 100644--- a/server/data/engine.ts+++ b/server/data/engine.ts@@ -278,9 +278,11 @@ export async function drainLanes(lanes: Array<{ run<T>(sql: string, options: obj}interface CatalogEntry {+ catalog: string;schema: string;name: string;type: string;+ qualifyCatalog?: true;}function toCount(cell: Cell): number {@@ -445,10 +447,11 @@ class BotDb implements BotDatabase {await this.statement(connection, sql, {}, (open, conn) => this.read(open, conn, sql));}- private async catalog(connection: DataConnection = "panel"): Promise<CatalogEntry[]> {- const sql = "SELECT table_schema, table_name, table_type FROM information_schema.tables WHERE table_catalog = current_database() AND table_schema NOT IN ('information_schema', 'pg_catalog') ORDER BY table_schema, table_name";+ private async catalog(connection: DataConnection = "panel", temporary = false): Promise<CatalogEntry[]> {+ const catalogs = temporary ? "(table_catalog = current_database() OR table_catalog = 'temp')" : "table_catalog = current_database()";+ const sql = `SELECT table_catalog, table_schema, table_name, table_type FROM information_schema.tables WHERE ${catalogs} AND table_schema NOT IN ('information_schema', 'pg_catalog') ORDER BY table_schema, table_name`;const result = await this.statement(connection, sql, {}, (open, conn) => this.read(open, conn, sql));- return result.rows.map((row) => ({ schema: String(row[0]), name: String(row[1]), type: String(row[2]) }));+ return result.rows.map((row) => ({ catalog: String(row[0]), schema: String(row[1]), name: String(row[2]), type: String(row[3]) }));}private displayName(entry: CatalogEntry): string {@@ -457,7 +460,7 @@ class BotDb implements BotDatabase {private qualified(entry: CatalogEntry, reserved: Set<string>): string {const part = (name: string) => (PLAIN_IDENTIFIER.test(name) && !reserved.has(name) ? name : quoteIdentifier(name));- return `${part(entry.schema)}.${part(entry.name)}`;+ return `${entry.qualifyCatalog || entry.catalog === "temp" ? `${part(entry.catalog)}.` : ""}${part(entry.schema)}.${part(entry.name)}`;}private splitIdentifier(text: string): string[] {@@ -478,18 +481,21 @@ class BotDb implements BotDatabase {return parts.map((part) => part.trim());}- private async lookup(name: string): Promise<CatalogEntry> {- const parts = (tableIdentifierParts(name) ?? this.splitIdentifier(name.trim())).slice(-2);+ private async lookup(name: string, connection: DataConnection = "panel"): Promise<CatalogEntry> {+ const parts = tableIdentifierParts(name) ?? this.splitIdentifier(name.trim());const table = parts[parts.length - 1];- const schema = parts.length === 2 ? parts[0] : null;+ const schema = parts.length > 1 ? parts[parts.length - 2] : undefined;+ const catalog = parts.length === 3 ? parts[0] : undefined;if (!table) throw new DataFailure({ code: "invalid_input", message: "A table name is required." });- const entries = await this.catalog();- const inSchema = schema ? entries.filter((entry) => entry.schema === schema || entry.schema.toLowerCase() === schema.toLowerCase()) : entries;+ if (parts.length > 3) throw new DataFailure({ code: "invalid_input", message: "A table name has at most three identifier parts." });+ const entries = await this.catalog(connection, true);+ const inCatalog = catalog === undefined ? entries : entries.filter((entry) => entry.catalog.toLowerCase() === catalog.toLowerCase());+ const inSchema = schema ? inCatalog.filter((entry) => entry.schema === schema || entry.schema.toLowerCase() === schema.toLowerCase()) : inCatalog;const rank = (entry: CatalogEntry) => (entry.schema === "main" ? 0 : entry.schema === DATA_RESULTS_SCHEMA ? 1 : 2);const exact = inSchema.filter((entry) => entry.name === table).sort((x, y) => rank(x) - rank(y));const folded = inSchema.filter((entry) => entry.name.toLowerCase() === table.toLowerCase()).sort((x, y) => rank(x) - rank(y));- const found = exact[0] ?? folded[0];- if (found) return found;+ const found = folded.find((entry) => entry.catalog === "temp") ?? exact[0] ?? folded[0];+ if (found) return catalog === undefined ? found : { ...found, qualifyCatalog: true };throw new DataFailure({code: "table_not_found",message: `Table ${name.trim()} does not exist.`,@@ -503,8 +509,8 @@ class BotDb implements BotDatabase {return closeNames(table, entries.map((entry) => this.displayName(entry)));}- async resolveTable(name: string): Promise<string> {- const entry = await this.lookup(name);+ async resolveTable(name: string, connection: DataConnection = "panel"): Promise<string> {+ const entry = await this.lookup(name, connection);const open = await this.open();return this.qualified(entry, open.reserved);}@@ -546,17 +552,17 @@ class BotDb implements BotDatabase {return { rowCount, columns: enriched };}- private async source(target: string): Promise<string> {+ private async source(target: string, connection: DataConnection): Promise<string> {const text = target.trim().replace(/;+\s*$/, "");// Keep accepting the display names callers could pass before quoted SQL// identifiers were recognized here (for example, Order Items).const displayName = /^[\w."$ -]+$/.test(text) && !/\s(?:from|select|with|values)\s/i.test(text) && !/^(?:select|with|from|values|pivot|unpivot|show|describe)\b/i.test(text);- if (tableIdentifierParts(text) || displayName) return this.resolveTable(text);+ if (tableIdentifierParts(text) || displayName) return this.resolveTable(text, connection);return `(${text}) AS omb_described`;}async describe(target: string, options: RunOptions): Promise<DescribeResult> {- const from = await this.source(target);+ const from = await this.source(target, options.connection);const all = await this.columnsOf(options.connection, from, options);const profiled = all.slice(0, DATA_LIMITS.describeColumnsMax);const { rowCount, columns } = await this.aggregate(options.connection, from, profiled, options);diff --git a/server/data/temporary-tables.e2e.test.ts b/server/data/temporary-tables.e2e.test.tsnew file mode 100644index 0000000000..960533c10a--- /dev/null+++ b/server/data/temporary-tables.e2e.test.ts@@ -0,0 +1,120 @@+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { afterAll, beforeAll, expect, it } from "vitest";++import { launchVerificationServer, runControlOmb } from "../../scripts/control-omb.ts";+import type { DataPage } from "../../shared/data-surface.ts";++const key = "data-temporary-tables-fixture";+let fixture: Awaited<ReturnType<typeof launchVerificationServer>>;+let next = 0;++async function api(method: string, path: string, body?: unknown, headers: Record<string, string> = {}, status?: number): Promise<any> {+ const response = await fetch(fixture.info.url + path, {+ method, headers: { origin: fixture.info.url, "content-type": "application/json", ...headers },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(30_000),+ });+ const result = await response.json();+ if (status !== undefined) expect(response.status, JSON.stringify(result)).toBe(status);+ else expect(response.ok, JSON.stringify(result)).toBe(true);+ return result;+}++beforeAll(async () => {+ fixture = await launchVerificationServer({ OMB_TEST_INTERNAL_CAPABILITY_KEY: key });+ expect(await runControlOmb(["doctor", "--url", fixture.info.url])).toMatchObject({ ok: true });+}, 60_000);+afterAll(async () => { await fixture?.close(); });++async function caller() {+ const { bot } = await api("POST", "/api/bots", { name: `Temporary Data ${++next}` });+ const { token } = await api("POST", "/api/testing/internal-capability", { botId: bot.id, threadId: bot.threadId, kind: "data" }, { "x-openmausbot-test-capability": key });+ return {+ botId: bot.id as string,+ call: async (name: string, args: Record<string, unknown>) => (await api("POST", "/api/internal/data/mcp", {+ method: "tools/call", params: { name, arguments: args },+ }, { authorization: `Bearer ${token}` })).result,+ page: (body: object, status?: number): Promise<DataPage> => api("POST", `/api/bots/${bot.id}/data/page`, { offset: 0, limit: 10, ...body }, {}, status),+ };+}++async function temporary(kind = "TABLE") {+ const h = await caller();+ const created = await h.call("data_sql", { sql: `CREATE TEMP ${kind} totals AS SELECT * FROM (VALUES (5), (9)) t(amount)` });+ const read = await h.call("data_sql", { sql: "SELECT amount FROM totals ORDER BY amount" });+ expect(read.structuredContent.rows).toEqual([[5], [9]]);+ return { ...h, created };+}++it.each(["TABLE", "VIEW"])("reports the temporary relation that CREATE TEMP %s actually created", async (kind) => {+ const { created } = await temporary(kind);+ expect(created.isError, JSON.stringify(created)).not.toBe(true);+ expect(created.structuredContent).toMatchObject({ table: "totals", rowCount: 2, columns: [{ name: "amount", type: "INTEGER" }] });+});++it("describes a temporary table on the same connection as its SQL", async () => {+ const h = await temporary();+ const result = await h.call("data_describe", { target: "totals" });+ expect(result.isError, JSON.stringify(result)).not.toBe(true);+ expect(result.structuredContent).toMatchObject({ rowCount: 2, columns: [{ name: "amount", min: "5", max: "9", approxUnique: 2 }] });+});++it("materializes a temporary source into a card that the panel can page", async () => {+ const h = await temporary();+ const result = await h.call("data_show", { table: "totals", kind: "table" });+ expect(result.isError, JSON.stringify(result)).not.toBe(true);+ expect((await h.page({ cardId: result.structuredContent.id })).rows.map(([amount]) => amount).sort()).toEqual([5, 9]);+});++it("exports a temporary table's actual rows", async () => {+ const h = await temporary();+ const path = join(fixture.info.dataDir, "workspaces", h.botId, "totals.csv");+ const result = await h.call("data_export", { table: "totals", format: "csv", path });+ expect(result.isError, JSON.stringify(result)).not.toBe(true);+ expect(result.structuredContent.rowCount).toBe(2);+ const [header, ...rows] = readFileSync(result.structuredContent.path, "utf8").trim().split(/\r?\n/);+ expect(header).toBe("amount");+ expect(rows.sort()).toEqual(["5", "9"]);+});++it("keeps a temporary source private to the bot connection until it is materialized", async () => {+ const h = await temporary();+ expect(await h.page({ table: "totals" }, 404)).toMatchObject({ error: { code: "table_not_found" } });+ const another = await caller();+ expect(await another.call("data_describe", { target: "totals" })).toMatchObject({ isError: true, structuredContent: { code: "table_not_found" } });+});++it("preserves DuckDB's temporary-table shadowing without changing the panel's persistent table", async () => {+ const h = await caller();+ expect((await h.call("data_sql", { sql: "CREATE TABLE totals AS SELECT 1 AS amount" })).isError).not.toBe(true);+ const created = await h.call("data_sql", { sql: "CREATE TEMP TABLE totals AS SELECT 42 AS amount, 'temporary' AS origin" });+ expect(created.isError, JSON.stringify(created)).not.toBe(true);+ expect(created.structuredContent.columns.map((column: { name: string }) => column.name)).toEqual(["amount", "origin"]);+ const shown = await h.call("data_show", { table: "totals", kind: "table" });+ expect(shown.isError, JSON.stringify(shown)).not.toBe(true);+ expect((await h.page({ cardId: shown.structuredContent.id })).rows).toEqual([[42, "temporary"]]);+ expect((await h.page({ table: "totals" })).rows).toEqual([[1]]);+});++it("honours an explicit catalog when a temporary table shadows a persistent table", async () => {+ const h = await caller();+ await h.call("data_sql", { sql: "CREATE TABLE totals AS SELECT 1 AS amount" });+ await h.call("data_sql", { sql: "CREATE TEMP TABLE totals AS SELECT 42 AS amount" });+ const current = await h.call("data_sql", { sql: "SELECT current_database() AS catalog" });+ const catalog = String(current.structuredContent.rows[0][0]).replaceAll('"', '""');+ const persistent = await h.call("data_show", { table: `"${catalog}".main.totals`, kind: "table" });+ expect(persistent.isError, JSON.stringify(persistent)).not.toBe(true);+ expect((await h.page({ cardId: persistent.structuredContent.id })).rows).toEqual([[1]]);+ const temporary = await h.call("data_describe", { target: "temp.main.totals" });+ expect(temporary.structuredContent.columns[0]).toMatchObject({ min: "42", max: "42" });+ expect(await h.page({ table: "temp.main.totals" }, 404)).toMatchObject({ error: { code: "table_not_found" } });+});++it("does not substitute a local table for a missing catalog", async () => {+ const h = await caller();+ await h.call("data_sql", { sql: "CREATE TABLE totals AS SELECT 1 AS amount" });+ const wrong = await h.call("data_show", { table: "other_catalog.main.totals", kind: "table" });+ expect(wrong).toMatchObject({ isError: true, structuredContent: { code: "table_not_found" } });+ expect(await h.page({ table: "other_catalog.main.totals" }, 404)).toMatchObject({ error: { code: "table_not_found" } });+ expect((await h.page({ table: "totals" })).rows).toEqual([[1]]);+});diff --git a/server/data/tools.ts b/server/data/tools.tsindex 6d1a95cc16..17c5376a5d 100644--- a/server/data/tools.ts+++ b/server/data/tools.ts@@ -546,7 +546,7 @@ export async function describeTarget(ctx: DataContext, target: string): Promise<let name: string | undefined;let sql: string | undefined;if (tableIdentifierParts(target)) {- name = await ctx.database.resolveTable(target.trim());+ name = await ctx.database.resolveTable(target.trim(), ctx.connection);relation = name;} else {const kind = gateSql(target);@@ -699,7 +699,7 @@ export async function showCard(context: DataContext, input: ShowInput, onCardReaif (kind.kind !== "read" || !kind.materialisable) throw fail("invalid_input", "A card shows a SELECT's result.", { sql: input.sql });from = queryRelation(input.sql);} else {- from = await ctx.database.resolveTable(input.table!);+ from = await ctx.database.resolveTable(input.table!, ctx.connection);cardSql = `SELECT * FROM ${from}`;}ctx.signal.throwIfAborted();@@ -865,7 +865,7 @@ export async function exportData(ctx: DataContext, input: ExportInput): Promise<else throw fail("invalid_input", `${card.id} has no data to export.`);stem = card.title;} else if (input.table) {- relation = await ctx.database.resolveTable(input.table);+ relation = await ctx.database.resolveTable(input.table, ctx.connection);stem = input.table;} else {const kind = gateSql(input.sql!);diff --git a/server/data/types.ts b/server/data/types.tsindex 459b0c7f3b..aec4c5ff2d 100644--- a/server/data/types.ts+++ b/server/data/types.ts@@ -66,7 +66,7 @@ export interface BotDatabase {listTables(): Promise<Array<{ name: string; sqlName?: string; rowCount: number; columns: DataColumn[] }>>;interrupt(connection: DataConnection): void;/** Resolves a bare or qualified identifier; `table_not_found` with candidates otherwise. */- resolveTable(name: string): Promise<string>;+ resolveTable(name: string, connection?: DataConnection): Promise<string>;close(): Promise<void>;}