diff --git a/internal/protocol/content.go b/internal/protocol/content.go index 2ca5269..c176240 100644 --- a/internal/protocol/content.go +++ b/internal/protocol/content.go @@ -282,7 +282,11 @@ func encodeAnthropicBlocks(blocks []bridgeBlock) []any { } parts = append(parts, map[string]any{"type": "tool_use", "id": block.ID, "name": block.Name, "input": input}) case "tool_result": - parts = append(parts, map[string]any{"type": "tool_result", "tool_use_id": block.CallID, "content": block.Result, "is_error": block.IsError}) + content := block.Result + if blocks, ok := content.([]bridgeBlock); ok { + content = encodeAnthropicBlocks(blocks) + } + parts = append(parts, map[string]any{"type": "tool_result", "tool_use_id": block.CallID, "content": content, "is_error": block.IsError}) case "reasoning": if block.Encrypted != "" { parts = append(parts, map[string]any{"type": "redacted_thinking", "data": block.Encrypted}) diff --git a/internal/protocol/request.go b/internal/protocol/request.go index 7fa1ee6..580d085 100644 --- a/internal/protocol/request.go +++ b/internal/protocol/request.go @@ -564,6 +564,22 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest default: return request, fmt.Errorf("unsupported input protocol %q", protocol) } + for i := range request.Messages { + for j := range request.Messages[i].Blocks { + block := &request.Messages[i].Blocks[j] + if block.Kind != "tool_result" || protocol == Chat { + continue + } + result, err := decodeToolImages(protocol, block.Result) + if err != nil { + return request, fmt.Errorf("messages[%d].tool_result[%d]: %w", i, j, err) + } + if _, images := result.([]bridgeBlock); images && block.CallID == "" { + return request, fmt.Errorf("messages[%d]: tool image result requires a call ID", i) + } + block.Result = result + } + } return request, nil } @@ -782,14 +798,22 @@ func encodeChatRequest(request bridgeRequest) (map[string]any, error) { } } if len(pending) == 0 && len(pendingOrder) > 0 { + var attachments []map[string]any for _, id := range pendingOrder { result := pendingResults[id] + text, images := chatToolImages(result) + if len(images) > 0 { + attachments = append(attachments, map[string]any{"role": "user", "content": encodeChatBlocks(images)}) + } messages = append(messages, map[string]any{ "role": "tool", "tool_call_id": id, - "content": bridgeToolResultContent(result.Result), + "content": text, }) } + for _, attachment := range attachments { + messages = append(messages, attachment) + } flushDeferred() pendingOrder = nil clear(pendingResults) @@ -981,7 +1005,7 @@ func encodeResponsesRequest(request bridgeRequest) map[string]any { items = append(items, map[string]any{ "type": "function_call_output", "call_id": block.CallID, - "output": bridgeToolResultContent(block.Result), + "output": responsesToolContent(block.Result), }) } } diff --git a/internal/protocol/tool_images.go b/internal/protocol/tool_images.go new file mode 100644 index 0000000..0dd369d --- /dev/null +++ b/internal/protocol/tool_images.go @@ -0,0 +1,120 @@ +package protocol + +import ( + "fmt" + "strings" + + "opencode2api/internal/jsonutil" +) + +// Only image-bearing tool results enter this path. Keep all legacy text and +// opaque results unchanged, and reuse bridgeBlock rather than a second model. +func decodeToolImages(from Protocol, value any) (any, error) { + parts, ok := value.([]any) + if !ok { + return value, nil + } + imageType, textType := "input_image", "input_text" + if from == Anthropic { + imageType, textType = "image", "text" + } + hasImage := false + for _, raw := range parts { + part, _ := raw.(map[string]any) + hasImage = hasImage || jsonutil.StringAt(part, "type") == imageType + } + if !hasImage { + return value, nil + } + for i, raw := range parts { + part, ok := raw.(map[string]any) + if !ok { + return nil, fmt.Errorf("content[%d] must be an object", i) + } + switch jsonutil.StringAt(part, "type") { + case textType: + if _, ok := part["text"].(string); !ok { + return nil, fmt.Errorf("content[%d] requires text", i) + } + case imageType: + if from == Anthropic { + source := jsonutil.MapAt(part, "source") + valid := false + switch jsonutil.StringAt(source, "type") { + case "url": + valid = jsonutil.StringAt(source, "url") != "" && source["data"] == nil && source["file_id"] == nil + case "base64": + valid = jsonutil.StringAt(source, "data") != "" && strings.HasPrefix(jsonutil.StringAt(source, "media_type"), "image/") && source["url"] == nil && source["file_id"] == nil + } + if !valid { + return nil, fmt.Errorf("content[%d] has an unsupported or conflicting image source", i) + } + } else if jsonutil.StringAt(part, "image_url") == "" || part["file_id"] != nil { + return nil, fmt.Errorf("content[%d] requires an image URL without a file reference", i) + } + default: + return nil, fmt.Errorf("content[%d] contains an unsupported block alongside tool images", i) + } + } + if from == Anthropic { + return decodeAnthropicBlocksChecked(value) + } + blocks, err := decodeOpenAIBlocksChecked(value) + if err != nil { + return nil, err + } + for i := range blocks { + block := &blocks[i] + if block.Kind != "image" || !strings.HasPrefix(block.URL, "data:") { + continue + } + header, data, ok := strings.Cut(strings.TrimPrefix(block.URL, "data:"), ",") + media, base64 := strings.CutSuffix(header, ";base64") + if !ok || !base64 || !strings.HasPrefix(media, "image/") || data == "" { + return nil, fmt.Errorf("content[%d] has an invalid image data URI", i) + } + block.URL, block.MediaType, block.Data = "", media, data + } + return blocks, nil +} + +func chatToolImages(result bridgeBlock) (string, []bridgeBlock) { + parts, ok := result.Result.([]bridgeBlock) + if !ok { + return bridgeToolResultContent(result.Result), nil + } + var text strings.Builder + var images []bridgeBlock + n := 0 + for _, part := range parts { + if part.Kind == "text" { + text.WriteString(part.Text) + continue + } + n++ + marker := fmt.Sprintf("[tool_image call_id=%s index=%d]", bridgeArgumentsJSON(bridgeBlock{Arguments: result.CallID}), n) + text.WriteString("\n" + marker + "\n") + images = append(images, bridgeBlock{Kind: "text", Text: marker}, part) + } + return text.String(), images +} + +func responsesToolContent(value any) any { + parts, ok := value.([]bridgeBlock) + if !ok { + return bridgeToolResultContent(value) + } + content := make([]any, 0, len(parts)) + for _, part := range parts { + if part.Kind == "text" { + content = append(content, map[string]any{"type": "input_text", "text": part.Text}) + } else { + url := part.URL + if url == "" { + url = "data:" + part.MediaType + ";base64," + part.Data + } + content = append(content, map[string]any{"type": "input_image", "image_url": url}) + } + } + return content +}