diff --git a/src/data/harness-prompts.ts b/src/data/harness-prompts.ts index b6190889..b45917df 100644 --- a/src/data/harness-prompts.ts +++ b/src/data/harness-prompts.ts @@ -215,6 +215,7 @@ export const ConnectorsNote = ({ lines }: { lines: string[] }) => `# Connectors The user connected these apps themselves, through Settings > Connectors. Their tools are deferred: load the ones you need with load_tools first (an app's tools all share its prefix, e.g. names ["gmail*"]). - This is the user's own account. Read and send only what the request is about, and nothing else in it. +- An app that answers with a preview (the rest was cut, or saved somewhere you can't open) gave you a truncated sample: it is never the total and never an empty result. Ask again for a smaller page (fewer results, no message payload, or ids only) and never report a count from a preview. ${lines.map((line) => `- ${line}`).join("\n")} `; diff --git a/src/harness/connectors/connector-account-tools.ts b/src/harness/connectors/connector-account-tools.ts index 3bd72760..b8237d69 100644 --- a/src/harness/connectors/connector-account-tools.ts +++ b/src/harness/connectors/connector-account-tools.ts @@ -7,6 +7,7 @@ import mcpResultToText from "../mcp/mcp-result-to-text"; import type { HarnessTool } from "../types"; import type { ConnectorProvider } from "./connector-provider"; import ensureConnectorEndpoint from "./ensure-connector-endpoint"; +import expandPreviewResult from "./expand-preview-result"; type Params = { connector: ConnectorRecord; @@ -113,7 +114,13 @@ export default function connectorAccountTools({ user_id, }); - return redact(typeof result == "string" ? result : JSON.stringify(result, null, 2)); + // Already the provider's REST answer, so there is no + // fuller call to ask for a cut result again. + return redact( + await expandPreviewResult({ + text: typeof result == "string" ? result : JSON.stringify(result, null, 2), + }), + ); } const { text, images } = mcpResultToText({ @@ -124,10 +131,27 @@ export default function connectorAccountTools({ }), }); - if (!images.length) return redact(text); + // The MCP router answers a large result with a preview. + // The provider's REST API returns the whole one, so a + // preview is asked again there: one more action of the + // same tool, counted as the one action this call made. + const answer = redact( + await expandPreviewResult({ + text, + retry: () => + provider.execute({ + tool: tool.name, + args, + account: account.provider_account_id, + user_id, + }), + }), + ); + + if (!images.length) return answer; return { - text: redact(text), + text: answer, images: images.map(({ data, mime_type }) => ({ url: `data:${mime_type};base64,${data}`, focus: `This came back from ${connector.name}. Describe what it shows and quote any text in it.`, diff --git a/src/harness/connectors/expand-preview-result.test.ts b/src/harness/connectors/expand-preview-result.test.ts new file mode 100644 index 00000000..49bc0e89 --- /dev/null +++ b/src/harness/connectors/expand-preview-result.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, test } from "bun:test"; +import expandPreviewResult from "./expand-preview-result"; + +function previewText() { + return JSON.stringify({ + data: { + results: [ + { + response: { + data_preview: { + messages: [{ messageId: "a" }, { messageId: "b" }, "...8 more items"], + }, + next_steps: "Write code to parse the saved response.", + }, + }, + ], + }, + }); +} + +const whole = { messages: [{ messageId: "a" }, { messageId: "b" }] }; + +describe("expandPreviewResult", () => { + test("asks the provider again and returns the whole result", async () => { + let calls = 0; + + const text = await expandPreviewResult({ + text: previewText(), + retry: async () => { + calls += 1; + + return whole; + }, + }); + + expect(calls).toBe(1); + expect(JSON.parse(text)).toEqual(whole); + }); + + test("keeps the preview's note when the retry fails", async () => { + const text = await expandPreviewResult({ + text: previewText(), + retry: async () => { + throw new Error("401 API key is required"); + }, + }); + + expect(text).toContain("2 of 10 items are here"); + }); + + test("keeps the preview's note when there is no retry to make", async () => { + const text = await expandPreviewResult({ text: previewText() }); + + expect(text).toContain("2 of 10 items are here"); + }); + + test("rewrites a retry that came back cut as well", async () => { + const text = await expandPreviewResult({ + text: previewText(), + retry: async () => ({ data_preview: { messages: [{ messageId: "a" }, "...9 more items"] } }), + }); + + expect(text).toContain("1 of 10 items are here"); + expect(text).not.toContain("data_preview"); + }); + + test("leaves a whole answer alone and asks nothing", async () => { + let calls = 0; + const text = JSON.stringify(whole); + + const answer = await expandPreviewResult({ + text, + retry: async () => { + calls += 1; + + return whole; + }, + }); + + expect(answer).toBe(text); + expect(calls).toBe(0); + }); +}); \ No newline at end of file diff --git a/src/harness/connectors/expand-preview-result.ts b/src/harness/connectors/expand-preview-result.ts new file mode 100644 index 00000000..814f833d --- /dev/null +++ b/src/harness/connectors/expand-preview-result.ts @@ -0,0 +1,41 @@ +import previewResult from "./preview-result"; + +type Params = { + text: string; + /** + * The same call over the provider's REST API, which answers with the whole + * result its MCP router cut. Left out when the text already came from + * REST, or when there is nothing left to ask. + */ + retry?: () => Promise; +}; + +/** + * A provider's preview replaced by the whole result when the provider can + * still give it, and by an honest account of what is missing when it can't. + * + * A retry runs only for an answer that was cut, and costs one more action of + * the same tool, so most answers pay nothing. + */ +export default async function expandPreviewResult({ text, retry }: Params): Promise { + const seen = previewResult({ text }); + + if (!seen.preview) return text; + + if (retry) { + try { + const full = await retry(); + + if (full != null) { + const whole = typeof full == "string" ? full : JSON.stringify(full, null, 2); + const again = previewResult({ text: whole }); + + return again.preview ? again.text : whole; + } + } catch { + // Best effort: the preview's own note still says what is missing. + } + } + + return seen.text; +} \ No newline at end of file diff --git a/src/harness/connectors/preview-result.test.ts b/src/harness/connectors/preview-result.test.ts new file mode 100644 index 00000000..4a36086b --- /dev/null +++ b/src/harness/connectors/preview-result.test.ts @@ -0,0 +1,89 @@ +import { describe, expect, test } from "bun:test"; +import previewResult from "./preview-result"; + +function gmailMessage({ id }: { id: string }) { + return { + messageId: id, + threadId: id, + labelIds: ["CATEGORY_PROMOTIONS", "...1 more items"], + subject: `Subject ${id}`, + preview: { body: `Body ${id}` }, + }; +} + +/** + * The answer Composio's MCP router gave a Gmail fetch of 10 messages: two of + * them, a marker for the other eight, and instructions to parse a file the + * app never receives. + */ +function gmailPreview() { + return { + successful: true, + data: { + results: [ + { + response: { + successful: true, + data_preview: { + messages: [ + gmailMessage({ id: "1a201de2616a75cd" }), + gmailMessage({ id: "1a201dc5ff69132f" }), + "...8 more items", + ], + nextPageToken: "token", + resultSizeEstimate: 201, + }, + tool_slug: "GMAIL_FETCH_EMAILS", + index: 0, + structure_info: { + data_structure: { properties: { messages: { type: "array", length: 10 } } }, + }, + next_steps: "Write code to parse the saved response and run the analysis.", + }, + error: null, + log_id: "log-1", + }, + ], + }, + }; +} + +describe("previewResult", () => { + test("says how much of a preview is missing and keeps the items", () => { + const result = previewResult({ text: JSON.stringify(gmailPreview()) }); + + expect(result.preview).toBe(true); + + if (!result.preview) throw new Error("expected a preview"); + + expect(result.text).toContain("2 of 10 items are here"); + expect(result.text).toContain("the other 8 were cut"); + expect(result.text).toContain("1a201de2616a75cd"); + expect(result.text).toContain("1a201dc5ff69132f"); + expect(result.text).not.toContain("structure_info"); + expect(result.text).not.toContain("next_steps"); + expect(result.text).not.toContain("log_id"); + expect(result.text).not.toContain("saved response"); + }); + + test("leaves a whole result alone", () => { + const result = previewResult({ + text: JSON.stringify({ messages: [{ messageId: "a" }, { messageId: "b" }] }), + }); + + expect(result).toEqual({ preview: false }); + }); + + test("leaves a non-JSON answer alone", () => { + expect(previewResult({ text: "Gmail: two messages" })).toEqual({ preview: false }); + }); + + test("says only part is here when the preview marks nothing as cut", () => { + const result = previewResult({ text: JSON.stringify({ data_preview: { messages: [] } }) }); + + if (!result.preview) throw new Error("expected a preview"); + + expect(result.text).toContain("only part of it is here"); + expect(result.text).toContain("never an empty result"); + }); +}); \ No newline at end of file diff --git a/src/harness/connectors/preview-result.ts b/src/harness/connectors/preview-result.ts new file mode 100644 index 00000000..fd5af591 --- /dev/null +++ b/src/harness/connectors/preview-result.ts @@ -0,0 +1,125 @@ +/** + * Composio's hosted MCP router cuts a large tool result down to a preview: + * `data` becomes `data_preview`, holding a couple of the items, a + * "...N more items" marker and instructions to parse a "saved response" + * that a programmatic client never gets, plus `structure_info`, `next_steps` + * and a `log_id`. Read as the whole answer it looks like an empty inbox (a + * Gmail fetch of 10 messages came back as 2, and a bot reported that the + * account had only those two), so a run that got a preview is told what it + * actually holds instead (ComposioHQ/composio#5025). + */ + +export type PreviewResult = { preview: false } | { preview: true; text: string }; + +const MoreItems = /^\.\.\.(\d+) more items$/; + +type Elision = { + /** Items the provider kept. */ + shown: number; + /** Items the provider cut. */ + left_out: number; +}; + +/** + * The biggest cut in the tree: the array the provider truncated most (the + * messages of a fetch, not the few label ids elided on each one). + */ +function largestElision({ value }: { value: unknown }): Elision { + let largest: Elision = { shown: 0, left_out: 0 }; + + const visit = (node: unknown) => { + if (Array.isArray(node)) { + let shown = 0; + let left_out = 0; + + for (const item of node) { + const match = typeof item == "string" ? MoreItems.exec(item) : null; + + if (match) left_out += Number(match[1]); + else if (item != null) shown += 1; + } + + if (left_out > largest.left_out) largest = { shown, left_out }; + + for (const item of node) visit(item); + + return; + } + + if (node && typeof node == "object") { + for (const item of Object.values(node as Record)) visit(item); + } + }; + + visit(value); + + return largest; +} + +/** + * Every `data_preview` the tree carries. The preview itself is not walked: + * only the key names it as cut. + */ +function collectPreviews({ value }: { value: unknown }): unknown[] { + const previews: unknown[] = []; + + const visit = (node: unknown) => { + if (Array.isArray(node)) { + for (const item of node) visit(item); + + return; + } + + if (!node || typeof node != "object") return; + + for (const [key, item] of Object.entries(node as Record)) { + if (key == "data_preview") previews.push(item); + else visit(item); + } + }; + + visit(value); + + return previews; +} + +function previewNote({ previews }: { previews: unknown[] }): string { + const { shown, left_out } = largestElision({ value: previews }); + + const count = left_out + ? `${shown} of ${shown + left_out} items are here and the other ${left_out} were cut before they reached you` + : "only part of it is here"; + + return [ + `The provider returned a preview, not the whole result: ${count}.`, + "This is a truncated sample, never the total and never an empty result: ask again for a smaller page (fewer results, no message payload, or ids only) to see the rest.", + ].join(" "); +} + +/** + * The text a run should see in place of the provider's answer: the preview + * rewritten to say how much of the result is missing, or `preview: false` + * when the answer is the whole one. + * + * `structure_info`, `next_steps` and `log_id` are dropped with the envelope: + * they describe the preview, and `next_steps` sends a run looking for a file + * the app never receives. + */ +export default function previewResult({ text }: { text: string }): PreviewResult { + let parsed: unknown; + + try { + parsed = JSON.parse(text); + } catch { + return { preview: false }; + } + + const previews = collectPreviews({ value: parsed }); + + if (!previews.length) return { preview: false }; + + return { + preview: true, + text: [previewNote({ previews }), ...previews.map((preview) => JSON.stringify(preview, null, 2))].join("\n\n"), + }; +} \ No newline at end of file