Skip to content
This repository was archived by the owner on May 23, 2026. It is now read-only.

Commit 4e14f79

Browse files
authored
fix: tweaks to transform logic for anthropic and bedrock (anomalyco#26276)
1 parent e0396b8 commit 4e14f79

3 files changed

Lines changed: 190 additions & 24 deletions

File tree

‎packages/opencode/src/provider/transform.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,9 +135,16 @@ function normalizeMessages(
135135
}
136136
if (!Array.isArray(msg.content)) return msg
137137
const filtered = msg.content.filter((part) => {
138-
if (part.type === "text" || part.type === "reasoning") {
138+
if (part.type === "text") {
139139
return part.text !== ""
140140
}
141+
if (part.type === "reasoning") {
142+
return (
143+
part.text.trim().length > 0 ||
144+
part.providerOptions?.anthropic?.signature != null ||
145+
part.providerOptions?.anthropic?.redactedData != null
146+
)
147+
}
141148
return true
142149
})
143150
if (filtered.length === 0) return undefined
@@ -156,9 +163,16 @@ function normalizeMessages(
156163
}
157164
if (!Array.isArray(msg.content)) return msg
158165
const filtered = msg.content.filter((part) => {
159-
if (part.type === "text" || part.type === "reasoning") {
166+
if (part.type === "text") {
160167
return part.text !== ""
161168
}
169+
if (part.type === "reasoning") {
170+
return (
171+
part.text.trim().length > 0 ||
172+
part.providerOptions?.bedrock?.signature != null ||
173+
part.providerOptions?.bedrock?.redactedData != null
174+
)
175+
}
162176
return true
163177
})
164178
if (filtered.length === 0) return undefined

‎packages/opencode/src/session/message-v2.ts‎

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ interface FetchDecompressionError extends Error {
3535
path: string
3636
}
3737

38-
export const SYNTHETIC_ATTACHMENT_PROMPT = "Attached image(s) from tool result:"
38+
export const SYNTHETIC_ATTACHMENT_PROMPT = "Attached media from tool result:"
3939
export { isMedia }
4040

4141
export const OutputLengthError = namedSchemaError("MessageOutputLengthError", {})
@@ -734,25 +734,25 @@ export const toModelMessagesEffect = Effect.fnUntraced(function* (
734734
const result: UIMessage[] = []
735735
const toolNames = new Set<string>()
736736
// Track media from tool results that need to be injected as user messages
737-
// for providers that don't support media in tool results.
737+
// for providers that don't support that media type in tool results.
738738
//
739739
// OpenAI-compatible APIs only support string content in tool results, so we need
740-
// to extract media and inject as user messages. Other SDKs (anthropic, google,
741-
// bedrock) handle type: "content" with media parts natively.
740+
// to extract media and inject as user messages. Some SDKs only support a subset
741+
// of media in tool results; e.g. Bedrock supports images but not PDFs there.
742742
//
743-
// Only apply this workaround if the model actually supports image input -
744-
// otherwise there's no point extracting images.
745-
const supportsMediaInToolResults = (() => {
743+
// Only apply this workaround if the model actually supports that media input -
744+
// otherwise unsupportedParts() will turn it into a user-visible error.
745+
const supportsMediaInToolResult = (attachment: { mime: string }) => {
746746
if (model.api.npm === "@ai-sdk/anthropic") return true
747747
if (model.api.npm === "@ai-sdk/openai") return true
748-
if (model.api.npm === "@ai-sdk/amazon-bedrock") return true
748+
if (model.api.npm === "@ai-sdk/amazon-bedrock") return attachment.mime.startsWith("image/")
749749
if (model.api.npm === "@ai-sdk/google-vertex/anthropic") return true
750750
if (model.api.npm === "@ai-sdk/google") {
751751
const id = model.api.id.toLowerCase()
752752
return id.includes("gemini-3") && !id.includes("gemini-2")
753753
}
754754
return false
755-
})()
755+
}
756756

757757
const toModelOutput = (options: { toolCallId: string; input: unknown; output: unknown }) => {
758758
const output = options.output
@@ -797,9 +797,9 @@ export const toModelMessagesEffect = Effect.fnUntraced(function* (
797797
role: "user",
798798
parts: [],
799799
}
800-
result.push(userMessage)
801800
for (const part of msg.parts) {
802-
if (part.type === "text" && !part.ignored)
801+
// User message parts should never be empty
802+
if (part.type === "text" && !part.ignored && part.text !== "")
803803
userMessage.parts.push({
804804
type: "text",
805805
text: part.text,
@@ -834,11 +834,12 @@ export const toModelMessagesEffect = Effect.fnUntraced(function* (
834834
})
835835
}
836836
}
837+
if (userMessage.parts.length > 0) result.push(userMessage)
837838
}
838839

839840
if (msg.info.role === "assistant") {
840841
const differentModel = `${model.providerID}/${model.id}` !== `${msg.info.providerID}/${msg.info.modelID}`
841-
const media: Array<{ mime: string; url: string }> = []
842+
const media: Array<{ mime: string; url: string; filename?: string }> = []
842843

843844
if (
844845
msg.info.error &&
@@ -864,11 +865,10 @@ export const toModelMessagesEffect = Effect.fnUntraced(function* (
864865
// a proxy, or a lower-level library, but preserving a non-empty separator
865866
// here is the only safe replay point we have.
866867
// Use a single space so the separator survives replay without changing
867-
// the neighboring signed reasoning blocks. Bedrock-hosted Claude stores
868-
// the same signature under the bedrock metadata namespace.
868+
// the neighboring signed reasoning blocks.
869869
const hasSignedReasoning = msg.parts.some((part) => {
870870
if (part.type !== "reasoning") return false
871-
return part.metadata?.anthropic?.signature != null || part.metadata?.bedrock?.signature != null
871+
return part.metadata?.anthropic?.signature != null
872872
})
873873
for (const part of msg.parts) {
874874
if (part.type === "text") {
@@ -894,11 +894,11 @@ export const toModelMessagesEffect = Effect.fnUntraced(function* (
894894
// For providers that don't support media in tool results, extract media files
895895
// (images, PDFs) to be sent as a separate user message
896896
const mediaAttachments = attachments.filter((a) => isMedia(a.mime))
897-
const nonMediaAttachments = attachments.filter((a) => !isMedia(a.mime))
898-
if (!supportsMediaInToolResults && mediaAttachments.length > 0) {
899-
media.push(...mediaAttachments)
897+
const extractedMedia = mediaAttachments.filter((a) => !supportsMediaInToolResult(a))
898+
if (extractedMedia.length > 0) {
899+
media.push(...extractedMedia)
900900
}
901-
const finalAttachments = supportsMediaInToolResults ? attachments : nonMediaAttachments
901+
const finalAttachments = attachments.filter((a) => !isMedia(a.mime) || supportsMediaInToolResult(a))
902902

903903
const output =
904904
finalAttachments.length > 0
@@ -988,6 +988,7 @@ export const toModelMessagesEffect = Effect.fnUntraced(function* (
988988
type: "file" as const,
989989
url: attachment.url,
990990
mediaType: attachment.mime,
991+
filename: attachment.filename,
991992
})),
992993
],
993994
})

‎packages/opencode/test/session/message-v2.test.ts‎

Lines changed: 154 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,54 @@ describe("session.message-v2.toModelMessage", () => {
155155
expect(await MessageV2.toModelMessages(input, model)).toStrictEqual([])
156156
})
157157

158+
test("filters out user messages with only empty text parts", async () => {
159+
const messageID = "m-user"
160+
161+
const input: MessageV2.WithParts[] = [
162+
{
163+
info: userInfo(messageID),
164+
parts: [
165+
{
166+
...basePart(messageID, "p1"),
167+
type: "text",
168+
text: "",
169+
},
170+
] as MessageV2.Part[],
171+
},
172+
]
173+
174+
expect(await MessageV2.toModelMessages(input, model)).toStrictEqual([])
175+
})
176+
177+
test("filters empty user text parts while keeping non-empty parts", async () => {
178+
const messageID = "m-user"
179+
180+
const input: MessageV2.WithParts[] = [
181+
{
182+
info: userInfo(messageID),
183+
parts: [
184+
{
185+
...basePart(messageID, "p1"),
186+
type: "text",
187+
text: "",
188+
},
189+
{
190+
...basePart(messageID, "p2"),
191+
type: "text",
192+
text: "hello",
193+
},
194+
] as MessageV2.Part[],
195+
},
196+
]
197+
198+
expect(await MessageV2.toModelMessages(input, model)).toStrictEqual([
199+
{
200+
role: "user",
201+
content: [{ type: "text", text: "hello" }],
202+
},
203+
])
204+
})
205+
158206
test("includes synthetic text parts", async () => {
159207
const messageID = "m-user"
160208

@@ -443,6 +491,108 @@ describe("session.message-v2.toModelMessage", () => {
443491
})
444492
})
445493

494+
test("moves bedrock pdf tool-result media into a separate user message", async () => {
495+
const bedrockModel: Provider.Model = {
496+
...model,
497+
id: ModelID.make("amazon-bedrock/anthropic.claude-sonnet-4-6"),
498+
providerID: ProviderID.make("amazon-bedrock"),
499+
api: {
500+
id: "anthropic.claude-sonnet-4-6",
501+
url: "https://bedrock-runtime.us-east-1.amazonaws.com",
502+
npm: "@ai-sdk/amazon-bedrock",
503+
},
504+
capabilities: {
505+
...model.capabilities,
506+
attachment: true,
507+
input: {
508+
...model.capabilities.input,
509+
image: true,
510+
pdf: true,
511+
},
512+
},
513+
}
514+
const pdf = Buffer.from("%PDF-1.4\n").toString("base64")
515+
const userID = "m-user-bedrock-pdf"
516+
const assistantID = "m-assistant-bedrock-pdf"
517+
const input: MessageV2.WithParts[] = [
518+
{
519+
info: userInfo(userID),
520+
parts: [
521+
{
522+
...basePart(userID, "u1-bedrock-pdf"),
523+
type: "text",
524+
text: "run tool",
525+
},
526+
] as MessageV2.Part[],
527+
},
528+
{
529+
info: assistantInfo(assistantID, userID),
530+
parts: [
531+
{
532+
...basePart(assistantID, "a1-bedrock-pdf"),
533+
type: "tool",
534+
callID: "call-bedrock-pdf-1",
535+
tool: "read",
536+
state: {
537+
status: "completed",
538+
input: { filePath: "/tmp/example.pdf" },
539+
output: "PDF read successfully",
540+
title: "Read",
541+
metadata: {},
542+
time: { start: 0, end: 1 },
543+
attachments: [
544+
{
545+
...basePart(assistantID, "file-bedrock-pdf-1"),
546+
type: "file",
547+
mime: "application/pdf",
548+
filename: "example.pdf",
549+
url: `data:application/pdf;base64,${pdf}`,
550+
},
551+
],
552+
},
553+
},
554+
] as MessageV2.Part[],
555+
},
556+
]
557+
558+
expect(await MessageV2.toModelMessages(input, bedrockModel)).toStrictEqual([
559+
{
560+
role: "user",
561+
content: [{ type: "text", text: "run tool" }],
562+
},
563+
{
564+
role: "assistant",
565+
content: [
566+
{
567+
type: "tool-call",
568+
toolCallId: "call-bedrock-pdf-1",
569+
toolName: "read",
570+
input: { filePath: "/tmp/example.pdf" },
571+
providerExecuted: undefined,
572+
},
573+
],
574+
},
575+
{
576+
role: "tool",
577+
content: [
578+
{
579+
type: "tool-result",
580+
toolCallId: "call-bedrock-pdf-1",
581+
toolName: "read",
582+
output: { type: "text", value: "PDF read successfully" },
583+
},
584+
],
585+
},
586+
{
587+
role: "user",
588+
content: [
589+
{ type: "text", text: "Attached media from tool result:" },
590+
{ type: "file", mediaType: "application/pdf", filename: "example.pdf", data: `data:application/pdf;base64,${pdf}` },
591+
],
592+
},
593+
])
594+
})
595+
446596
test("omits provider metadata when assistant model differs", async () => {
447597
const userID = "m-user"
448598
const assistantID = "m-assistant"
@@ -1134,8 +1284,9 @@ describe("session.message-v2.toModelMessage", () => {
11341284
expect((result[1].content as any[]).find((p) => p.type === "text").text).toBe("the answer")
11351285
})
11361286

1137-
test("substitutes space for empty text when reasoning signature is under 'bedrock' namespace", async () => {
1138-
// AWS Bedrock hosts Anthropic Claude but stores signatures under metadata.bedrock
1287+
test("leaves empty text alone when reasoning signature is under 'bedrock' namespace", async () => {
1288+
// Bedrock signed reasoning is preserved as reasoning metadata, but unlike the
1289+
// direct Anthropic path we do not preserve empty text separators for Bedrock.
11391290
const assistantID = "m-assistant-bedrock"
11401291
const input: MessageV2.WithParts[] = [
11411292
{
@@ -1157,7 +1308,7 @@ describe("session.message-v2.toModelMessage", () => {
11571308

11581309
expect(result).toHaveLength(1)
11591310
const texts = (result[0].content as any[]).filter((p) => p.type === "text")
1160-
expect(texts.map((t) => t.text)).toStrictEqual([" ", "answer"])
1311+
expect(texts.map((t) => t.text)).toStrictEqual(["", "answer"])
11611312
})
11621313

11631314
test("leaves empty text alone when reasoning has no Anthropic signature", async () => {

0 commit comments

Comments
 (0)