Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Let agents upload images for X posts through their own connection (#2470)

Joshua France9bf2fb9b8c78
diff --git a/skills-seed/composio/SKILL.md b/skills-seed/composio/SKILL.md
index 9336301da..09a7658c6 100644
--- a/skills-seed/composio/SKILL.md
+++ b/skills-seed/composio/SKILL.md
@@ -72,4 +72,15 @@ The API checks active account ownership and toolkit on every execution. Personal
Do not call Composio's callback completion API from the computer. Callback identity verification belongs to the signed-in browser and trusted QM backend. If verification setup is missing, ask the operator to fix it.
-Automatic file transfer is unsupported. A local filename does not upload bytes. When Composio is unavailable, use direct OAuth only if independently configured and authorized; do not use it to bypass a denial.
+Tools don't transfer files: a local filename passed as an argument uploads nothing. The one exception is X images, below. When Composio is unavailable, use direct OAuth only if independently configured and authorized; do not use it to bypass a denial.
+
+### Images for X posts
+
+X's post tool attaches media by ID but can't upload it. Upload the image from the computer first, then post with the returned ID:
+
+```js
+const data = (await import("node:fs")).readFileSync("chart.png").toString("base64");
+const { mediaId } = await apps("twitter/media", { accountId: account.id, data });
+```
+
+Pass `mediaId` in the post tool's media IDs argument (discover its exact name with `tools`). Only the caller's own active X connection works. It accepts one PNG, JPEG or WebP image of up to 5 MB per call; for several images, upload each and pass all IDs. GIFs and video aren't supported. Uploading posts nothing and is safe to retry; unattached media expires within a day. A `403` from X (`providerStatus`) usually means the connection lacks media permission, so offer to reconnect X.
diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.ts
index f7eb105dc..b01444062 100644
--- a/src/api/agent-api-catalog.ts
+++ b/src/api/agent-api-catalog.ts
@@ -28,6 +28,7 @@ const CONVERSATION_UPDATE =
const FAMILIES: AgentApiFamily[] = [
{
match: (method, path) =>
+ (method === "POST" && path === "/v1/composio/twitter/media") ||
(method === "GET" &&
["identity", "connections", "toolkits", "tools"].some((name) => path === `/v1/composio/${name}`)) ||
(method === "POST" && ["authorize", "execute", "disconnect"].some((name) => path === `/v1/composio/${name}`)),
@@ -63,6 +64,12 @@ const FAMILIES: AgentApiFamily[] = [
summary:
"read your canonical Composio userId and verified linked userIds used by the web app picker; this selects accounts and does not grant access to them",
},
+ {
+ method: "POST",
+ path: "/v1/composio/twitter/media",
+ summary:
+ "{accountId,data} uploads one base64 PNG, JPEG or WebP image (5 MB max) through your own active X connection and returns mediaId for a post's media ids",
+ },
],
},
{
diff --git a/src/api/routes/composio-twitter-media.ts b/src/api/routes/composio-twitter-media.ts
new file mode 100644
index 000000000..4c84140e3
--- /dev/null
+++ b/src/api/routes/composio-twitter-media.ts
@@ -0,0 +1,158 @@
+import { ACCOUNT_ID, activeRun, composioUserIds, credential, ownedAccount, request } from "./composio.ts";
+import { sendJson } from "../http.ts";
+import { sniffImageDimensions } from "../../core/image-downscale.ts";
+import { redactSecrets } from "../../harness/redact-secrets.ts";
+import { createExactSecretValueMasker } from "../../security/secret-masking.ts";
+import { errMessage, reportFailure } from "../../util/errors.ts";
+import { audit } from "./shared.ts";
+import type { ApiCtx, Route } from "./route.ts";
+
+const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
+const CHUNK_BYTES = 2 * 1024 * 1024;
+const UPLOAD_TIMEOUT_MS = 60_000;
+const X_MEDIA_UPLOAD = "https://api.x.com/2/media/upload";
+
+class XMediaError extends Error {
+ readonly status: number;
+ readonly detail: string | undefined;
+ constructor(endpoint: string, status: number, response: unknown) {
+ super(`X ${endpoint} returned status ${status}: ${JSON.stringify(response)?.slice(0, 1000)}`);
+ this.status = status;
+ const { detail, errors } = (response ?? {}) as { detail?: unknown; errors?: unknown };
+ const messages = [
+ detail,
+ ...(Array.isArray(errors) ? errors.map((e) => (e as { message?: unknown })?.message) : []),
+ ];
+ this.detail = messages.filter((m): m is string => typeof m === "string").join(" ") || undefined;
+ }
+}
+
+async function xMedia(
+ ctx: ApiCtx,
+ key: string,
+ accountId: string,
+ endpoint: string,
+ body?: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const result = await request(
+ ctx,
+ key,
+ "/tools/execute/proxy",
+ { connected_account_id: accountId, endpoint, method: "POST", ...(body ? { body } : {}) },
+ UPLOAD_TIMEOUT_MS,
+ );
+ const status = typeof result.status === "number" ? result.status : 0;
+ if (status < 200 || status >= 300) throw new XMediaError(endpoint, status, result.data);
+ const data = (result.data as { data?: unknown } | undefined)?.data;
+ return data && typeof data === "object" ? (data as Record<string, unknown>) : {};
+}
+
+async function uploadMedia(ctx: ApiCtx): Promise<void> {
+ if (!ctx.capability || ctx.actor) return sendJson(ctx.res, 403, { error: "agent_capability_required" });
+ const access = await credential(ctx);
+ if (!access) return;
+ const body = ctx.body as Record<string, unknown> | null;
+ if (
+ !body ||
+ Object.keys(body).some((key) => key !== "accountId" && key !== "data") ||
+ typeof body.accountId !== "string" ||
+ !ACCOUNT_ID.test(body.accountId) ||
+ typeof body.data !== "string" ||
+ !body.data
+ )
+ return sendJson(ctx.res, 400, {
+ error: "invalid_upload",
+ message: "Supply accountId and the image as base64 data only.",
+ });
+ if (body.data.length > Math.ceil(MAX_IMAGE_BYTES / 3) * 4)
+ return sendJson(ctx.res, 413, { error: "media_too_large", message: "Images must be 5 MB or smaller." });
+ const bytes = Buffer.from(body.data, "base64");
+ if (bytes.toString("base64") !== body.data)
+ return sendJson(ctx.res, 400, { error: "invalid_upload", message: "data must be standard padded base64." });
+ if (bytes.length > MAX_IMAGE_BYTES)
+ return sendJson(ctx.res, 413, { error: "media_too_large", message: "Images must be 5 MB or smaller." });
+ const format = sniffImageDimensions(bytes)?.format;
+ if (!format || format === "gif")
+ return sendJson(ctx.res, 415, { error: "unsupported_media", message: "Upload a PNG, JPEG, or WebP image." });
+ const mediaType = `image/${format}`;
+ const accountId = body.accountId;
+ const resource = `${accountId}/media`;
+ const mask = createExactSecretValueMasker([access.key]);
+ try {
+ const owned = await ownedAccount(ctx, access, accountId);
+ if (
+ !owned ||
+ owned.toolkit !== "twitter" ||
+ owned.account.status !== "ACTIVE" ||
+ owned.account.is_disabled === true
+ )
+ return sendJson(ctx.res, 403, { error: "connection_not_authorized" });
+ if (!(await activeRun(ctx))) return;
+ if (!composioUserIds(access.principal).includes(String(owned.account.user_id)))
+ return sendJson(ctx.res, 403, { error: "connection_not_authorized" });
+ audit(ctx.deps, {
+ principalId: access.principal,
+ action: "composio.twitter_media.started",
+ resource,
+ scopeLabel: ctx.capability.scopeId,
+ });
+ const started = await xMedia(ctx, access.key, accountId, `${X_MEDIA_UPLOAD}/initialize`, {
+ media_type: mediaType,
+ total_bytes: bytes.length,
+ media_category: "tweet_image",
+ });
+ const mediaId = started.id;
+ if (typeof mediaId !== "string" || !/^\d{1,32}$/.test(mediaId)) throw new Error("Invalid media id");
+ for (let offset = 0, segment = 0; offset < bytes.length; offset += CHUNK_BYTES, segment++) {
+ if (!(await activeRun(ctx))) return;
+ await xMedia(ctx, access.key, accountId, `${X_MEDIA_UPLOAD}/${mediaId}/append`, {
+ media: bytes.subarray(offset, offset + CHUNK_BYTES).toString("base64"),
+ segment_index: segment,
+ });
+ }
+ if (!(await activeRun(ctx))) return;
+ const finished = await xMedia(ctx, access.key, accountId, `${X_MEDIA_UPLOAD}/${mediaId}/finalize`);
+ if (finished.id !== mediaId) throw new Error("Media id changed during upload");
+ audit(ctx.deps, {
+ principalId: access.principal,
+ action: "composio.twitter_media.completed",
+ resource: `${resource}/${mediaId}`,
+ scopeLabel: ctx.capability.scopeId,
+ });
+ return sendJson(ctx.res, 200, {
+ mediaId,
+ mediaType,
+ bytes: bytes.length,
+ expiresAfterSecs: typeof finished.expires_after_secs === "number" ? finished.expires_after_secs : null,
+ });
+ } catch (error) {
+ audit(ctx.deps, {
+ principalId: access.principal,
+ action: "composio.twitter_media.failed",
+ resource,
+ scopeLabel: ctx.capability.scopeId,
+ });
+ reportFailure("composio: twitter media", new Error(mask(redactSecrets(errMessage(error)))), resource);
+ const status = error instanceof XMediaError ? error.status : undefined;
+ const detail = error instanceof XMediaError && error.detail ? mask(redactSecrets(error.detail)).slice(0, 300) : "";
+ return sendJson(ctx.res, 502, {
+ error: "media_upload_failed",
+ ...(status ? { providerStatus: status } : {}),
+ ...(detail ? { providerDetail: detail } : {}),
+ message:
+ status === 401 || status === 403
+ ? "X refused the upload. The connection may lack media permission; reconnect X, then try again."
+ : "The upload failed. Retrying is safe: unattached media posts nothing and expires within a day.",
+ });
+ }
+}
+
+export const composioTwitterMediaRoutes: ReadonlyArray<Route<ApiCtx>> = [
+ {
+ method: "POST",
+ path: "/v1/composio/twitter/media",
+ auth: "either",
+ maxBodyBytes: 7_200_000,
+ handle: uploadMedia,
+ },
+];
diff --git a/src/api/routes/composio.ts b/src/api/routes/composio.ts
index 99161ed79..3e2c8f408 100644
--- a/src/api/routes/composio.ts
+++ b/src/api/routes/composio.ts
@@ -18,7 +18,7 @@ import { errMessage, httpFailure, reportFailure } from "../../util/errors.ts";
import { activePrincipal, audit } from "./shared.ts";
import type { ApiCtx, Route } from "./route.ts";
-const ACCOUNT_ID = /^ca_[a-zA-Z0-9_-]+$/;
+export const ACCOUNT_ID = /^ca_[a-zA-Z0-9_-]+$/;
export function composioUserId(org: string, principal: string): string {
return `qm_${createHash("sha256")
@@ -30,7 +30,7 @@ export function composioUserIds(principal: string): string[] {
return [...new Set(personIds(principal).map((id) => composioUserId(orgId(), id)))];
}
-async function activeRun(ctx: ApiCtx): Promise<boolean> {
+export async function activeRun(ctx: ApiCtx): Promise<boolean> {
const cap = ctx.capability;
if (!cap) return true;
const run = cap.runId ? await ctx.deps.runs?.get(cap.runId) : null;
@@ -301,7 +301,7 @@ async function authorize(ctx: ApiCtx, linkSlack = false): Promise<void> {
}
}
-async function ownedAccount(
+export async function ownedAccount(
ctx: ApiCtx,
access: { key: string; principal: string },
accountId: string,
diff --git a/src/api/routes/index.ts b/src/api/routes/index.ts
index e9dd0d3b9..33162b951 100644
--- a/src/api/routes/index.ts
+++ b/src/api/routes/index.ts
@@ -2,6 +2,7 @@ import { browserModelRoutes } from "./browser-model.ts";
import { deploymentLiveSmokeRoutes } from "./deployment-live-smoke.ts";
import { backgroundWorkRoutes } from "./background-work.ts";
import { composioRoutes } from "./composio.ts";
+import { composioTwitterMediaRoutes } from "./composio-twitter-media.ts";
import { loopIngressRoutes, loopIngressRawRoutes } from "./loop-ingress.ts";
import { sendJson } from "../http.ts";
import { type ApiCtx, type BaseCtx, type Route } from "./route.ts";
@@ -95,6 +96,7 @@ export const apiRoutes: ReadonlyArray<Route<ApiCtx>> = [
...secretDropRoutes,
...connectorRoutes,
...composioRoutes,
+ ...composioTwitterMediaRoutes,
...adminRoutes,
...skillPackRoutes,
...surfaceRoutes,
diff --git a/src/core/image-downscale.ts b/src/core/image-downscale.ts
index 7c29982d3..e4040e904 100644
--- a/src/core/image-downscale.ts
+++ b/src/core/image-downscale.ts
@@ -31,26 +31,26 @@ const FORMAT_BY_MIME = new Map<string, ImageDimensions["format"]>([
const JPEG_SOF_MARKERS = new Set([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf]);
-function readUInt24LE(bytes: Uint8Array, offset: number): number {
+function readUInt24LE(bytes: Buffer, offset: number): number {
return bytes[offset]! | (bytes[offset + 1]! << 8) | (bytes[offset + 2]! << 16);
}
-function pngDimensions(bytes: Uint8Array): ImageDimensions | undefined {
+function pngDimensions(bytes: Buffer): ImageDimensions | undefined {
if (bytes.length < 24) return undefined;
const signature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
if (!signature.every((v, i) => bytes[i] === v)) return undefined;
- if (Buffer.from(bytes.subarray(12, 16)).toString("ascii") !== "IHDR") return undefined;
- return { width: Buffer.from(bytes).readUInt32BE(16), height: Buffer.from(bytes).readUInt32BE(20), format: "png" };
+ if (bytes.toString("ascii", 12, 16) !== "IHDR") return undefined;
+ return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20), format: "png" };
}
-function gifDimensions(bytes: Uint8Array): ImageDimensions | undefined {
+function gifDimensions(bytes: Buffer): ImageDimensions | undefined {
if (bytes.length < 10) return undefined;
- const header = Buffer.from(bytes.subarray(0, 6)).toString("ascii");
+ const header = bytes.toString("ascii", 0, 6);
if (header !== "GIF87a" && header !== "GIF89a") return undefined;
- return { width: Buffer.from(bytes).readUInt16LE(6), height: Buffer.from(bytes).readUInt16LE(8), format: "gif" };
+ return { width: bytes.readUInt16LE(6), height: bytes.readUInt16LE(8), format: "gif" };
}
-function jpegDimensions(bytes: Uint8Array): ImageDimensions | undefined {
+function jpegDimensions(bytes: Buffer): ImageDimensions | undefined {
if (bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8) return undefined;
let offset = 2;
while (offset + 3 < bytes.length) {
@@ -62,14 +62,14 @@ function jpegDimensions(bytes: Uint8Array): ImageDimensions | undefined {
if (marker === 0xd9 || marker === 0xda) return undefined;
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) continue;
if (offset + 2 > bytes.length) return undefined;
- const length = Buffer.from(bytes).readUInt16BE(offset);
+ const length = bytes.readUInt16BE(offset);
if (length < 2 || offset + length > bytes.length) return undefined;
const start = offset + 2;
if (JPEG_SOF_MARKERS.has(marker)) {
if (start + 5 > bytes.length) return undefined;
return {
- width: Buffer.from(bytes).readUInt16BE(start + 3),
- height: Buffer.from(bytes).readUInt16BE(start + 1),
+ width: bytes.readUInt16BE(start + 3),
+ height: bytes.readUInt16BE(start + 1),
format: "jpeg",
};
}
@@ -78,14 +78,14 @@ function jpegDimensions(bytes: Uint8Array): ImageDimensions | undefined {
return undefined;
}
-function webpDimensions(bytes: Uint8Array): ImageDimensions | undefined {
+function webpDimensions(bytes: Buffer): ImageDimensions | undefined {
if (bytes.length < 30) return undefined;
- if (Buffer.from(bytes.subarray(0, 4)).toString("ascii") !== "RIFF") return undefined;
- if (Buffer.from(bytes.subarray(8, 12)).toString("ascii") !== "WEBP") return undefined;
+ if (bytes.toString("ascii", 0, 4) !== "RIFF") return undefined;
+ if (bytes.toString("ascii", 8, 12) !== "WEBP") return undefined;
let offset = 12;
while (offset + 8 <= bytes.length) {
- const type = Buffer.from(bytes.subarray(offset, offset + 4)).toString("ascii");
- const length = Buffer.from(bytes).readUInt32LE(offset + 4);
+ const type = bytes.toString("ascii", offset, offset + 4);
+ const length = bytes.readUInt32LE(offset + 4);
const start = offset + 8;
if (start + length > bytes.length) return undefined;
if (type === "VP8X" && length >= 10) {
@@ -110,8 +110,8 @@ function webpDimensions(bytes: Uint8Array): ImageDimensions | undefined {
bytes[start + 5] === 0x2a
) {
return {
- width: Buffer.from(bytes).readUInt16LE(start + 6) & 0x3fff,
- height: Buffer.from(bytes).readUInt16LE(start + 8) & 0x3fff,
+ width: bytes.readUInt16LE(start + 6) & 0x3fff,
+ height: bytes.readUInt16LE(start + 8) & 0x3fff,
format: "webp",
};
}
@@ -120,7 +120,8 @@ function webpDimensions(bytes: Uint8Array): ImageDimensions | undefined {
return undefined;
}
-export function sniffImageDimensions(bytes: Uint8Array): ImageDimensions | undefined {
+export function sniffImageDimensions(input: Uint8Array): ImageDimensions | undefined {
+ const bytes = Buffer.from(input.buffer, input.byteOffset, input.byteLength);
return pngDimensions(bytes) ?? jpegDimensions(bytes) ?? gifDimensions(bytes) ?? webpDimensions(bytes);
}
diff --git a/test/composio-twitter-media.test.ts b/test/composio-twitter-media.test.ts
new file mode 100644
index 000000000..221841f42
--- /dev/null
+++ b/test/composio-twitter-media.test.ts
@@ -0,0 +1,271 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import type { ServerResponse } from "node:http";
+import type { CapabilityClaims } from "../src/auth/capability-token.ts";
+import { composioUserId } from "../src/api/routes/composio.ts";
+import { composioTwitterMediaRoutes } from "../src/api/routes/composio-twitter-media.ts";
+import type { ApiCtx } from "../src/api/routes/route.ts";
+import type { ServerDeps } from "../src/api/deps.ts";
+import { createKeychain } from "../src/credentials/keychain.ts";
+import { createMemoryMap } from "../src/persistence/durable-map.ts";
+import { deriveConnectorKey } from "../src/connectors/connector-client-store.ts";
+import { orgId } from "../src/config.ts";
+
+const PNG = Buffer.concat([
+ Buffer.from("89504e470d0a1a0a0000000d49484452000000010000000108020000009077" + "53de", "hex"),
+ Buffer.alloc(32, 7),
+]);
+const JPEG = Buffer.from(
+ "/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////wgALCAABAAEBAREA/8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABPxA=",
+ "base64",
+);
+const WEBP = Buffer.from("UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==", "base64");
+const cap: CapabilityClaims = {
+ runId: "test-run",
+ sessionId: "test-session",
+ threadRef: "test-thread",
+ runAttempt: 1,
+ runLeaseToken: "test-lease",
+ actorId: "alice",
+ scopeId: "personal:alice",
+ ownerConnections: true,
+ liveActor: true,
+ exp: Date.now() + 60_000,
+};
+const xAccount = {
+ id: "ca_alice",
+ user_id: composioUserId(orgId(), "alice"),
+ status: "ACTIVE",
+ toolkit: { slug: "twitter" },
+};
+const proxied = (data: unknown, status = 200) => ({ data, status, headers: { "set-cookie": "hidden" } });
+
+async function fixture() {
+ const keychain = createKeychain({
+ creds: createMemoryMap(),
+ grants: createMemoryMap(),
+ asks: createMemoryMap(),
+ key: deriveConnectorKey("composio-test"),
+ });
+ await keychain.save({ ownerId: "alice", service: "composio", envKey: "COMPOSIO_API_KEY", secret: "private-key" });
+ const calls: Array<{ url: string; body: Record<string, unknown> | null }> = [];
+ const replies: unknown[] = [];
+ const audits: string[] = [];
+ const deps: Partial<ServerDeps> = {
+ keychain,
+ serviceCreds: keychain,
+ auditLog: { record: (e: { action: string }) => audits.push(e.action) } as unknown as ServerDeps["auditLog"],
+ runs: {
+ get: async () => ({
+ status: "running",
+ sessionId: "test-thread",
+ attempts: 1,
+ leaseToken: "test-lease",
+ leaseExpiresAt: Date.now() + 60_000,
+ request: { actor: { id: "alice" } },
+ }),
+ } as unknown as ServerDeps["runs"],
+ composioFetch: (async (input, init) => {
+ calls.push({ url: String(input), body: init?.body ? JSON.parse(String(init.body)) : null });
+ const reply = replies.shift();
+ if (reply instanceof Error) throw reply;
+ return Response.json(reply);
+ }) as typeof fetch,
+ };
+ async function upload(body: unknown, options: { capability?: CapabilityClaims; actor?: string } = {}) {
+ let status = 0;
+ let text = "";
+ const res = {
+ setHeader() {},
+ getHeader() {},
+ writeHead(code: number) {
+ status = code;
+ },
+ end(value: string) {
+ text = value;
+ },
+ } as unknown as ServerResponse;
+ const ctx = {
+ deps,
+ res,
+ url: new URL("/v1/composio/twitter/media", "http://localhost"),
+ body,
+ capability: "capability" in options ? options.capability : cap,
+ actor: options.actor ? { p: options.actor, exp: Date.now() + 60_000 } : null,
+ } as unknown as ApiCtx;
+ await composioTwitterMediaRoutes[0]!.handle(ctx);
+ return { status, data: JSON.parse(text), text };
+ }
+ return { upload, calls, replies, audits, deps };
+}
+
+test("uploads an image through the caller's own X connection and returns only the media id", async () => {
+ const f = await fixture();
+ f.replies.push(
+ xAccount,
+ proxied({ data: { id: "1001" } }),
+ proxied({}),
+ proxied({ data: { id: "1001", expires_after_secs: 86400 } }),
+ );
+ const result = await f.upload({ accountId: "ca_alice", data: PNG.toString("base64") });
+ assert.equal(result.status, 200);
+ assert.deepEqual(result.data, {
+ mediaId: "1001",
+ mediaType: "image/png",
+ bytes: PNG.length,
+ expiresAfterSecs: 86400,
+ });
+ assert.doesNotMatch(result.text, /private-key|hidden/);
+ const proxyCalls = f.calls.slice(1).map((call) => call.body);
+ assert.ok(f.calls.slice(1).every((call) => call.url.endsWith("/tools/execute/proxy")));
+ assert.deepEqual(proxyCalls, [
+ {
+ connected_account_id: "ca_alice",
+ endpoint: "https://api.x.com/2/media/upload/initialize",
+ method: "POST",
+ body: { media_type: "image/png", total_bytes: PNG.length, media_category: "tweet_image" },
+ },
+ {
+ connected_account_id: "ca_alice",
+ endpoint: "https://api.x.com/2/media/upload/1001/append",
+ method: "POST",
+ body: { media: PNG.toString("base64"), segment_index: 0 },
+ },
+ { connected_account_id: "ca_alice", endpoint: "https://api.x.com/2/media/upload/1001/finalize", method: "POST" },
+ ]);
+ assert.deepEqual(f.audits, ["composio.twitter_media.started", "composio.twitter_media.completed"]);
+});
+
+test("images larger than one proxy request are appended in ordered segments", async () => {
+ const f = await fixture();
+ const big = Buffer.concat([PNG, Buffer.alloc(5 * 1024 * 1024 - PNG.length, 1)]);
+ f.replies.push(xAccount, proxied({ data: { id: "1002" } }), proxied({}), proxied({}), proxied({}));
+ f.replies.push(proxied({ data: { id: "1002" } }));
+ const result = await f.upload({ accountId: "ca_alice", data: big.toString("base64") });
+ assert.equal(result.status, 200);
+ const appends = f.calls.filter((call) => String(call.body?.endpoint).endsWith("/append"));
+ assert.deepEqual(
+ appends.map((call) => (call.body!.body as { segment_index: number }).segment_index),
+ [0, 1, 2],
+ );
+ assert.deepEqual(
+ Buffer.concat(appends.map((call) => Buffer.from((call.body!.body as { media: string }).media, "base64"))),
+ big,
+ );
+});
+
+test("other owners, inactive or disabled accounts and non-X connections are refused before uploading", async () => {
+ for (const account of [
+ { ...xAccount, user_id: composioUserId(orgId(), "bob") },
+ { ...xAccount, id: "ca_bob" },
+ { ...xAccount, status: "EXPIRED" },
+ { ...xAccount, is_disabled: true },
+ { ...xAccount, toolkit: { slug: "gmail" } },
+ ]) {
+ const f = await fixture();
+ f.replies.push(account);
+ const result = await f.upload({ accountId: "ca_alice", data: PNG.toString("base64") });
+ assert.equal(result.status, 403);
+ assert.equal(f.calls.length, 1);
+ }
+});
+
+test("the agent cannot choose the endpoint, identity or media type, and only real images are sent", async () => {
+ const cases: Array<[unknown, number]> = [
+ [{ accountId: "ca_alice", data: PNG.toString("base64"), endpoint: "https://api.x.com/2/tweets" }, 400],
+ [{ accountId: "ca_alice", data: PNG.toString("base64"), user_id: "bob" }, 400],
+ [{ accountId: "../connected_accounts", data: PNG.toString("base64") }, 400],
+ [{ accountId: "ca_alice", data: "not base64!" }, 400],
+ [{ accountId: "ca_alice", data: Buffer.from("474946383961010001000000", "hex").toString("base64") }, 415],
+ [{ accountId: "ca_alice", data: PNG.subarray(0, 12).toString("base64") }, 415],
+ [{ accountId: "ca_alice", data: Buffer.from("<svg/>").toString("base64") }, 415],
+ [{ accountId: "ca_alice", data: Buffer.alloc(5 * 1024 * 1024 + 1, 0xff).toString("base64") }, 413],
+ ];
+ for (const [body, status] of cases) {
+ const f = await fixture();
+ assert.equal((await f.upload(body)).status, status);
+ assert.equal(f.calls.length, 0);
+ }
+});
+
+test("uploads need the current run's agent capability", async () => {
+ for (const options of [
+ { capability: undefined, actor: "alice" },
+ { actor: "alice" },
+ { capability: { ...cap, runLeaseToken: "stale" } },
+ ]) {
+ const f = await fixture();
+ assert.equal((await f.upload({ accountId: "ca_alice", data: PNG.toString("base64") }, options)).status, 403);
+ assert.equal(f.calls.length, 0);
+ }
+});
+
+test("ending the run during account lookup prevents the upload", async () => {
+ const f = await fixture();
+ const original = f.deps.composioFetch!;
+ f.deps.composioFetch = async (...args) => {
+ const response = await original(...args);
+ f.deps.runs = { get: async () => ({ status: "done" }) } as unknown as ServerDeps["runs"];
+ return response;
+ };
+ f.replies.push(xAccount);
+ assert.equal((await f.upload({ accountId: "ca_alice", data: PNG.toString("base64") })).status, 403);
+ assert.equal(f.calls.length, 1);
+});
+
+test("an X refusal stops the upload and points the agent at reconnecting", async () => {
+ const f = await fixture();
+ f.replies.push(xAccount, proxied({ title: "Forbidden", detail: "Missing media.write" }, 403));
+ const result = await f.upload({ accountId: "ca_alice", data: PNG.toString("base64") });
+ assert.equal(result.status, 502);
+ assert.equal(result.data.providerStatus, 403);
+ assert.equal(result.data.providerDetail, "Missing media.write");
+ assert.match(result.data.message, /reconnect X/);
+ assert.equal(f.calls.length, 2);
+ assert.deepEqual(f.audits, ["composio.twitter_media.started", "composio.twitter_media.failed"]);
+});
+
+test("JPEG and WebP images are typed from their bytes", async () => {
+ for (const [image, mediaType] of [
+ [JPEG, "image/jpeg"],
+ [WEBP, "image/webp"],
+ ] as const) {
+ const f = await fixture();
+ f.replies.push(xAccount, proxied({ data: { id: "1003" } }), proxied({}), proxied({ data: { id: "1003" } }));
+ const result = await f.upload({ accountId: "ca_alice", data: image.toString("base64") });
+ assert.equal(result.status, 200);
+ assert.equal(result.data.mediaType, mediaType);
+ assert.equal((f.calls[1]!.body!.body as { media_type: string }).media_type, mediaType);
+ }
+});
+
+test("ending the run partway through stops sending segments", async () => {
+ const f = await fixture();
+ const original = f.deps.composioFetch!;
+ f.deps.composioFetch = async (...args) => {
+ const response = await original(...args);
+ if (f.calls.length === 2) f.deps.runs = { get: async () => ({ status: "done" }) } as unknown as ServerDeps["runs"];
+ return response;
+ };
+ f.replies.push(xAccount, proxied({ data: { id: "1004" } }));
+ const result = await f.upload({ accountId: "ca_alice", data: PNG.toString("base64") });
+ assert.equal(result.status, 403);
+ assert.equal(result.data.error, "inactive_run");
+ assert.equal(f.calls.length, 2);
+});
+
+test("provider details are masked before they reach the agent", async () => {
+ const f = await fixture();
+ f.replies.push(
+ xAccount,
+ proxied(
+ { detail: "rejected key private-key for this request", errors: [{ message: "media type unrecognized" }] },
+ 400,
+ ),
+ );
+ const result = await f.upload({ accountId: "ca_alice", data: PNG.toString("base64") });
+ assert.equal(result.status, 502);
+ assert.equal(result.data.providerStatus, 400);
+ assert.doesNotMatch(result.text, /private-key/);
+ assert.match(result.data.providerDetail, /rejected key .* media type unrecognized/);
+});
diff --git a/test/image-downscale.test.ts b/test/image-downscale.test.ts
index f9d33808b..b90508cd2 100644
--- a/test/image-downscale.test.ts
+++ b/test/image-downscale.test.ts
@@ -155,3 +155,11 @@ test("downscaleVisionImage falls back to original bytes when no converter is ava
assert.equal(warnings.length, 1);
assert.match(warnings[0]!, /no image converter was found on PATH/);
});
+
+test("sniffing a large image with many segments takes linear time", () => {
+ const segments = Buffer.alloc(1024 * 1024, Buffer.from([0xff, 0xfe, 0x00, 0x02]));
+ const crafted = Buffer.concat([Buffer.from([0xff, 0xd8]), segments]);
+ const started = performance.now();
+ assert.equal(sniffImageDimensions(crafted), undefined);
+ assert.ok(performance.now() - started < 2_000);
+});