mirror of
https://github.com/sipeed/picoclaw.git
synced 2026-06-12 18:08:54 +00:00
cb1e1a3595
* fix(feishu): fix image download with API fallback and post image support - Add Image.Get API fallback when MessageResource.Get fails (different permission scope: im:resource vs im:message:readonly) - Extract and download images from post (rich text) messages - Extract images from interactive card messages - Deduplicate post image keys across locales - Add comprehensive tests for new helpers Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(media): add image path tags alongside base64 for LLM file access Images are still base64-encoded into msg.Media for multimodal LLMs, but now also get [image:path] tags injected into message content so the LLM knows the local file path for save/forward operations. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor(media): only auto-inject images for tool results, not user messages Channel-received images (role=user) now get path tags only, letting the LLM decide whether to view via load_image or just operate on the file. Tool result images (role=tool, e.g. load_image) are base64-encoded into a synthetic user message appended after the tool message, since many LLM APIs don't support image_url in tool messages. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(media): preserve tool-message ordering for multi-tool-call scenarios Move synthetic user message (carrying base64 tool images) to after the entire contiguous tool-message block instead of immediately after each tool message. This preserves the assistant→tool→tool ordering required by OpenAI-compatible APIs. Also fix load_image to use generic [image: photo] placeholder so injectPathTags can properly replace it with the actual path. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(test): update load_image test for [image: photo] placeholder The test was checking ForLLM for the media:// ref, but load_image now emits the generic [image: photo] placeholder instead. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(media): match all channel image placeholders in injectPathTags Different channels emit different placeholder formats — Telegram/Feishu use [image: photo], WeCom/WeChat/Line use bare [image], QQ/Discord use [image: <filename>]. The previous string-match code only handled [image: photo], so for the other channels the path tag was appended as a duplicate, producing content like "[image] [image:/path]". Switch to per-type regex that matches all generic placeholder shapes while leaving path tags ([image:/path]) untouched. Also fixes the same issue for [audio], [video], [file] tags. Added test coverage for the various placeholder shapes. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(media): skip path tag append for JSON content (Feishu cards/posts) When content is structured JSON (interactive cards, post messages), injectPathTags now skips the fallback append — only placeholder replacement is attempted. This prevents corrupting JSON payloads like {"schema":"2.0",...} with appended [image:/path] tags. Adds looksLikeJSON() helper and three test cases covering JSON objects, arrays, and an end-to-end resolveMediaRefs scenario with Feishu card content. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(media): prepend path tags for JSON content, narrow looksLikeJSON Two fixes from code review: 1. looksLikeJSON now only checks for '{' prefix (not '['), avoiding false positives on regular text like "[update] see attached". 2. For JSON content (Feishu cards/posts), path tags are prepended before the JSON instead of being silently dropped. This ensures the LLM can discover attached images via the path tag while the JSON payload stays valid for downstream parsing. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
164 lines
4.6 KiB
Go
164 lines
4.6 KiB
Go
package fstools
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
|
|
"github.com/sipeed/picoclaw/pkg/config"
|
|
"github.com/sipeed/picoclaw/pkg/media"
|
|
)
|
|
|
|
// LoadImageTool loads a local image file into the MediaStore and returns a
|
|
// media:// reference. The agent loop's resolveMediaRefs will then base64-encode
|
|
// it and attach it as an image_url part in the next LLM request, enabling
|
|
// vision on local files — the same pipeline used when a user sends an image
|
|
// through a chat channel.
|
|
//
|
|
// This is intentionally different from SendFileTool:
|
|
// - SendFileTool → MediaResult + WithResponseHandled() → sends file to user, ends turn
|
|
// - LoadImageTool → plain ToolResult with media:// in ForLLM → LLM sees the image next turn
|
|
type LoadImageTool struct {
|
|
workspace string
|
|
restrict bool
|
|
maxFileSize int
|
|
mediaStore media.MediaStore
|
|
allowPaths []*regexp.Regexp
|
|
|
|
defaultChannel string
|
|
defaultChatID string
|
|
}
|
|
|
|
func NewLoadImageTool(
|
|
workspace string,
|
|
restrict bool,
|
|
maxFileSize int,
|
|
store media.MediaStore,
|
|
allowPaths ...[]*regexp.Regexp,
|
|
) *LoadImageTool {
|
|
if maxFileSize <= 0 {
|
|
maxFileSize = config.DefaultMaxMediaSize
|
|
}
|
|
var patterns []*regexp.Regexp
|
|
if len(allowPaths) > 0 {
|
|
patterns = allowPaths[0]
|
|
}
|
|
return &LoadImageTool{
|
|
workspace: workspace,
|
|
restrict: restrict,
|
|
maxFileSize: maxFileSize,
|
|
mediaStore: store,
|
|
allowPaths: patterns,
|
|
}
|
|
}
|
|
|
|
func (t *LoadImageTool) Name() string { return "load_image" }
|
|
|
|
func (t *LoadImageTool) Description() string {
|
|
return "Load a local image file so you can analyze its contents with vision. " +
|
|
"Supported formats: JPEG, PNG, GIF, WebP, BMP. " +
|
|
"After calling this tool, describe or analyze the image in your next response."
|
|
}
|
|
|
|
func (t *LoadImageTool) Parameters() map[string]any {
|
|
return map[string]any{
|
|
"type": "object",
|
|
"properties": map[string]any{
|
|
"path": map[string]any{
|
|
"type": "string",
|
|
"description": "Path to the local image file. Relative paths are resolved from workspace.",
|
|
},
|
|
},
|
|
"required": []string{"path"},
|
|
}
|
|
}
|
|
|
|
func (t *LoadImageTool) SetContext(channel, chatID string) {
|
|
t.defaultChannel = channel
|
|
t.defaultChatID = chatID
|
|
}
|
|
|
|
func (t *LoadImageTool) SetMediaStore(store media.MediaStore) {
|
|
t.mediaStore = store
|
|
}
|
|
|
|
func (t *LoadImageTool) Execute(ctx context.Context, args map[string]any) *ToolResult {
|
|
path, _ := args["path"].(string)
|
|
if strings.TrimSpace(path) == "" {
|
|
return ErrorResult("path is required")
|
|
}
|
|
|
|
// Prefer context-injected channel/chatID (set by ExecuteWithContext), fall back to SetContext values.
|
|
channel := ToolChannel(ctx)
|
|
if channel == "" {
|
|
channel = t.defaultChannel
|
|
}
|
|
chatID := ToolChatID(ctx)
|
|
if chatID == "" {
|
|
chatID = t.defaultChatID
|
|
}
|
|
if channel == "" || chatID == "" {
|
|
return ErrorResult("no target channel/chat available")
|
|
}
|
|
|
|
if t.mediaStore == nil {
|
|
return ErrorResult("media store not configured")
|
|
}
|
|
|
|
resolved, err := validatePathWithAllowPaths(path, t.workspace, t.restrict, t.allowPaths)
|
|
if err != nil {
|
|
return ErrorResult(fmt.Sprintf("invalid path: %v", err))
|
|
}
|
|
|
|
info, err := os.Stat(resolved)
|
|
if err != nil {
|
|
return ErrorResult(fmt.Sprintf("file not found: %v", err))
|
|
}
|
|
if info.IsDir() {
|
|
return ErrorResult("path is a directory, expected an image file")
|
|
}
|
|
if info.Size() > int64(t.maxFileSize) {
|
|
return ErrorResult(fmt.Sprintf(
|
|
"file too large: %d bytes (max %d bytes)", info.Size(), t.maxFileSize,
|
|
))
|
|
}
|
|
|
|
// Detect MIME type — reuse the helper already in send_file.go
|
|
mediaType := detectMediaType(resolved)
|
|
if !strings.HasPrefix(mediaType, "image/") {
|
|
return ErrorResult(fmt.Sprintf(
|
|
"file does not appear to be an image (detected type: %s)", mediaType,
|
|
))
|
|
}
|
|
|
|
filename := filepath.Base(resolved)
|
|
scope := fmt.Sprintf("tool:load_image:%s:%s", channel, chatID)
|
|
|
|
ref, err := t.mediaStore.Store(resolved, media.MediaMeta{
|
|
Filename: filename,
|
|
ContentType: mediaType,
|
|
Source: "tool:load_image",
|
|
CleanupPolicy: media.CleanupPolicyForgetOnly,
|
|
}, scope)
|
|
if err != nil {
|
|
return ErrorResult(fmt.Sprintf("failed to register image in media store: %v", err))
|
|
}
|
|
|
|
// Build the tool result text. The media:// ref in Media will be picked
|
|
// up by resolveMediaRefs in agent_media.go and base64-encoded for tool
|
|
// result messages (role="tool"), so the LLM can see the image content.
|
|
msg := fmt.Sprintf("Image loaded: %s\n[image: photo]", filename)
|
|
|
|
return &ToolResult{
|
|
ForLLM: msg,
|
|
ForUser: fmt.Sprintf("Loaded image: %s", filename),
|
|
// Media refs inside ForLLM are resolved by resolveMediaRefs in the
|
|
// agent loop before the next LLM call. Do NOT use MediaResult here —
|
|
// that would send the file to the user channel instead.
|
|
Media: []string{ref},
|
|
}
|
|
}
|