Skip to content

Commit c9b95e7

Browse files
authored
feat(core): read audio and video files for models that accept them (#68388)
1 parent 08288c9 commit c9b95e7

9 files changed

Lines changed: 206 additions & 38 deletions

File tree

‎packages/core/src/aisdk.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -570,7 +570,7 @@ function toolMessage(input: ToolMessage) {
570570
if (part.type !== "tool-result" || part.result.type !== "content") return toolResultPart(part)
571571
const value = part.result.value.filter((item) => {
572572
if (item.type !== "file") return true
573-
if (!item.mime.startsWith("image/") && item.mime !== "application/pdf") return true
573+
if (!/^(image|audio|video)\//.test(item.mime) && item.mime !== "application/pdf") return true
574574
media.push({
575575
type: "file",
576576
mediaType: item.mime,

‎packages/core/src/mime.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,26 @@ export function detectMedia(bytes: Uint8Array) {
3333
/** The bare type, lowercased and without parameters: `Application/PDF; name=a.pdf` is `application/pdf`. */
3434
export const essence = (mime: string) => mime.split(";", 1)[0].trim().toLowerCase()
3535

36+
// Audio and video formats Gemini, the main model family that accepts them, documents. Other containers stay binary files,
37+
// since a stored attachment the provider rejects would fail every later request.
38+
export const audioVideo = new Set([
39+
"audio/wav",
40+
"audio/mpeg",
41+
"audio/aiff",
42+
"audio/aac",
43+
"audio/ogg",
44+
"audio/flac",
45+
"audio/mp4",
46+
"video/mp4",
47+
"video/mpeg",
48+
"video/quicktime",
49+
"video/x-msvideo",
50+
"video/x-flv",
51+
"video/webm",
52+
"video/x-ms-wmv",
53+
"video/3gpp",
54+
])
55+
3656
export const isTextual = (mime: string) =>
3757
!mime ||
3858
mime.startsWith("text/") ||

‎packages/core/src/session/compaction.ts‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1154,14 +1154,19 @@ const clip = (value: string) => {
11541154
/** The newest whole, real user messages within `keep` tokens: no synthetic guidance, no half of an attachment. */
11551155
export const recentUserMessages = (
11561156
messages: ReadonlyArray<SessionMessage.Info>,
1157-
model: Pick<SessionContext.Loaded["model"], "ref" | "capabilities">,
1157+
model: Pick<SessionContext.Loaded["model"], "ref" | "capabilities" | "model">,
11581158
keep: number,
11591159
) => {
11601160
const users = messages
11611161
.filter((message) => message.type === "user")
11621162
.map((message) => ({ ...message, skills: undefined }))
1163-
const sendable = SessionModelRequest.boundImages(
1164-
SessionModelRequest.unsupportedParts(toLLMMessages(users, model.ref), model.capabilities),
1163+
const sendable = SessionModelRequest.boundMedia(
1164+
SessionModelRequest.unsupportedParts(
1165+
toLLMMessages(users, model.ref),
1166+
model.capabilities,
1167+
model.model.provider,
1168+
model.model.api.name,
1169+
),
11651170
)
11661171
return sendable.slice(oldestToDrop(sendable, estimateMessage, keep))
11671172
}
@@ -1178,8 +1183,13 @@ export const estimatePrompt = (context: SessionContext.Loaded): Estimate => {
11781183
// TODO: Pass compaction history the runner has already shaped. This and `recentUserMessages` repeat the
11791184
// runner's unsupported-media and image-budget passes; here the image budget only sees images since the anchor,
11801185
// so image-heavy sessions can estimate high.
1181-
const sent = SessionModelRequest.boundImages(
1182-
SessionModelRequest.unsupportedParts(base.messages, context.model.capabilities),
1186+
const sent = SessionModelRequest.boundMedia(
1187+
SessionModelRequest.unsupportedParts(
1188+
base.messages,
1189+
context.model.capabilities,
1190+
context.model.model.provider,
1191+
context.model.model.api.name,
1192+
),
11831193
)
11841194
// The anchor's usage covers its own output, but not its local tool results, which the provider never saw.
11851195
const unmeasured = sent.filter((message) => message.role !== "assistant" || message.id !== anchor?.id)

‎packages/core/src/session/model-request.ts‎

Lines changed: 53 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,10 @@ import type { SessionMessage } from "./message.js"
5151

5252
const IMAGE_BYTES_TRIGGER = 25 * 1024 * 1024 // 25 MiB
5353
const IMAGE_BYTES_TARGET = 15 * 1024 * 1024 // 15 MiB
54+
// Audio and video are larger and fewer, so they keep a few of the newest within a budget of their own. Together with the
55+
// image budget a request stays under Gemini's 100 MB inline limit.
56+
const AUDIO_VIDEO_TRIGGER = { bytes: 60 * 1024 * 1024, count: 4 }
57+
const AUDIO_VIDEO_TARGET = { bytes: 30 * 1024 * 1024, count: 2 }
5458
const IMAGE_REMOVED =
5559
"[This image was removed to reduce the request size and is no longer visible. Do not make claims about its contents from memory. If needed, retrieve it again with an available tool or ask the user to attach it again.]"
5660
// Used when the catalog has no output limit for the model.
@@ -146,21 +150,28 @@ const mimeToModality = (mime: string) => {
146150
// xAI rejects any other image type (e.g. GIF) with invalid_image, and the stored image would fail every later turn.
147151
const XAI_IMAGE_MIMES = new Set(["image/png", "image/jpeg", "image/webp"])
148152

153+
// Only Gemini's protocols carry audio and video; other protocols reject them, even for a model that lists the modality
154+
// (e.g. a Gemini model behind an OpenAI Chat-compatible route).
155+
const AUDIO_VIDEO_APIS = new Set(["generate-content", "interactions"])
156+
149157
const unsupportedMedia = (
150158
input: string,
151159
name: string | undefined,
152160
capabilities: Model.Capabilities,
153161
provider: string | undefined,
162+
api: string | undefined,
154163
) => {
155164
// Stored media can carry any case or parameters (MCP servers report them as-is), so classify the bare type.
156165
const mime = Mime.essence(input)
157166
const modality = mimeToModality(mime)
158167
if (!modality) return
159-
const unsupported = !capabilities.input.some((item) => item.startsWith(modality))
160-
? modality
161-
: provider === "xai" && modality === "image" && !XAI_IMAGE_MIMES.has(mime)
162-
? mime
163-
: undefined
168+
const unsupported =
169+
!capabilities.input.some((item) => item.startsWith(modality)) ||
170+
((modality === "audio" || modality === "video") && api !== undefined && !AUDIO_VIDEO_APIS.has(api))
171+
? modality
172+
: provider === "xai" && modality === "image" && !XAI_IMAGE_MIMES.has(mime)
173+
? mime
174+
: undefined
164175
if (!unsupported) return
165176
return `ERROR: Cannot read ${name ? `"${name}"` : modality} (this model does not support ${unsupported} input). Inform the user.`
166177
}
@@ -222,35 +233,57 @@ export const unsupportedParts = (
222233
messages: LLMRequest["messages"],
223234
capabilities: Model.Capabilities,
224235
provider?: string,
225-
) => replaceMedia(messages, (media) => unsupportedMedia(media.mime, media.name, capabilities, provider))
236+
api?: string,
237+
) => replaceMedia(messages, (media) => unsupportedMedia(media.mime, media.name, capabilities, provider, api))
238+
239+
/** Keeps the newest images, audio and video within their budgets and replaces older ones with a note to read them again. */
240+
export const boundMedia = (messages: LLMRequest["messages"]) =>
241+
bound(
242+
bound(messages, isImage, { bytes: IMAGE_BYTES_TRIGGER }, { bytes: IMAGE_BYTES_TARGET }, () => IMAGE_REMOVED),
243+
isAudioVideo,
244+
AUDIO_VIDEO_TRIGGER,
245+
AUDIO_VIDEO_TARGET,
246+
(media) =>
247+
`[This ${media.mime.startsWith("audio/") ? "audio" : "video"} was removed to reduce the request size and is no longer available. Do not make claims about its contents from memory. If needed, read ${media.name ?? "the file"} again or ask the user to attach it again.]`,
248+
)
226249

227-
export const boundImages = (messages: LLMRequest["messages"]) => {
228-
const isImage = (mime: string) => mime.toLowerCase().startsWith("image/")
250+
const isImage = (mime: string) => mime.toLowerCase().startsWith("image/")
251+
const isAudioVideo = (mime: string) => /^(audio|video)\//i.test(mime)
252+
253+
type Budget = { readonly bytes: number; readonly count?: number }
254+
255+
const bound = (
256+
messages: LLMRequest["messages"],
257+
matches: (mime: string) => boolean,
258+
trigger: Budget,
259+
target: Budget,
260+
removed: (media: { mime: string; name: string | undefined }) => string,
261+
) => {
229262
const sizes = messages.flatMap((message) =>
230263
message.content.flatMap((part) => {
231-
if (part.type === "media") return isImage(part.media.mediaType) ? [mediaBytes(part.media)] : []
264+
if (part.type === "media") return matches(part.media.mediaType) ? [mediaBytes(part.media)] : []
232265
if (part.type !== "tool-result" || part.result.type !== "content") return []
233266
return part.result.value.flatMap((item: Content) =>
234-
item.type === "file" && isImage(item.mime) ? [item.uri.length] : [],
267+
item.type === "file" && matches(item.mime) ? [item.uri.length] : [],
235268
)
236269
}),
237270
)
238-
// Replay the images in order, dropping the oldest down to the target whenever the kept payload passes the trigger.
239-
// A new image then moves the cut only every (trigger - target) bytes instead of on every request, so the replaced
240-
// prefix, and with it the provider's prompt cache, stays the same between cuts.
271+
// Replay the media in order, dropping the oldest down to the target whenever the kept payload passes the trigger.
272+
// A new item then moves the cut only every (trigger - target) instead of on every request, so the replaced prefix,
273+
// and with it the provider's prompt cache, stays the same between cuts.
241274
let cut = 0
242275
let kept = 0
243-
for (const size of sizes) {
276+
for (const [index, size] of sizes.entries()) {
244277
kept += size
245-
if (kept <= IMAGE_BYTES_TRIGGER) continue
246-
while (kept > IMAGE_BYTES_TARGET) kept -= sizes[cut++]!
278+
if (kept <= trigger.bytes && index + 1 - cut <= (trigger.count ?? Infinity)) continue
279+
while (kept > target.bytes || index + 1 - cut > (target.count ?? Infinity)) kept -= sizes[cut++]!
247280
}
248281
if (cut === 0) return messages
249282

250283
let index = 0
251284
return replaceMedia(messages, (media) => {
252-
if (!isImage(media.mime)) return
253-
return index++ < cut ? IMAGE_REMOVED : undefined
285+
if (!matches(media.mime)) return
286+
return index++ < cut ? removed(media) : undefined
254287
})
255288
}
256289

@@ -343,14 +376,15 @@ export const layer = Layer.effect(
343376
cache: model.cache?.ttl === undefined ? undefined : { ttl: model.cache.ttl },
344377
system: shaped.system,
345378
// Strip the stored metadata hooks could read, so it never reaches the provider.
346-
messages: boundImages(
379+
messages: boundMedia(
347380
unsupportedParts(
348381
shaped.messages.map((message) => {
349382
const { metadata, ...rest } = message
350383
return metadata === undefined ? message : Message.make(rest)
351384
}),
352385
model.capabilities,
353386
model.model.provider,
387+
model.model.api.name,
354388
),
355389
),
356390
tools: Array.from(hooked, ([name, t]) => ({ ...t, name })),

‎packages/core/src/session/runner/to-llm-message.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import type { Model } from "@opencode/schema/model"
1313
import { getFilename } from "@opencode/util/path"
1414
import { Option, Schema } from "effect"
1515
import { fileURLToPath } from "url"
16+
import { Mime } from "../../mime.js"
1617
import { SessionMessage } from "../message.js"
1718
import { SessionCompactionBackground } from "../compaction-background.js"
1819
import { SessionCompactionSubagents } from "../compaction-subagents.js"
@@ -63,7 +64,8 @@ const directoryAttachment = (file: FileAttachment): TextPart => ({
6364
.join("\n")}`,
6465
})
6566

66-
const isMediaAttachment = (file: FileAttachment) => imageMimes.has(file.mime) || file.mime === "application/pdf"
67+
const isMediaAttachment = (file: FileAttachment) =>
68+
imageMimes.has(file.mime) || file.mime === "application/pdf" || Mime.audioVideo.has(file.mime)
6769

6870
const mediaLabel = (file: FileAttachment, labelAllInline: boolean) => {
6971
const location = attachmentLocation(file)

‎packages/core/src/tool/plugin/read.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -373,14 +373,21 @@ const tooLarge = (line: ReadToolFileSystem.OversizedLine, next: number | undefin
373373
`Line ${line.line} is ${size(line.bytes)}, more than the ${size(ReadToolFileSystem.MAX_READ_BYTES)} one read returns, so it isn't shown.` +
374374
(next === undefined ? "" : ` Continue reading with offset: ${next}.`)
375375

376+
const mediaKind = (mime: string) => {
377+
if (mime === "application/pdf") return "PDF"
378+
if (mime.startsWith("audio/")) return "Audio"
379+
if (mime.startsWith("video/")) return "Video"
380+
return "Image"
381+
}
382+
376383
export const toModelContent = (
377384
path: string,
378385
offset: number | undefined,
379386
output: ReadToolFileSystem.TextPage | ReadToolFileSystem.DirectoryContent | ReadToolFileSystem.Media,
380387
) => {
381388
if (output.type === "media")
382389
return [
383-
{ type: "text", text: output.mime === "application/pdf" ? "PDF read successfully" : "Image read successfully" },
390+
{ type: "text", text: `${mediaKind(output.mime)} read successfully` },
384391
{
385392
type: "file",
386393
uri: `data:${output.mime};base64,${Buffer.from(output.bytes).toString("base64")}`,

‎packages/core/src/tool/read-filesystem.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ export const read = Effect.fn("ReadTool.read")(function* (
132132
if ("type" in first) return first
133133

134134
const media = Mime.detectMedia(first.bytes)
135-
if (media && MEDIA_MIMES.has(media)) {
135+
if (media && (MEDIA_MIMES.has(media) || Mime.audioVideo.has(media))) {
136136
if (first.info.size > MAX_MEDIA_INGEST_BYTES)
137137
return yield* new MediaIngestLimitError({ resource, maximumBytes: MAX_MEDIA_INGEST_BYTES })
138138
const whole = yield* readFile(files, input, resource)

‎packages/core/test/session-model-request.test.ts‎

Lines changed: 53 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { describe, expect, test } from "bun:test"
22
import { Message, ToolMessage, ToolResultPart, Media, UserMessage, TextPart } from "@opencode/ai/effect"
3-
import { boundImages, unsupportedParts } from "@opencode/core/session/model-request"
3+
import { boundMedia, unsupportedParts } from "@opencode/core/session/model-request"
44

55
const capabilities = (input: string[]) => ({ tools: true, input, output: ["text"] })
66

@@ -215,10 +215,28 @@ describe("SessionModelRequest.unsupportedParts", () => {
215215
})
216216
})
217217

218-
describe("SessionModelRequest.boundImages", () => {
218+
describe("SessionModelRequest.unsupportedParts audio and video", () => {
219+
test("refuses audio and video on protocols that cannot carry them, even when the model lists them", () => {
220+
const messages = [
221+
Message.user([
222+
{ type: "media", media: Media.base64("AAAA", "audio/wav"), filename: "clip.wav" },
223+
{ type: "media", media: Media.base64("AAAA", "video/mp4"), filename: "clip.mp4" },
224+
]),
225+
]
226+
const accepts = capabilities(["text", "audio", "video"])
227+
228+
expect(unsupportedParts(messages, accepts, "google", "generate-content")).toEqual(messages)
229+
expect(unsupportedParts(messages, accepts, "openrouter", "chat-completions")[0]?.content).toEqual([
230+
TextPart.make('ERROR: Cannot read "clip.wav" (this model does not support audio input). Inform the user.'),
231+
TextPart.make('ERROR: Cannot read "clip.mp4" (this model does not support video input). Inform the user.'),
232+
])
233+
})
234+
})
235+
236+
describe("SessionModelRequest.boundMedia", () => {
219237
test("preserves images below the trigger", () => {
220238
const messages = [Message.user({ type: "media", media: Media.base64("aGVsbG8=", "image/png") })]
221-
expect(boundImages(messages)).toBe(messages)
239+
expect(boundMedia(messages)).toBe(messages)
222240
})
223241

224242
test("replaces oldest images until the retained payload reaches the target", () => {
@@ -231,7 +249,7 @@ describe("SessionModelRequest.boundImages", () => {
231249
Message.user({ type: "media", media: Media.base64(image, "image/png"), filename: "second.png" }),
232250
third,
233251
]
234-
const result = boundImages(messages)
252+
const result = boundMedia(messages)
235253

236254
expect(result[0]).toBeInstanceOf(UserMessage)
237255
expect(result[0]?.content).toEqual([{ type: "text", text: expect.stringContaining("image was removed") }])
@@ -244,21 +262,46 @@ describe("SessionModelRequest.boundImages", () => {
244262
test("keeps the replaced prefix stable as new images arrive, so the prompt cache survives", () => {
245263
const image = (name: string) =>
246264
Message.user({ type: "media", media: Media.base64("a".repeat(3 * 1024 * 1024), "image/png"), filename: name })
247-
const removed = (messages: ReturnType<typeof boundImages>) =>
265+
const removed = (messages: ReturnType<typeof boundMedia>) =>
248266
messages.filter((message) => message.content[0]?.type === "text").length
249267
const history = Array.from({ length: 9 }, (_, i) => image(`${i}.png`))
250268

251269
// 27 MiB passes the 25 MiB trigger: the oldest four go, leaving 15 MiB.
252-
expect(removed(boundImages(history))).toBe(4)
270+
expect(removed(boundMedia(history))).toBe(4)
253271
// Each later image used to move the cut by one; now the cut holds until the kept payload passes the trigger again.
254-
expect(removed(boundImages([...history, image("9.png")]))).toBe(4)
255-
expect(removed(boundImages([...history, image("9.png"), image("10.png"), image("11.png")]))).toBe(4)
256-
expect(removed(boundImages([...history, ...Array.from({ length: 4 }, (_, i) => image(`${9 + i}.png`))]))).toBe(8)
272+
expect(removed(boundMedia([...history, image("9.png")]))).toBe(4)
273+
expect(removed(boundMedia([...history, image("9.png"), image("10.png"), image("11.png")]))).toBe(4)
274+
expect(removed(boundMedia([...history, ...Array.from({ length: 4 }, (_, i) => image(`${9 + i}.png`))]))).toBe(8)
275+
})
276+
277+
test("keeps the newest audio and video and asks the model to read older ones again", () => {
278+
const clip = (name: string, mime: string) =>
279+
Message.tool(
280+
ToolResultPart.make({
281+
id: name,
282+
name: "read",
283+
result: { type: "content", value: [{ type: "file", uri: `data:${mime};base64,AAAA`, mime, name }] },
284+
}),
285+
)
286+
const image = Message.user({ type: "media", media: Media.base64("aGVsbG8=", "image/png"), filename: "logo.png" })
287+
const history = [clip("a.wav", "audio/wav"), image, clip("b.mp4", "video/mp4"), clip("c.wav", "audio/wav")]
288+
289+
expect(boundMedia([...history, clip("d.mp4", "video/mp4")])).toEqual([...history, clip("d.mp4", "video/mp4")])
290+
const result = boundMedia([...history, clip("d.mp4", "video/mp4"), clip("e.wav", "audio/wav")])
291+
expect(result[1]).toBe(image)
292+
expect(result.flatMap((message): ReadonlyArray<unknown> => message.content)).toMatchObject([
293+
{ result: { value: [{ type: "text", text: expect.stringContaining("This audio was removed") }] } },
294+
{ type: "media" },
295+
{ result: { value: [{ type: "text", text: expect.stringContaining("read b.mp4 again") }] } },
296+
{ result: { value: [{ type: "text", text: expect.stringContaining("read c.wav again") }] } },
297+
{ result: { value: [{ type: "file", name: "d.mp4" }] } },
298+
{ result: { value: [{ type: "file", name: "e.wav" }] } },
299+
])
257300
})
258301

259302
test("replaces images nested in tool results", () => {
260303
const image = "a".repeat(13 * 1024 * 1024)
261-
const result = boundImages([
304+
const result = boundMedia([
262305
Message.tool(
263306
ToolResultPart.make({
264307
id: "call_1",

0 commit comments

Comments
 (0)