Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Connected apps: upload a local file a tool takes, so Google Drive uploads work (#6206)
Milind Soni0356137ac574
diff --git a/cloudflare/composio-broker/src/files.test.ts b/cloudflare/composio-broker/src/files.test.tsnew file mode 100644index 0000000000..0ad17c6101--- /dev/null+++ b/cloudflare/composio-broker/src/files.test.ts@@ -0,0 +1,96 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import worker from "./index";++const token = "b".repeat(64);+const upload = { toolkit_slug: "googledrive", tool_slug: "GOOGLEDRIVE_UPLOAD_FILE", filename: "report.pdf", mimetype: "application/pdf", md5: "0".repeat(32) };++function env(limited = false) {+ return {+ COMPOSIO_API_BASE: "https://backend.composio.dev/api/v3.1",+ COMPOSIO_API_KEY: "ak_test",+ SESSION_LIMITER: { limit: async () => ({ success: !limited }) },+ DB: {+ prepare(sql: string) {+ return {+ bind() {+ return {+ run: async () => ({ meta: { changes: 1 } }),+ first: async () => (sql.includes("FROM installations") ? { id: "install-1", composio_user_id: "omb_user", session_id: "trs_files", disabled_at: null } : null),+ };+ },+ };+ },+ },+ };+}++const drive = (status = "ACTIVE") => Response.json({ items: [{ id: "ca_drive", status, toolkit: { slug: "googledrive" } }] });+/** Composio as the broker sees it: the installation's accounts, then the upload link it hands out. */+const composio = (link: unknown, accounts = drive()) => async (input: string | URL | Request) =>+ (String(input).includes("/connected_accounts") ? accounts.clone() : Response.json(link));++const ctx = { waitUntil(promise: Promise<unknown>) { void promise; } };+const post = (body: unknown, headers: Record<string, string> = { authorization: `Bearer ${token}` }) => new Request("https://broker.test/v1/files/upload", {+ method: "POST",+ headers: { ...headers, "content-type": "application/json" },+ body: JSON.stringify(body),+});++afterEach(() => vi.unstubAllGlobals());++describe("file uploads for connected-app tools", () => {+ it("asks Composio for an upload link with the project key and hands back only the link and key", async () => {+ const calls: Array<{ url: string; init?: RequestInit }> = [];+ const answer = composio({ id: "f1", key: "proj/googledrive/report.pdf", new_presigned_url: "https://storage.composio.dev/put?sig=1", type: "new" });+ vi.stubGlobal("fetch", async (input: string | URL | Request, init?: RequestInit) => {+ calls.push({ url: String(input), init });+ return answer(input);+ });+ const response = await worker.fetch(post(upload), env() as never, ctx as never);+ expect(response.status).toBe(200);+ await expect(response.json()).resolves.toEqual({ key: "proj/googledrive/report.pdf", url: "https://storage.composio.dev/put?sig=1" });+ expect(calls).toHaveLength(2);+ expect(calls[0]!.url).toContain("/connected_accounts?");+ expect(new URL(calls[0]!.url).searchParams.get("user_ids")).toBe("omb_user");+ expect(calls[1]!.url).toBe("https://backend.composio.dev/api/v3.1/files/upload/request");+ expect(new Headers(calls[1]!.init?.headers).get("x-api-key")).toBe("ak_test");+ expect(JSON.parse(String(calls[1]!.init?.body))).toEqual(upload);+ });++ it("refuses an unknown caller, a malformed request and a rate-limited installation before asking Composio", async () => {+ const fetchSpy = vi.fn(async () => Response.json({}));+ vi.stubGlobal("fetch", fetchSpy);+ expect((await worker.fetch(post(upload, {}), env() as never, ctx as never)).status).toBe(401);+ for (const bad of [{ ...upload, md5: "nope" }, { ...upload, filename: "../x.pdf" }, { ...upload, tool_slug: "googledrive_upload" }, { ...upload, extra: 1 }]) {+ expect((await worker.fetch(post(bad), env() as never, ctx as never)).status).toBe(400);+ }+ expect((await worker.fetch(post(upload), env(true) as never, ctx as never)).status).toBe(429);+ expect(fetchSpy).not.toHaveBeenCalled();+ });++ it("passes Composio's refusal on and hands out only HTTPS links on Composio's storage", async () => {+ vi.stubGlobal("fetch", async (input: string | URL | Request) =>+ (String(input).includes("/connected_accounts") ? drive() : Response.json({ message: "Toolkit not found" }, { status: 404 })));+ const refused = await worker.fetch(post(upload), env() as never, ctx as never);+ expect(refused.status).toBe(502);+ await expect(refused.json()).resolves.toEqual({ error: "Toolkit not found" });+ for (const link of ["http://storage.composio.dev/put", "https://169.254.169.254/latest", "https://attacker.example/put", "https://storage.composio.dev.attacker.example/put"]) {+ vi.stubGlobal("fetch", composio({ key: "k", new_presigned_url: link }));+ expect((await worker.fetch(post(upload), env() as never, ctx as never)).status, link).toBe(502);+ }+ vi.stubGlobal("fetch", composio({ key: "k", new_presigned_url: "https://composio-files.s3.us-east-1.amazonaws.com/k?X-Amz-Signature=1" }));+ expect((await worker.fetch(post(upload), env() as never, ctx as never)).status).toBe(200);+ });++ it("hands out no link for a toolkit the installation has no working connection to", async () => {+ for (const accounts of [Response.json({ items: [] }), drive("EXPIRED")]) {+ const calls: string[] = [];+ const answer = composio({ key: "k", new_presigned_url: "https://storage.composio.dev/put" }, accounts);+ vi.stubGlobal("fetch", async (input: string | URL | Request) => { calls.push(String(input)); return answer(input); });+ const response = await worker.fetch(post(upload), env() as never, ctx as never);+ expect(response.status).toBe(409);+ expect(calls.some((url) => url.includes("/files/upload/request"))).toBe(false);+ }+ });+});diff --git a/cloudflare/composio-broker/src/files.ts b/cloudflare/composio-broker/src/files.tsnew file mode 100644index 0000000000..dfd9cc8be1--- /dev/null+++ b/cloudflare/composio-broker/src/files.ts@@ -0,0 +1,45 @@+// A connected-app tool that takes a file (Google Drive's GOOGLEDRIVE_UPLOAD_FILE, a Gmail attachment) reads it from+// Composio's file storage by `s3key`, never from the caller's disk. The app asks here for a place to put the file's+// bytes: Composio answers a one-time upload link and the key the tool call then names. The bytes go from the app to+// that link directly and never pass through this Worker.+import { z } from "zod";++import { composioUploadLink } from "../../../shared/composio-storage";+import { actingUser, composioRequest, json, listConnectedAccounts, readJsonBody, upstreamError, type InstallationRow } from "./common";++const uploadRequestSchema = z.object({+ toolkit_slug: z.string().regex(/^[a-z0-9_][a-z0-9_-]{0,80}$/),+ tool_slug: z.string().regex(/^[A-Z0-9][A-Z0-9_]{0,127}$/),+ // A bare file name: no folder, no control characters.+ // eslint-disable-next-line no-control-regex+ filename: z.string().min(1).max(255).refine((name) => !/[\u0000-\u001f\u007f/\\]/.test(name)),+ mimetype: z.string().max(127).regex(/^[A-Za-z0-9][\w.+-]*\/[\w.+-]+$/),+ md5: z.string().regex(/^[0-9a-f]{32}$/),+}).strict();++const uploadResponseSchema = z.object({+ key: z.string().min(1).max(1024),+ new_presigned_url: z.string().optional(),+ newPresignedUrl: z.string().optional(),+});++/** POST /v1/files/upload: Composio's upload link and key for one file a tool call will name. Only for a toolkit the+ * installation has a working connection to: nothing else could use the file. */+export async function requestFileUpload(request: Request, installation: InstallationRow, env: Env) {+ const parsed = uploadRequestSchema.safeParse(await readJsonBody(request, 4096));+ if (!parsed.success) return json({ error: "invalid file upload request" }, 400);+ const accounts = await listConnectedAccounts(env, actingUser(installation), [parsed.data.toolkit_slug]).catch(() => null);+ if (!accounts) return json({ error: "Connected apps could not be checked. Try again." }, 502);+ if (!accounts.some((account) => /^active$/i.test(account.status ?? "") && account.toolkit?.slug?.toLowerCase() === parsed.data.toolkit_slug)) {+ return json({ error: `${parsed.data.toolkit_slug} is not connected` }, 409);+ }+ const response = await composioRequest(env, "/files/upload/request", {+ method: "POST",+ body: JSON.stringify(parsed.data),+ });+ if (!response.ok) return json({ error: await upstreamError(response, `File upload request failed (${response.status})`) }, 502);+ const body = uploadResponseSchema.safeParse(await response.json().catch(() => null));+ const url = body.success ? composioUploadLink(body.data.new_presigned_url ?? body.data.newPresignedUrl) : null;+ if (!body.success || !url) return json({ error: "Composio returned no upload link on its storage" }, 502);+ return json({ key: body.data.key, url: url.toString() });+}diff --git a/cloudflare/composio-broker/src/index.ts b/cloudflare/composio-broker/src/index.tsindex 1a0db80704..710a0b9fa0 100644--- a/cloudflare/composio-broker/src/index.ts+++ b/cloudflare/composio-broker/src/index.ts@@ -18,6 +18,7 @@ import {type InstallationRow,} from "./common";import { eraseInstallation } from "./erase";+import { requestFileUpload } from "./files";import { adoptSharedUser, me, shareUser } from "./sharing";import { createTrigger, deleteTrigger, getTriggerType, listTriggers, listTriggerTypes, updateTrigger } from "./triggers";@@ -733,6 +734,10 @@ async function route(request: Request, env: Env, ctx: ExecutionContext) {return adopted.response;}if (request.method === "POST" && url.pathname === "/v1/mcp") return proxyMcp(request, installation, env, ctx);+ if (request.method === "POST" && url.pathname === "/v1/files/upload") {+ await limitSessionRequests(installation, env);+ return requestFileUpload(request, installation, env);+ }if (request.method === "GET" && url.pathname === "/v1/catalog") return catalog(env, url);if (request.method === "GET" && url.pathname === "/v1/connectors/connected") return connectedServices(installation, env, ctx);if (request.method === "GET" && url.pathname === "/v1/connectors") return connectionStatus(url, installation, env, ctx);diff --git a/docs/composio.md b/docs/composio.mdindex 5eb48e2b2a..3e36d6e2fe 100644--- a/docs/composio.md+++ b/docs/composio.md@@ -119,6 +119,18 @@ OpenMausBot uses your project's own auth config for an app automatically, in plaOn a MausBot Cloud plan, connected apps run through OpenMausBot's managed connection service rather than your own Composio project, so you cannot add permissions yourself; ask OpenMausBot support instead.+## Files a tool takes++Composio runs app tools on its own servers, so a tool that takes a file (Google Drive's `GOOGLEDRIVE_UPLOAD_FILE` with `file_to_upload`, a Gmail attachment) reads it from Composio's file storage by `s3key`, never from this computer. A bot gives such a field the full path of a file (`C:\Users\…\report.pdf`, `/Users/…/report.pdf`, or that path as the `s3key` of a `{ name, mimetype, s3key }` object), and the harness (`server/connector-files.ts`) uploads it:++- **Which files.** Only a file in the bot's working folder or Local VM folder, or one attached to this conversation (by its exact path: never the attachment store as a whole, which holds every conversation's and every team member's files). Never a file in a hidden folder (`.ssh`, `.aws`, `.config`, any dotfile) below the bot's folder or the home folder, nor in the app's own data (`DATA_DIR`, the desktop app's data folder) unless the bot's own folder is inside it, as its workspace is. Such a file is refused with the reason and the call does not go out.+- **Anything else goes as it is.** A value that is not an existing file in those folders (a Dropbox path such as `/Apps/report.pdf`, `/images/logo.png`, text that starts with `/`, anything with a line break) is sent unchanged, with no refusal.+- **When.** The files are read before the call's checks and listed in full (name, path, size) on a "Send on your behalf?" card, ahead of the arguments it cuts at 400 characters. They are uploaded only after the last check before sending, so a call refused there, or whose permission or turn ended meanwhile, uploads nothing.+- **Where.** The harness asks for an upload link (`POST /v1/files/upload` on the managed service, which gives one only for a toolkit the installation has a working connection to; Composio's `POST /files/upload/request` with your own project key). It puts the bytes only to an HTTPS link on Composio's storage (`*.composio.dev` or AWS S3; with `OMB_COMPOSIO_API`, that backend's origin), never following a redirect. The call then carries `{ name, mimetype, s3key }`.+- **Failures.** A failed upload is refused with what failed, and nothing is written to the app. When Composio still cannot fetch a call's file (`Failed to download file with s3key …`), the bot is told to give a local path instead of an invented key. At most 10 files per call. Plain text needs no file: `GOOGLEDRIVE_CREATE_FILE_FROM_TEXT` takes the text itself.++The managed service needs the updated broker as well as the updated app for this.+## Apps with no Composio-managed sign-inSome apps, such as Xero and Buffer, have no sign-in that Composio provides: they connect only through an auth config holding your own OAuth app. Without one, Composio answers "Composio does not manage auth for toolkit … and no auth config without required fields is available".diff --git a/server/composio-files.test.ts b/server/composio-files.test.tsnew file mode 100644index 0000000000..8428db4d6a--- /dev/null+++ b/server/composio-files.test.ts@@ -0,0 +1,44 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import type { AppConfig } from "./config.ts";+import { requestFileUpload } from "./composio-files.ts";++const request = { toolkit_slug: "googledrive", tool_slug: "GOOGLEDRIVE_UPLOAD_FILE", filename: "report.pdf", mimetype: "application/pdf", md5: "0".repeat(32) };+const withKey = { composio: { apiKey: "ak_test" } } as unknown as AppConfig;+const service = { url: "https://connect.example", token: "d".repeat(64) };+const answering = (body: unknown, calls: Array<{ url: string; init?: RequestInit }> = []) => async (url: string, init?: RequestInit) => {+ calls.push({ url, init });+ return Response.json(body);+};++afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); });++describe("upload links for connected-app files", () => {+ it("asks Composio with the project key, and the service for a member's own installation", async () => {+ vi.stubEnv("OMB_COMPOSIO_API", undefined);+ const calls: Array<{ url: string; init?: RequestInit }> = [];+ vi.stubGlobal("fetch", answering({ key: "projects/p/requests/googledrive/report.pdf", new_presigned_url: "https://storage.composio.dev/p/report.pdf?X-Amz-Signature=1" }, calls));+ await expect(requestFileUpload(withKey, request)).resolves.toEqual({ key: "projects/p/requests/googledrive/report.pdf", url: "https://storage.composio.dev/p/report.pdf?X-Amz-Signature=1" });+ expect(calls[0]!.url).toBe("https://backend.composio.dev/api/v3.1/files/upload/request");+ expect(new Headers(calls[0]!.init?.headers).get("x-api-key")).toBe("ak_test");+ vi.stubGlobal("fetch", answering({ key: "k", url: "https://bucket.s3.us-east-1.amazonaws.com/k?X-Amz-Signature=1" }, calls));+ await expect(requestFileUpload(withKey, request, service)).resolves.toMatchObject({ key: "k" });+ expect(calls[1]!.url).toBe("https://connect.example/v1/files/upload");+ expect(new Headers(calls[1]!.init?.headers).get("authorization")).toBe(`Bearer ${service.token}`);+ });++ it("refuses a link anywhere but Composio's storage over HTTPS", async () => {+ vi.stubEnv("OMB_COMPOSIO_API", undefined);+ for (const link of ["https://attacker.example/put", "http://storage.composio.dev/put", "http://127.0.0.1:8787/put", "https://169.254.169.254/x", "https://storage.composio.dev.evil.example/x"]) {+ vi.stubGlobal("fetch", answering({ key: "k", new_presigned_url: link }));+ await expect(requestFileUpload(withKey, request), link).rejects.toThrow("not on its storage");+ vi.stubGlobal("fetch", answering({ key: "k", url: link }));+ await expect(requestFileUpload(withKey, request, service), link).rejects.toThrow("not on its storage");+ }+ });++ it("takes a link on this computer only from a service run on this computer", async () => {+ vi.stubGlobal("fetch", answering({ key: "k", url: "http://127.0.0.1:9000/upload/1" }));+ await expect(requestFileUpload(withKey, request, { url: "http://127.0.0.1:9000", token: service.token })).resolves.toMatchObject({ url: "http://127.0.0.1:9000/upload/1" });+ });+});diff --git a/server/composio-files.ts b/server/composio-files.tsnew file mode 100644index 0000000000..5d89777287--- /dev/null+++ b/server/composio-files.ts@@ -0,0 +1,63 @@+// Where to put one file's bytes so a connected-app tool can read it by `s3key`: Composio's one-time upload link, asked+// for with the project key, or through the managed connection service, which holds the key+// (cloudflare/composio-broker/src/files.ts). Chosen the way relayMcp chooses: a member's own installation, else the+// project key, else the service.+import { z } from "zod";++import type { AppConfig } from "./config.ts";+import { brokerAccess, type BrokerAccess } from "./composio-broker-access.ts";+import { apiBase, projectHeaders, responseError } from "./composio-project.ts";+import { projectApiKey } from "./composio-session.ts";+import { composioUploadLink } from "../shared/composio-storage.ts";++/** A service run on this computer for development or tests hands out links on this computer too. */+function loopback(link: string | undefined): boolean {+ try {+ const url = new URL(link ?? "");+ return (url.protocol === "http:" || url.protocol === "https:") && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);+ } catch {+ return false;+ }+}++function sameOrigin(link: string | undefined, other: string | undefined): boolean {+ try { return Boolean(link && other) && new URL(link!).origin === new URL(other!).origin; } catch { return false; }+}++function hostOf(link: string | undefined): string {+ try { return new URL(link ?? "").host || "no host"; } catch { return "no link"; }+}++export interface FileUploadRequest {+ toolkit_slug: string;+ tool_slug: string;+ filename: string;+ mimetype: string;+ md5: string;+}++const projectAnswerSchema = z.object({ key: z.string().min(1), new_presigned_url: z.string().optional(), newPresignedUrl: z.string().optional() });+const serviceAnswerSchema = z.object({ key: z.string().min(1), url: z.string().min(1) });++export async function requestFileUpload(cfg: AppConfig, request: FileUploadRequest, as?: BrokerAccess): Promise<{ key: string; url: string }> {+ const apiKey = as ? null : projectApiKey(cfg);+ const broker = apiKey ? null : as ?? brokerAccess();+ if (!apiKey && !broker) throw new Error("connected apps are unavailable");+ const response = await fetch(apiKey ? `${apiBase()}/files/upload/request` : `${broker!.url}/v1/files/upload`, {+ method: "POST",+ headers: apiKey ? projectHeaders(apiKey, true) : { authorization: `Bearer ${broker!.token}`, "content-type": "application/json" },+ body: JSON.stringify(request),+ signal: AbortSignal.timeout(30_000),+ });+ if (!response.ok) throw new Error(await responseError(response, `the upload service answered HTTP ${response.status}`));+ const body: unknown = await response.json();+ const answer = apiKey ? projectAnswerSchema.parse(body) : serviceAnswerSchema.parse(body);+ const link = "url" in answer ? answer.url : answer.new_presigned_url ?? answer.newPresignedUrl;+ // Composio's storage; or, from a service on this computer, a link on this computer; or, with the project key, a link+ // on the origin of an explicitly named Composio backend (OMB_COMPOSIO_API), as trustedSessionMcpUrl allows its Sessions.+ const url = composioUploadLink(link)+ ?? (broker && loopback(broker.url) && loopback(link) ? new URL(link!) : null)+ ?? (apiKey && sameOrigin(link, process.env.OMB_COMPOSIO_API) && (link!.startsWith("https:") || loopback(link)) ? new URL(link!) : null);+ if (!url) throw new Error(`Composio returned an upload link that is not on its storage (${hostOf(link)})`);+ return { key: answer.key, url: url.toString() };+}diff --git a/server/composio.ts b/server/composio.tsindex 7860266965..ad2603e6d2 100644--- a/server/composio.ts+++ b/server/composio.ts@@ -259,7 +259,7 @@ export async function relayMcp(cfg: AppConfig,payload: JsonValue,transportSessionId?: string,- beforeSend?: () => void, signal?: AbortSignal, as?: BrokerAccess,+ beforeSend?: () => void | JsonValue | Promise<void | JsonValue>, signal?: AbortSignal, as?: BrokerAccess,): Promise<{ status: number; bytes: Uint8Array; contentType: string; transportSessionId?: string }> {const apiKey = as ? null : projectApiKey(cfg);let url: string;@@ -291,7 +291,7 @@ export async function relayMcp(headers.set("mcp-session-id", forwardedTransportSessionId);}// Discovery may await I/O: check turn authority and permissions after it, right before dispatch.- beforeSend?.();+ const sent = await beforeSend?.(); if (sent !== undefined) payload = sent; // beforeSend may answer the frame to send instead (files it uploaded)const response = await withToolsListFallback(identity, payload, () => fetch(url, {method: "POST",headers,diff --git a/server/connected-app-tools.e2e.test.ts b/server/connected-app-tools.e2e.test.tsindex a87f9ca865..9c137526f0 100644--- a/server/connected-app-tools.e2e.test.ts+++ b/server/connected-app-tools.e2e.test.ts@@ -1,7 +1,7 @@import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";-import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";-import { join } from "node:path";+import { dirname, join } from "node:path";import { createInterface } from "node:readline";import { expect, it } from "vitest";@@ -132,3 +132,61 @@ it("a bot with HighLevel read only runs HighLevel's reads, which name the resourrmSync(scratch, { recursive: true, force: true });}}, 120_000);++it("a bot's Google Drive upload of a file in its working folder reaches Composio as an uploaded file; another path goes as it is and a hidden file is refused", async () => {+ const apps = await startFakeConnectedApps();+ apps.connected = { googledrive: true };+ const scratch = mkdtempSync(join(tmpdir(), "omb-app-tools-"));+ const gate = join(scratch, "finish");+ const fixture = await launchVerificationServer({+ ...process.env, OMB_COMPOSIO_BROKER_URL: apps.url, OMB_COMPOSIO_BROKER_TOKEN: apps.token, FAKE_CLAUDE_MODE: "slow", FAKE_CLAUDE_SLOW_FINISH_GATE: gate,+ });+ const api = apiOn(fixture.info.url);+ try {+ const bot = (await api("POST", "/api/bots", { name: "Drive" }, 201)).bot;+ await api("PATCH", `/api/bots/${bot.id}`, { composio: true, connectorTools: { googledrive: { tools: "*" } } });+ await api("POST", `/api/bots/${bot.id}/messages`, { threadId: bot.threadId, text: "Put the report in my Drive", sendId: "drive-upload-e2e-0001" }, 202);+ let dump: any;+ await expect.poll(() => {+ try { dump = JSON.parse(readFileSync(fixture.fixtureDumpPath, "utf8")); } catch { return false; }+ return Boolean(dump.mcpConfig?.mcpServers?.composio);+ }, { timeout: 20_000 }).toBe(true);+ const report = join(fixture.info.dataDir, "workspaces", bot.id, "report.pdf");+ writeFileSync(report, "%PDF-1.4 the report");+ const upload = (file: string) => ask(dump.mcpConfig.mcpServers.composio, {+ name: "COMPOSIO_MULTI_EXECUTE_TOOL", arguments: { tools: [{ tool_slug: "GOOGLEDRIVE_UPLOAD_FILE", arguments: { file_to_upload: file } }] },+ });++ const { answer } = await upload(report);+ expect(answer.result.isError, JSON.stringify(answer)).not.toBe(true);+ expect(apps.uploads).toHaveLength(1);+ expect(apps.uploads[0]!.request).toMatchObject({ toolkit_slug: "googledrive", tool_slug: "GOOGLEDRIVE_UPLOAD_FILE", filename: "report.pdf", mimetype: "application/pdf" });+ expect(apps.uploads[0]!.bytes?.toString()).toBe("%PDF-1.4 the report");+ expect(apps.calls.at(-1)).toMatchObject({ tool: "GOOGLEDRIVE_UPLOAD_FILE", arguments: { file_to_upload: { name: "report.pdf", mimetype: "application/pdf", s3key: "fake-files/1" } } });++ // A path that is not one of the bot's files goes to the app as it is: only Composio can say what it means there.+ const outside = join(scratch, "elsewhere.pdf");+ writeFileSync(outside, "not the bot's");+ const passed = (await upload(outside)).answer;+ expect(passed.result.isError).not.toBe(true);+ expect(apps.calls.at(-1)).toMatchObject({ tool: "GOOGLEDRIVE_UPLOAD_FILE", arguments: { file_to_upload: outside } });+ expect(apps.uploads).toHaveLength(1);++ // A hidden folder, even inside the bot's own folder, never goes out.+ const hidden = join(fixture.info.dataDir, "workspaces", bot.id, ".secrets", "token.txt");+ mkdirSync(dirname(hidden), { recursive: true });+ writeFileSync(hidden, "secret");+ const before = apps.calls.length;+ const refused = (await upload(hidden)).answer;+ expect(refused.result.isError).toBe(true);+ expect(refused.result.content[0].text).toContain("hidden folder or in the app's own data");+ expect(refused.result.content[0].text).toContain("Nothing was written to Google Drive");+ expect(apps.calls.length, "the call never reached Composio").toBe(before);+ expect(apps.uploads).toHaveLength(1);+ writeFileSync(gate, "");+ } finally {+ await fixture.close();+ await apps.close();+ rmSync(scratch, { recursive: true, force: true });+ }+}, 120_000);diff --git a/server/connector-files.test.ts b/server/connector-files.test.tsnew file mode 100644index 0000000000..1f016de5d0--- /dev/null+++ b/server/connector-files.test.ts@@ -0,0 +1,244 @@+import { createHash } from "node:crypto";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";++import { connectorCallsIn, outboundCallsIn } from "../shared/outbound.ts";+import {+ connectorFileScope, localFileReferences, openBotFile, prepareConnectorFiles, stageConnectorFiles, withMissingFileHint,+ type BotFileScope, type FileStagingDeps,+} from "./connector-files.ts";+import { outboundCard } from "./outbound-requests.ts";++const call = <A,>(name: string, args: A, id = 1) => ({ jsonrpc: "2.0", id, method: "tools/call", params: { name, arguments: args } });+const multi = (...tools: Array<{ tool_slug: string; arguments: any }>) => call("COMPOSIO_MULTI_EXECUTE_TOOL", { tools });+const report = new TextEncoder().encode("%PDF-1.4 quarterly report");++function deps(overrides: Partial<FileStagingDeps> = {}) {+ const opened: string[] = [];+ const requests: unknown[] = [];+ const puts: Array<{ url: string; bytes: number; mimetype: string }> = [];+ const value: FileStagingDeps = {+ open: async (path) => { opened.push(path); return { name: "report.pdf", mime: "application/pdf", bytes: report }; },+ requestUpload: async (request) => { requests.push(request); return { key: `staged/${requests.length}.pdf`, url: `https://storage.composio.dev/upload/${requests.length}` }; },+ put: async (url, bytes, mimetype) => { puts.push({ url, bytes: bytes.byteLength, mimetype }); },+ toolkitFor: (tool) => tool.split("_")[0]!.toLowerCase(),+ appFor: (tool) => (tool.startsWith("GOOGLEDRIVE_") ? "Google Drive" : "the app"),+ ...overrides,+ };+ return { value, opened, requests, puts };+}++afterEach(() => vi.unstubAllGlobals());++describe("connected-app file arguments", () => {+ it("uploads a Windows path given as Google Drive's file_to_upload and names it by its staged key", async () => {+ const frame = multi({ tool_slug: "GOOGLEDRIVE_UPLOAD_FILE", arguments: { file_to_upload: "C:\\Users\\sam\\Documents\\report.pdf", folder_to_upload_to: "1AbC" } });+ const { value, opened, requests, puts } = deps();+ const staged = await stageConnectorFiles(frame, value);+ expect("frame" in staged).toBe(true);+ const sent = (staged as { frame: ReturnType<typeof multi> }).frame;+ expect(sent.params.arguments.tools[0]!.arguments).toEqual({+ file_to_upload: { name: "report.pdf", mimetype: "application/pdf", s3key: "staged/1.pdf" },+ folder_to_upload_to: "1AbC",+ });+ expect(opened).toEqual(["C:\\Users\\sam\\Documents\\report.pdf"]);+ expect(requests).toEqual([{+ toolkit_slug: "googledrive", tool_slug: "GOOGLEDRIVE_UPLOAD_FILE", filename: "report.pdf", mimetype: "application/pdf",+ md5: createHash("md5").update(report).digest("hex"),+ }]);+ expect(puts).toEqual([{ url: "https://storage.composio.dev/upload/1", bytes: report.byteLength, mimetype: "application/pdf" }]);+ // The bot's own frame is left as it was.+ expect(frame.params.arguments.tools[0]!.arguments.file_to_upload).toBe("C:\\Users\\sam\\Documents\\report.pdf");+ });++ it("reads a path written where Composio wants an s3key, keeping the name and type the bot gave", async () => {+ const frame = multi({ tool_slug: "GMAIL_SEND_EMAIL", arguments: { to: "[email protected]", attachment: { name: "Q3.pdf", mimetype: "application/pdf", s3key: "/Users/sam/work/out.pdf" } } });+ const { value, opened } = deps();+ const staged = await stageConnectorFiles(frame, value) as { frame: ReturnType<typeof multi> };+ expect(opened).toEqual(["/Users/sam/work/out.pdf"]);+ expect(staged.frame.params.arguments.tools[0]!.arguments.attachment).toEqual({ name: "Q3.pdf", mimetype: "application/pdf", s3key: "staged/1.pdf" });+ });++ it("uploads each path in a list of attachments, and a directly called tool's file", async () => {+ const { value, opened } = deps();+ const listed = await stageConnectorFiles(multi({ tool_slug: "GMAIL_SEND_EMAIL", arguments: { attachments: ["/tmp/a.pdf", "/tmp/b.pdf"] } }), value) as { frame: ReturnType<typeof multi> };+ expect((listed.frame.params.arguments.tools[0]!.arguments as { attachments: unknown[] }).attachments).toEqual([+ { name: "report.pdf", mimetype: "application/pdf", s3key: "staged/1.pdf" },+ { name: "report.pdf", mimetype: "application/pdf", s3key: "staged/2.pdf" },+ ]);+ const direct = await stageConnectorFiles(call("GOOGLEDRIVE_UPLOAD_FILE", { file_to_upload: "~/report.pdf" }), value) as { frame: ReturnType<typeof call> };+ expect((direct.frame.params.arguments as { file_to_upload: unknown }).file_to_upload).toMatchObject({ s3key: "staged/3.pdf" });+ expect(opened.at(-1)).not.toMatch(/^~/);+ });++ it("leaves ids, real keys, text, multi-line values and non-call frames alone", async () => {+ const untouched = [+ multi({ tool_slug: "GOOGLEDRIVE_CREATE_FILE_FROM_TEXT", arguments: { file_name: "notes.txt", text_content: "/etc/hosts is a file", mime_type: "text/plain" } }),+ multi({ tool_slug: "GOOGLEDRIVE_EDIT_FILE", arguments: { file_id: "1AbC", content: "C:\\ is a drive" } }),+ multi({ tool_slug: "GOOGLEDRIVE_UPLOAD_FILE", arguments: { file_to_upload: { name: "a.pdf", mimetype: "application/pdf", s3key: "proj/ab12/a.pdf" } } }),+ multi({ tool_slug: "GOOGLEDRIVE_UPLOAD_FROM_URL", arguments: { file_url: "https://example.com/a.pdf" } }),+ multi({ tool_slug: "SLACK_UPLOAD_FILE", arguments: { file: "/tmp/a.pdf\nand then some text" } }),+ call("COMPOSIO_REMOTE_WORKBENCH", { code_to_execute: "upload_local_file('/tmp/a.pdf')" }),+ call("COMPOSIO_SEARCH_TOOLS", { queries: [{ use_case: "upload /tmp/a.pdf to drive" }] }),+ { jsonrpc: "2.0", id: 2, method: "tools/list" },+ ];+ const { value, opened } = deps();+ for (const frame of untouched) {+ expect(localFileReferences(frame).references).toEqual([]);+ expect((await stageConnectorFiles(frame, value) as { frame: unknown }).frame).toBe(frame);+ }+ expect(opened).toEqual([]);+ });++ it("sends a path that is not one of the bot's files as it is, with no refusal and no upload", async () => {+ // Dropbox and Drive paths, a web path: only a file the bot may send is uploaded.+ const frame = multi(+ { tool_slug: "DROPBOX_UPLOAD_FILE", arguments: { file: "/Apps/report.pdf" } },+ { tool_slug: "WEBFLOW_UPLOAD_ASSET", arguments: { image: "/images/logo.png" } },+ );+ const { value, opened, requests } = deps({ open: async (path) => { opened.push(path); return null; } });+ const prepared = await prepareConnectorFiles(frame, value);+ expect("refusal" in prepared).toBe(false);+ expect(prepared).toMatchObject({ files: [] });+ expect((prepared as { upload?: unknown }).upload).toBeUndefined();+ expect((await stageConnectorFiles(frame, value) as { frame: unknown }).frame).toBe(frame);+ expect(opened).toEqual(["/Apps/report.pdf", "/images/logo.png", "/Apps/report.pdf", "/images/logo.png"]);+ expect(requests).toEqual([]);+ });++ it("reads files first and uploads nothing until upload runs, listing each file on its call's approval card", async () => {+ const frame = multi(+ { tool_slug: "GMAIL_SEND_EMAIL", arguments: { to: "[email protected]", body: "x".repeat(600), attachment: "/Users/sam/work/Q3 board deck.pdf" } },+ { tool_slug: "GMAIL_FETCH_EMAILS", arguments: { query: "from:a" } },+ );+ const { value, requests, puts } = deps();+ const prepared = await prepareConnectorFiles(frame, value);+ if ("refusal" in prepared) throw new Error(prepared.refusal);+ expect(requests).toEqual([]);+ expect(puts).toEqual([]);+ const card = outboundCard(prepared.cardCalls(outboundCallsIn(frame.params.name, frame.params.arguments)));+ expect(card.summary).toContain(`Uploads report.pdf (/Users/sam/work/Q3 board deck.pdf, ${report.byteLength} B)`);+ expect(card.summary.indexOf("Q3 board deck.pdf")).toBeLessThan(card.summary.indexOf("[arguments truncated]"));+ expect(prepared.cardCalls(connectorCallsIn(frame.params.name, frame.params.arguments))[1]).not.toHaveProperty("files");+ const sent = await prepared.upload!() as ReturnType<typeof multi>;+ expect(requests).toHaveLength(1);+ expect(sent.params.arguments.tools[0]!.arguments.attachment).toMatchObject({ s3key: "staged/1.pdf" });+ });++ it("refuses with what to do when a file may not be sent, naming the app and writing nothing", async () => {+ const { value, requests } = deps({ open: async () => { throw new Error("it is in a hidden folder or in the app's own data, which is never sent to an app"); } });+ const staged = await stageConnectorFiles(multi({ tool_slug: "GOOGLEDRIVE_UPLOAD_FILE", arguments: { file_to_upload: "C:\\Users\\sam\\.ssh\\id_ed25519" } }), value);+ expect("refusal" in staged && staged.refusal).toContain("could not send C:\\Users\\sam\\.ssh\\id_ed25519 to Google Drive (it is in a hidden folder");+ expect("refusal" in staged && staged.refusal).toContain("Nothing was written to Google Drive");+ expect(requests).toEqual([]);+ });++ it("refuses plainly when the upload itself fails", async () => {+ const { value } = deps({ requestUpload: async () => { throw new Error("connected-apps service answered HTTP 503"); } });+ const staged = await stageConnectorFiles(multi({ tool_slug: "GOOGLEDRIVE_UPLOAD_FILE", arguments: { file_to_upload: "/tmp/report.pdf" } }), value);+ expect("refusal" in staged && staged.refusal).toContain("uploading report.pdf for Google Drive failed (connected-apps service answered HTTP 503)");+ expect("refusal" in staged && staged.refusal).toContain("do not keep retrying");+ });++ it("puts the bytes without following a redirect", async () => {+ const seen: RequestInit[] = [];+ vi.stubGlobal("fetch", async (_url: string, init: RequestInit) => { seen.push(init); return new Response("{}"); });+ const { value } = deps();+ delete value.put;+ await stageConnectorFiles(multi({ tool_slug: "GOOGLEDRIVE_UPLOAD_FILE", arguments: { file_to_upload: "/tmp/report.pdf" } }), value);+ expect(seen).toHaveLength(1);+ expect(seen[0]).toMatchObject({ method: "PUT", redirect: "error" });+ });++ it("caps the files one call uploads", async () => {+ const { value, requests } = deps();+ const attachments = Array.from({ length: 11 }, (_, index) => `/tmp/${index}.pdf`);+ const staged = await stageConnectorFiles(multi({ tool_slug: "GMAIL_SEND_EMAIL", arguments: { attachments } }), value);+ expect("refusal" in staged && staged.refusal).toContain("at most 10");+ expect(requests).toEqual([]);+ });+});++describe("which files a bot may send", () => {+ const made: string[] = [];+ afterEach(() => { for (const dir of made.splice(0)) rmSync(dir, { recursive: true, force: true }); });+ const dir = () => { const path = mkdtempSync(join(tmpdir(), "omb-connector-files-")); made.push(path); return path; };+ const put = (path: string) => { mkdirSync(join(path, ".."), { recursive: true }); writeFileSync(path, report); return path; };+ const scope = (over: Partial<BotFileScope>): BotFileScope => ({ roots: [], attachments: [], refuse: [], ...over });++ it("reads a file in the bot's folder, and passes over one outside it or missing", async () => {+ const work = dir(), elsewhere = dir();+ put(join(work, "report.pdf"));+ put(join(elsewhere, "secret.pdf"));+ const file = await openBotFile(join(work, "report.pdf"), scope({ roots: [work], home: elsewhere }));+ expect(file).toMatchObject({ name: "report.pdf", mime: "application/pdf" });+ expect(Buffer.from(file!.bytes).equals(Buffer.from(report))).toBe(true);+ await expect(openBotFile(join(elsewhere, "secret.pdf"), scope({ roots: [work] }))).resolves.toBeNull();+ await expect(openBotFile(join(work, "missing.pdf"), scope({ roots: [work] }))).resolves.toBeNull();+ await expect(openBotFile(work, scope({ roots: [dirname(work)] }))).resolves.toBeNull();+ });++ it("reads only this conversation's own attachments from the attachment store", async () => {+ const data = dir();+ const store = join(data, "attachments");+ const mine = put(join(store, "mine.pdf"));+ const someoneElses = put(join(store, "someone-elses.pdf"));+ const turn = connectorFileScope({+ roots: [join(data, "workspaces", "bot"), store], attachmentStore: store,+ messages: [{ attachments: [{ path: mine }] }, {}], appData: [data, undefined], guestRoot: "/workspace",+ });+ expect(turn).toEqual({ roots: [join(data, "workspaces", "bot")], attachments: [mine], refuse: [data] });+ await expect(openBotFile(mine, { ...turn, home: dir() })).resolves.toMatchObject({ name: "mine.pdf" });+ await expect(openBotFile(someoneElses, { ...turn, home: dir() })).resolves.toBeNull();+ });++ it("never sends the home folder's hidden folders or the app's own data, even when the bot works in the home folder", async () => {+ const home = dir();+ const data = join(home, ".openmausbot"), desktop = join(home, "AppData", "Roaming", "MausBot");+ const inHome = scope({ roots: [home], refuse: [data, desktop], home });+ const sensitive = /hidden folder or in the app's own data/;+ await expect(openBotFile(put(join(home, ".ssh", "id_ed25519")), inHome)).rejects.toThrow(sensitive);+ await expect(openBotFile(put(join(home, ".aws", "credentials")), inHome)).rejects.toThrow(sensitive);+ await expect(openBotFile(put(join(home, ".config", "gh", "hosts.yml")), inHome)).rejects.toThrow(sensitive);+ await expect(openBotFile(put(join(home, ".netrc")), inHome)).rejects.toThrow(sensitive);+ await expect(openBotFile(put(join(data, "config.json")), inHome)).rejects.toThrow(sensitive);+ await expect(openBotFile(put(join(desktop, "Local State")), inHome)).rejects.toThrow(sensitive);+ await expect(openBotFile(put(join(home, "Documents", "report.pdf")), inHome)).resolves.toMatchObject({ name: "report.pdf" });+ // The bot's own workspace sits inside the app's data folder, and is its to send from, but not a hidden folder in it.+ const workspace = join(data, "workspaces", "bot");+ const own = scope({ roots: [workspace], refuse: [data, desktop], home });+ await expect(openBotFile(put(join(workspace, "out", "chart.pdf")), own)).resolves.toMatchObject({ name: "chart.pdf" });+ await expect(openBotFile(put(join(workspace, ".claude", "settings.json")), own)).rejects.toThrow(sensitive);+ await expect(openBotFile(put(join(data, "secrets.json")), own)).resolves.toBeNull();+ });++ it("reads a Local VM path from the VM's folder on this computer", async () => {+ const host = dir();+ put(join(host, "out", "chart.png"));+ const file = await openBotFile("/workspace/out/chart.png", scope({ guest: { root: "/workspace", host }, home: dir() }));+ expect(file?.name).toBe("chart.png");+ });+});++describe("missing staged file note", () => {+ const encode = (value: unknown) => new TextEncoder().encode(JSON.stringify(value));+ const failed = (text: string) => ({ jsonrpc: "2.0", id: 9, result: { content: [{ type: "text", text: JSON.stringify({ successful: false, error: text, data: {} }) }], isError: true } });++ it("tells the bot to give a local path when Composio could not fetch the file", () => {+ const out = JSON.parse(new TextDecoder().decode(withMissingFileHint(+ encode(failed("Failed to download file with s3key C:\\Users\\sam\\report.pdf: storage returned HTTP 404")), "application/json", ["GOOGLEDRIVE_UPLOAD_FILE"],+ )));+ expect(out.result.content).toHaveLength(2);+ expect(out.result.content[1].text).toContain("never reads this computer's disk");+ expect(out.result.content[1].text).toContain("full path of a file in your working folder");+ });++ it("leaves other failures and successes byte for byte", () => {+ const other = encode(failed("404 File not found: 1AbC"));+ expect(withMissingFileHint(other, "application/json", ["GOOGLEDRIVE_EDIT_FILE"])).toBe(other);+ const ok = encode({ jsonrpc: "2.0", id: 1, result: { content: [{ type: "text", text: "Failed to download file is a phrase" }] } });+ expect(withMissingFileHint(ok, "application/json", [])).toBe(ok);+ });+});diff --git a/server/connector-files.ts b/server/connector-files.tsnew file mode 100644index 0000000000..1797f41ed2--- /dev/null+++ b/server/connector-files.ts@@ -0,0 +1,337 @@+// A connected-app tool that takes a file (GOOGLEDRIVE_UPLOAD_FILE's file_to_upload, a Gmail attachment) reads it from+// Composio's file storage by `s3key`: Composio runs the tool on its own servers and never sees this computer's disk. A+// bot that names a file in its working folder (C:\Users\…\report.pdf) gets the file uploaded here first, and the call+// carries the `{ name, mimetype, s3key }` Composio asks for. Without this, every such call failed at Composio with a+// storage error the bot could not act on. Files are read before the call's checks and approval card (which lists them),+// and uploaded only after its last check, right before it goes out.+import { createHash } from "node:crypto";+import { realpath } from "node:fs/promises";+import { homedir } from "node:os";+import { basename, dirname, isAbsolute, join, relative } from "node:path";+import { fileURLToPath } from "node:url";++import { connectorCallsIn } from "../shared/outbound.ts";+import { FILE_MAX_BYTES, limitMegabytes } from "../shared/upload-limits.ts";+import { guestWorkspaceToHost } from "./bot-attachment.ts";+import type { BrokerAccess } from "./composio-broker-access.ts";+import { requestFileUpload } from "./composio-files.ts";+import type { AppConfig } from "./config.ts";+import { withFailedCallHint } from "./connector-scope-hint.ts";+import { serviceSlugFor, serviceSlugForCandidates } from "./connector-verdict.ts";+import { openMessageFile, type OpenedMessageFile } from "./message-file.ts";++type Json = Record<string, unknown>;++const isRecord = (value: unknown): value is Json => typeof value === "object" && value !== null && !Array.isArray(value);++/** Fields Composio's tools take a file in, besides any `{ s3key }` object. */+const FILE_FIELDS = new Set(["file_to_upload", "file", "files", "file_upload", "upload", "attachment", "attachments", "document", "image", "media"]);+/** Where a `{ … }` file object may carry a path instead of a staged key. */+const PATH_KEYS = ["s3key", "path", "file_path", "local_path", "filepath"] as const;+/** An absolute path on this computer, in any spelling a bot writes one: C:\…, C:/…, \\server\share, /…, ~/…, file://… */+const LOCAL_PATH = /^(?:[A-Za-z]:[\\/]|\\\\[^\\]|\/(?!\/)|~[\\/]|file:\/\/)/;+const MIME = /^[A-Za-z0-9][\w.+-]*\/[\w.+-]+$/;+const MAX_FILES_PER_REQUEST = 10;+const MAX_DEPTH = 6;++export interface StagedFile {+ name: string;+ mimetype: string;+ s3key: string;+}++export interface OpenedLocalFile {+ name: string;+ mime: string;+ bytes: Uint8Array;+}++export interface FileStagingDeps {+ /** The file at `path` when the bot may send it; null when there is no such file there, or it is outside the bot's+ * folders: the value is then not one of its files and is left as it is. Throws why a file there may not be sent. */+ open(path: string): Promise<OpenedLocalFile | null>;+ /** Composio's upload link and key for the file (server/composio-files.ts). */+ requestUpload(request: { toolkit_slug: string; tool_slug: string; filename: string; mimetype: string; md5: string }): Promise<{ key: string; url: string }>;+ /** The toolkit a tool belongs to (GOOGLEDRIVE_UPLOAD_FILE → googledrive). */+ toolkitFor(tool: string): string;+ /** The app's name for people (Google Drive). */+ appFor(tool: string): string;+ put?(url: string, bytes: Uint8Array, mimetype: string): Promise<void>;+}++interface FileReference {+ tool: string;+ field: string;+ path: string;+ name?: string;+ mimetype?: string;+ /** The call's arguments in the frame as the bot sent it, to find the call on its approval card. */+ source: unknown;+ replace(staged: StagedFile): void;+}++/** A file one call will upload, as its approval card lists it. */+export interface CardFile {+ name: string;+ path: string;+ bytes: number;+}++function localPath(value: unknown): value is string {+ return typeof value === "string" && !/[\r\n]/.test(value) && LOCAL_PATH.test(value.trim());+}++function referenceIn(owner: Json | unknown[], key: string | number, field: string, call: { slug: string; source: unknown }, value: unknown, found: FileReference[]): boolean {+ const set = (staged: StagedFile) => { (owner as Record<string | number, unknown>)[key] = staged; };+ const base = { tool: call.slug, field, source: call.source, replace: set };+ if (FILE_FIELDS.has(field.toLowerCase()) && localPath(value)) {+ found.push({ ...base, path: value.trim() });+ return true;+ }+ if (!isRecord(value)) return false;+ const pathKey = PATH_KEYS.find((candidate) => localPath(value[candidate]));+ // Only a file object: `{ s3key }` anywhere, or a path inside a field that takes a file.+ if (!pathKey || (pathKey !== "s3key" && !FILE_FIELDS.has(field.toLowerCase()))) return false;+ const name = typeof value.name === "string" && value.name.trim() ? basename(value.name.trim().replace(/\\/g, "/")) : undefined;+ const given = typeof value.mimetype === "string" ? value.mimetype : typeof value.mime_type === "string" ? value.mime_type : undefined;+ found.push({ ...base, path: (value[pathKey] as string).trim(), ...(name ? { name } : {}), ...(given && MIME.test(given.trim()) ? { mimetype: given.trim() } : {}) });+ return true;+}++function collect(node: unknown, field: string, call: { slug: string; source: unknown }, found: FileReference[], depth: number): void {+ if (depth > MAX_DEPTH) return;+ if (Array.isArray(node)) {+ node.forEach((item, index) => {+ if (!referenceIn(node, index, field, call, item, found)) collect(item, field, call, found, depth + 1);+ });+ return;+ }+ if (!isRecord(node)) return;+ for (const [key, value] of Object.entries(node)) {+ if (!referenceIn(node, key, key, call, value, found)) collect(value, key, call, found, depth + 1);+ }+}++/** The values a tools/call frame gives where a connected-app tool takes a file and that read as a path on this+ * computer, in a copy of the frame whose values can be replaced. Search, schema and connection tools carry none. */+export function localFileReferences(frame: unknown): { frame: unknown; references: FileReference[] } {+ if (!isRecord(frame) || frame.method !== "tools/call" || !isRecord(frame.params) || typeof frame.params.name !== "string") return { frame, references: [] };+ const copy = structuredClone(frame) as Json & { params: { name: string; arguments?: unknown } };+ const sent = connectorCallsIn(frame.params.name, frame.params.arguments);+ const references: FileReference[] = [];+ connectorCallsIn(copy.params.name, copy.params.arguments).forEach((call, index) => {+ if (call.slug === "COMPOSIO_PROXY_EXECUTE" || call.arguments === undefined) return;+ collect(call.arguments, "", { slug: call.slug, source: sent[index]?.arguments }, references, 0);+ });+ return { frame: copy, references };+}++/** Where a bot's files may come from: its folders (never the attachment store as a whole), this conversation's own+ * attachments by path, never the app's own data or a hidden folder, its Local VM folder. */+export interface BotFileScope {+ roots: readonly string[];+ /** This conversation's attachments, each allowed by its exact path. */+ attachments: readonly string[];+ /** The app's own data folders: a file in one goes out only from a folder of the bot's inside it (its workspace). */+ refuse: readonly string[];+ guest?: { root: string; host: string } | undefined;+ /** The home folder, whose hidden folders (.ssh, .aws, .config…) never go out. */+ home?: string;+}++const SENSITIVE = "it is in a hidden folder or in the app's own data, which is never sent to an app";++const within = (root: string, path: string) => {+ const rel = relative(root, path);+ return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);+};+const hiddenBelow = (root: string, path: string) => relative(root, path).split(/[\\/]/).some((part) => part.startsWith("."));+const real = (path: string) => realpath(path).catch(() => null);++/** The bot's file at `path`, read through the chat file-link resolver (realpath containment, no-follow, secret folders,+ * 100 MB), or null when nothing the bot may send is there. A Local VM path is read from the VM's host folder. */+export async function openBotFile(path: string, scope: BotFileScope): Promise<OpenedLocalFile | null> {+ const target = (scope.guest ? guestWorkspaceToHost(path, scope.guest.root, scope.guest.host) : null) ?? path;+ const canonical = await real(target);+ const attachments = (await Promise.all(scope.attachments.map(real))).filter((one): one is string => one !== null);+ const attached = canonical !== null && attachments.includes(canonical);+ const roots = attached ? [dirname(canonical)] : scope.guest ? [scope.guest.host, ...scope.roots] : scope.roots;+ let file: OpenedMessageFile;+ try {+ file = await openMessageFile(target, roots, FILE_MAX_BYTES);+ } catch (error) {+ const { status, code } = (error ?? {}) as { status?: unknown; code?: unknown };+ if (code === "outside_workspace" || code === "directory" || status === 404) return null;+ if (code === "file_too_large") throw new Error(`it is larger than ${limitMegabytes(FILE_MAX_BYTES)} MB`);+ throw error;+ }+ try {+ const realRoots = (await Promise.all(roots.map(real))).filter((one): one is string => one !== null);+ const root = realRoots.filter((one) => within(one, file.path)).sort((a, b) => b.length - a.length)[0] ?? dirname(file.path);+ const appData = (await Promise.all(scope.refuse.map(real))).filter((one): one is string => one !== null);+ // A bot's own workspace sits inside the app's data folder: only a folder strictly inside it may send from there.+ const ownAppFolder = appData.some((data) => within(data, root));+ const home = await real(scope.home ?? homedir());+ if (hiddenBelow(root, file.path)+ || (!ownAppFolder && appData.some((data) => data === file.path || within(data, file.path)))+ || (!ownAppFolder && home !== null && within(home, file.path) && hiddenBelow(home, file.path))) {+ throw new Error(SENSITIVE);+ }+ return { name: file.name, mime: file.mime, bytes: await file.handle.readFile() };+ } finally {+ await file.handle.close().catch(() => undefined);+ }+}++/** The scope of one turn: the bot's folders without the attachment store (which holds every conversation's and every+ * team member's files), this conversation's own attachments by path, and the app's own data folders. */+export function connectorFileScope(input: {+ roots: readonly string[];+ attachmentStore: string;+ messages: ReadonlyArray<{ attachments?: ReadonlyArray<{ path: string }> | undefined }>;+ appData: ReadonlyArray<string | undefined>;+ vm?: { workspaceDir: string } | undefined;+ guestRoot: string;+}): BotFileScope {+ return {+ roots: input.roots.filter((root) => root !== input.attachmentStore),+ attachments: input.messages.flatMap((message) => (message.attachments ?? []).map((file) => file.path)),+ refuse: input.appData.filter((dir): dir is string => Boolean(dir)),+ ...(input.vm ? { guest: { root: input.guestRoot, host: input.vm.workspaceDir } } : {}),+ };+}++/** The relay's staging for one call: the bot's files, uploaded through the same connection the call goes out on. */+export function connectorFileDeps(options: {+ scope: BotFileScope;+ via: readonly [AppConfig, BrokerAccess?];+ serviceSlugs: readonly string[];+ appFor(tool: string): string | null;+}): FileStagingDeps {+ const toolkit = (tool: string) => serviceSlugForCandidates(tool, options.serviceSlugs) ?? serviceSlugFor(tool);+ return {+ open: (path) => openBotFile(path, options.scope),+ requestUpload: (request) => requestFileUpload(options.via[0], request, options.via[1]),+ toolkitFor: (tool) => toolkit(tool) ?? tool.toLowerCase(),+ appFor: (tool) => options.appFor(tool) ?? toolkit(tool) ?? "the app",+ };+}++/** A path as the file system reads it: ~/ is the home folder, file:// a file URL. */+function onDisk(path: string): string {+ if (/^~[\\/]/.test(path)) return join(homedir(), path.slice(2));+ if (/^file:\/\//i.test(path)) {+ try { return fileURLToPath(path); } catch { return path; }+ }+ return path;+}++async function putBytes(url: string, bytes: Uint8Array, mimetype: string): Promise<void> {+ const body = new Uint8Array(bytes.byteLength);+ body.set(bytes);+ // The link is Composio's own storage: a redirect elsewhere is refused, never followed with the file.+ const response = await fetch(url, { method: "PUT", body, redirect: "error", headers: { "content-type": mimetype }, signal: AbortSignal.timeout(5 * 60_000) });+ await response.body?.cancel().catch(() => undefined);+ if (!response.ok) throw new Error(`the upload was refused (HTTP ${response.status})`);+}++const reasonOf = (error: unknown) => (error instanceof Error ? error.message : String(error)).replace(/\s+/g, " ").trim().slice(0, 240);++/** What the bot is told when a file it named may not be sent. */+export function unreadableFileText(reference: Pick<FileReference, "tool" | "field" | "path">, app: string, reason: string): string {+ return `OpenMausBot did not run ${reference.tool}: it could not send ${reference.path} to ${app} (${reason}). `+ + `Nothing was written to ${app}. Give ${reference.field || "the file field"} the full path of a file in your working folder or one `+ + "attached to this conversation, and OpenMausBot uploads it for the call. For plain text, a tool that takes the text itself, "+ + "such as GOOGLEDRIVE_CREATE_FILE_FROM_TEXT, needs no file.";+}++/** What the bot is told when the file was read but Composio did not take it. */+export function uploadFailedText(reference: Pick<FileReference, "tool">, name: string, app: string, reason: string): string {+ return `OpenMausBot did not run ${reference.tool}: uploading ${name} for ${app} failed (${reason}). Nothing was written to ${app}. `+ + "This is usually brief: try the call once more. If it fails again, tell the person the upload to "+ + `${app} failed and why, and do not keep retrying.`;+}++export interface PreparedFiles {+ /** The files the call will upload, for its approval card. */+ files: Array<CardFile & { tool: string; source: unknown }>;+ /** Uploads them and answers the frame that names each by its key; rejects with the text the bot is told. Absent when+ * the call names none: the frame goes out as sent. Run only once the call has passed every check. */+ upload?: () => Promise<unknown>;+ /** `calls` (connectorCallsIn of the frame as sent) with the files each will upload. */+ cardCalls<T extends { arguments?: unknown }>(calls: T[]): Array<T & { files?: CardFile[] }>;+}++/**+ * Reads, here and before anything goes out, each file of the bot's that `frame` names where a connected-app tool takes a+ * file. A value that is not one of the bot's files is left as it is (a Drive folder path such as /Apps/report.pdf, text+ * that starts with /). Answers the refusal the bot is told when a file it named may not be sent.+ */+export async function prepareConnectorFiles(frame: unknown, deps: FileStagingDeps): Promise<PreparedFiles | { refusal: string }> {+ const found = localFileReferences(frame);+ const ready: Array<{ reference: FileReference; file: OpenedLocalFile; name: string; mimetype: string }> = [];+ for (const reference of found.references) {+ let file: OpenedLocalFile | null;+ try {+ file = await deps.open(onDisk(reference.path));+ } catch (error) {+ return { refusal: unreadableFileText(reference, deps.appFor(reference.tool), reasonOf(error)) };+ }+ if (!file) continue;+ if (ready.length === MAX_FILES_PER_REQUEST) {+ return { refusal: `OpenMausBot did not run this call: it names more than ${MAX_FILES_PER_REQUEST} files, and one call can upload at most ${MAX_FILES_PER_REQUEST}. Send them in smaller batches.` };+ }+ ready.push({ reference, file, name: reference.name ?? file.name, mimetype: reference.mimetype ?? file.mime.split(";")[0]!.trim() });+ }+ const files = ready.map(({ reference, file, name }) => ({ tool: reference.tool, source: reference.source, name, path: reference.path, bytes: file.bytes.byteLength }));+ const cardCalls = <T extends { arguments?: unknown }>(calls: T[]) => calls.map((call) => {+ const mine = files.filter((one) => one.source !== undefined && one.source === call.arguments).map(({ name, path, bytes }) => ({ name, path, bytes }));+ return mine.length ? { ...call, files: mine } : call;+ });+ if (!ready.length) return { files, cardCalls };+ const put = deps.put ?? putBytes;+ const upload = async () => {+ for (const { reference, file, name, mimetype } of ready) {+ const app = deps.appFor(reference.tool);+ try {+ const md5 = createHash("md5").update(file.bytes).digest("hex");+ const link = await deps.requestUpload({ toolkit_slug: deps.toolkitFor(reference.tool), tool_slug: reference.tool, filename: name, mimetype, md5 });+ await put(link.url, file.bytes, mimetype);+ reference.replace({ name, mimetype, s3key: link.key });+ } catch (error) {+ throw new Error(uploadFailedText(reference, name, app, reasonOf(error)));+ }+ }+ return found.frame;+ };+ return { files, upload, cardCalls };+}++/** prepareConnectorFiles and its upload at once: the frame to send, or the refusal. */+export async function stageConnectorFiles(frame: unknown, deps: FileStagingDeps): Promise<{ frame: unknown } | { refusal: string }> {+ const prepared = await prepareConnectorFiles(frame, deps);+ if ("refusal" in prepared) return prepared;+ if (!prepared.upload) return { frame };+ try {+ return { frame: await prepared.upload() };+ } catch (error) {+ return { refusal: error instanceof Error ? error.message : String(error) };+ }+}++/** Composio could not find the file a call named: a made-up key, a stale one, or a path it cannot reach. */+const MISSING_STAGED_FILE = /Failed to download file|storage returned HTTP 404|invalid s3key|s3key (?:was )?not found/i;++export function missingFileHint(): string {+ return "OpenMausBot note: Composio could not get the file this call named. Composio runs the tool on its own servers, so it "+ + "never reads this computer's disk and an s3key cannot be made up. Give the file field the full path of a file in your "+ + 'working folder or attached to this conversation, for example {"file_to_upload": "C:\\\\Users\\\\you\\\\report.pdf"} '+ + "or a path starting with /, and OpenMausBot uploads it for the call. For plain text, use a tool that takes the text itself, "+ + "such as GOOGLEDRIVE_CREATE_FILE_FROM_TEXT.";+}++/** Adds missingFileHint to a failed result whose error is Composio not finding the call's file. */+export function withMissingFileHint(bytes: Uint8Array, contentType: string, slugs: readonly string[]): Uint8Array {+ return withFailedCallHint(bytes, contentType, MISSING_STAGED_FILE, missingFileHint, slugs);+}+diff --git a/server/connector-scope-hint.test.ts b/server/connector-scope-hint.test.tsindex 7804cfe7b9..d4a7739eda 100644--- a/server/connector-scope-hint.test.ts+++ b/server/connector-scope-hint.test.ts@@ -48,6 +48,14 @@ describe("connector scope hint (MOCA-273)", () => {expect(withScopeHint(unreadable, "application/json", ["GMAIL_CREATE_FILTER"])).toBe(unreadable);});+ it("tells the person to sign Google Drive in again with every permission ticked when no special permission is known", () => {+ const hint = scopeHint(["GOOGLEDRIVE_UPLOAD_FILE"]);+ expect(hint).toContain("Google's sign-in screen lets a person leave a permission unticked");+ expect(hint).toContain("open Connected apps, go to the Connected tab, choose Disconnect on Google Drive, then Connect it again");+ expect(hint).not.toContain("Reconnecting will not add it");+ expect(scopeHint(["SLACK_SEND_MESSAGE"])).not.toContain("Google");+ });+it("does not name an app it does not know", () => {const hint = scopeHint([]);expect(hint).toContain("The app refused this");diff --git a/server/connector-scope-hint.ts b/server/connector-scope-hint.tsindex f30bdaf9ac..6c15de8ad7 100644--- a/server/connector-scope-hint.ts+++ b/server/connector-scope-hint.ts@@ -18,11 +18,27 @@ function appName(slug: string): string {return toolkit.charAt(0) + toolkit.slice(1).toLowerCase();}+const GOOGLE_APPS: Record<string, string> = {+ GOOGLEDRIVE: "Google Drive", GOOGLECALENDAR: "Google Calendar", GOOGLEDOCS: "Google Docs", GOOGLESHEETS: "Google Sheets",+ GOOGLESLIDES: "Google Slides", GOOGLETASKS: "Google Tasks", GOOGLEMEET: "Google Meet", GOOGLEPHOTOS: "Google Photos",+};+export function scopeHint(slugs: readonly string[]): string {const slug = slugs.find((candidate) => requiredScope(candidate)) ?? slugs[0] ?? "";const app = slug ? appName(slug) : null;const scope = slug ? requiredScope(slug) : null;- const permission = scope ? `the ${scope} permission` : "the permission this action needs";+ if (!scope) {+ // Composio's default connection asks for the app's usual permissions, so a refusal here is most often a permission+ // the person left unticked on the provider's consent screen: signing in again with it ticked fixes it.+ const toolkit = slug.split("_")[0] ?? "";+ const named = GOOGLE_APPS[toolkit] ?? app ?? "the app";+ return `OpenMausBot note: ${app ?? "The app"} refused this because the connected account has not granted the permission this action needs. `+ + `${app === "Google" ? "Google's sign-in screen lets a person leave a permission unticked, and then every call that needs it fails. " : ""}`+ + `Tell the person to open Connected apps, go to the Connected tab, choose Disconnect on ${named}, then Connect it again `+ + "and allow every permission the sign-in screen asks for. If it still fails after that, the default Composio connection does not "+ + `ask for this permission: with their own Composio project key they can add it in an auth config for ${named}. Do not retry this call before they reconnect.`;+ }+ const permission = `the ${scope} permission`;return `OpenMausBot note: ${app ?? "The app"} refused this because the connected account has not granted ${permission}. ` +`Reconnecting will not add it: the default Composio connection never asks for it. ` +`To allow it, the person creates their own ${app ? `${app} ` : ""}auth config in their Composio project that includes ${permission}, ` +diff --git a/server/connector-signed-out-hint.ts b/server/connector-signed-out-hint.tsindex 2b47ac7248..e56e1a664c 100644--- a/server/connector-signed-out-hint.ts+++ b/server/connector-signed-out-hint.ts@@ -10,6 +10,7 @@ export function signedOutHint(services: readonly string[]): string {const target = services.length ? `with toolkits ${JSON.stringify(services)}` : "for that app";return `OpenMausBot note: ${apps} is signed out (its sign-in expired or was revoked), so this call did not run. ` +`Call COMPOSIO_MANAGE_CONNECTIONS ${target} to show the person a card that reconnects it, then end this turn. ` ++ "If no card can be shown, tell the person to open Connected apps, go to the Connected tab and choose Reconnect on the app. " +"Do not retry this call before they reconnect.";}diff --git a/server/index.ts b/server/index.tsindex 8fae99be44..300b915246 100644--- a/server/index.ts+++ b/server/index.ts@@ -652,6 +652,7 @@ import { createCardRequester, linePersonKey } from "./host/thread-person.ts"; imimport { createThreadRoutes } from "./routes/threads.ts";import { createWebhookRoutes } from "./routes/webhooks.ts";import { withScopeHint } from "./connector-scope-hint.ts";+import { connectorFileDeps, connectorFileScope, prepareConnectorFiles, withMissingFileHint } from "./connector-files.ts";import { createConnectorCards } from "./host/connector-cards.ts";import { createLoginMailCodes } from "./host/login-mail-codes.ts";import { onThreadSeen, personAsks as personAskAt, sawThread } from "./thread-presence.ts"; import { createWarmSummaryHost, HARNESS_IDLE_FRACTION } from "./host/warm-summary-host.ts";@@ -14406,10 +14407,12 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {}const opaque = connectorCalls.some(call => call.slug === "COMPOSIO_PROXY_EXECUTE");if (opaque && currentSender.connectorTools !== undefined && !sandbox.open(currentSender)) return refuseOutbound(sandbox.refusal);+ // Files the call names on this computer are read now and listed on its card; they go to Composio's storage (Composio runs the tool, never reading this disk) only after the last check below.+ const files = await prepareConnectorFiles(body, connectorFileDeps({ scope: connectorFileScope({ roots: messageFileRootsForThread(currentSender.id, internalCapability.threadId), attachmentStore: ATTACHMENTS_DIR, messages: store.messagesFor(internalCapability.threadId), appData: [DATA_DIR, process.env.OMB_USER_DATA], vm: localVmThreadTargets.get(internalCapability.threadId), guestRoot: VM_WORKSPACE_GUEST }), via: teamConnections.via(actor.access), serviceSlugs, appFor: (tool) => describeTool(tool).app })); if ("refusal" in files) return refuseOutbound(files.refusal);const fullAccess = outboundTool !== null && sendsFreely();const held: OutboundHoldAnswer = outboundTool? await outboundHold.hold({- bot: currentSender, threadId: internalCapability.threadId, tool: outboundTool, calls: outboundCalls, opaque, fullAccess,+ bot: currentSender, threadId: internalCapability.threadId, tool: outboundTool, calls: files.cardCalls(outboundCalls), opaque, fullAccess,active: () => internalCapabilityIsActive(internalCapability),}): { ok: true, approved: false };@@ -14428,7 +14431,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {Array.isArray(req.headers["mcp-session-id"])? req.headers["mcp-session-id"][0]: req.headers["mcp-session-id"],- () => {+ async () => {requireActiveInternalCapability();const fresh = store.bot(internalCapability.botId);if (!fresh || fresh.composio === false || !composio.configured(cfg) || managedPolicy.appsCallRefusal(connectorCalls, serviceSlugs)) refuseDispatch("Connected apps were disabled while this call waited.");@@ -14452,7 +14455,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {refuseDispatch(error instanceof Error ? error.message : String(error));}}- for (const key of nextDrafts) reservedDrafts.add(key);+ const sent = files.upload ? await files.upload().catch((error: unknown) => refuseDispatch(error instanceof Error ? error.message : String(error))) : undefined; requireActiveInternalCapability(); for (const key of nextDrafts) reservedDrafts.add(key); return sent as typeof body | undefined;}, undefined, teamConnections.via(actor.access)[1],); } catch (error) {if (dispatchRefusal) return refuseOutbound(dispatchRefusal);@@ -14464,7 +14467,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {};if (upstream.transportSessionId) headers["mcp-session-id"] = upstream.transportSessionId; if (connectorCalls.length) connectionHealth.appCall({ ...(internalCapability.connectorsFor ? { person: internalCapability.connectorsFor } : {}), slugs: connectorCalls.map((one) => one.slug), status: upstream.status, bytes: upstream.bytes, contentType: upstream.contentType });res.writeHead(upstream.status, headers);- return res.end(Buffer.from(withScopeHint(proactive.fence.confines(internalCapability.threadId) ? recordsAnswer(upstream.bytes, upstream.contentType) : upstream.bytes, upstream.contentType, connectorCalls.map((call) => call.slug))));+ return res.end(Buffer.from(withMissingFileHint(withScopeHint(proactive.fence.confines(internalCapability.threadId) ? recordsAnswer(upstream.bytes, upstream.contentType) : upstream.bytes, upstream.contentType, connectorCalls.map((call) => call.slug)), upstream.contentType, connectorCalls.map((call) => call.slug))));}if (path === "/api/internal/computer-control") {const botId = url.searchParams.get("botId") ?? "";diff --git a/server/outbound-hold.ts b/server/outbound-hold.tsindex fe69ec78af..a13e5962d8 100644--- a/server/outbound-hold.ts+++ b/server/outbound-hold.ts@@ -1,11 +1,11 @@-import type { ConnectorCall, OutboundPolicy } from "../shared/outbound.ts";+import type { OutboundPolicy } from "../shared/outbound.ts";import { DEFAULT_OUTBOUND_POLICY } from "../shared/outbound.ts";import type { Notification } from "../shared/notification.ts";import { HELD_NOTE } from "./auto-approve.ts";import { appendDecision } from "./decision-log.ts";import { buildNotification } from "./notify.ts";import type { OutboundRequestService } from "./outbound-requests.ts";-import { outboundCard } from "./outbound-requests.ts";+import { outboundCard, type CardCall } from "./outbound-requests.ts";import type { BotRecord, GroupRecord, Store } from "./store.ts";import { turnWaitedOnPerson } from "./waiting-on-person.ts";@@ -38,7 +38,7 @@ function sendsWithoutAsking(rule: OutboundPolicy | undefined, fullAccess: booleaexport interface OutboundHold {/** A send goes out without asking (Full access with no rule of its own, or "allow") or waits on the "Send on your behalf?" card. `fullAccess`: the turn runs at Full access. */- hold(input: { bot: OutboundHoldBot; threadId: string; tool: string; calls: ConnectorCall[]; opaque: boolean; fullAccess: boolean; active: () => boolean }): Promise<OutboundHoldAnswer>;+ hold(input: { bot: OutboundHoldBot; threadId: string; tool: string; calls: CardCall[]; opaque: boolean; fullAccess: boolean; active: () => boolean }): Promise<OutboundHoldAnswer>;/** At dispatch time, against the bot as it is now: a send that needs no card is recorded; otherwise the hold must have been approved. Throws the refusal text. */beforeDispatch(input: { bot: OutboundHoldBot; threadId: string; tool: string; opaque: boolean; fullAccess: boolean; approved: boolean }): void;}diff --git a/server/outbound-requests.test.ts b/server/outbound-requests.test.tsindex 8b01172d6f..c4ff64c558 100644--- a/server/outbound-requests.test.ts+++ b/server/outbound-requests.test.ts@@ -54,3 +54,17 @@ describe("OutboundRequestService", () => {});});});++describe("outboundCard", () => {+ it("lists every file a send uploads before its arguments are cut", async () => {+ const { outboundCard } = await import("./outbound-requests.ts");+ const card = outboundCard([{+ slug: "GMAIL_SEND_EMAIL",+ arguments: { to: "[email protected]", body: "x".repeat(800), attachment: "/Users/sam/.private/plans.pdf" },+ files: [{ name: "plans.pdf", path: "/Users/sam/.private/plans.pdf", bytes: 2_500_000 }],+ }]);+ expect(card.summary).toContain("Uploads plans.pdf (/Users/sam/.private/plans.pdf, 2.4 MB)");+ expect(card.summary.indexOf("plans.pdf")).toBeLessThan(card.summary.indexOf("[arguments truncated]"));+ expect(outboundCard([{ slug: "GMAIL_SEND_EMAIL", arguments: { to: "[email protected]" } }]).summary).not.toContain("Uploads");+ });+});diff --git a/server/outbound-requests.ts b/server/outbound-requests.tsindex 4c5e36ca74..f3b5c456b7 100644--- a/server/outbound-requests.ts+++ b/server/outbound-requests.ts@@ -66,16 +66,25 @@ export class OutboundRequestService {}}-/** What a "Send on your behalf?" card shows: each app action and its arguments, cut at 400 characters. */-export function outboundCard(outboundCalls: ConnectorCall[]): { app: string | null; calls: { app: string | null; label: string }[]; summary: string } {+/** One app action on a card, with the files of this computer it will upload (server/connector-files.ts). */+export type CardCall = ConnectorCall & { files?: ReadonlyArray<{ name: string; path: string; bytes: number }> };++function fileSize(bytes: number): string {+ return bytes < 1024 ? `${bytes} B` : bytes < 1024 * 1024 ? `${Math.round(bytes / 1024)} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`;+}++/** What a "Send on your behalf?" card shows: each app action, the files it uploads in full, and its arguments cut at 400+ * characters. The files come first so no argument can push one out of sight. */+export function outboundCard(outboundCalls: CardCall[]): { app: string | null; calls: { app: string | null; label: string }[]; summary: string } {const calls = outboundCalls.map((call) => {const { app, label } = describeTool(call.slug);return { app, label };});const summary = outboundCalls.map((call, index) => {const described = calls[index];+ const files = call.files?.length ? `\nUploads ${call.files.map((file) => `${file.name} (${file.path}, ${fileSize(file.bytes)})`).join("; ")}` : "";const argsText = call.arguments === undefined ? "" : JSON.stringify(call.arguments);- return `${described.app ? `${described.app} · ` : ""}${described.label}${argsText ? `\n${argsText.slice(0, 400)}${argsText.length > 400 ? "… [arguments truncated]" : ""}` : ""}`;+ return `${described.app ? `${described.app} · ` : ""}${described.label}${files}${argsText ? `\n${argsText.slice(0, 400)}${argsText.length > 400 ? "… [arguments truncated]" : ""}` : ""}`;}).join("\n\n");return { app: calls[0]?.app ?? null, calls, summary };}diff --git a/server/system-prompt.ts b/server/system-prompt.tsindex 40e598827f..8d32fb40cb 100644--- a/server/system-prompt.ts+++ b/server/system-prompt.ts@@ -211,8 +211,11 @@ function syncedFoldersPrompt(synced: ReadonlyArray<{ computerName: string; pcPat+ " A path on that computer inside one of these means its copy here. Read from these copies, never change or delete files in them directly: to change a file in a folder lent with editing, use shared_computer edit_file for a passage or write_file for a whole file, which reaches their computer; save other work in your own working folder; the person gets it on their computer in Documents › MausBot.";}+/** Composio runs app tools on its own servers; OpenMausBot uploads a local file a tool takes (server/connector-files.ts). */+const APP_FILE_PROMPT = " A file argument such as file_to_upload takes the full path of a file in your working folder or attached here; OpenMausBot uploads it.";+export const COMPOSIO_PROMPT =- " The user's connected apps (Gmail, Calendar, Slack, Notion, and the rest) are reachable through the composio tools — find the right one with COMPOSIO_SEARCH_TOOLS, read its arguments with COMPOSIO_GET_TOOL_SCHEMAS, then run it with COMPOSIO_MULTI_EXECUTE_TOOL. Reach for them before telling the user you have no access to a service.";+ " The user's connected apps (Gmail, Calendar, Slack, Notion, and the rest) are reachable through the composio tools — find the right one with COMPOSIO_SEARCH_TOOLS, read its arguments with COMPOSIO_GET_TOOL_SCHEMAS, then run it with COMPOSIO_MULTI_EXECUTE_TOOL. Reach for them before telling the user you have no access to a service." + APP_FILE_PROMPT;/** The app tools a bot with these apps can call by name, on every engine. */const APP_TOOLS_PROMPT: Record<string, { label: string; tools: string; note?: string }> = {@@ -234,7 +237,7 @@ export function composioSystemPrompt(grants: Record<string, ConnectorToolGrant>return " No connected apps are assigned to this bot. If a task needs one, or an app's sign-in has expired, call COMPOSIO_MANAGE_CONNECTIONS to show the user a card that connects it, and ask them to allow that app for this bot in OpenMausBot.";}const named = services.map(connectorServiceLabel).join(", ");- return ` The user's connected apps assigned to this bot (${named}) are reachable through the composio tools — find the right one with COMPOSIO_SEARCH_TOOLS, read its arguments with COMPOSIO_GET_TOOL_SCHEMAS, then run it with COMPOSIO_MULTI_EXECUTE_TOOL. Only the tools this bot was granted will run; when a needed tool is refused, tell the user and ask them to grant it in OpenMausBot. Reach for the granted services before telling the user you have no access.${appToolsPrompt(services)}`;+ return ` The user's connected apps assigned to this bot (${named}) are reachable through the composio tools — find the right one with COMPOSIO_SEARCH_TOOLS, read its arguments with COMPOSIO_GET_TOOL_SCHEMAS, then run it with COMPOSIO_MULTI_EXECUTE_TOOL. Only the tools this bot was granted will run; when a needed tool is refused, tell the user and ask them to grant it in OpenMausBot. Reach for the granted services before telling the user you have no access.${APP_FILE_PROMPT}${appToolsPrompt(services)}`;}function connectorServiceLabel(slug: string): string {diff --git a/server/testing/fake-connected-apps.ts b/server/testing/fake-connected-apps.tsindex 93ce3fc561..b5eb519595 100644--- a/server/testing/fake-connected-apps.ts+++ b/server/testing/fake-connected-apps.ts@@ -22,6 +22,8 @@ export interface FakeConnectedApps {gmailError?: string;/** Every tool call that reached the service, with its arguments and the whole multi-execute item. */calls: Array<{ tool: string; arguments: unknown; item: Record<string, unknown> }>;+ /** Each file a tool call was to read: the upload request, then the bytes put to its link. */+ uploads: Array<{ request: unknown; key: string; bytes?: Buffer; contentType?: string }>;close(): Promise<void>;}@@ -34,7 +36,7 @@ const field = (value: unknown, name: string): unknown => (value && typeof valueexport async function startFakeConnectedApps(): Promise<FakeConnectedApps> {const fake: Omit<FakeConnectedApps, "url" | "token" | "close"> = {- connected: { gmail: true, googlecalendar: true }, address: "[email protected]", events: [], emails: [], calls: [], threads: {}, outlook: [],+ connected: { gmail: true, googlecalendar: true }, address: "[email protected]", events: [], emails: [], calls: [], threads: {}, outlook: [], uploads: [],calendars: [{ id: "[email protected]", primary: true, accessRole: "owner", selected: true }],};@@ -69,9 +71,21 @@ export async function startFakeConnectedApps(): Promise<FakeConnectedApps> {}const server = createServer(async (req, res) => {- let raw = "";- for await (const chunk of req) raw += chunk;+ const chunks: Buffer[] = [];+ for await (const chunk of req) chunks.push(chunk as Buffer);+ const raw = Buffer.concat(chunks).toString("utf8");res.setHeader("content-type", "application/json");+ // Composio's upload link, then the bytes put to it (cloudflare/composio-broker/src/files.ts).+ if (req.method === "POST" && req.url === "/v1/files/upload") {+ const key = `fake-files/${fake.uploads.length + 1}`;+ fake.uploads.push({ request: JSON.parse(raw), key });+ return res.end(JSON.stringify({ key, url: `http://127.0.0.1:${(server.address() as { port: number }).port}/upload/${fake.uploads.length}` }));+ }+ const put = req.method === "PUT" ? /^\/upload\/(\d+)$/.exec(req.url ?? "") : null;+ if (put && fake.uploads[Number(put[1]) - 1]) {+ Object.assign(fake.uploads[Number(put[1]) - 1]!, { bytes: Buffer.concat(chunks), contentType: req.headers["content-type"] });+ return res.end("{}");+ }if (req.method === "GET" && req.url === "/v1/connectors/connected") {return res.end(JSON.stringify({ services: Object.fromEntries(Object.entries(fake.connected).map(([slug, connected]) => [slug, { connected }])) }));}diff --git a/server/trust-controls.e2e.test.ts b/server/trust-controls.e2e.test.tsindex 8e7707f825..9f44a80da6 100644--- a/server/trust-controls.e2e.test.ts+++ b/server/trust-controls.e2e.test.ts@@ -1,7 +1,7 @@import { spawn, type ChildProcess } from "node:child_process";-import { closeSync, existsSync, openSync, readFileSync, writeFileSync } from "node:fs";+import { closeSync, existsSync, mkdirSync, openSync, readFileSync, writeFileSync } from "node:fs";import { createServer, type Server } from "node:http";-import { join } from "node:path";+import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";import { afterAll, beforeAll, expect, it } from "vitest";import { launchVerificationServer, verificationServerEnvironment, type VerificationServer } from "../scripts/control-omb.ts";@@ -24,6 +24,8 @@ let sandboxBot: any;const gmailDrafts = new Map<string, Record<string, unknown>>();let brokerOrigin = "";const relayed: unknown[] = [];+/** Files put to the fixture's upload links: what a connected-app call's local file sent to Composio's storage. */+const uploads: Array<{ request: unknown; bytes?: string }> = [];const evidence: unknown[] = [];let blockSession: (() => void) | undefined;let sessionEntered = false;@@ -66,8 +68,17 @@ beforeAll(async () => {broker = createServer(async (req, res) => {let raw = "";for await (const chunk of req) raw += chunk;+ const put = req.method === "PUT" ? /^\/upload\/(\d+)$/.exec(req.url ?? "") : null;+ if (put) {+ uploads[Number(put[1]) - 1]!.bytes = raw;+ return res.end();+ }const body = raw ? JSON.parse(raw) : {};res.setHeader("content-type", "application/json");+ if (req.url === "/api/files/upload/request") {+ uploads.push({ request: body });+ return res.end(JSON.stringify({ key: `fixture-files/${uploads.length}`, new_presigned_url: `${brokerOrigin}/upload/${uploads.length}` }));+ }if (req.url === "/v1/connectors/connected") return res.end(JSON.stringify({ services: { gmail: { connected: true }, slack: { connected: true } } }));if (req.url === "/api/tool_router/session/fixture-session") {if (blockSession) {@@ -444,6 +455,42 @@ it.each(["scope", "turn"])("rechecks %s revocation after project-session metadatexpect(relayed).toHaveLength(before);});+it.each(["scope", "turn"])("lists a send's file on its card and uploads nothing when %s revocation lands before the send", async (revocation) => {+ const b = await bot("File upload race " + revocation);+ const file = join(fixture.info.dataDir, "workspaces", b.id, "board deck.pdf");+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, "%PDF-1.4 deck");+ const token = await mint(b.id, b.threadId);+ const before = relayed.length, uploaded = uploads.length;+ const send = () => relay(token, "GMAIL_SEND_EMAIL", { to: "[email protected]", body: "y".repeat(600), attachment: file });+ const held = send();+ const card = await pending(b.threadId);+ expect(card.card.subtitle).toContain(`Uploads board deck.pdf (${file}, 13 B)`);+ expect(card.card.subtitle.indexOf(file)).toBeLessThan(card.card.subtitle.indexOf("[arguments truncated]"));+ expect(uploads, "nothing is uploaded while the card waits").toHaveLength(uploaded);+ sessionEntered = false;+ blockSession = () => {};+ await api("POST", `/api/threads/${b.threadId}/respond`, { requestId: card.card.requestId, behavior: "allow" });+ await expect.poll(() => sessionEntered, { timeout: 5_000 }).toBe(true);+ if (revocation === "scope") await api("PATCH", `/api/bots/${b.id}`, { connectorScopes: { apps: { gmail: "read" } } });+ else await mint(b.id, b.threadId);+ blockSession();+ blockSession = undefined;+ const result = await held;+ if (revocation === "scope") expect(result.body.result.isError).toBe(true);+ else expect(result.status).toBe(401);+ expect(uploads, "a revoked send uploads nothing").toHaveLength(uploaded);+ expect(relayed).toHaveLength(before);+ if (revocation === "turn") return;+ await api("PATCH", `/api/bots/${b.id}`, { connectorScopes: null });+ const allowed = send();+ await api("POST", `/api/threads/${b.threadId}/respond`, { requestId: (await pending(b.threadId)).card.requestId, behavior: "allow" });+ expect((await allowed).body.result.isError).not.toBe(true);+ expect(uploads).toHaveLength(uploaded + 1);+ expect(uploads.at(-1)).toMatchObject({ request: { toolkit_slug: "gmail", tool_slug: "GMAIL_SEND_EMAIL", filename: "board deck.pdf", mimetype: "application/pdf" }, bytes: "%PDF-1.4 deck" });+ expect((relayed.at(-1) as any).params.arguments.attachment).toEqual({ name: "board deck.pdf", mimetype: "application/pdf", s3key: `fixture-files/${uploaded + 1}` });+});+it("does not consume a Gmail draft reservation when the fresh scope check refuses dispatch", async () => {const b = await bot("Draft scope race");const token = await mint(b.id, b.threadId);diff --git a/shared/composio-storage.ts b/shared/composio-storage.tsnew file mode 100644index 0000000000..2e8d84ffda--- /dev/null+++ b/shared/composio-storage.ts@@ -0,0 +1,22 @@+// The hosts Composio hands out file upload links on: its own storage (storage.composio.dev in its API reference) and the+// AWS S3 storage behind it (its upload answer names `storage_backend: "s3"`). A file's bytes are put only to one of+// these, over HTTPS, so a link pointing anywhere else (this computer, a private address, another site) is never used.+const S3_HOST = /^(?:[a-z0-9][a-z0-9.-]*\.)?s3(?:[.-][a-z0-9-]+)*\.amazonaws\.com$/;++export function composioStorageHost(hostname: string): boolean {+ const host = hostname.toLowerCase();+ return host === "composio.dev" || host.endsWith(".composio.dev") || S3_HOST.test(host);+}++/** The link as a URL when it is HTTPS on Composio's storage, else null. */+export function composioUploadLink(link: string | undefined): URL | null {+ if (!link) return null;+ let url: URL;+ try {+ url = new URL(link);+ } catch {+ return null;+ }+ if (url.protocol !== "https:" || url.username || url.password || url.port) return null;+ return composioStorageHost(url.hostname) ? url : null;+}