Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(data): load relative sources from the conversation folder

Afloatbcc2ae3d668f
diff --git a/server/data/load-working-folder.e2e.test.ts b/server/data/load-working-folder.e2e.test.ts
new file mode 100644
index 0000000000..30928b389b
--- /dev/null
+++ b/server/data/load-working-folder.e2e.test.ts
@@ -0,0 +1,71 @@
+import { mkdirSync, writeFileSync } 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, DataSheet } from "../../shared/data-surface.ts";
+
+const key = "data-working-folder-fixture";
+let fixture: Awaited<ReturnType<typeof launchVerificationServer>>;
+
+async function api<T>(method: string, path: string, body?: unknown, headers: Record<string, string> = {}): Promise<T> {
+ 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();
+ expect(response.ok, JSON.stringify(result)).toBe(true);
+ return result as T;
+}
+
+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 task(botId: string, title: string, amount: number) {
+ const cwd = join(fixture.info.dataDir, "projects", title);
+ mkdirSync(join(cwd, "incoming"), { recursive: true });
+ writeFileSync(join(cwd, "report.csv"), `item,amount\n${title},${amount}\n`);
+ writeFileSync(join(cwd, "incoming", "report.csv"), `item,amount\n${title},${amount}\n`);
+ const { task } = await api<{ task: { threadId: string } }>("POST", `/api/bots/${botId}/tasks`, { title, cwd });
+ const { token } = await api<{ token: string }>("POST", "/api/testing/internal-capability", {
+ botId, threadId: task.threadId, kind: "data",
+ }, { "x-openmausbot-test-capability": key });
+ return {
+ cwd,
+ load: async (source: string, name: string) => {
+ const { result } = await api<{ result: { isError?: boolean; content: unknown; structuredContent: unknown } }>("POST", "/api/internal/data/mcp", {
+ method: "tools/call", params: { name: "data_load", arguments: { source, name } },
+ }, { authorization: `Bearer ${token}` });
+ return result;
+ },
+ };
+}
+
+it.each(["report.csv", "./incoming", "incoming/*.csv"])("loads %s from the calling conversation's working folder", async (source) => {
+ const { bot } = await api<{ bot: { id: string } }>("POST", "/api/bots", { name: `Data ${source}` });
+ const first = await task(bot.id, `north-${bot.id}`, 5);
+ const second = await task(bot.id, `south-${bot.id}`, 9);
+ for (const [caller, table, amount] of [[first, "north", 5], [second, "south", 9]] as const) {
+ const loaded = await caller.load(source, table);
+ expect(loaded.isError, JSON.stringify(loaded)).not.toBe(true);
+ const page = await api<DataPage>("POST", `/api/bots/${bot.id}/data/page`, { table, offset: 0, limit: 10 });
+ expect(page.rows.map((row) => Number(row[1]))).toEqual([amount]);
+ const { sheet } = await api<{ sheet: DataSheet }>("GET", `/api/bots/${bot.id}/data`);
+ expect(sheet.sources.find((entry) => entry.name === table)?.source).toBe(join(caller.cwd, source));
+ }
+});
+
+it("keeps an absolute source outside the calling conversation's folder", async () => {
+ const { bot } = await api<{ bot: { id: string } }>("POST", "/api/bots", { name: "Absolute Data source" });
+ const caller = await task(bot.id, `caller-${bot.id}`, 1);
+ const outside = join(fixture.info.dataDir, "absolute-report.csv");
+ writeFileSync(outside, "item,amount\nabsolute,42\n");
+ const loaded = await caller.load(outside, "absolute_report");
+ expect(loaded.isError, JSON.stringify(loaded)).not.toBe(true);
+ const page = await api<DataPage>("POST", `/api/bots/${bot.id}/data/page`, { table: "absolute_report", offset: 0, limit: 10 });
+ expect(page.rows).toEqual([["absolute", "42"]]);
+});
diff --git a/server/data/tools.ts b/server/data/tools.ts
index 6d1a95cc16..cfffd096bc 100644
--- a/server/data/tools.ts
+++ b/server/data/tools.ts
@@ -52,7 +52,7 @@ export const DATA_TOOLS = [
"data_load",
"Load data into a named table of this bot's database: a local file, folder or glob (csv, tsv, json, ndjson, parquet, xlsx, sqlite; .gz/.zst too), an http(s)/s3/gs/az URL, a postgres:// or mysql:// connection string (snapshots the tables read-only), or a Google Sheets URL. Replaces a table of the same name unless replace is false. Returns each table's columns, row count and sample values.",
{
- source: { type: "string", minLength: 1, maxLength: 4000 },
+ source: { type: "string", minLength: 1, maxLength: 4000, description: "Local paths are relative to this conversation's working folder." },
name: { type: "string", pattern: IDENT, description: "Table name. Default: from the file name." },
kind: { type: "string", enum: ["auto", "csv", "tsv", "parquet", "json", "xlsx", "sqlite", "folder", "url", "postgres", "mysql", "gsheet"], description: "Default auto: decided from the source." },
sheet: { type: "string", maxLength: 200, description: "The workbook sheet, or the table (schema.table) to snapshot from a database. Default: the first sheet; every table." },
@@ -283,6 +283,7 @@ export function toDataError(error: unknown, sql?: string, signal?: AbortSignal):
export interface DataContext {
database: BotDatabase;
sheet: DataSheetStore;
+ cwd?: string;
compileChart: ChartCompiler;
validateVegaLite: VegaLiteValidator;
renderer: ChartRenderer;
@@ -392,7 +393,7 @@ export function tableNameFrom(stem: string): string {
return name;
}
-export function planLoad(input: LoadInput): LoadPlan[] {
+export function planLoad(input: LoadInput, cwd?: string): LoadPlan[] {
const { source } = input;
const kind = input.kind ?? "auto";
const warnings: string[] = [];
@@ -417,7 +418,7 @@ export function planLoad(input: LoadInput): LoadPlan[] {
if (reader === "xlsx") extensions.push("excel");
return [{ kind: "url", source: stripCredentials(source), stem: input.name ?? (stemOf(pathname) || "download"), reader: readerExpression(reader, source, input, false), extensions, warnings }];
}
- const local = source.startsWith("~/") || source === "~" ? join(homedir(), source.slice(1)) : source;
+ const local = source.startsWith("~/") || source === "~" ? join(homedir(), source.slice(1)) : cwd ? resolve(cwd, source) : source;
if ((GLOB_CHARS.test(local) || kind === "folder") && !existsSync(local)) {
const reader = readerFor(extensionOf(local), kind === "folder" ? undefined : kind);
if (!reader || reader === "sqlite" || reader === "xlsx") throw fail("source_unsupported", "A glob needs a file extension DuckDB reads many of: *.csv, *.parquet, *.json.", { hint: "Pass kind: csv, json or parquet with the glob." });
@@ -463,7 +464,7 @@ export interface LoadOutput { tables: LoadedTable[]; warnings: string[]; elapsed
export async function loadData(ctx: DataContext, input: LoadInput): Promise<LoadOutput> {
const started = Date.now();
- const plans = planLoad(input);
+ const plans = planLoad(input, ctx.cwd);
const replace = input.replace !== false;
const existing = new Set((await ctx.database.listTables()).map((table) => table.name.toLowerCase()));
const tables: LoadedTable[] = [];
diff --git a/server/index.ts b/server/index.ts
index c0cc5e72dd..cc8a0ab46b 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -12963,7 +12963,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
}
requireActiveInternalCapability();
return json(res, 200, { result: await dataRpc(body, {
- database, sheet: dataSheets.for(internalSender.id),
+ database, sheet: dataSheets.for(internalSender.id), cwd: messageFileRootsForThread(internalSender.id, internalCapability.threadId)[0],
compileChart, validateVegaLite, renderer: chartRenderer,
exportRoots: () => dataExportRoots(internalSender),
signal: abort.signal, assertActive: requireActiveInternalCapability,