The Open Framework for Building Agents
fix(eve): resolve every attachment to a staged file or a note (#4635)
Andrew Barba0248e696a585
diff --git a/.changeset/attachments-eve-fetches-links.md b/.changeset/attachments-eve-fetches-links.mdnew file mode 100644index 000000000..8f8e1b882--- /dev/null+++ b/.changeset/attachments-eve-fetches-links.md@@ -0,0 +1,5 @@+---+"eve": minor+---++eve now downloads attachment links itself instead of handing them to the model provider. When a channel's `fetchFile` returns `null`, or the channel has none, eve fetches a public `https:` link with the 25 MB upload cap and a 30-second timeout, at most 10 links per message and one at a time, and any other link or failed download reaches the model as a note. A private or expired link, such as a Google Drive file shared in Slack, no longer fails every later model call, and sessions that already hold such a link recover.diff --git a/.changeset/attachments-labels-verified-media.md b/.changeset/attachments-labels-verified-media.mdnew file mode 100644index 000000000..11b51d556--- /dev/null+++ b/.changeset/attachments-labels-verified-media.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Every attachment now reaches the model with a label that names its sandbox path, including images and PDFs that also arrive as bytes, so the agent can pass a visible file to `bash` or open it again. eve checks image and PDF media types against the file's bytes. Only PNG, JPEG, GIF, and WebP images up to 3 MiB and 8000 pixels per side, and PDFs up to 20 MiB, go to the model as bytes, and tool results follow the same rule. A HEIC photo, an oversized screenshot, or a mislabeled file renders as its label instead of failing the model call. Live sessions pay one prompt-cache rewrite after upgrading.diff --git a/.changeset/attachments-never-unresolved.md b/.changeset/attachments-never-unresolved.mdnew file mode 100644index 000000000..20b8753c4--- /dev/null+++ b/.changeset/attachments-never-unresolved.md@@ -0,0 +1,5 @@+---+"eve": patch+---++A turn cancelled before its first model call now stages its attachments, so a photo sent just before a follow-up message no longer breaks every later turn. File parts eve can't stage become a note instead of entering session history. Byte-valued file parts cross the queue as `data:` URLs, a string with any URL scheme reaches the channel's `fetchFile` instead of being decoded as base64, and `message.received` reports an inline file's size instead of echoing its `data:` URL.diff --git a/.changeset/attachments-read-file-pdf.md b/.changeset/attachments-read-file-pdf.mdnew file mode 100644index 000000000..e83edc846--- /dev/null+++ b/.changeset/attachments-read-file-pdf.md@@ -0,0 +1,5 @@+---+"eve": minor+---++`read_file` now shows PDFs up to 20 MiB to the model as files, so the agent can reopen an attached PDF after compaction, or read one that a tool or `bash` wrote to the sandbox. Its output's `image` field is now `file` and carries `pages` for PDFs. `read_file` also refuses images over 8000 pixels per side, which providers reject.diff --git a/docs/channels/chat-sdk.mdx b/docs/channels/chat-sdk.mdxindex 125d94d3a..5219d15c7 100644--- a/docs/channels/chat-sdk.mdx+++ b/docs/channels/chat-sdk.mdx@@ -245,7 +245,7 @@ bot.onNewMention(async (thread, message) => {});```-When the adapter can download an attachment (it sets `fetchData`, as the Slack, Google Chat, WhatsApp, and Twilio adapters do), eve downloads it with the adapter's credentials when the turn runs, not in the webhook, and passes the bytes. Platform file URLs usually need those credentials, so the model provider couldn't open them. eve rebuilds the download with the adapter's `rehydrateAttachment`; an adapter without one can't download after the webhook returns, so its files reach the agent as a short note. A failed download, or a file over 25 MB, also becomes a note. An attachment with only a URL is passed as that URL.+When the adapter can download an attachment (it sets `fetchData`, as the Slack, Google Chat, WhatsApp, and Twilio adapters do), eve downloads it with the adapter's credentials when the turn runs, not in the webhook, and passes the bytes. Platform file URLs usually need those credentials, so the model provider couldn't open them. eve rebuilds the download with the adapter's `rehydrateAttachment`; an adapter without one can't download after the webhook returns, so its files reach the agent as a short note. A failed download, or a file over 25 MB, also becomes a note. An attachment with only a URL is downloaded by eve when the URL is public `https:`; otherwise it becomes a note.See [File uploads](./custom#file-uploads) for how eve stages remote file URLs before the model call.diff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdxindex a595de4f6..823a0c9be 100644--- a/docs/channels/custom.mdx+++ b/docs/channels/custom.mdx@@ -552,7 +552,9 @@ defineChannel({If `fetchFile` throws, eve replaces that attachment with a model-visible error note and continues the turn. Built-in channels include safe details such as the upstream HTTP status. Custom channel errors use a generic note, while eve keeps the original error in operator logs.-The `URL` object survives the queue boundary as a string and is reconstituted inside the workflow step. The staging pipeline calls `fetchFile` with the URL serialized as a string (the URL's `href`), which is why the example matches on `url.startsWith(...)`. Return bytes to stage the file to the sandbox, or `null` to let the URL pass through to the model provider.+The `URL` object survives the queue boundary as a string and is reconstituted inside the workflow step. A string with a URL scheme, such as `https://...` or `myapp-file:abc`, is handled the same way. The staging pipeline calls `fetchFile` with the URL serialized as a string (the URL's `href`), which is why the example matches on `url.startsWith(...)`.++Return bytes to stage the file to the sandbox. Return `null` when the URL is not one your channel resolves: eve then downloads a public `https:` URL itself, with the 25 MB default size cap and a 30-second timeout, and refuses private or reserved addresses. It downloads at most 10 URLs per message, one at a time. Any other URL, or a download that fails, reaches the model as a note. The model provider never fetches an attachment, so a link that expires or needs credentials can't fail later model calls.The framework handles staging bytes to the sandbox, enforcing upload policy, hydrating files for the model call, and reconstituting `URL` objects after queue serialization. See [Inbound attachments](../sandbox#inbound-attachments) for the shared storage, size, and provider-input behavior.diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdxindex d6d9ccd9a..123c033d3 100644--- a/docs/channels/slack.mdx+++ b/docs/channels/slack.mdx@@ -399,7 +399,7 @@ slackChannel({});```-The bases say where a call may go. `apiBaseUrl` is the base Slack Web API method names resolve against, and defaults to `https://slack.com/api/`. `fileBaseUrl` adds a base for attachment downloads and falls back to `apiBaseUrl`: a download URL under it is fetched with the bot token, in addition to `files.slack.com` and Enterprise Grid file URLs. Every other URL passes through to the model provider unchanged. Both bases must be absolute `http:` or `https:` URLs carrying no query string or fragment; `slackChannel()` throws on one that is not, naming the option. A missing trailing slash is added, so `https://sim.example/api` sends `chat.postMessage` to `https://sim.example/api/chat.postMessage`.+The bases say where a call may go. `apiBaseUrl` is the base Slack Web API method names resolve against, and defaults to `https://slack.com/api/`. `fileBaseUrl` adds a base for attachment downloads and falls back to `apiBaseUrl`: a download URL under it is fetched with the bot token, in addition to `files.slack.com` and Enterprise Grid file URLs. eve downloads every other public `https:` URL without the bot token. Both bases must be absolute `http:` or `https:` URLs carrying no query string or fragment; `slackChannel()` throws on one that is not, naming the option. A missing trailing slash is added, so `https://sim.example/api` sends `chat.postMessage` to `https://sim.example/api/chat.postMessage`.`api.fetch` says how the traffic travels. It replaces the global `fetch` for calls to the configured bases — use it to attach the per-call header a host behind an authenticating proxy requires, as the example does for a simulator behind Vercel Deployment Protection. eve confines it to those bases' origins, so that header reaches the simulator alone: `files.slack.com`, and any other host Slack names in a response or an inbound payload, keep the global `fetch`. A wrapper therefore attaches its credential unconditionally. With no base configured every call already goes to Slack's own hosts, and `api.fetch` carries all of them, which is what observes or stubs the traffic in a test.diff --git a/docs/concepts/built-in-tools.md b/docs/concepts/built-in-tools.mdindex 7ee01d8ba..dc1b32a63 100644--- a/docs/concepts/built-in-tools.md+++ b/docs/concepts/built-in-tools.md@@ -81,7 +81,7 @@ export default disableTool();### `read_file`-`read_file` reads text files from the sandbox with line-numbered output, and shows PNG, JPEG, GIF, and WebP images up to 3 MiB to the model as images. Images are detected from their bytes, so a missing or mismatched filename extension does not matter, and text files are always read as text. It accepts absolute paths and paths beginning with `$HOME/`.+`read_file` reads text files from the sandbox with line-numbered output, and shows PNG, JPEG, GIF, and WebP images up to 3 MiB and 8000 pixels per side, and PDFs up to 20 MiB, to the model as files. Images and PDFs are detected from their bytes, so a missing or mismatched filename extension does not matter, and other text files are always read as text. It accepts absolute paths and paths beginning with `$HOME/`.```sheve add tool/read_filediff --git a/docs/guides/client/streaming.mdx b/docs/guides/client/streaming.mdxindex fcd53d1e7..2a00e12ca 100644--- a/docs/guides/client/streaming.mdx+++ b/docs/guides/client/streaming.mdx@@ -161,7 +161,7 @@ A call to a tool that runs as a [task](/docs/tools/workflows#run-calls-as-tasks-When a submitted message includes attachments, `message.received.data.message` stays theflattened compatibility summary, while `message.received.data.parts` carries renderable text andfile metadata. File parts never include raw bytes or internal sandbox paths; `url` appears only for-client-resolvable `http(s)` and `data:` URLs.+`http(s)` URLs, and an inline file reports its `size` instead.## Authorization pausesdiff --git a/docs/sandbox/index.mdx b/docs/sandbox/index.mdxindex bb6d894f9..29e3e1bf2 100644--- a/docs/sandbox/index.mdx+++ b/docs/sandbox/index.mdx@@ -153,14 +153,18 @@ Docker and microsandbox mount the compiled trees read-only under `/eve/resourceseve writes byte-backed files that reach the agent into the sandbox under `/workspace/.eve/attachments/` and keeps only a reference in session history. This covers files attached to user messages and files that tools return to the model with `toolOutputPart.file` or as MCP image, audio, and blob content.-Before every model call, eve reads the referenced files back from the sandbox:+Before every model call, eve reads the referenced files back from the sandbox. Every file, whether attached to a message or returned by a tool, reaches the model with a label that names its sandbox path, such as `Attached file /workspace/.eve/attachments/<hash>/report.csv (text/csv)`. The agent can open that path with `read_file` or `bash`. The file's bytes follow its label only when every major provider reads the format natively:-- An image up to 3 MiB or a PDF up to 20 MiB attached to a message reaches the model as a file. Larger files and other types reach the model as a text reference, such as `Attached file /workspace/.eve/attachments/<hash>/report.csv (text/csv)`, that the agent can open with `read_file` or `bash`.-- A file returned by a tool always reaches the model as a file.+- A PNG, JPEG, GIF, or WebP image up to 3 MiB and at most 8000 pixels per side.+- A PDF up to 20 MiB.++Other files, such as CSV, HEIC, audio, and video, reach the model as the label alone. eve checks image and PDF media types against the file's bytes when it stages the file. A file whose bytes don't match its declared image or PDF type is staged as `application/octet-stream`, so a provider never receives bytes it would reject.If a referenced file is missing, or its bytes no longer match what eve staged because something in the sandbox overwrote it, the model receives a `FileNotFound` note in its place.-Each call sends the same bytes for the same file, so the model still sees attachments from earlier turns and the provider's prompt cache stays valid. Compaction replaces files in older tool results with their text reference. The `read_file` tool shows PNG, JPEG, GIF, and WebP files up to 3 MiB to the model as images, so the agent can look at an image again after compaction.+A file that eve can't stage never enters session history. When a channel's `fetchFile` fails, or a file part's `data` is not bytes, base64, a `data:` URL, or a URL, the model receives a note that names the file instead.++Each call sends the same bytes for the same file, so the model still sees attachments from earlier turns and the provider's prompt cache stays valid. Compaction replaces files in older tool results with their text reference. The `read_file` tool shows the same images and PDFs to the model as files, so the agent can look at an attachment again after compaction, or open a PDF that a tool or `bash` wrote to the sandbox.## Custom providersdiff --git a/docs/tools/overview.mdx b/docs/tools/overview.mdxindex 74bf9b49a..e40607269 100644--- a/docs/tools/overview.mdx+++ b/docs/tools/overview.mdx@@ -336,7 +336,7 @@ File payloads must be base64 strings — raw bytes (`Uint8Array`, `Buffer`) areeve writes each returned file to the session sandbox and keeps only a reference in session history, so the file's bytes are not stored again on every workflow step. Every later model call sends the same file, which keeps it visible on later turns and keeps the provider's prompt cache valid. See [Inbound attachments](/docs/sandbox#inbound-attachments). Compaction counts an image at roughly what providers bill for it rather than its base64 length.-When compaction drops older tool results, each file becomes a text reference such as `Attached file /workspace/.eve/attachments/<hash>/chart.png (image/png)`. The built-in `read_file` tool shows PNG, JPEG, GIF, and WebP files up to 3 MiB to the model as images, so the agent can open a compacted image again.+When compaction drops older tool results, each file becomes a text reference such as `Attached file /workspace/.eve/attachments/<hash>/chart.png (image/png)`. The built-in `read_file` tool shows PNG, JPEG, GIF, and WebP images up to 3 MiB and PDFs up to 20 MiB to the model as files, so the agent can open a compacted image or PDF again.Do not return secrets, credentials, unnecessary personal data, or unbounded sensitive content from tools. Filter, minimize, and redact tool outputs before returning them.diff --git a/e2e/fixtures/agent-compaction-regressions/agent/agent.ts b/e2e/fixtures/agent-compaction-regressions/agent/agent.tsindex 9ce1fc68a..286508229 100644--- a/e2e/fixtures/agent-compaction-regressions/agent/agent.ts+++ b/e2e/fixtures/agent-compaction-regressions/agent/agent.ts@@ -110,7 +110,7 @@ const taskModel = mockModel({toolText.includes(CONTENT_OUTPUT_LEAD_MARKER) ? "LEAD_PRESERVED" : "LEAD_LOST",// The stub names the file's sandbox path, which ends in its filename.toolText.includes("Attached file ") &&- toolText.includes(`${CONTENT_OUTPUT_FILENAME} (application/octet-stream)`)+ toolText.includes(`${CONTENT_OUTPUT_FILENAME} (image/png)`)? "FILE_STUB_RENDERED": "FILE_STUB_LOST",request.userMessages.some((text) => text.includes("[case: content-output-file-stub]"))diff --git a/e2e/fixtures/agent-compaction-regressions/agent/tools/emit-compaction-content.ts b/e2e/fixtures/agent-compaction-regressions/agent/tools/emit-compaction-content.tsindex 180a058f0..104919df4 100644--- a/e2e/fixtures/agent-compaction-regressions/agent/tools/emit-compaction-content.ts+++ b/e2e/fixtures/agent-compaction-regressions/agent/tools/emit-compaction-content.ts@@ -8,10 +8,20 @@ import {CONTENT_OUTPUT_TAIL_MARKER,} from "../../constants";-// The canary sits within the first 2000 serialized characters, where the old-// prefix-clipping rendering would expose it to the compaction model. The rest-// of the payload pushes the trailing text far past that clip budget.-const INLINE_FILE_BASE64 = `${"A".repeat(400)}${CONTENT_OUTPUT_PAYLOAD_CANARY}${"A".repeat(11_600)}`;+// A PNG signature and 2000x2000 IHDR chunk (33 bytes, so 44 base64 characters+// with no padding) make eve verify the file as an image it inlines, so the+// payload reaches the model and weighs on history like any screenshot. The+// canary sits within the first 2000 serialized characters, where the old+// prefix-clipping rendering would expose it to the compaction model, and on a+// base64 group boundary so it survives eve's decode and re-encode unchanged.+// The rest of the payload pushes the trailing text far past that clip budget.+const PNG_HEADER = Buffer.from(+ "89504e470d0a1a0a" + "0000000d49484452" + "000007d0000007d00806000000" + "00000000",+ "hex",+);+const INLINE_FILE_BASE64 =+ `${PNG_HEADER.toString("base64")}${"A".repeat(400)}` ++ `${CONTENT_OUTPUT_PAYLOAD_CANARY}${"A".repeat(11_599)}`;export default defineTool({description:@@ -28,7 +38,7 @@ export default defineTool({toolOutputPart.text(`Alice's completed review note: ${CONTENT_OUTPUT_LEAD_MARKER}`),toolOutputPart.file(INLINE_FILE_BASE64, {filename: CONTENT_OUTPUT_FILENAME,- mediaType: "application/octet-stream",+ mediaType: "image/png",}),// "The attachment's filename" is deliberately not spelled out: the// checkpoint can only carry it by reading the rendered stub.diff --git a/packages/eve/src/channel/adapter.ts b/packages/eve/src/channel/adapter.tsindex 34266b9b3..74591e888 100644--- a/packages/eve/src/channel/adapter.ts+++ b/packages/eve/src/channel/adapter.ts@@ -6,6 +6,7 @@ import { createLogger } from "#internal/logging.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import type { SessionHandle } from "#channel/session.js";import type { DeliverPayload } from "#channel/types.js";+import type { UploadPolicy } from "#public/channels/upload-policy.js";import type {FetchFileContext,FetchFileResult,@@ -159,16 +160,25 @@ export type ChannelAdapter<TCtx extends ChannelAdapterContext<any> = ChannelAdap/*** Fetches bytes for a URL encountered in `FilePart.data`.*- * Called by the staging pipeline when it encounters a `URL` object- * on a `FilePart`. Return `null` to let the URL pass through to the- * model provider (e.g. public images). Return bytes or- * {@link FetchFileResult} to stage the file to the sandbox.+ * Called by the staging pipeline when it encounters a link on a+ * `FilePart`. Return bytes or {@link FetchFileResult} to stage the file+ * to the sandbox. Return `null` when the link is not this channel's: eve+ * then downloads a public `https:` link itself, and any other link+ * reaches the model as a note.** Credentials should be captured in the closure at channel* construction time.*/readonly fetchFile?: FetchFileFunction;+ /**+ * Upload policy staging applies to every inbound attachment, on its final+ * bytes and verified media type, including links eve downloads itself.+ * Without one, staging checks nothing and eve's own downloads stop at the+ * framework default size.+ */+ readonly uploadPolicy?: UploadPolicy;+/*** Framework-owned observability projection for the active channel.*diff --git a/packages/eve/src/channel/channel-address.ts b/packages/eve/src/channel/channel-address.tsindex 5f4e39433..78296f45e 100644--- a/packages/eve/src/channel/channel-address.ts+++ b/packages/eve/src/channel/channel-address.ts@@ -6,7 +6,7 @@ import {type ChannelDeliverySource,} from "#channel/delivery-metadata.js";import type { SendPayload } from "#channel/routes.js";-import { normalizeSendInput, serializeUrlFilePartsInMessage } from "#channel/send-input.js";+import { normalizeSendInput, serializeFilePartsInMessage } from "#channel/send-input.js";import { createSession, sessionCallbackToTurnCaller, type Session } from "#channel/session.js";import type {CancelTurnResult,@@ -93,7 +93,7 @@ export function createChannelAddress<TState = undefined>(input: {kind: "send" as const,payload: {...payload,- message: serializeUrlFilePartsInMessage(payload.message),+ message: serializeFilePartsInMessage(payload.message),},requestId: metadata.requestId,turnPolicy:@@ -123,7 +123,7 @@ export function createChannelAddress<TState = undefined>(input: {initiatorAuth: options.initiatorAuth,input: {context: payload.context,- message: serializeUrlFilePartsInMessage(payload.message) ?? "",+ message: serializeFilePartsInMessage(payload.message) ?? "",outputSchema: payload.outputSchema,state: payload.state,},diff --git a/packages/eve/src/channel/send-input.test.ts b/packages/eve/src/channel/send-input.test.tsnew file mode 100644index 000000000..758f7ba93--- /dev/null+++ b/packages/eve/src/channel/send-input.test.ts@@ -0,0 +1,25 @@+import type { FilePart, UserContent } from "ai";+import { describe, expect, it } from "vitest";++import { serializeFilePartsInMessage } from "#channel/send-input.js";+import { readFileData } from "#internal/attachments/data.js";++describe("serializeFilePartsInMessage", () => {+ it("carries bytes and URLs across a JSON boundary intact", () => {+ const bytes = Buffer.from([0x89, 0x50, 0x4e, 0x47]);+ const message: UserContent = [+ { type: "text", text: "two files" },+ { data: bytes, filename: "a.png", mediaType: "image/png", type: "file" },+ { data: new URL("https://example.com/b.pdf"), mediaType: "application/pdf", type: "file" },+ ];++ const crossed = JSON.parse(JSON.stringify(serializeFilePartsInMessage(message))) as Exclude<+ UserContent,+ string+ >;++ expect(crossed[0]).toEqual({ type: "text", text: "two files" });+ expect(readFileData((crossed[1] as FilePart).data)).toEqual({ bytes, kind: "bytes" });+ expect((crossed[2] as FilePart).data).toBe("eve-url:https://example.com/b.pdf");+ });+});diff --git a/packages/eve/src/channel/send-input.ts b/packages/eve/src/channel/send-input.tsindex a7962483f..7fc88e37c 100644--- a/packages/eve/src/channel/send-input.ts+++ b/packages/eve/src/channel/send-input.ts@@ -10,18 +10,28 @@ export function normalizeSendInput(input: string | UserContent | SendPayload): Sreturn input;}-/** Serializes non-data URL file parts before input crosses the durable boundary. */-export function serializeUrlFilePartsInMessage(+/**+ * Serializes file parts before input crosses the durable boundary: `URL`s+ * become `eve-url:` markers and bytes become `data:` URLs, so no world+ * serializer has to round-trip a `URL` or a typed array.+ */+export function serializeFilePartsInMessage(message: string | UserContent | undefined,): string | UserContent | undefined {if (message === undefined || typeof message === "string") return message;let changed = false;const result = message.map((part): FilePart | typeof part => {- if (part.type === "file" && part.data instanceof URL && part.data.protocol !== "data:") {+ if (part.type !== "file") return part;+ if (part.data instanceof URL && part.data.protocol !== "data:") {changed = true;return { ...part, data: serializeUrlFilePart(part.data) };}+ if (part.data instanceof Uint8Array || part.data instanceof ArrayBuffer) {+ changed = true;+ const base64 = Buffer.from(new Uint8Array(part.data)).toString("base64");+ return { ...part, data: `data:${part.mediaType};base64,${base64}` };+ }return part;});return changed ? result : message;diff --git a/packages/eve/src/channel/session.ts b/packages/eve/src/channel/session.tsindex 486788043..74683f6d6 100644--- a/packages/eve/src/channel/session.ts+++ b/packages/eve/src/channel/session.ts@@ -19,7 +19,7 @@ import type {TurnCaller,} from "#channel/types.js";import { DEFAULT_TURN_POLICY } from "#channel/types.js";-import { serializeUrlFilePartsInMessage } from "#channel/send-input.js";+import { serializeFilePartsInMessage } from "#channel/send-input.js";import type { SessionAuth } from "#context/keys.js";import {AuthKey,@@ -120,7 +120,7 @@ export function createSession(context?: readonly string[];message: string | UserContent | undefined;outputSchema?: JsonObject;- }>({ message: serializeUrlFilePartsInMessage(message) }, readClientContext(options));+ }>({ message: serializeFilePartsInMessage(message) }, readClientContext(options));if (options.context !== undefined) payload.context = options.context;if (options.outputSchema !== undefined) payload.outputSchema = options.outputSchema;const commandWithoutCaller = {diff --git a/packages/eve/src/eve-channel/request.ts b/packages/eve/src/eve-channel/request.tsindex d6afefb20..c7d0f0805 100644--- a/packages/eve/src/eve-channel/request.ts+++ b/packages/eve/src/eve-channel/request.ts@@ -479,8 +479,8 @@ function parseMessagePart(raw: unknown): TextPart | FilePart | Response {);}// Callers must never supply framework-internal refs (`eve-url:`,- // `eve-sandbox:`, `eve-attachment:`): the staging pipeline trusts the- // scheme and would reconstitute the string into a privileged sandbox read.+ // `eve-sandbox:`): the staging pipeline trusts the scheme and would+ // reconstitute the string into a privileged sandbox read.if (hasInternalRefScheme(part.data)) {return Response.json({ error: "File part 'data' must not use a framework-internal ref scheme.", ok: false },diff --git a/packages/eve/src/execution/cancelled-model-call-batch.ts b/packages/eve/src/execution/cancelled-model-call-batch.tsindex c155364ce..1df35fdc0 100644--- a/packages/eve/src/execution/cancelled-model-call-batch.ts+++ b/packages/eve/src/execution/cancelled-model-call-batch.ts@@ -1,6 +1,8 @@import { contextStorage, type ContextContainer } from "#context/container.js";-import { AuthKey, TurnDeliveryIdsKey } from "#context/keys.js";+import { createLogger } from "#internal/logging.js";+import { AuthKey, SandboxKey, TurnDeliveryIdsKey } from "#context/keys.js";import { preserveSerializedSessionDynamicModelSelection } from "#context/serialized-dynamic-model-selection.js";+import { withContextScope } from "#context/run-step.js";import { serializeContext } from "#context/serialize.js";import { preserveCancelledTurnMessage } from "#execution/cancelled-turn-message.js";import { createDurableSessionValues } from "#execution/durable-session-store.js";@@ -11,6 +13,8 @@ import { takeDeferredMessage } from "#harness/hitl/index.js";import { preserveSerializedInstrumentationState } from "#instrumentation/state.js";import { preserveSerializedAgentTraceState } from "#tracing/agent-trace-context-store.js";+const log = createLogger("execution.cancelled-turn");+export interface CompletedModelCallCheckpoint {readonly result: StepResult;readonly serializedContext: Record<string, unknown>;@@ -35,9 +39,28 @@ async function cancelledWithoutCheckpoint(session = deferred.session;if (deferred.message !== undefined) preserved = { ...stepInput, message: deferred.message };}+ // A cancellation at step entry lands before the framework providers exist, and staging the+ // message's attachments needs the sandbox.+ if (ctx.get(SandboxKey) === undefined && hasFileParts(preserved?.message)) {+ try {+ const scoped = await withContextScope(ctx, session, async (current) => ({+ result: undefined,+ session: await preserveCancelledTurnMessage(current, preserved),+ }));+ return scoped.session;+ } catch (error) {+ // A cancellation must still settle; without a sandbox the attachments become notes.+ log.warn("staging a cancelled turn's attachments failed", { error });+ ctx.clearVirtualContext();+ }+ }return await contextStorage.run(ctx, () => preserveCancelledTurnMessage(session, preserved));}+function hasFileParts(message: StepInput["message"]): boolean {+ return Array.isArray(message) && message.some((part) => part.type === "file");+}+/** Builds the successful step result that commits a cancelled batch's completed model calls. */export async function createCancelledModelCallBatchResult(input: {readonly beforeBatchContext: Record<string, unknown>;diff --git a/packages/eve/src/execution/sandbox/read-file.test.ts b/packages/eve/src/execution/sandbox/read-file.test.tsindex d509288e5..f31052e4b 100644--- a/packages/eve/src/execution/sandbox/read-file.test.ts+++ b/packages/eve/src/execution/sandbox/read-file.test.ts@@ -58,7 +58,7 @@ describe("read_file images", () => {);// The raw output feeds action.result, so it carries metadata only.- expect(output.image).toEqual({+ expect(output.file).toEqual({height: 32,mediaType: "image/png",size: png.byteLength,@@ -97,7 +97,7 @@ describe("read_file images", () => {expect(path).toMatch(/^\/workspace\/\.eve\/attachments\/[0-9a-f]{16}\/file-[0-9a-f]{16}\.png$/);const output = await executeReadFileOnSandbox(sandbox.session, { filePath: path });- expect(output.image).toMatchObject({ mediaType: "image/png" });+ expect(output.file).toMatchObject({ mediaType: "image/png" });});it.each([@@ -111,7 +111,7 @@ describe("read_file images", () => {const output = await executeReadFileOnSandbox(sandbox.session, {filePath: "/workspace/image",});- expect(output.image).toMatchObject({ mediaType, size: bytes.byteLength });+ expect(output.file).toMatchObject({ mediaType, size: bytes.byteLength });});it("reads text with an image suffix using normal pagination", async () => {@@ -142,7 +142,7 @@ describe("read_file images", () => {const output = await contextStorage.run(sandboxContext(sandbox), () =>executeReadFileOnSandbox(sandbox.session, { filePath: "/workspace/file" }),);- expect(output.image).toBeUndefined();+ expect(output.file).toBeUndefined();expect(output.totalLines).toBe(content === "" ? 0 : 1);});@@ -170,10 +170,22 @@ describe("read_file images", () => {expect(modelOutput).toEqual({type: "text",- value: `${output.content} The image changed after it was read; read it again.`,+ value: `${output.content} The file changed after it was read; read it again.`,});});+ it("rejects images wider than providers accept", async () => {+ const sandbox = mockSandbox();+ await sandbox.session.writeBinaryFile({+ content: pngBytes(8001, 10),+ path: "/workspace/wide.png",+ });++ await expect(+ executeReadFileOnSandbox(sandbox.session, { filePath: "/workspace/wide.png" }),+ ).rejects.toThrow("8001x10 pixels");+ });+it.each(["photo.png", "photo"])("rejects oversized images named %s", async (filename) => {const sandbox = mockSandbox();await sandbox.session.writeBinaryFile({@@ -186,3 +198,61 @@ describe("read_file images", () => {).rejects.toThrow("read_file shows images up to 3 MiB");});});++describe("read_file PDFs", () => {+ const pdf = Buffer.from(+ "%PDF-1.4\n%\xe2\xe3\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n" ++ "2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj\n3 0 obj<</Type/Page>>endobj\n%%EOF\n",+ "latin1",+ );++ it("shows a PDF to the model as a file, whatever its name", async () => {+ const sandbox = mockSandbox();+ const path = "/workspace/.eve/attachments/abc/report";+ await sandbox.session.writeBinaryFile({ content: pdf, path });++ const output = await executeReadFileOnSandbox(sandbox.session, { filePath: path });+ const modelOutput = await contextStorage.run(sandboxContext(sandbox), async () =>+ readFile.toModelOutput?.(output),+ );++ expect(output.file).toEqual({ mediaType: "application/pdf", pages: 1, size: pdf.byteLength });+ expect(modelOutput).toEqual({+ type: "content",+ value: [+ { text: `PDF ${path} (application/pdf, ${pdf.byteLength} bytes, 1 page).`, type: "text" },+ {+ data: { data: pdf.toString("base64"), type: "data" },+ filename: "report",+ mediaType: "application/pdf",+ type: "file",+ },+ ],+ });+ });++ it("reads text that mentions the PDF header as text", async () => {+ const sandbox = mockSandbox();+ const content = "# Notes\nEvery PDF starts with %PDF- followed by its version.\n";+ await sandbox.session.writeTextFile({ content, path: "/workspace/notes.md" });++ const output = await contextStorage.run(sandboxContext(sandbox), () =>+ executeReadFileOnSandbox(sandbox.session, { filePath: "/workspace/notes.md" }),+ );++ expect(output.file).toBeUndefined();+ expect(output.totalLines).toBe(2);+ });++ it("rejects PDFs over 20 MiB", async () => {+ const sandbox = mockSandbox();+ await sandbox.session.writeBinaryFile({+ content: Buffer.concat([pdf, Buffer.alloc(20 * 1024 * 1024)]),+ path: "/workspace/big.pdf",+ });++ await expect(+ executeReadFileOnSandbox(sandbox.session, { filePath: "/workspace/big.pdf" }),+ ).rejects.toThrow("read_file shows PDFs up to 20 MiB");+ });+});diff --git a/packages/eve/src/execution/sandbox/read-file.ts b/packages/eve/src/execution/sandbox/read-file.tsindex 8d2444ff7..b74a22b35 100644--- a/packages/eve/src/execution/sandbox/read-file.ts+++ b/packages/eve/src/execution/sandbox/read-file.ts@@ -8,9 +8,11 @@ import {import { resolveAbsoluteFilePath } from "#execution/sandbox/require-sandbox.js";import {detectImageMediaType,+ hasPdfHeader,readMediaMetadata,type MediaMetadata,} from "#internal/attachments/media-metadata.js";+import { inlinesSandboxRefAsBytes } from "#internal/attachments/sandbox-refs.js";import type { SandboxSession } from "#shared/sandbox-session.js";import { capLineLength, MAX_OUTPUT_BYTES } from "#execution/sandbox/truncate-output.js";@@ -21,8 +23,6 @@ import { capLineLength, MAX_OUTPUT_BYTES } from "#execution/sandbox/truncate-outconst DEFAULT_OFFSET = 1;const DEFAULT_LIMIT = 2000;-// Matches the inline cap for inbound image attachments.-const MAX_IMAGE_BYTES = 3 * 1024 * 1024;// ---------------------------------------------------------------------------// Input / result shapes// ---------------------------------------------------------------------------@@ -42,10 +42,10 @@ export interface ReadFileInput {export interface ReadFileResult {readonly content: string;/**- * Set when the file is a PNG, JPEG, GIF, or WebP image the model sees as- * an image. Carries no bytes, so `action.result` stays small.+ * Set when the file is a PNG, JPEG, GIF, or WebP image or a PDF that the+ * model reads natively. Carries no bytes, so `action.result` stays small.*/- readonly image?: MediaMetadata;+ readonly file?: MediaMetadata;readonly nextOffset?: number;readonly path: string;readonly totalLines: number;@@ -59,8 +59,8 @@ export interface ReadFileResult {/*** Reads one text file from the sandbox, applies output shaping* (offset, limit, line numbering, truncation), and persists a full-file- * stamp into durable read-file state for stale-write detection. Image- * files return their bytes for the model to view instead.+ * stamp into durable read-file state for stale-write detection. Images and+ * PDFs return their bytes for the model to view instead.** Used by the framework `read_file` tool and authored wrappers around its* exported definition.@@ -81,18 +81,21 @@ export async function executeReadFileOnSandbox();}- // ── Classify as text, image, or unsupported binary ──────────────────+ // ── Classify as PDF, text, image, or unsupported binary ───────────+ if (hasPdfHeader(bytes)) {+ return buildFileReadResult(bytes, normalizedPath, "application/pdf");+ }// Clean text stays text even behind an ASCII image signature such as// `GIF89a`; real images always carry NUL or non-UTF-8 bytes.const rawContent = decodeUtf8(bytes);if (rawContent === undefined || rawContent.includes("\0")) {const imageMediaType = detectImageMediaType(bytes);if (imageMediaType !== undefined) {- return buildImageReadResult(bytes, normalizedPath, imageMediaType);+ return buildFileReadResult(bytes, normalizedPath, imageMediaType);}throw new Error(`File "${filePath}" appears to be a binary file. ` +- "read_file only supports text files and PNG, JPEG, GIF, or WebP images.",+ "read_file only supports text files, PNG, JPEG, GIF, or WebP images, and PDFs.",);}@@ -208,18 +211,32 @@ function decodeUtf8(bytes: Uint8Array): string | undefined {}}-function buildImageReadResult(bytes: Uint8Array, path: string, mediaType: string): ReadFileResult {- if (bytes.byteLength > MAX_IMAGE_BYTES) {+// Uses the same rule as attachments, so every file read_file accepts reaches+// the model as bytes.+function buildFileReadResult(bytes: Uint8Array, path: string, mediaType: string): ReadFileResult {+ const file = readMediaMetadata(bytes, mediaType);+ const pdf = mediaType === "application/pdf";+ if (!inlinesSandboxRefAsBytes({ ...file, path })) {throw new Error(- `Image "${path}" is ${bytes.byteLength} bytes; read_file shows images up to 3 MiB. ` +- "Resize or crop it in the sandbox first.",+ ? `PDF "${path}" is ${bytes.byteLength} bytes; read_file shows PDFs up to 20 MiB. ` ++ "Split it or extract its text in the sandbox first."+ : `Image "${path}" is ${describeImage(file)}; read_file shows images up to 3 MiB and ` ++ "8000 pixels per side. Resize or crop it in the sandbox first.",);}+ const pages =+ file.pages === undefined ? "" : `, ${file.pages} ${file.pages === 1 ? "page" : "pages"}`;return {- content: `Image ${path} (${mediaType}, ${bytes.byteLength} bytes).`,- image: readMediaMetadata(bytes, mediaType),+ content: `${pdf ? "PDF" : "Image"} ${path} (${mediaType}, ${bytes.byteLength} bytes${pages}).`,+ file,path,totalLines: 0,truncated: false,};}++function describeImage(file: MediaMetadata): string {+ const size = `${file.size} bytes`;+ return file.width === undefined ? size : `${file.width}x${file.height} pixels, ${size}`;+}diff --git a/packages/eve/src/execution/session/turn-step.test.ts b/packages/eve/src/execution/session/turn-step.test.tsindex 804942028..5b3ac9fdf 100644--- a/packages/eve/src/execution/session/turn-step.test.ts+++ b/packages/eve/src/execution/session/turn-step.test.ts@@ -82,6 +82,9 @@ import type { TurnStepInput, TurnStepPayload } from "#execution/session/turn-steimport type { DeliverHookPayload } from "#channel/types.js";import type { RuntimeActionResult } from "#shared/action-types.js";import { setEveAttributes } from "#runtime/attributes/emit.js";+import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";+import { isSandboxRefUrl } from "#internal/attachments/sandbox-refs.js";+import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";type LegacyStepPayload =| DeliverHookPayload@@ -123,6 +126,12 @@ const REQUEST_EVENT = { sequence: 0, stepIndex: 0, turnId: "turn_0" };// be written; the attribute contract is covered by emit.test.ts.vi.mock("#runtime/attributes/emit.js", () => ({ setEveAttributes: vi.fn(async () => {}) }));+// Real by default; a test hands a session a mock sandbox with `mockResolvedValueOnce`.+vi.mock("#execution/sandbox/ensure.js", async (importOriginal) => {+ const actual = await importOriginal<typeof import("#execution/sandbox/ensure.js")>();+ return { ...actual, ensureSandboxAccess: vi.fn(actual.ensureSandboxAccess) };+});+const bindSessionInstrumentationSpy = vi.hoisted(() => vi.fn());/** When set, `bindSessionInstrumentation` binds this runtime instead of the global one. */const instrumentationRuntimeOverride = vi.hoisted(() => ({@@ -278,6 +287,9 @@ function createTurnStepTestBundle(modelCallsPerStep?: number) {const threadContextAdapter: ChannelAdapter = {kind: "thread-context",+ async fetchFile() {+ return Buffer.from("diagram-bytes");+ },deliver(payload: DeliverPayload, adapterCtx: ChannelAdapterContext) {if (typeof payload.message === "string" && payload.message.startsWith("seed:")) {adapterCtx.ctx.set(ThreadKey, payload.message.slice(5));@@ -2043,39 +2055,19 @@ describe("turnStep", () => {]);});- it("preserves a cancelled turn message that carries an attachment", async () => {+ // #3419: a cancellation at step entry lands before the framework providers exist.+ it("stages the attachment of a turn cancelled before its first model call", async () => {const session = createStubSession();installSessionStoreMocks([session]);- vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({- adapterRegistry: {- adaptersByKind: new Map([[threadContextAdapter.kind, threadContextAdapter]]),- },- compiledArtifactsSource: {},- graph: {- nodesByNodeId: new Map(),- root: {- sandboxRegistry: { sandbox: null },- turnAgent: TestTurnAgent,- },- },- moduleMap: { nodes: {} },- hookRegistry: createRuntimeHookRegistry([]),- resolvedAgent: { config: {} },- subagentRegistry: {},- toolRegistry: {},- turnAgent: TestTurnAgent,- } as never);- vi.mocked(createExecutionNodeStep).mockImplementation(() => {- return async (): Promise<StepResult> => {- throw new TurnCancelledError();- };- });+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(createTurnStepTestBundle());+ const sandbox = mockSandbox({ id: "sbx_cancelled" });+ vi.mocked(ensureSandboxAccess).mockResolvedValueOnce(sandbox.access as never);+ const controller = new AbortController();+ controller.abort(new TurnCancelledError());const result = await turnStep({- input: {- kind: "deliver",- payloads: [{ message: "attach:look at this" }],- },+ abortSignal: controller.signal,+ input: { kind: "deliver", payloads: [{ message: "attach:look at this" }] },sessionWritable: createTestWritable(),serializedContext: createSerializedContext(),sessionState: createStubSessionState(),@@ -2086,12 +2078,15 @@ describe("turnStep", () => {{content: [{ text: "thread=unset; user=look at this", type: "text" },- expect.objectContaining({ filename: "diagram.png", type: "file" }),+ expect.objectContaining({ data: expect.any(URL), type: "file" }),],kind: "user",role: "user",},]);+ const [, file] = result.history[0]!.content as [unknown, { data: URL }];+ expect(isSandboxRefUrl(file.data)).toBe(true);+ expect(sandbox.writes).toHaveLength(1);});it("prepares the session trace boundary before instrumenting a first-turn delivery", async () => {diff --git a/packages/eve/src/execution/web-fetch/request.ts b/packages/eve/src/execution/web-fetch/request.tsindex 94a7b8d81..30c7b3533 100644--- a/packages/eve/src/execution/web-fetch/request.ts+++ b/packages/eve/src/execution/web-fetch/request.ts@@ -176,7 +176,7 @@ async function consumeResponse(response: Response, maxResponseSize: number): Proif (declaredLength !== undefined && declaredLength > maxResponseSize) {await cancelResponseBody(response);- throw createResponseTooLargeError();+ throw createResponseTooLargeError(maxResponseSize);}const body = await readBoundedBody(response, maxResponseSize);@@ -217,7 +217,7 @@ async function readBoundedBody(response: Response, maxResponseSize: number): ProbyteLength += value.byteLength;if (byteLength > maxResponseSize) {await reader.cancel();- throw createResponseTooLargeError();+ throw createResponseTooLargeError(maxResponseSize);}chunks.push(value);@@ -243,6 +243,6 @@ async function cancelResponseBody(response: Response): Promise<void> {}}-function createResponseTooLargeError(): Error {- return new Error("Response too large (exceeds 5 MB limit).");+function createResponseTooLargeError(maxResponseSize: number): Error {+ return new Error(`Response too large (exceeds ${maxResponseSize} bytes).`);}diff --git a/packages/eve/src/harness/attachment-staging.integration.test.ts b/packages/eve/src/harness/attachment-staging.integration.test.tsindex 9ad7ef35a..75a7c0b91 100644--- a/packages/eve/src/harness/attachment-staging.integration.test.ts+++ b/packages/eve/src/harness/attachment-staging.integration.test.ts@@ -1,4 +1,4 @@-import type { FilePart, UserContent } from "ai";+import type { FilePart, ModelMessage, ToolResultPart, UserContent } from "ai";import { describe, expect, it, vi } from "vitest";import type { ChannelAdapter, FetchFileResult } from "#channel/adapter.js";@@ -11,8 +11,13 @@ import {ATTACHMENTS_ROOT,hydrateSandboxAttachments,stageAttachmentsToSandbox,+ stageToolResultMedia,} from "#harness/attachment-staging.js";import { captureLogRecords } from "#internal/testing/log-records.js";+import { pngBytes } from "#internal/testing/media-fixtures.js";+import { requestPublicUrl } from "#execution/web-fetch/request.js";++vi.mock("#execution/web-fetch/request.js", () => ({ requestPublicUrl: vi.fn() }));/*** Integration coverage for {@link stageAttachmentsToSandbox}.@@ -72,11 +77,17 @@ describe("stageAttachmentsToSandbox (integration)", () => {expect(sandbox.writes).toHaveLength(0);});- it("returns the message unchanged when no SandboxKey is bound on the context", async () => {+ it("replaces each file with a note when no sandbox is bound, so history never keeps it", async () => {const runtime = await createTestRuntime();- const payload = Buffer.from("bytes", "utf8");const content: UserContent = [- { data: payload, filename: "orphan.txt", mediaType: "text/plain", type: "file" },+ { type: "text", text: "see attached" },+ { data: Buffer.from("bytes"), filename: "orphan.txt", mediaType: "text/plain", type: "file" },+ {+ data: "eve-url:telegram-file:photo",+ filename: "photo.jpg",+ mediaType: "image/jpeg",+ type: "file",+ },];// `runAsSession` without a sandbox argument leaves SandboxKey unbound.@@ -84,7 +95,32 @@ describe("stageAttachmentsToSandbox (integration)", () => {stageAttachmentsToSandbox(content),);- expect(staged).toBe(content);+ expect(staged).toEqual([+ { type: "text", text: "see attached" },+ { text: "Attachment orphan.txt could not be stored: no sandbox is available.", type: "text" },+ { text: "Attachment photo.jpg could not be stored: no sandbox is available.", type: "text" },+ ]);+ });++ it("replaces data that is not bytes, base64, or a URL with a note", async () => {+ const sandbox = mockSandbox({ id: "sbx_unreadable" });+ const runtime = await createTestRuntime();+ // A Uint8Array that crossed a JSON boundary arrives as a plain object.+ const content: UserContent = [+ {+ data: { 0: 1, 1: 2 } as never,+ filename: "photo.png",+ mediaType: "image/png",+ type: "file",+ },+ ];++ const staged = await runtime.runAsSession({ sandbox }, async () =>+ stageAttachmentsToSandbox(content),+ );++ expect(staged).toEqual([{ text: "Attachment photo.png could not be read.", type: "text" }]);+ expect(sandbox.writes).toHaveLength(0);});it("dedupes repeated uploads of the same payload within one session", async () => {@@ -167,8 +203,54 @@ describe("stageAttachmentsToSandbox (integration)", () => {expect(written.equals(resolvedBytes)).toBe(true);});+ it("hands a string with any scheme to fetchFile instead of decoding it as base64", async () => {+ const urls: string[] = [];+ const adapter: ChannelAdapter<any> = {+ async fetchFile(url) {+ urls.push(url);+ return Buffer.from("stored-upload");+ },+ kind: "custom-channel",+ state: {},+ };+ const sandbox = mockSandbox({ id: "sbx_custom_scheme" });+ const runtime = await createTestRuntime();+ const content: UserContent = [+ { data: "myapp-file:abc", filename: "upload.txt", mediaType: "text/plain", type: "file" },+ ];++ const staged = (await runtime.runAsSession({ channel: adapter, sandbox }, async () =>+ stageAttachmentsToSandbox(content),+ )) as UserContent;++ expect(urls).toEqual(["myapp-file:abc"]);+ expect(decodeSandboxRef((staged[0] as FilePart).data as URL).size).toBe(+ Buffer.byteLength("stored-upload"),+ );+ });++ it("turns a link with a scheme no channel resolves into a note", async () => {+ const sandbox = mockSandbox({ id: "sbx_unknown_scheme" });+ const runtime = await createTestRuntime();+ const content: UserContent = [+ { data: "myapp-file:abc", filename: "upload.txt", mediaType: "text/plain", type: "file" },+ ];++ const staged = await runtime.runAsSession({ sandbox }, async () =>+ stageAttachmentsToSandbox(content),+ );++ expect(staged).toEqual([+ {+ text: expect.stringMatching(/^Attachment upload\.txt could not be retrieved/),+ type: "text",+ },+ ]);+ expect(sandbox.writes).toHaveLength(0);+ });+it("refines FilePart.mediaType when fetchFile returns a FetchFileResult", async () => {- const resolvedBytes = Buffer.from("PNGDATA", "utf8");+ const resolvedBytes = pngBytes(1, 1);const adapter: ChannelAdapter<any> = {async fetchFile() {const result: FetchFileResult = {@@ -228,24 +310,174 @@ describe("stageAttachmentsToSandbox (integration)", () => {expect(filePart.mediaType).toBe("text/csv");});- it("passes URL FileParts through unchanged when the active adapter has no fetchFile function", async () => {+ it("downloads a link no channel resolver claims, so the provider never fetches it", async () => {+ vi.mocked(requestPublicUrl).mockResolvedValueOnce(+ new Response(pngBytes(1, 1), { headers: { "content-type": "image/png" } }),+ );const adapter: ChannelAdapter<any> = { kind: "custom-channel", state: {} };- const fileUrl = new URL("https://example.com/a.bin");- const sandbox = mockSandbox({ id: "sbx_no_resolver" });+ const sandbox = mockSandbox({ id: "sbx_public_link" });const runtime = await createTestRuntime();const content: UserContent = [- { data: fileUrl, filename: "a.bin", mediaType: "application/octet-stream", type: "file" },+ {+ data: new URL("https://example.com/a.bin"),+ filename: "a.bin",+ mediaType: "application/octet-stream",+ type: "file",+ },];const staged = (await runtime.runAsSession({ channel: adapter, sandbox }, async () =>stageAttachmentsToSandbox(content),)) as UserContent;- // Without fetchFile, URL FileParts pass through for the model- // provider to handle directly.+ expect(vi.mocked(requestPublicUrl)).toHaveBeenCalledWith(+ "https://example.com/a.bin",+ expect.objectContaining({ maxResponseSize: 25 * 1024 * 1024 }),+ );const filePart = staged[0] as FilePart;- expect(filePart.data).toBeInstanceOf(URL);- expect((filePart.data as URL).href).toBe("https://example.com/a.bin");+ expect(isSandboxRefUrl(filePart.data)).toBe(true);+ expect(filePart.mediaType).toBe("image/png");+ });++ it("turns a link eve can't download into a note", async () => {+ const sandbox = mockSandbox({ id: "sbx_bad_link" });+ const runtime = await createTestRuntime();+ vi.mocked(requestPublicUrl)+ .mockResolvedValueOnce(new Response("missing", { status: 404 }))+ .mockResolvedValueOnce(+ new Response("<html>sign in</html>", { headers: { "content-type": "text/html" } }),+ )+ .mockRejectedValueOnce(new Error("URL must not target localhost"));+ const link = (data: string, filename: string): FilePart => ({+ data,+ filename,+ mediaType: "application/pdf",+ type: "file",+ });++ const staged = await runtime.runAsSession({ sandbox }, async () =>+ stageAttachmentsToSandbox([+ link("http://example.com/plain.pdf", "plain.pdf"),+ link("https://example.com/gone.pdf", "gone.pdf"),+ link("https://docs.example.com/d/1", "doc.pdf"),+ link("https://127.0.0.1/internal.pdf", "internal.pdf"),+ ]),+ );++ expect(staged).toEqual([+ {+ text: "Attachment plain.pdf could not be retrieved: eve downloads only public https:// links.",+ type: "text",+ },+ {+ text: "Attachment gone.pdf could not be retrieved: The link returned HTTP 404.",+ type: "text",+ },+ {+ text: "Attachment doc.pdf could not be retrieved: The link returned a web page instead of a file.",+ type: "text",+ },+ {+ text: "Attachment internal.pdf could not be retrieved: The link could not be downloaded.",+ type: "text",+ },+ ]);+ expect(sandbox.writes).toHaveLength(0);+ });++ it("downloads at most 10 links per message, one at a time", async () => {+ let inFlight = 0;+ let maxInFlight = 0;+ vi.mocked(requestPublicUrl).mockImplementation(async () => {+ maxInFlight = Math.max(maxInFlight, ++inFlight);+ await new Promise((resolve) => setTimeout(resolve, 1));+ inFlight -= 1;+ return new Response("bytes", { headers: { "content-type": "text/plain" } });+ });+ const sandbox = mockSandbox({ id: "sbx_download_budget" });+ const runtime = await createTestRuntime();+ const content: UserContent = Array.from({ length: 12 }, (_, index) => ({+ data: `https://example.com/${index}.txt`,+ filename: `${index}.txt`,+ mediaType: "text/plain",+ type: "file" as const,+ }));++ const staged = (await runtime.runAsSession({ sandbox }, async () =>+ stageAttachmentsToSandbox(content),+ )) as Exclude<UserContent, string>;+ vi.mocked(requestPublicUrl).mockReset();++ expect(staged.filter((part) => part.type === "file")).toHaveLength(10);+ expect(staged.slice(10)).toEqual([+ {+ text: "Attachment 10.txt could not be retrieved: eve downloads at most 10 links per message.",+ type: "text",+ },+ {+ text: "Attachment 11.txt could not be retrieved: eve downloads at most 10 links per message.",+ type: "text",+ },+ ]);+ expect(maxInFlight).toBe(1);+ });++ it("holds every staged file to the channel's upload policy, on its bytes and verified type", async () => {+ vi.mocked(requestPublicUrl).mockResolvedValueOnce(+ new Response("a much larger file", { headers: { "content-type": "text/plain" } }),+ );+ const adapter: ChannelAdapter<any> = {+ kind: "custom-channel",+ state: {},+ uploadPolicy: { allowedMediaTypes: ["application/pdf", "text/*"], maxBytes: 64 },+ };+ const sandbox = mockSandbox({ id: "sbx_policy" });+ const runtime = await createTestRuntime();+ const content: UserContent = [+ {+ data: "https://example.com/notes.txt",+ filename: "notes.txt",+ mediaType: "text/plain",+ type: "file",+ },+ // Declared as an allowed PDF, but the bytes are a PNG.+ { data: pngBytes(1, 1), filename: "scan.pdf", mediaType: "application/pdf", type: "file" },+ { data: Buffer.alloc(65, 0x41), filename: "big.txt", mediaType: "text/plain", type: "file" },+ ];++ const staged = await runtime.runAsSession({ channel: adapter, sandbox }, async () =>+ stageAttachmentsToSandbox(content),+ );++ expect(vi.mocked(requestPublicUrl)).toHaveBeenCalledWith(+ "https://example.com/notes.txt",+ expect.objectContaining({ maxResponseSize: 64 }),+ );+ expect((staged as Exclude<UserContent, string>).slice(1)).toEqual([+ {+ text: "Attachment scan.pdf was not accepted: this channel doesn't accept image/png files.",+ type: "text",+ },+ {+ text: "Attachment big.txt was not accepted: it is 65 bytes, over this channel's 64-byte upload limit.",+ type: "text",+ },+ ]);+ expect(sandbox.writes).toHaveLength(1);+ });++ it("leaves a provider file reference for the provider to resolve", async () => {+ const sandbox = mockSandbox({ id: "sbx_reference" });+ const runtime = await createTestRuntime();+ const content: UserContent = [+ { data: { openai: "file-abc" }, mediaType: "application/pdf", type: "file" },+ ];++ const staged = await runtime.runAsSession({ sandbox }, async () =>+ stageAttachmentsToSandbox(content),+ );++ expect(staged).toEqual(content);expect(sandbox.writes).toHaveLength(0);});@@ -411,13 +643,10 @@ describe("stageAttachmentsToSandbox (integration)", () => {});describe("hydrateSandboxAttachments (integration)", () => {- // 1 KiB of PNG-like bytes. Small enough to fall under the image- // inline-cap, arbitrary enough that the byte-equality assertion- // catches any corruption on the sandbox round trip.- const smallImageBytes = Buffer.alloc(1024, 0x89);- // 1 KiB of PDF-like bytes. Small enough to fall under the PDF- // inline-cap.- const smallPdfBytes = Buffer.alloc(1024, 0x25);+ // A small PNG and PDF under the inline caps; the byte-equality assertions+ // catch any corruption on the sandbox round trip.+ const smallImageBytes = pngBytes(32, 32, 1024);+ const smallPdfBytes = pdfBytes(1024);it("hydrates small images inline as bytes — provider consumes them multimodally", async () => {const sandbox = mockSandbox({ id: "sbx_hydrate_image" });@@ -455,6 +684,12 @@ describe("hydrateSandboxAttachments (integration)", () => {expect(hydratedFilePart.filename).toMatch(/^\/workspace\/\.eve\/attachments\/[0-9a-f]{16}\/logo\.png$/,);+ // A label naming the sandbox path precedes the bytes.+ expect(hydratedContent).toEqual([+ { type: "text", text: "describe the image" },+ { text: `Attached file ${hydratedFilePart.filename} (image/png)`, type: "text" },+ hydratedFilePart,+ ]);});it("hydrates small PDFs inline as bytes — provider handles them natively", async () => {@@ -523,7 +758,7 @@ describe("hydrateSandboxAttachments (integration)", () => {const runtime = await createTestRuntime();// One byte over the 3 MiB cap so the ref size fails the inline// check without allocating two massive buffers in the test.- const oversizedImage = Buffer.alloc(3 * 1024 * 1024 + 1, 0x89);+ const oversizedImage = pngBytes(32, 32, 3 * 1024 * 1024 + 1);const stagedContent = (await runtime.runAsSession({ sandbox }, async () =>stageAttachmentsToSandbox([@@ -549,7 +784,7 @@ describe("hydrateSandboxAttachments (integration)", () => {it("treats oversized PDFs (>20 MiB) as non-inlinable — renders a text reference instead of bytes", async () => {const sandbox = mockSandbox({ id: "sbx_hydrate_big_pdf" });const runtime = await createTestRuntime();- const oversizedPdf = Buffer.alloc(20 * 1024 * 1024 + 1, 0x25);+ const oversizedPdf = pdfBytes(20 * 1024 * 1024 + 1);const stagedContent = (await runtime.runAsSession({ sandbox }, async () =>stageAttachmentsToSandbox([@@ -608,6 +843,138 @@ describe("hydrateSandboxAttachments (integration)", () => {});});+ it("inlines only images whose bytes prove a format every provider reads", async () => {+ const sandbox = mockSandbox({ id: "sbx_verified_media" });+ const runtime = await createTestRuntime();++ const staged = (await runtime.runAsSession({ sandbox }, async () =>+ stageAttachmentsToSandbox([+ {+ data: Buffer.from("not a png"),+ filename: "fake.png",+ mediaType: "image/png",+ type: "file",+ },+ {+ data: Buffer.from("ftypheic"),+ filename: "photo.heic",+ mediaType: "image/heic",+ type: "file",+ },+ { data: pngBytes(8001, 10), filename: "wide.png", mediaType: "image/png", type: "file" },+ { data: pngBytes(4, 4), filename: "real.jpg", mediaType: "image/jpeg", type: "file" },+ ] as UserContent),+ )) as FilePart[];+ const hydrated = await runtime.runAsSession({ sandbox }, async () =>+ hydrateSandboxAttachments([{ content: staged, role: "user" }]),+ );++ expect(staged.map((part) => part.mediaType)).toEqual([+ "application/octet-stream",+ "image/heic",+ "image/png",+ "image/png",+ ]);+ expect(hydrated[0]?.content).toEqual([+ { text: `Attached file ${staged[0]!.filename} (application/octet-stream)`, type: "text" },+ { text: `Attached file ${staged[1]!.filename} (image/heic)`, type: "text" },+ { text: `Attached file ${staged[2]!.filename} (image/png)`, type: "text" },+ { text: `Attached file ${staged[3]!.filename} (image/png)`, type: "text" },+ expect.objectContaining({ mediaType: "image/png", type: "file" }),+ ]);+ });++ it("applies the same rule to files a tool returns", async () => {+ const sandbox = mockSandbox({ id: "sbx_tool_gate" });+ const runtime = await createTestRuntime();+ const file = (data: Buffer, filename: string, mediaType = "image/png") => ({+ data: { data: data.toString("base64"), type: "data" as const },+ filename,+ mediaType,+ type: "file" as const,+ });+ const messages: ModelMessage[] = [+ {+ content: [+ {+ output: {+ type: "content",+ value: [+ file(pngBytes(9000, 9000), "huge.png"),+ file(pngBytes(8, 8), "shot.png"),+ file(pngBytes(8, 8), "mislabeled.jpg", "image/jpeg"),+ ],+ },+ toolCallId: "shot-1",+ toolName: "screenshot",+ type: "tool-result",+ },+ ],+ role: "tool",+ },+ ];++ const hydrated = await runtime.runAsSession({ sandbox }, async () =>+ hydrateSandboxAttachments(await stageToolResultMedia(messages)),+ );++ const [result] = hydrated[0]!.content as ToolResultPart[];+ expect(result!.output).toEqual({+ type: "content",+ value: [+ {+ text: expect.stringMatching(/^Attached file .*\/huge\.png \(image\/png\)$/),+ type: "text",+ },+ {+ text: expect.stringMatching(/^Attached file .*\/shot\.png \(image\/png\)$/),+ type: "text",+ },+ expect.objectContaining({ filename: "shot.png", type: "file" }),+ {+ text: expect.stringMatching(/^Attached file .*\/mislabeled\.jpg \(image\/png\)$/),+ type: "text",+ },+ // The bytes go to the provider under the type they prove.+ expect.objectContaining({ filename: "mislabeled.jpg", mediaType: "image/png" }),+ ],+ });+ });++ it("renders a link or eve-url marker left in history by an older release as a note", async () => {+ const runtime = await createTestRuntime();+ const messages: ModelMessage[] = [+ {+ content: [+ { text: "what is in these?", type: "text" },+ {+ data: new URL("https://docs.example.com/d/1"),+ filename: "sheet.pdf",+ mediaType: "application/pdf",+ type: "file",+ },+ {+ data: "eve-url:telegram-file:photo",+ filename: "photo.jpg",+ mediaType: "image/jpeg",+ type: "file",+ },+ ],+ role: "user",+ },+ ];++ const hydrated = await runtime.runAsSession(undefined, async () =>+ hydrateSandboxAttachments(messages),+ );++ expect(hydrated[0]?.content).toEqual([+ { text: "what is in these?", type: "text" },+ { text: "Attachment sheet.pdf could not be retrieved.", type: "text" },+ { text: "Attachment photo.jpg could not be retrieved.", type: "text" },+ ]);+ });+it("returns the input array unchanged (no allocation) when no messages contain sandbox refs", async () => {const sandbox = mockSandbox({ id: "sbx_noop" });const runtime = await createTestRuntime();@@ -739,18 +1106,16 @@ describe("hydrateSandboxAttachments (integration)", () => {const stagedContent = (await runtime.runAsSession({ sandbox }, async () =>stageAttachmentsToSandbox([- {- data: Buffer.from("original"),- filename: "logo.png",- mediaType: "image/png",- type: "file",- },+ { data: smallImageBytes, filename: "logo.png", mediaType: "image/png", type: "file" },] as UserContent),)) as UserContent;const stagedPath = (stagedContent[0] as FilePart).filename as string;// Same size, different bytes: only the content address can tell them apart.- await sandbox.session.writeBinaryFile({ content: Buffer.from("replaced"), path: stagedPath });+ await sandbox.session.writeBinaryFile({+ content: Buffer.alloc(smallImageBytes.byteLength, 0x41),+ path: stagedPath,+ });const messages = [{ content: stagedContent, role: "user" as const }];const hydrated = await runtime.runAsSession({ sandbox }, async () =>@@ -792,3 +1157,7 @@ describe("hydrateSandboxAttachments (integration)", () => {}});});++function pdfBytes(paddingBytes: number): Buffer {+ return Buffer.concat([Buffer.from("%PDF-1.4\n"), Buffer.alloc(paddingBytes, 0x25)]);+}diff --git a/packages/eve/src/harness/attachment-staging.test.ts b/packages/eve/src/harness/attachment-staging.test.tsindex 645a75e17..4f0ff4aae 100644--- a/packages/eve/src/harness/attachment-staging.test.ts+++ b/packages/eve/src/harness/attachment-staging.test.ts@@ -210,30 +210,6 @@ describe("stageAttachmentsForAdapter", () => {expect(written.toString("utf8")).toBe(payload);});- it("leaves remote URL parts unchanged — the provider fetches them at call time", async () => {- const sandbox = mockSandbox();- const content: UserContent = [- {- data: new URL("https://example.com/chart.png"),- filename: "chart.png",- mediaType: "image/png",- type: "file",- },- ];-- const staged = (await stageAttachmentsForAdapter(- content,- sandbox.session,- STUB_ADAPTER_CTX,- )) as UserContent;- const filePart = staged[0] as FilePart;-- expect(filePart.filename).toBe("chart.png");- expect(filePart.data).toBeInstanceOf(URL);- expect((filePart.data as URL).protocol).toBe("https:");- expect(sandbox.writes).toHaveLength(0);- });-it("passes already-staged eve-sandbox: ref parts through unchanged (idempotent)", async () => {const sandbox = mockSandbox();const existingRef = new URL(diff --git a/packages/eve/src/harness/attachment-staging.ts b/packages/eve/src/harness/attachment-staging.tsindex 9bf0ae215..cb7d8d121 100644--- a/packages/eve/src/harness/attachment-staging.ts+++ b/packages/eve/src/harness/attachment-staging.ts@@ -10,10 +10,17 @@ import { contextStorage, loadContext } from "#context/container.js";import { SandboxKey } from "#context/keys.js";import { createFrameworkUserMessage } from "#harness/messages.js";import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";-import { fileDataToBytes } from "#internal/attachments/data.js";+import { isUnresolvedFileData, readFileData } from "#internal/attachments/data.js";import { EveAttachmentError } from "#internal/attachments/errors.js";import { createLogger } from "#internal/logging.js";-import { readMediaMetadata } from "#internal/attachments/media-metadata.js";+import { maxBytesOf } from "#internal/attachments/limited-read.js";+import { readMediaMetadata, verifyMediaType } from "#internal/attachments/media-metadata.js";+import {+ DEFAULT_UPLOAD_POLICY,+ isMediaTypeAllowed,+ type UploadPolicy,+} from "#public/channels/upload-policy.js";+import { createPublicDownloads, type PublicDownloads } from "#internal/attachments/public-link.js";import { deserializeUrlFilePart, isSerializedUrlFilePart } from "#internal/attachments/url-refs.js";import {decodeSandboxRef,@@ -55,10 +62,10 @@ type ToolOutputFilePart = Extract<ToolOutputContentPart, { type: "file" }>;/*** Writes inbound `FilePart` bytes into the sandbox and rewrites each- * staged part to a compact `eve-sandbox:` ref.- *- * Remote HTTP URLs pass through for provider-side fetches; existing- * `eve-sandbox:` refs pass through so staging is idempotent.+ * staged part to a compact `eve-sandbox:` ref. Links resolve through the+ * channel's `fetchFile` or eve's public download; a file eve can't stage+ * becomes a note. Existing `eve-sandbox:` refs pass through so staging is+ * idempotent.*/export async function stageAttachmentsForAdapter(content: string | UserContent,@@ -70,11 +77,13 @@ export async function stageAttachmentsForAdapter(}const reconstituted = reconstitueFilePartUrls(content);+ const policy = adapterCtx.ctx.get(ChannelKey)?.uploadPolicy;+ const downloads = createPublicDownloads(maxBytesOf(policy ?? DEFAULT_UPLOAD_POLICY));return Promise.all(reconstituted.map(async (part) => {if (part.type === "file") {- return stageFilePart(part, sandbox, adapterCtx);+ return stageFilePart(part, sandbox, adapterCtx, downloads, policy);}return part;}),@@ -82,8 +91,9 @@ export async function stageAttachmentsForAdapter(}/**- * Context-bound variant of {@link stageAttachmentsForAdapter}. Returns- * the input unchanged when there is no active sandbox or no file parts.+ * Context-bound variant of {@link stageAttachmentsForAdapter}. Without an+ * active sandbox, every file part becomes a note: history never keeps an+ * attachment eve did not stage.*/export async function stageAttachmentsToSandbox(message: string | UserContent,@@ -99,14 +109,15 @@ export async function stageAttachmentsToSandbox(}const container = loadContext();- const sandboxAccess = container.get(SandboxKey);- if (sandboxAccess === undefined) {- return message;- }-- const sandbox = await sandboxAccess.get();+ const sandbox = (await container.get(SandboxKey)?.get()) ?? null;if (sandbox === null) {- return message;+ return message.map((part) =>+ part.type === "file" &&+ !isSandboxRefUrl(part.data) &&+ readFileData(part.data).kind !== "reference"+ ? attachmentNote(part, "could not be stored: no sandbox is available.")+ : part,+ );}// Build the adapter context once up front. When an adapter is bound,@@ -131,8 +142,8 @@ export async function stageAttachmentsToSandbox(* Moves inline file payloads in `content` tool outputs into the sandbox and* leaves `eve-sandbox:` refs in their place, so durable history never* carries tool-result bytes. {@link hydrateSandboxAttachments} restores the- * bytes on every model call. Without an active sandbox, messages pass- * through unchanged.+ * bytes on every model call. Without an active sandbox, each file becomes a+ * note instead.*/export async function stageToolResultMedia<T extends ModelMessage>(messages: readonly T[],@@ -140,10 +151,7 @@ export async function stageToolResultMedia<T extends ModelMessage>(if (!messages.some(hasInlineToolResultFile)) {return [...messages];}- const sandbox = await contextStorage.getStore()?.get(SandboxKey)?.get();- if (sandbox === undefined || sandbox === null) {- return [...messages];- }+ const sandbox = (await contextStorage.getStore()?.get(SandboxKey)?.get()) ?? null;return Promise.all(messages.map(async (message) => {if (message.role !== "tool" || !hasInlineToolResultFile(message)) {@@ -164,18 +172,19 @@ export async function stageToolResultMedia<T extends ModelMessage>(/*** Hydrates `eve-sandbox:` file refs for a single model call.*- * Tool-result refs always hydrate as bytes: the tool chose to show them to- * the model. Inbound attachments inline small images and PDFs; larger or- * unsupported files become text references to their sandbox path. Every+ * Every attachment, inbound or returned by a tool, renders as a label naming+ * its sandbox path. Small verified images and PDFs follow their label as+ * bytes; anything else stays a label the agent can open with tools. Every* decision is pure in the ref, so each message renders identically on every* call and the provider's prompt cache stays valid. The returned messages* must not be written back to session history, which stays ref-only.*/export async function hydrateSandboxAttachments(- messages: readonly ModelMessage[],+ input: readonly ModelMessage[],): Promise<ModelMessage[]> {+ const messages = replaceUnresolvedFileParts(input);if (!messagesContainSandboxRef(messages)) {- return messages as ModelMessage[];+ return messages;}const sandboxAccess = loadContext().get(SandboxKey);@@ -204,6 +213,29 @@ export async function hydrateSandboxAttachments();}+/**+ * History written before eve resolved every attachment can still hold a link+ * or an `eve-url:` marker that a provider would try to fetch on every call.+ * Each renders as a note, so such a session recovers.+ */+function replaceUnresolvedFileParts(messages: readonly ModelMessage[]): ModelMessage[] {+ let changed = false;+ const result = messages.map((message) => {+ if (message.role !== "user" || !Array.isArray(message.content)) return message;+ if (!message.content.some(isUnresolvedFilePart)) return message;+ changed = true;+ const content = message.content.map((part) =>+ isUnresolvedFilePart(part) ? attachmentNote(part, "could not be retrieved.") : part,+ );+ return { ...message, content };+ });+ return changed ? result : (messages as ModelMessage[]);+}++function isUnresolvedFilePart(part: Exclude<UserContent, string>[number]): part is FilePart {+ return part.type === "file" && !isSandboxRefUrl(part.data) && isUnresolvedFileData(part.data);+}+function hasFileParts(content: Exclude<UserContent, string>): boolean {for (const part of content) {if (part.type === "file") {@@ -262,18 +294,28 @@ function isToolOutputRefFile(part: ToolOutputContentPart): part is ToolOutputFilasync function stageToolOutputFiles(output: ToolResultOutput,- sandbox: SandboxSession,+ sandbox: SandboxSession | null,): Promise<ToolResultOutput> {if (output.type !== "content" || !output.value.some(isInlineToolOutputFile)) {return output;}const value = await Promise.all(- output.value.map(async (part) => {+ output.value.map(async (part): Promise<ToolOutputContentPart> => {if (!isInlineToolOutputFile(part) || part.data.type !== "data") return part;- const bytes = await fileDataToBytes(part.data.data);- if (bytes === null) return part;- const ref = await writeSandboxRef(bytes, part.mediaType, part.filename, sandbox);- return { ...part, data: { type: "url" as const, url: encodeSandboxRef(ref) } };+ const data = readFileData(part.data.data);+ if (data.kind === "link") return part;+ if (sandbox === null || data.kind !== "bytes") {+ return {+ text: `Returned file ${part.filename ?? "file"} (${part.mediaType}) could not be stored.`,+ type: "text",+ };+ }+ const ref = await writeSandboxRef(data.bytes, part.mediaType, part.filename, sandbox);+ return {+ ...part,+ data: { type: "url" as const, url: encodeSandboxRef(ref) },+ mediaType: ref.mediaType,+ };}),);return { ...output, value };@@ -301,25 +343,27 @@ async function hydrateMessageContent(content: unknown, sandbox: SandboxSession):if (!Array.isArray(content)) {return content;}- return Promise.all(- content.map(async (part) => {+ const hydrated = await Promise.all(+ content.map(async (part): Promise<unknown[]> => {if (isSandboxRefFilePart(part)) {const ref = decodeSandboxRef(part.data as URL);+ const label = renderSandboxRefAsTextPart(ref);if (!inlinesSandboxRefAsBytes(ref)) {- return renderSandboxRefAsTextPart(ref);+ return [label];}const bytes = await readSandboxRefBytes(ref, sandbox);return bytes === null- ? renderMissingSandboxRef(ref)- : { ...part, data: bytes, mediaType: ref.mediaType };+ ? [renderMissingSandboxRef(ref)]+ : [label, { ...part, data: bytes, mediaType: ref.mediaType }];}if ((part as { type?: unknown }).type === "tool-result") {const toolResult = part as ToolResultPart;- return { ...toolResult, output: await hydrateToolOutput(toolResult.output, sandbox) };+ return [{ ...toolResult, output: await hydrateToolOutput(toolResult.output, sandbox) }];}- return part;+ return [part];}),);+ return hydrated.flat();}async function hydrateToolOutput(@@ -330,18 +374,20 @@ async function hydrateToolOutput(return output;}const value = await Promise.all(- output.value.map(async (part): Promise<ToolOutputContentPart> => {- if (!isToolOutputRefFile(part) || part.data.type !== "url") return part;+ output.value.map(async (part): Promise<ToolOutputContentPart[]> => {+ if (!isToolOutputRefFile(part) || part.data.type !== "url") return [part];const ref = decodeSandboxRef(part.data.url);+ const label = renderSandboxRefAsTextPart(ref);+ if (!inlinesSandboxRefAsBytes(ref)) return [label];const bytes = await readSandboxRefBytes(ref, sandbox);- if (bytes === null) return renderMissingSandboxRef(ref);- return {- ...part,- data: { data: Buffer.from(bytes).toString("base64"), type: "data" },- };+ if (bytes === null) return [renderMissingSandboxRef(ref)];+ return [+ label,+ { ...part, data: { data: Buffer.from(bytes).toString("base64"), type: "data" } },+ ];}),);- return { ...output, value };+ return { ...output, value: value.flat() };}async function readSandboxRefBytes(@@ -428,8 +474,9 @@ function createReturnedFilesMessage(files: readonly FilePart[]): ModelMessage {}/**- * Renders a sandbox-resident attachment as a {@link TextPart} the model- * can use to reach the payload through filesystem tools.+ * Labels a sandbox-resident attachment with a {@link TextPart} the model can+ * use to reach the payload through filesystem tools, whether or not the+ * bytes follow.** Matches the text shape produced by the compaction summarizer for* `FilePart`s so the model sees one consistent surface for "there is a@@ -444,100 +491,139 @@ async function stageFilePart(part: FilePart,sandbox: SandboxSession,adapterCtx: ChannelAdapterContext,+ downloads: PublicDownloads,+ policy: UploadPolicy | undefined,): Promise<FilePart | TextPart> {if (isSandboxRefUrl(part.data)) {return part;}- // URL objects (including reconstituted ones) → try fetchFile- if (part.data instanceof URL && part.data.protocol !== "data:") {- let resolved: FetchFileResult | null;- try {- resolved = await tryFetchFile(part.data.href, adapterCtx);- } catch (error) {- if (!(error instanceof EveAttachmentError)) throw error;- const filename = part.filename?.trim() || "file";- log.warn("attachment resolver failed — degrading to text part", {- adapterKind: error.adapterKind,- error: error.cause,- filename,- kind: error.kind,- });- return {- text: `Attachment ${filename} could not be retrieved: ${error.message}`,- type: "text",- };- }- if (resolved === null) {- return part;- }- return stageResolvedBytes(part, resolved, sandbox);+ const data = readFileData(part.data);+ if (data.kind === "bytes") {+ return stageResolvedBytes(part, { bytes: data.bytes }, sandbox, policy);}-- // Inline data (Buffer, base64, data URL) → stage directly- const bytes = await fileDataToBytes(part.data);- if (bytes === null) {+ // The provider already holds a referenced file.+ if (data.kind === "reference") {return part;}- return stageResolvedBytes(part, { bytes }, sandbox);+ if (data.kind === "unreadable") {+ log.warn("attachment data is not bytes, base64, or a URL — degrading to text part", {+ filename: part.filename,+ mediaType: part.mediaType,+ });+ return attachmentNote(part, "could not be read.");+ }++ let resolved: FetchFileResult;+ try {+ resolved = await resolveLink(data.url, adapterCtx, downloads);+ } catch (error) {+ if (!(error instanceof EveAttachmentError)) throw error;+ log.warn("attachment resolver failed — degrading to text part", {+ adapterKind: error.adapterKind,+ error: error.cause,+ filename: part.filename,+ kind: error.kind,+ });+ return attachmentNote(part, `could not be retrieved: ${error.message}`);+ }+ return stageResolvedBytes(part, resolved, sandbox, policy);}+/** A model-visible note that stands in for an attachment eve could not stage. */+function attachmentNote(part: FilePart, outcome: string): TextPart {+ return { text: `Attachment ${part.filename?.trim() || "file"} ${outcome}`, type: "text" };+}++/**+ * Stages resolved bytes, or a note when they break the channel's upload+ * policy. A link's size is unknown until it downloads, and only the bytes+ * prove the media type, so the policy runs here as well as at the route.+ */async function stageResolvedBytes(part: FilePart,resolved: FetchFileResult,sandbox: SandboxSession,-): Promise<FilePart> {- const mediaType = resolved.mediaType ?? part.mediaType ?? DEFAULT_MEDIA_TYPE;+ policy: UploadPolicy | undefined,+): Promise<FilePart | TextPart> {+ const mediaType = verifyMediaType(+ resolved.bytes,+ resolved.mediaType ?? part.mediaType ?? DEFAULT_MEDIA_TYPE,+ );+ if (policy !== undefined) {+ const limit = maxBytesOf(policy);+ if (resolved.bytes.byteLength > limit) {+ return attachmentNote(+ part,+ `was not accepted: it is ${resolved.bytes.byteLength} bytes, over this channel's ${limit}-byte upload limit.`,+ );+ }+ if (!isMediaTypeAllowed(mediaType, policy)) {+ return attachmentNote(+ part,+ `was not accepted: this channel doesn't accept ${mediaType} files.`,+ );+ }+ }const ref = await writeSandboxRef(resolved.bytes,mediaType,resolved.filename ?? part.filename,sandbox,);- return { ...part, data: encodeSandboxRef(ref), filename: ref.path, mediaType };+ return { ...part, data: encodeSandboxRef(ref), filename: ref.path, mediaType: ref.mediaType };}-/** Writes content-addressed bytes under {@link ATTACHMENTS_ROOT} and describes them as a ref. */+/**+ * Writes content-addressed bytes under {@link ATTACHMENTS_ROOT} and describes+ * them as a ref whose media type the bytes confirm.+ */async function writeSandboxRef(bytes: Buffer,- mediaType: string,+ declaredMediaType: string,filename: string | undefined,sandbox: SandboxSession,): Promise<SandboxRef> {+ const mediaType = verifyMediaType(bytes, declaredMediaType);const sha = sha256Prefix(bytes);const authored = `${ATTACHMENTS_ROOT}/${sha}/${safeFilename(filename, sha, mediaType)}`;await sandbox.writeBinaryFile({ content: bytes, path: authored });return { ...readMediaMetadata(bytes, mediaType), path: sandbox.resolvePath(authored) };}-async function tryFetchFile(- url: string,+/**+ * Resolves a link through the channel's `fetchFile`. When the channel has none+ * or returns `null`, eve downloads a public `https:` link itself; a provider+ * never fetches an attachment.+ */+async function resolveLink(+ url: URL,adapterCtx: ChannelAdapterContext,-): Promise<FetchFileResult | null> {+ downloads: PublicDownloads,+): Promise<FetchFileResult> {const adapter = adapterCtx.ctx.get(ChannelKey);- if (adapter?.fetchFile === undefined) {- return null;- }+ const adapterKind = adapter === undefined ? "none" : getAdapterKind(adapter);- const adapterKind = getAdapterKind(adapter);-- try {- const result = await adapter.fetchFile(url, adapterCtx);- if (result === null) {- return null;+ if (adapter?.fetchFile !== undefined) {+ let result: Awaited<ReturnType<NonNullable<typeof adapter.fetchFile>>>;+ try {+ result = await adapter.fetchFile(url.href, adapterCtx);+ } catch (cause) {+ if (cause instanceof EveAttachmentError) {+ throw cause;+ }+ throw new EveAttachmentError({+ adapterKind,+ cause,+ kind: "resolver-threw",+ message: `Attachment retrieval failed in the "${adapterKind}" channel.`,+ });}- return Buffer.isBuffer(result) ? { bytes: result } : result;- } catch (cause) {- if (cause instanceof EveAttachmentError) {- throw cause;+ if (result !== null) {+ return Buffer.isBuffer(result) ? { bytes: result } : result;}- throw new EveAttachmentError({- adapterKind,- cause,- kind: "resolver-threw",- message: `Attachment retrieval failed in the "${adapterKind}" channel.`,- });}+ return downloads(url, adapterKind);}/**diff --git a/packages/eve/src/harness/token-estimate.ts b/packages/eve/src/harness/token-estimate.tsindex 5aa5a5f5c..c5e8663eb 100644--- a/packages/eve/src/harness/token-estimate.ts+++ b/packages/eve/src/harness/token-estimate.ts@@ -65,11 +65,7 @@ function estimateFilePartTokens(value: unknown): number | undefined {}function estimateFileDataTokens(data: unknown, mediaType: string): number | undefined {- if (isSandboxRefUrl(data)) {- // Inbound attachments that hydrate as text references stay text.- const ref = decodeSandboxRef(data);- return inlinesSandboxRefAsBytes(ref) ? estimateMediaTokens(ref) : undefined;- }+ if (isSandboxRefUrl(data)) return estimateSandboxRefTokens(data);if (data instanceof URL) return estimateRemoteTokens(mediaType);if (isTaggedFileData(data)) {switch (data.type) {@@ -77,7 +73,7 @@ function estimateFileDataTokens(data: unknown, mediaType: string): number | undereturn estimateInlineTokens(data.data, mediaType);case "url":return isSandboxRefUrl(data.url)- ? estimateMediaTokens(decodeSandboxRef(data.url))+ ? estimateSandboxRefTokens(data.url): estimateRemoteTokens(mediaType);case "reference":return estimateRemoteTokens(mediaType);@@ -88,6 +84,12 @@ function estimateFileDataTokens(data: unknown, mediaType: string): number | undereturn estimateInlineTokens(data, mediaType);}+/** Attachments that render as their label alone stay text. */+function estimateSandboxRefTokens(url: URL): number | undefined {+ const ref = decodeSandboxRef(url);+ return inlinesSandboxRefAsBytes(ref) ? estimateMediaTokens(ref) : undefined;+}+function isTaggedFileData(value: unknown,): value is { readonly type: string; readonly data?: unknown; readonly url?: unknown } {diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex 3c211323a..8b4999cc0 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -10482,9 +10482,9 @@ describe("createToolLoopHarness", () => {toolResults: [],});- // Small PNG-like payload — under the 3 MiB image inline cap so- // the hydration pass substitutes bytes (not a text reference).- const imageBytes = Buffer.alloc(1024, 0x89);+ // A small PNG under the 3 MiB image inline cap, so the hydration pass+ // adds its bytes after the label.+ const imageBytes = pngBytes(64, 64, 1024);const userContent: UserContent = [{ type: "text", text: "describe the image" },{ data: imageBytes, filename: "logo.png", mediaType: "image/png", type: "file" },@@ -10618,7 +10618,21 @@ describe("createToolLoopHarness", () => {expect(laterCalls).toHaveLength(2);for (const call of laterCalls) {expect(call.messages.find((message) => message.role === "tool")?.content).toEqual([- toolResult,+ {+ ...toolResult,+ output: {+ type: "content",+ value: [+ {+ text: expect.stringMatching(+ /^Attached file \/workspace\/\.eve\/attachments\/[0-9a-f]{16}\/chart\.png \(image\/png\)$/,+ ),+ type: "text",+ },+ file,+ ],+ },+ },]);}});diff --git a/packages/eve/src/internal/attachments/data.test.ts b/packages/eve/src/internal/attachments/data.test.tsindex 5c07f3e47..75d67878d 100644--- a/packages/eve/src/internal/attachments/data.test.ts+++ b/packages/eve/src/internal/attachments/data.test.ts@@ -1,80 +1,69 @@import { describe, expect, it } from "vitest";-import { fileDataToBytes, getKnownByteLength } from "#internal/attachments/data.js";-import { encodeAttachmentRef } from "#internal/attachments/refs.js";+import { getKnownByteLength, readFileData } from "#internal/attachments/data.js";-describe("fileDataToBytes", () => {- it("passes Uint8Array payloads through as Buffer copies", async () => {- const bytes = new Uint8Array([1, 2, 3, 4]);- const buffer = await fileDataToBytes(bytes);+function bytesOf(data: unknown): string | undefined {+ const read = readFileData(data);+ return read.kind === "bytes" ? read.bytes.toString("utf8") : undefined;+}- expect(buffer).toBeInstanceOf(Buffer);- expect(buffer?.equals(Buffer.from([1, 2, 3, 4]))).toBe(true);- });-- it("wraps ArrayBuffer payloads", async () => {- const buffer = await fileDataToBytes(new ArrayBuffer(3));- expect(buffer?.byteLength).toBe(3);- });-- it("returns Buffer inputs verbatim", async () => {+describe("readFileData", () => {+ it("reads typed arrays, ArrayBuffers, and Buffers as bytes", () => {const source = Buffer.from("direct", "utf8");- const buffer = await fileDataToBytes(source);- expect(buffer).toBe(source);- });-- it("decodes data-URL base64 payloads", async () => {- const payload = "hello-from-data-url";- const dataUrl = `data:text/plain;base64,${Buffer.from(payload, "utf8").toString("base64")}`;- const buffer = await fileDataToBytes(dataUrl);- expect(buffer?.toString("utf8")).toBe(payload);+ expect(readFileData(source)).toEqual({ bytes: source, kind: "bytes" });+ expect(bytesOf(new Uint8Array([104, 105]))).toBe("hi");+ expect(bytesOf(new Uint8Array([104, 105]).buffer)).toBe("hi");});- it("decodes data-URL percent-encoded UTF-8 payloads", async () => {- const buffer = await fileDataToBytes("data:text/plain,hello%20world");- expect(buffer?.toString("utf8")).toBe("hello world");+ it("decodes base64 and percent-encoded data URLs, as strings or URLs", () => {+ expect(bytesOf(`data:text/plain;base64,${Buffer.from("hello").toString("base64")}`)).toBe(+ "hello",+ );+ expect(bytesOf("data:text/plain,hello%20world")).toBe("hello world");+ expect(bytesOf(new URL("data:text/plain;base64,aGVsbG8="))).toBe("hello");});- it("returns null for malformed data URLs with no comma", async () => {- expect(await fileDataToBytes("data:text/plain;base64")).toBeNull();+ it("treats bare strings as base64 payloads (AI SDK DataContent contract)", () => {+ expect(bytesOf(Buffer.from("bare-base64").toString("base64"))).toBe("bare-base64");});- it("returns null for http/https URLs (provider fetches them)", async () => {- expect(await fileDataToBytes("https://example.com/file.png")).toBeNull();- expect(await fileDataToBytes("http://example.com/file.png")).toBeNull();- });-- it("returns null for URL instances that are not data: URLs", async () => {- expect(await fileDataToBytes(new URL("https://example.com/a.png"))).toBeNull();- });-- it("decodes data: URL instances", async () => {- const url = new URL("data:text/plain;base64,aGVsbG8=");- const buffer = await fileDataToBytes(url);- expect(buffer?.toString("utf8")).toBe("hello");+ it("reads any other scheme as a link instead of decoding it as base64", () => {+ expect(readFileData("https://example.com/file.png")).toEqual({+ kind: "link",+ url: new URL("https://example.com/file.png"),+ });+ expect(readFileData("myapp-file:abc")).toEqual({+ kind: "link",+ url: new URL("myapp-file:abc"),+ });+ const url = new URL("https://example.com/a.png");+ expect(readFileData(url)).toEqual({ kind: "link", url });});- it("treats bare strings as base64 payloads (AI SDK DataContent contract)", async () => {- const payload = "bare-base64";- const base64 = Buffer.from(payload, "utf8").toString("base64");- const buffer = await fileDataToBytes(base64);- expect(buffer?.toString("utf8")).toBe(payload);+ it("refuses caller-supplied framework refs", () => {+ expect(readFileData("eve-sandbox:?path=/etc/passwd&size=1&type=text/plain")).toEqual({+ kind: "unreadable",+ });+ expect(readFileData("eve-url:https://example.com/a.png")).toEqual({ kind: "unreadable" });});- it("returns null for unsupported input types", async () => {- expect(await fileDataToBytes(42)).toBeNull();- expect(await fileDataToBytes(null)).toBeNull();- expect(await fileDataToBytes({})).toBeNull();+ it("reads the AI SDK's tagged shapes and provider references", () => {+ expect(bytesOf({ data: "aGk=", type: "data" })).toBe("hi");+ expect(bytesOf({ text: "plain", type: "text" })).toBe("plain");+ expect(readFileData({ type: "url", url: "https://example.com/a" })).toEqual({+ kind: "link",+ url: new URL("https://example.com/a"),+ });+ expect(readFileData({ reference: { openai: "file-1" }, type: "reference" })).toEqual({+ kind: "reference",+ });+ expect(readFileData({ openai: "file-1" })).toEqual({ kind: "reference" });});- it("returns null for eve-attachment: URLs (caller owns the resolver dispatch)", async () => {- // The pure decoder deliberately does NOT reach into AsyncLocalStorage- // to resolve refs. The harness attachment-staging layer owns that- // dispatch explicitly so the ambient channel lookup happens in one- // named place. Integration coverage for the full resolve path lives- // in `harness/attachment-staging.integration.test.ts`.- const url = encodeAttachmentRef({ params: { url: "https://files.slack.com/x" } });- expect(await fileDataToBytes(url)).toBeNull();+ it("reports unsupported shapes and malformed data URLs as unreadable", () => {+ for (const value of [42, null, {}, { 0: 1, 1: 2 }, "data:text/plain;base64"]) {+ expect(readFileData(value), JSON.stringify(value)).toEqual({ kind: "unreadable" });+ }});});@@ -96,17 +85,18 @@ describe("getKnownByteLength", () => {});it("handles padded base64 strings accurately", () => {- expect(getKnownByteLength("YQ==")).toBe(1); // one byte- expect(getKnownByteLength("YWI=")).toBe(2); // two bytes- expect(getKnownByteLength("YWJj")).toBe(3); // three bytes+ expect(getKnownByteLength("YQ==")).toBe(1);+ expect(getKnownByteLength("YWI=")).toBe(2);+ expect(getKnownByteLength("YWJj")).toBe(3);});it("returns 0 for empty strings", () => {expect(getKnownByteLength("")).toBe(0);});- it("returns null for http/https URLs", () => {+ it("returns null for links, whatever their scheme", () => {expect(getKnownByteLength("https://example.com/file")).toBeNull();+ expect(getKnownByteLength("myapp-file:abc")).toBeNull();expect(getKnownByteLength(new URL("https://example.com/file"))).toBeNull();});@@ -121,21 +111,6 @@ describe("getKnownByteLength", () => {});it("computes byte length for percent-encoded data URLs by UTF-8 octet count", () => {- // "héllo" → 5 characters, 6 UTF-8 bytes (é = C3 A9)expect(getKnownByteLength("data:text/plain,h%C3%A9llo")).toBe(6);});-- it("returns ref.size for eve-attachment: URLs when the adapter populated it", () => {- const url = encodeAttachmentRef({- params: { url: "https://files.slack.com/x" },- size: 13319,- });-- expect(getKnownByteLength(url)).toBe(13319);- });-- it("returns null for eve-attachment: URLs without a size in the payload", () => {- const url = encodeAttachmentRef({ params: { url: "u" } });- expect(getKnownByteLength(url)).toBeNull();- });});diff --git a/packages/eve/src/internal/attachments/data.ts b/packages/eve/src/internal/attachments/data.tsindex 77b64f8ae..4b1016a71 100644--- a/packages/eve/src/internal/attachments/data.ts+++ b/packages/eve/src/internal/attachments/data.ts@@ -1,134 +1,165 @@/**- * Shared helpers for decoding AI SDK `FilePart.data` values into raw- * bytes and inspecting their size without fetching remote resources.+ * Shared helpers for reading AI SDK `FilePart.data` values without+ * fetching remote resources.*- * URL-shaped inputs that require IO return `null`; channel attachment- * refs are resolved explicitly by the staging layer.+ * Every value has one meaning: typed arrays, base64 strings, `data:` URLs,+ * and tagged `data` or `text` shapes carry bytes; any other string or `URL`+ * with a scheme is a link the staging layer resolves; a provider reference+ * names a file the provider already holds. Anything else is unreadable.*/-import { isAttachmentRefUrl, parseAttachmentRef } from "#internal/attachments/refs.js";+import { hasInternalRefScheme } from "#internal/attachments/url-refs.js";++/** What a `FilePart.data` value carries. */+export type FileData =+ | { readonly kind: "bytes"; readonly bytes: Buffer }+ | { readonly kind: "link"; readonly url: URL }+ | { readonly kind: "reference" }+ | { readonly kind: "unreadable" };++// Base64 has no colon, so a leading scheme always marks a link.+const SCHEME_PREFIX = /^[a-z][a-z\d+.-]*:/i;++const REFERENCE: FileData = { kind: "reference" };+const UNREADABLE: FileData = { kind: "unreadable" };/**- * Converts any inline AI SDK `FilePart.data` value into raw bytes.- *- * Returns `null` for every URL-shaped input the caller is expected to- * handle out-of-band, including `eve-attachment:` refs and remote URLs.+ * Classifies one `FilePart.data` value. A string with a framework-internal+ * scheme is unreadable: only eve mints those refs, so a caller-supplied one+ * must never turn into a privileged read.*/-export async function fileDataToBytes(data: unknown): Promise<Buffer | null> {- // Buffer extends Uint8Array — check it first so genuine Buffer inputs- // short-circuit to identity instead of an unnecessary copy.- if (typeof Buffer !== "undefined" && Buffer.isBuffer(data)) {- return data;- }-+export function readFileData(data: unknown): FileData {if (data instanceof Uint8Array) {- return Buffer.from(data);+ return { bytes: Buffer.isBuffer(data) ? data : Buffer.from(data), kind: "bytes" };}-if (data instanceof ArrayBuffer) {- return Buffer.from(new Uint8Array(data));+ return { bytes: Buffer.from(new Uint8Array(data)), kind: "bytes" };+ }+ if (data instanceof URL) {+ return data.protocol === "data:" ? decodeDataUrl(data.href) : { kind: "link", url: data };}-if (typeof data === "string") {- return decodeStringData(data);+ return readStringData(data);+ }+ if (data === null || typeof data !== "object") {+ return UNREADABLE;+ }+ const tagged = data as { readonly type?: unknown; readonly [key: string]: unknown };+ switch (tagged.type) {+ case "data":+ return readFileData(tagged.data);+ case "url":+ return tagged.url instanceof URL || typeof tagged.url === "string"+ ? readFileData(tagged.url)+ : UNREADABLE;+ case "text":+ return typeof tagged.text === "string"+ ? { bytes: Buffer.from(tagged.text, "utf8"), kind: "bytes" }+ : UNREADABLE;+ case "reference":+ return REFERENCE;+ default:+ return isProviderReference(data) ? REFERENCE : UNREADABLE;}+}- if (data instanceof URL) {- if (data.protocol === "data:") {- return decodeStringData(data.href);- }- // Every other URL scheme (including eve-attachment: and http(s):)- // requires IO the caller must own.- return null;+/**+ * Whether `FilePart.data` is a link or unreadable, so eve must resolve it+ * before a provider sees it. Never decodes the payload.+ */+export function isUnresolvedFileData(data: unknown): boolean {+ if (data instanceof Uint8Array || data instanceof ArrayBuffer) return false;+ if (typeof data === "string") return SCHEME_PREFIX.test(data) && !data.startsWith("data:");+ if (data instanceof URL) return data.protocol !== "data:";+ if (data === null || typeof data !== "object") return true;+ const tagged = data as { readonly type?: unknown; readonly [key: string]: unknown };+ switch (tagged.type) {+ case "data":+ return isUnresolvedFileData(tagged.data);+ case "url":+ return true;+ case "text":+ return typeof tagged.text !== "string";+ case "reference":+ return false;+ default:+ return !isProviderReference(data);}-- return null;}/**- * Returns the byte length of `FilePart.data` without performing any IO.+ * Returns the byte length of `FilePart.data` without performing any IO, or+ * `null` when only a fetch could tell.*/export function getKnownByteLength(data: unknown): number | null {- if (typeof Buffer !== "undefined" && Buffer.isBuffer(data)) {+ if (data instanceof Uint8Array || data instanceof ArrayBuffer) {return data.byteLength;}-- if (data instanceof Uint8Array) {- return data.byteLength;+ if (data instanceof URL) {+ return data.protocol === "data:" ? computeStringByteLength(data.href) : null;}-- if (data instanceof ArrayBuffer) {- return data.byteLength;+ if (typeof data !== "string") {+ return null;}-- if (typeof data === "string") {+ if (data.startsWith("data:")) {return computeStringByteLength(data);}+ return SCHEME_PREFIX.test(data) ? null : estimateBase64ByteLength(data);+}- if (isAttachmentRefUrl(data)) {- const ref = parseAttachmentRef(data);- return ref.size ?? null;+function readStringData(data: string): FileData {+ if (data.startsWith("data:")) {+ return decodeDataUrl(data);}-- if (data instanceof URL) {- if (data.protocol === "data:") {- return computeStringByteLength(data.href);- }- return null;+ if (SCHEME_PREFIX.test(data)) {+ if (hasInternalRefScheme(data)) return UNREADABLE;+ const url = URL.parse(data);+ return url === null ? UNREADABLE : { kind: "link", url };}+ // Bare strings are base64 payloads, matching AI SDK's `DataContent`.+ return { bytes: Buffer.from(data, "base64"), kind: "bytes" };+}- return null;+/** A bare AI SDK `ProviderReference`: provider names mapped to file ids. */+function isProviderReference(data: object): boolean {+ const values = Object.values(data);+ return values.length > 0 && values.every((value) => typeof value === "string");}-function decodeStringData(value: string): Buffer | null {- if (value.startsWith("data:")) {- const comma = value.indexOf(",");- if (comma === -1) {- return null;- }- const header = value.slice(5, comma);- const body = value.slice(comma + 1);- if (header.endsWith(";base64")) {- return Buffer.from(body, "base64");- }- return Buffer.from(decodeURIComponent(body), "utf8");+function decodeDataUrl(value: string): FileData {+ const comma = value.indexOf(",");+ if (comma === -1) {+ return UNREADABLE;}-- if (/^https?:\/\//.test(value)) {- return null;+ const header = value.slice(5, comma);+ const body = value.slice(comma + 1);+ if (header.endsWith(";base64")) {+ return { bytes: Buffer.from(body, "base64"), kind: "bytes" };+ }+ try {+ return { bytes: Buffer.from(decodeURIComponent(body), "utf8"), kind: "bytes" };+ } catch {+ return UNREADABLE;}-- // Bare strings are treated as base64 payloads, matching AI SDK's- // `DataContent` convention.- return Buffer.from(value, "base64");}function computeStringByteLength(value: string): number | null {- if (value.startsWith("data:")) {- const comma = value.indexOf(",");- if (comma === -1) {- return null;- }- const header = value.slice(5, comma);- const body = value.slice(comma + 1);- if (header.endsWith(";base64")) {- return estimateBase64ByteLength(body);- }- // Percent-encoded UTF-8 payload — estimate by decoding; the bytes- // we care about are the final UTF-8 octets, not the percent-encoded- // string length.- try {- return Buffer.byteLength(decodeURIComponent(body), "utf8");- } catch {- return Buffer.byteLength(body, "utf8");- }- }-- if (/^https?:\/\//.test(value)) {+ const comma = value.indexOf(",");+ if (comma === -1) {return null;}-- return estimateBase64ByteLength(value);+ const header = value.slice(5, comma);+ const body = value.slice(comma + 1);+ if (header.endsWith(";base64")) {+ return estimateBase64ByteLength(body);+ }+ // Percent-encoded UTF-8 payload: count the decoded octets, not the+ // percent-encoded string length.+ try {+ return Buffer.byteLength(decodeURIComponent(body), "utf8");+ } catch {+ return Buffer.byteLength(body, "utf8");+ }}function estimateBase64ByteLength(base64: string): number {diff --git a/packages/eve/src/internal/attachments/errors.ts b/packages/eve/src/internal/attachments/errors.tsindex c32a44f1d..ec8382953 100644--- a/packages/eve/src/internal/attachments/errors.ts+++ b/packages/eve/src/internal/attachments/errors.ts@@ -22,8 +22,8 @@ interface EveAttachmentErrorInput {}/**- * Error surfaced when an attachment resolver fails to produce bytes for- * an {@link AttachmentRef}.+ * Error surfaced when a channel's `fetchFile` fails to produce bytes for an+ * attachment URL.** Channels can inspect the `.kind` discriminator to decide whether to* drop the attachment and continue the turn (the default posture fordiff --git a/packages/eve/src/internal/attachments/media-metadata.ts b/packages/eve/src/internal/attachments/media-metadata.tsindex 0a8d5abae..0fbe2042a 100644--- a/packages/eve/src/internal/attachments/media-metadata.ts+++ b/packages/eve/src/internal/attachments/media-metadata.ts@@ -55,6 +55,51 @@ export function estimateMediaTokens(metadata: MediaMetadata): number {return Math.ceil(metadata.size / 3);}+const GENERIC_MEDIA_TYPE = "application/octet-stream";+const PDF_MEDIA_TYPE = "application/pdf";++/**+ * The media type a staged file carries: the format its bytes prove for an+ * image, PDF, or untyped file, or the declared type otherwise. A declared+ * PNG, JPEG, GIF, WebP, or PDF that the bytes don't confirm becomes+ * `application/octet-stream`, so no provider receives bytes it would reject.+ */+export function verifyMediaType(bytes: Uint8Array, declared: string): string {+ const normalized = declared.toLowerCase();+ const checkable =+ normalized.startsWith("image/") ||+ normalized === PDF_MEDIA_TYPE ||+ normalized === GENERIC_MEDIA_TYPE;+ if (!checkable) return declared;+ const detected =+ detectImageMediaType(bytes) ?? (hasPdfHeader(bytes) ? PDF_MEDIA_TYPE : undefined);+ if (detected !== undefined) return detected;+ return VERIFIABLE_MEDIA_TYPES.has(normalized) ? GENERIC_MEDIA_TYPE : declared;+}++/** The image formats eve can verify from bytes, and that every major provider reads. */+export const INLINE_IMAGE_MEDIA_TYPES: ReadonlySet<string> = new Set([+ "image/gif",+ "image/jpeg",+ "image/png",+ "image/webp",+]);++const VERIFIABLE_MEDIA_TYPES: ReadonlySet<string> = new Set([+ ...INLINE_IMAGE_MEDIA_TYPES,+ "image/jpg",+ PDF_MEDIA_TYPE,+]);++/**+ * Whether the bytes start with a PDF header. The format allows leading bytes,+ * but providers expect the header first, and a match deeper in would mark text+ * that only mentions it.+ */+export function hasPdfHeader(bytes: Uint8Array): boolean {+ return readAscii(bytes, 0, 5) === "%PDF-";+}+/** Names the PNG, GIF, JPEG, or WebP format its leading bytes identify. */export function detectImageMediaType(bytes: Uint8Array): string | undefined {const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);diff --git a/packages/eve/src/internal/attachments/public-link.ts b/packages/eve/src/internal/attachments/public-link.tsnew file mode 100644index 000000000..cacbccba7--- /dev/null+++ b/packages/eve/src/internal/attachments/public-link.ts@@ -0,0 +1,70 @@+import type { FetchFileResult } from "#channel/adapter.js";+import { requestPublicUrl } from "#execution/web-fetch/request.js";+import { EveAttachmentError } from "#internal/attachments/errors.js";++const DOWNLOAD_TIMEOUT_MS = 30_000;+/** Links eve downloads for one message. Each buffers up to the upload cap, so they run one at a time. */+const MAX_DOWNLOADS_PER_MESSAGE = 10;+const GENERIC_MEDIA_TYPES = new Set(["application/octet-stream", "binary/octet-stream"]);++/** Downloads one message's unclaimed links: at most {@link MAX_DOWNLOADS_PER_MESSAGE}, one at a time. */+export type PublicDownloads = (url: URL, adapterKind: string) => Promise<FetchFileResult>;++/** Starts the download budget for one message's attachments, each capped at `maxBytes`. */+export function createPublicDownloads(maxBytes: number): PublicDownloads {+ let started = 0;+ let previous: Promise<unknown> = Promise.resolve();+ return async (url, adapterKind) => {+ if (url.protocol === "https:" && ++started > MAX_DOWNLOADS_PER_MESSAGE) {+ throw refusal(+ adapterKind,+ `eve downloads at most ${MAX_DOWNLOADS_PER_MESSAGE} links per message.`,+ );+ }+ const download = previous.then(() => fetchPublicAttachment(url, adapterKind, maxBytes));+ previous = download.catch(() => undefined);+ return await download;+ };+}++/**+ * Downloads an attachment link that no channel resolver claimed, so a+ * provider never fetches it and an unreachable link fails as a note instead+ * of on every later model call. Only public `https:` destinations qualify;+ * private and reserved addresses are refused.+ */+async function fetchPublicAttachment(+ url: URL,+ adapterKind: string,+ maxBytes: number,+): Promise<FetchFileResult> {+ if (url.protocol !== "https:") {+ throw refusal(adapterKind, "eve downloads only public https:// links.");+ }+ let response: Response;+ try {+ response = await requestPublicUrl(url.href, {+ headers: {},+ maxResponseSize: maxBytes,+ signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),+ });+ } catch (cause) {+ throw refusal(adapterKind, "The link could not be downloaded.", cause);+ }+ if (!response.ok) {+ throw refusal(adapterKind, `The link returned HTTP ${response.status}.`);+ }+ const mediaType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();+ // A private document's link usually answers with a sign-in page.+ if (mediaType === "text/html") {+ throw refusal(adapterKind, "The link returned a web page instead of a file.");+ }+ const bytes = Buffer.from(await response.arrayBuffer());+ return mediaType === undefined || mediaType === "" || GENERIC_MEDIA_TYPES.has(mediaType)+ ? { bytes }+ : { bytes, mediaType };+}++function refusal(adapterKind: string, message: string, cause?: unknown): EveAttachmentError {+ return new EveAttachmentError({ adapterKind, cause, kind: "resolver-threw", message });+}diff --git a/packages/eve/src/internal/attachments/refs.test.ts b/packages/eve/src/internal/attachments/refs.test.tsdeleted file mode 100644index cfd503415..000000000--- a/packages/eve/src/internal/attachments/refs.test.ts+++ /dev/null@@ -1,167 +0,0 @@-import { describe, expect, it } from "vitest";--import {- ATTACHMENT_REF_SCHEME,- ATTACHMENT_REF_WIRE_VERSION,- type AttachmentRef,- encodeAttachmentRef,- isAttachmentRefUrl,- parseAttachmentRef,-} from "#internal/attachments/refs.js";--interface SlackParams {- readonly file_id: string;- readonly url: string;-}--describe("encodeAttachmentRef", () => {- it("builds an eve-attachment: URL with a v=1 version and a base64url JSON payload", () => {- const ref: AttachmentRef<SlackParams> = {- params: { file_id: "F123ABC", url: "https://files.slack.com/report.csv" },- size: 13319,- };-- const url = encodeAttachmentRef(ref);-- expect(url.protocol).toBe(ATTACHMENT_REF_SCHEME);- expect(url.searchParams.get("v")).toBe(ATTACHMENT_REF_WIRE_VERSION);-- const payload = url.searchParams.get("p");- expect(payload).not.toBeNull();- const decoded = JSON.parse(Buffer.from(payload!, "base64url").toString("utf8"));- expect(decoded).toEqual({- params: { file_id: "F123ABC", url: "https://files.slack.com/report.csv" },- size: 13319,- });- });-- it("omits size from the payload when unset", () => {- const url = encodeAttachmentRef({ params: { url: "u" } });- const payload = url.searchParams.get("p");- const decoded = JSON.parse(Buffer.from(payload!, "base64url").toString("utf8"));- expect(decoded).toEqual({ params: { url: "u" } });- expect("size" in decoded).toBe(false);- });-- it("encodes typed params with numbers, booleans, and nested objects", () => {- interface Custom {- readonly blob_key: string;- readonly is_private: boolean;- readonly revision: number;- readonly meta: { readonly author: string };- }- const ref: AttachmentRef<Custom> = {- params: { blob_key: "k", is_private: true, revision: 7, meta: { author: "alice" } },- };- const parsed = parseAttachmentRef<Custom>(encodeAttachmentRef(ref));- expect(parsed.params).toEqual({- blob_key: "k",- is_private: true,- revision: 7,- meta: { author: "alice" },- });- });-- it("rejects a non-integer size", () => {- expect(() => encodeAttachmentRef({ params: {}, size: 1.5 })).toThrow(/non-negative integer/u);- });-- it("rejects a negative size", () => {- expect(() => encodeAttachmentRef({ params: {}, size: -1 })).toThrow(/non-negative integer/u);- });-- it("rejects a non-finite size", () => {- expect(() => encodeAttachmentRef({ params: {}, size: Number.POSITIVE_INFINITY })).toThrow(- /non-negative integer/u,- );- });-});--describe("parseAttachmentRef", () => {- it("round-trips encode → parse preserving params and size", () => {- const input: AttachmentRef<SlackParams> = {- params: { file_id: "F123", url: "https://files.slack.com/x" },- size: 42,- };-- const parsed = parseAttachmentRef<SlackParams>(encodeAttachmentRef(input));-- expect(parsed.params).toEqual({ file_id: "F123", url: "https://files.slack.com/x" });- expect(parsed.size).toBe(42);- });-- it("omits size on the parsed ref when the payload carries no size", () => {- const ref = parseAttachmentRef(encodeAttachmentRef({ params: { url: "u" } }));- expect(ref.size).toBeUndefined();- });-- it("rejects non-eve-attachment schemes", () => {- expect(() => parseAttachmentRef(new URL("https://files.slack.com/x"))).toThrow(- /eve-attachment:/u,- );- expect(() => parseAttachmentRef(new URL("data:,hello"))).toThrow(/eve-attachment:/u);- });-- it("rejects a missing or unrecognized wire version", () => {- expect(() => parseAttachmentRef(new URL("eve-attachment:?p=eyJwYXJhbXMiOnt9fQ"))).toThrow(- /wire format version/u,- );- expect(() => parseAttachmentRef(new URL("eve-attachment:?v=2&p=eyJwYXJhbXMiOnt9fQ"))).toThrow(- /wire format version/u,- );- });-- it("rejects a missing payload", () => {- expect(() => parseAttachmentRef(new URL("eve-attachment:?v=1"))).toThrow(/"p" payload/u);- });-- it("rejects a payload that is not base64url-encoded JSON", () => {- expect(() => parseAttachmentRef(new URL("eve-attachment:?v=1&p=!!!notjson!!!"))).toThrow(- /base64url-encoded JSON/u,- );- });-- it("rejects a payload that decodes to a non-object", () => {- const encoded = Buffer.from(JSON.stringify("literal"), "utf8").toString("base64url");- expect(() => parseAttachmentRef(new URL(`eve-attachment:?v=1&p=${encoded}`))).toThrow(- /JSON object/u,- );- });-- it("rejects a payload missing the params field", () => {- const encoded = Buffer.from(JSON.stringify({ size: 1 }), "utf8").toString("base64url");- expect(() => parseAttachmentRef(new URL(`eve-attachment:?v=1&p=${encoded}`))).toThrow(- /"params" field/u,- );- });-- it("rejects a payload with a malformed size", () => {- for (const size of [-1, 1.5, "42"]) {- const encoded = Buffer.from(JSON.stringify({ params: {}, size }), "utf8").toString(- "base64url",- );- expect(() => parseAttachmentRef(new URL(`eve-attachment:?v=1&p=${encoded}`))).toThrow(- /non-negative integer/u,- );- }- });-});--describe("isAttachmentRefUrl", () => {- it("returns true only for URL instances with the eve-attachment scheme", () => {- expect(isAttachmentRefUrl(encodeAttachmentRef({ params: { url: "u" } }))).toBe(true);- expect(isAttachmentRefUrl(new URL("https://example.com"))).toBe(false);- expect(isAttachmentRefUrl(new URL("data:,hello"))).toBe(false);- });-- it("rejects string inputs even when they look like attachment refs", () => {- expect(isAttachmentRefUrl("eve-attachment:?v=1&p=eyJwYXJhbXMiOnt9fQ")).toBe(false);- });-- it("rejects non-URL inputs", () => {- expect(isAttachmentRefUrl(null)).toBe(false);- expect(isAttachmentRefUrl(undefined)).toBe(false);- expect(isAttachmentRefUrl({})).toBe(false);- expect(isAttachmentRefUrl(42)).toBe(false);- });-});diff --git a/packages/eve/src/internal/attachments/refs.ts b/packages/eve/src/internal/attachments/refs.tsdeleted file mode 100644index 45e6d6074..000000000--- a/packages/eve/src/internal/attachments/refs.ts+++ /dev/null@@ -1,141 +0,0 @@-/**- * Opaque attachment references: the wire format a channel uses to carry- * file identity across step boundaries without inlining the bytes.- *- * Refs are compact custom-scheme URLs:- *- * ```- * eve-attachment:?v=1&p=<base64url-encoded JSON of { params, size? }>- * ```- */--/**- * Custom URL scheme used by every attachment ref. The trailing colon- * is part of the scheme per WHATWG URL semantics.- */-export const ATTACHMENT_REF_SCHEME = "eve-attachment:";--/**- * Current wire format version. Decoders reject any other value so a- * future format bump doesn't silently misparse.- */-export const ATTACHMENT_REF_WIRE_VERSION = "1";--import { toErrorMessage } from "#shared/errors.js";--const VERSION_QUERY_KEY = "v";-const PAYLOAD_QUERY_KEY = "p";--/**- * Serializable description of one inbound file attachment.- *- * `params` is an adapter-defined, JSON-safe object typed by the generic- * parameter. It identifies the upstream file and must not carry- * credentials; resolvers read credentials from adapter context or closure.- *- * `size` is optional. Populating it when the upstream protocol exposes- * the byte length up front lets upload-policy size checks run without- * fetching the bytes.- */-export interface AttachmentRef<TParams = unknown> {- readonly params: TParams;- readonly size?: number;-}--function isValidSize(value: number): boolean {- return Number.isFinite(value) && Number.isInteger(value) && value >= 0;-}--/**- * Encodes an {@link AttachmentRef} as a URL suitable for use as- * `FilePart.data`.- *- * `TParams` links the encoded payload shape to the channel resolver.- */-export function encodeAttachmentRef<TParams>(ref: AttachmentRef<TParams>): URL {- if (ref.size !== undefined && !isValidSize(ref.size)) {- throw new RangeError(- `AttachmentRef.size must be a non-negative integer. Received: ${String(ref.size)}.`,- );- }-- const payload =- ref.size === undefined ? { params: ref.params } : { params: ref.params, size: ref.size };- const encoded = Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");-- const url = new URL(ATTACHMENT_REF_SCHEME);- url.searchParams.set(VERSION_QUERY_KEY, ATTACHMENT_REF_WIRE_VERSION);- url.searchParams.set(PAYLOAD_QUERY_KEY, encoded);- return url;-}--/**- * Parses an {@link AttachmentRef} back out of a URL.- */-export function parseAttachmentRef<TParams = unknown>(url: URL): AttachmentRef<TParams> {- if (url.protocol !== ATTACHMENT_REF_SCHEME) {- throw new Error(- `AttachmentRef URL must use scheme "${ATTACHMENT_REF_SCHEME}". Got: "${url.protocol}".`,- );- }-- const version = url.searchParams.get(VERSION_QUERY_KEY);- if (version !== ATTACHMENT_REF_WIRE_VERSION) {- throw new Error(- `AttachmentRef wire format version must be "${ATTACHMENT_REF_WIRE_VERSION}". Got: ${- version === null ? "missing" : JSON.stringify(version)- }.`,- );- }-- const encoded = url.searchParams.get(PAYLOAD_QUERY_KEY);- if (encoded === null || encoded === "") {- throw new Error('AttachmentRef URL is missing the required "p" payload query param.');- }-- let payload: unknown;- try {- const json = Buffer.from(encoded, "base64url").toString("utf8");- payload = JSON.parse(json);- } catch (cause) {- throw new Error(- `AttachmentRef payload is not valid base64url-encoded JSON: ${toErrorMessage(cause)}`,- );- }-- if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {- throw new Error("AttachmentRef payload must decode to a JSON object.");- }-- const record = payload as Record<string, unknown>;- if (!("params" in record)) {- throw new Error('AttachmentRef payload is missing the required "params" field.');- }-- const params = record.params as TParams;-- if (!("size" in record)) {- return { params };- }-- const size = record.size;- if (typeof size !== "number" || !isValidSize(size)) {- throw new Error(- `AttachmentRef payload "size" must be a non-negative integer. Got: ${JSON.stringify(size)}.`,- );- }-- return { params, size };-}--/**- * Cheap runtime check: does this value look like an attachment-ref URL?- *- * Accepts `URL` instances with the `eve-attachment:` scheme. Strings- * are NOT accepted — the staging layer only checks URL-instance- * `FilePart.data` values, matching the existing `data instanceof URL`- * branch in `fileDataToBytes`.- */-export function isAttachmentRefUrl(value: unknown): value is URL {- return value instanceof URL && value.protocol === ATTACHMENT_REF_SCHEME;-}diff --git a/packages/eve/src/internal/attachments/sandbox-refs.test.ts b/packages/eve/src/internal/attachments/sandbox-refs.test.tsindex 53eba01c3..5fafa3c1d 100644--- a/packages/eve/src/internal/attachments/sandbox-refs.test.ts+++ b/packages/eve/src/internal/attachments/sandbox-refs.test.ts@@ -137,7 +137,7 @@ describe("isSandboxRefUrl", () => {});it("returns false for a URL with a different scheme", () => {- expect(isSandboxRefUrl(new URL("eve-attachment:?v=1&p=e30"))).toBe(false);+ expect(isSandboxRefUrl(new URL("https://example.com/a.png"))).toBe(false);expect(isSandboxRefUrl(new URL("https://example.com/a"))).toBe(false);expect(isSandboxRefUrl(new URL("data:text/plain;base64,Zm9v"))).toBe(false);});diff --git a/packages/eve/src/internal/attachments/sandbox-refs.ts b/packages/eve/src/internal/attachments/sandbox-refs.tsindex fcf33aae2..0557a642b 100644--- a/packages/eve/src/internal/attachments/sandbox-refs.ts+++ b/packages/eve/src/internal/attachments/sandbox-refs.ts@@ -9,7 +9,10 @@* ```*/-import type { MediaMetadata } from "#internal/attachments/media-metadata.js";+import {+ INLINE_IMAGE_MEDIA_TYPES,+ type MediaMetadata,+} from "#internal/attachments/media-metadata.js";/*** Custom URL scheme used by every sandbox-resident attachment ref. The@@ -28,6 +31,9 @@ const METADATA_QUERY_KEYS = ["width", "height", "pages"] as const;*/const INLINE_IMAGE_MAX_BYTES = 3 * 1024 * 1024;+/** Providers reject an image wider or taller than this, failing the whole request. */+const INLINE_IMAGE_MAX_SIDE_PX = 8000;+/** Upper bound, in bytes, on inbound PDFs that hydrate as inline bytes. */const INLINE_PDF_MAX_BYTES = 20 * 1024 * 1024;@@ -116,13 +122,20 @@ export function decodeSandboxRef(value: URL | string): SandboxRef {}/**- * Whether an inbound attachment ref reaches the model as bytes rather than a- * text reference. Only shapes every major provider reads natively qualify:- * images up to 3 MiB and PDFs up to 20 MiB. Pure in the ref, so a message- * renders the same way on every model call.+ * Whether an attachment ref reaches the model as bytes as well as its label.+ * Only shapes every major provider reads natively qualify: PNG, JPEG, GIF,+ * and WebP images up to 3 MiB and 8000 px per side, and PDFs up to 20 MiB.+ * Staging verifies these media types from the bytes. Pure in the ref, so a+ * message renders the same way on every model call.*/export function inlinesSandboxRefAsBytes(ref: SandboxRef): boolean {- if (ref.mediaType.startsWith("image/")) return ref.size <= INLINE_IMAGE_MAX_BYTES;+ if (INLINE_IMAGE_MEDIA_TYPES.has(ref.mediaType)) {+ return (+ ref.size <= INLINE_IMAGE_MAX_BYTES &&+ (ref.width ?? 0) <= INLINE_IMAGE_MAX_SIDE_PX &&+ (ref.height ?? 0) <= INLINE_IMAGE_MAX_SIDE_PX+ );+ }if (ref.mediaType === "application/pdf") return ref.size <= INLINE_PDF_MAX_BYTES;return false;}@@ -133,7 +146,7 @@ export function inlinesSandboxRefAsBytes(ref: SandboxRef): boolean {* Accepts `URL` instances with the `eve-sandbox:` scheme. Strings are* NOT accepted — the staging and hydration layers only inspect* URL-instance `FilePart.data` values, matching the existing- * `data instanceof URL` branch in `fileDataToBytes`.+ * `data instanceof URL` branch in `readFileData`.*/export function isSandboxRefUrl(value: unknown): value is URL {return value instanceof URL && value.protocol === SANDBOX_URL_SCHEME;diff --git a/packages/eve/src/internal/attachments/url-refs.ts b/packages/eve/src/internal/attachments/url-refs.tsindex 3e39c4c1e..d4a9b3572 100644--- a/packages/eve/src/internal/attachments/url-refs.ts+++ b/packages/eve/src/internal/attachments/url-refs.ts@@ -9,7 +9,6 @@* work reliably.*/-import { ATTACHMENT_REF_SCHEME } from "#internal/attachments/refs.js";import { SANDBOX_URL_SCHEME } from "#internal/attachments/sandbox-refs.js";const EVE_URL_SCHEME = "eve-url:";@@ -27,15 +26,14 @@ export function deserializeUrlFilePart(data: string): URL {}/**- * Framework-internal `FilePart.data` ref schemes (`eve-url:`, `eve-sandbox:`,- * `eve-attachment:`). eve produces these during its own serialization and- * staging; an inbound channel payload must never carry one. The staging- * pipeline trusts the scheme prefix and reconstitutes such a string into a- * privileged sandbox/attachment read, so a caller-supplied ref is an- * arbitrary-read / path-traversal vector and must be rejected at the channel- * boundary.+ * Framework-internal `FilePart.data` ref schemes (`eve-url:`, `eve-sandbox:`).+ * eve produces these during its own serialization and staging; an inbound+ * channel payload must never carry one. The staging pipeline trusts the+ * scheme prefix and reconstitutes such a string into a privileged sandbox+ * read, so a caller-supplied ref is an arbitrary-read / path-traversal vector+ * and must be rejected at the channel boundary.*/-const INTERNAL_REF_SCHEMES = [EVE_URL_SCHEME, SANDBOX_URL_SCHEME, ATTACHMENT_REF_SCHEME];+const INTERNAL_REF_SCHEMES = [EVE_URL_SCHEME, SANDBOX_URL_SCHEME];/*** Whether a `FilePart.data` string carries a framework-internal ref scheme.diff --git a/packages/eve/src/protocol/message.test.ts b/packages/eve/src/protocol/message.test.tsindex b88c22906..fd077bc44 100644--- a/packages/eve/src/protocol/message.test.ts+++ b/packages/eve/src/protocol/message.test.ts@@ -671,17 +671,16 @@ describe("createMessageReceivedEvent", () => {]);});- it("exposes data URLs but not opaque base64 strings", () => {- const dataUrl = "data:text/plain;base64,aGVsbG8=";-- expect(projectParts([{ data: dataUrl, mediaType: "text/plain", type: "file" }])).toEqual([- { mediaType: "text/plain", type: "file", url: dataUrl },- ]);+ it("projects data URLs and base64 strings as their size, never their bytes", () => {expect(projectParts([+ { data: "data:text/plain;base64,aGVsbG8=", mediaType: "text/plain", type: "file" },{ data: "aGVsbG8=", filename: "note.txt", mediaType: "text/plain", type: "file" },]),- ).toEqual([{ filename: "note.txt", mediaType: "text/plain", type: "file" }]);+ ).toEqual([+ { mediaType: "text/plain", size: 5, type: "file" },+ { filename: "note.txt", mediaType: "text/plain", size: 5, type: "file" },+ ]);});it("exposes tagged URL file data", () => {diff --git a/packages/eve/src/protocol/message.ts b/packages/eve/src/protocol/message.tsindex 807ffb2ce..280bf1bb8 100644--- a/packages/eve/src/protocol/message.ts+++ b/packages/eve/src/protocol/message.ts@@ -5,6 +5,7 @@ import {hasInternalRefScheme,isSerializedUrlFilePart,} from "#internal/attachments/url-refs.js";+import { getKnownByteLength } from "#internal/attachments/data.js";import { decodeSandboxRef, isSandboxRefUrl } from "#internal/attachments/sandbox-refs.js";import { createEventId } from "#protocol/event-id.js";import {@@ -1092,12 +1093,16 @@ function projectFileLikePart(return tagged;}- const size = byteLengthOf(data);- if (size !== undefined) {- return createProjectedFilePart({ filename, mediaType, size });+ const link = clientUrlFragment(data);+ if (link.url !== undefined) {+ return createProjectedFilePart({ filename, mediaType, ...link });}-- return createProjectedFilePart({ filename, mediaType, ...clientUrlFragment(data) });+ // Inline payloads report their size only: this event is stored with the+ // session stream, which must not keep attachment bytes.+ const size = getKnownByteLength(data);+ return size === null+ ? createProjectedFilePart({ filename, mediaType })+ : createProjectedFilePart({ filename, mediaType, size });}function projectTaggedFileData(@@ -1191,10 +1196,6 @@ function clientUrlFragment(data: unknown): { readonly url?: string } {return {};}- if (data.startsWith("data:")) {- return { url: data };- }-try {const url = new URL(data);return isClientResolvableUrl(url) ? { url: url.href } : {};@@ -1204,7 +1205,7 @@ function clientUrlFragment(data: unknown): { readonly url?: string } {}function isClientResolvableUrl(url: URL): boolean {- return url.protocol === "http:" || url.protocol === "https:" || url.protocol === "data:";+ return url.protocol === "http:" || url.protocol === "https:";}function basenameOf(path: string): string {diff --git a/packages/eve/src/shared/channel-definition.ts b/packages/eve/src/shared/channel-definition.tsindex af0ca3e1f..4e8b88c23 100644--- a/packages/eve/src/shared/channel-definition.ts+++ b/packages/eve/src/shared/channel-definition.ts@@ -95,10 +95,11 @@ export interface GenericChannelDefinition<readonly events?: TEvents;/**- * Fetches bytes for a `URL` object encountered on a `FilePart.data` by the- * staging pipeline. Return `null` to pass the URL through to the model- * provider unchanged, or bytes / {@link FetchFileResult} to stage the file to- * the sandbox.+ * Fetches bytes for a link encountered on a `FilePart.data` by the staging+ * pipeline. Return bytes / {@link FetchFileResult} to stage the file to the+ * sandbox, or `null` when the link is not this channel's: eve then downloads+ * a public `https:` link itself, and any other link reaches the model as a+ * note. A provider never fetches an attachment.*/readonly fetchFile?: FetchFileFunction;diff --git a/packages/eve/src/tools/provided/read-file.ts b/packages/eve/src/tools/provided/read-file.tsindex 850d0ebac..a4ee2dbcc 100644--- a/packages/eve/src/tools/provided/read-file.ts+++ b/packages/eve/src/tools/provided/read-file.ts@@ -17,10 +17,11 @@ export interface ReadFileToolInput {export interface ReadFileToolOutput {content: string;- /** Set when the file is a PNG, JPEG, GIF, or WebP image the model sees as an image. */- image?: {+ /** Set when the file is a PNG, JPEG, GIF, or WebP image or a PDF that the model reads natively. */+ file?: {height?: number;mediaType: string;+ pages?: number;size: number;width?: number;};@@ -62,11 +63,12 @@ export const READ_FILE_OUTPUT_SCHEMA = defineJsonSchema<ReadFileToolOutput>({type: "object",properties: {content: { type: "string" },- image: {+ file: {type: "object",properties: {height: { type: "integer", minimum: 1 },mediaType: { type: "string" },+ pages: { type: "integer", minimum: 1 },size: { type: "integer", minimum: 0 },width: { type: "integer", minimum: 1 },},@@ -98,7 +100,7 @@ export const readFile: ToolDefinition<ReadFileToolInput, ReadFileToolOutput> = f"- To read later sections, call this tool again with a larger offset.",'- Contents are returned with each line prefixed by its line number as `<line>: <content>`. For example, if a file has contents "foo\\n", you will receive "1: foo\\n".',"- Any line longer than 2000 characters is truncated.",- "- PNG, JPEG, GIF, and WebP files up to 3 MiB are shown to you as images, including files named in `Attached file <path>` references.",+ "- PNG, JPEG, GIF, and WebP images up to 3 MiB and PDFs up to 20 MiB are shown to you as files, including files named in `Attached file <path>` references.","- Call this tool in parallel when you know there are multiple files you want to read.","- Avoid tiny repeated slices (30 line chunks). If you need more context, read a larger window.",].join("\n"),@@ -108,7 +110,7 @@ export const readFile: ToolDefinition<ReadFileToolInput, ReadFileToolOutput> = finputSchema: READ_FILE_INPUT_SCHEMA,outputSchema: READ_FILE_OUTPUT_SCHEMA,async toModelOutput(output) {- if (output.image === undefined) return toolOutput.json(output);+ if (output.file === undefined) return toolOutput.json(output);// The bytes load here rather than in `execute`, so `action.result` never// carries them. The harness then stages this file part under its own name// as a sandbox ref before it enters history.@@ -119,19 +121,18 @@ export const readFile: ToolDefinition<ReadFileToolInput, ReadFileToolOutput> = f: await sandbox.readBinaryFile({path: await resolveAbsoluteFilePath(sandbox, output.path),});- if (bytes === null)- return toolOutput.text(`${output.content} The image could not be loaded.`);+ if (bytes === null) return toolOutput.text(`${output.content} The file could not be loaded.`);// A file replaced after `execute` would otherwise skip its size cap.- if (bytes.byteLength !== output.image.size) {+ if (bytes.byteLength !== output.file.size) {return toolOutput.text(- `${output.content} The image changed after it was read; read it again.`,+ `${output.content} The file changed after it was read; read it again.`,);}return toolOutput.content([toolOutputPart.text(output.content),toolOutputPart.file(Buffer.from(bytes).toString("base64"), {filename: basename(output.path),- mediaType: output.image.mediaType,+ mediaType: output.file.mediaType,}),]);},