From a455e4025cdca45c775b666cd7c20e1ab8ce9f08 Mon Sep 17 00:00:00 2001 From: Sycun <165354365+Sycun@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:32:07 +0800 Subject: [PATCH] feat(vision): support native image blocks in host tool replies and route vision via Pi Host tool results can now carry images, which reach image-capable models as native content blocks while staying out of the host event stream and exported history. The vision client drops its own HTTP stack and reuses the Pi multimodal single shot, keeping path validation and preprocessing unchanged. --- internal/agentruntime/types.go | 1 + internal/vision/client.go | 52 ++++---------- internal/vision/client_pi_test.go | 108 ++++++++++++++++++++++++++++++ internal/vision/tool.go | 2 +- runtime/pi/src/worker.ts | 31 ++++++--- runtime/pi/test/worker.test.mjs | 30 +++++++++ 6 files changed, 176 insertions(+), 48 deletions(-) create mode 100644 internal/vision/client_pi_test.go diff --git a/internal/agentruntime/types.go b/internal/agentruntime/types.go index ef977b6d..7250c37d 100644 --- a/internal/agentruntime/types.go +++ b/internal/agentruntime/types.go @@ -97,6 +97,7 @@ type ToolCall struct { type ToolResult struct { Content string `json:"content"` + Images []Image `json:"images,omitempty"` IsError bool `json:"isError,omitempty"` ExecutionID string `json:"executionId,omitempty"` Terminate bool `json:"terminate,omitempty"` diff --git a/internal/vision/client.go b/internal/vision/client.go index 127ccff2..2152aa8d 100644 --- a/internal/vision/client.go +++ b/internal/vision/client.go @@ -2,26 +2,25 @@ package vision import ( "context" - "encoding/base64" "fmt" - "net" - "net/http" "strings" "time" + "cyberstrike-ai/internal/agentruntime" "cyberstrike-ai/internal/config" - "cyberstrike-ai/internal/openai" + "cyberstrike-ai/internal/multiagent" ) // Client 调用独立 Vision ChatModel(单次 Generate)。 type Client struct { - cfg config.VisionConfig - mainOA config.OpenAIConfig + cfg config.VisionConfig + mainOA config.OpenAIConfig + runtime config.AgentRuntimeConfig } // NewClient 构造视觉客户端。 -func NewClient(visionCfg config.VisionConfig, mainOpenAI config.OpenAIConfig) *Client { - return &Client{cfg: visionCfg, mainOA: mainOpenAI} +func NewClient(visionCfg config.VisionConfig, mainOpenAI config.OpenAIConfig, runtime config.AgentRuntimeConfig) *Client { + return &Client{cfg: visionCfg, mainOA: mainOpenAI, runtime: runtime} } // Analyze 将图片字节送入 VL 模型并返回文本描述。 @@ -41,38 +40,13 @@ func (c *Client) Analyze(ctx context.Context, img ImagePayload, question string) return "", fmt.Errorf("vision model is empty") } - timeout := time.Duration(c.cfg.TimeoutSecondsEffective()) * time.Second - ctx, cancel := context.WithTimeout(ctx, timeout) + ctx, cancel := context.WithTimeout(ctx, time.Duration(c.cfg.TimeoutSecondsEffective())*time.Second) defer cancel() - httpClient := &http.Client{ - Timeout: timeout + 15*time.Second, - Transport: &http.Transport{ - DialContext: (&net.Dialer{ - Timeout: 60 * time.Second, - KeepAlive: 60 * time.Second, - }).DialContext, - ResponseHeaderTimeout: timeout + 10*time.Second, - }, - } - - b64 := base64.StdEncoding.EncodeToString(img.Bytes) - payload := map[string]any{"model": oa.Model, "max_completion_tokens": oa.MaxCompletionTokensEffective(), "messages": []map[string]any{{"role": "user", "content": []map[string]any{{"type": "text", "text": buildVisionPrompt(question)}, {"type": "image_url", "image_url": map[string]any{"url": "data:" + mime + ";base64," + b64, "detail": c.cfg.DetailEffective()}}}}}} - var reply struct { - Choices []struct { - Message struct { - Content string `json:"content"` - } `json:"message"` - } `json:"choices"` - } - client := openai.NewClient(&oa, httpClient, nil) - if err := client.ChatCompletion(ctx, payload, &reply); err != nil { - return "", err - } - if len(reply.Choices) == 0 || strings.TrimSpace(reply.Choices[0].Message.Content) == "" { - return "", fmt.Errorf("vision model returned empty content") - } - return strings.TrimSpace(reply.Choices[0].Message.Content), nil + return multiagent.CompleteVisionWithRuntime(ctx, c.runtime, oa, multiagent.SingleShot{ + Message: buildVisionPrompt(question), + Images: []agentruntime.Image{{MIMEType: mime, Data: img.Bytes}}, + }) } func buildVisionPrompt(question string) string { @@ -96,4 +70,4 @@ func looksLikeCaptchaQuestion(q string) bool { } } return strings.Contains(s, "只输出") && (strings.Contains(s, "字符") || strings.Contains(s, "character")) -} +} \ No newline at end of file diff --git a/internal/vision/client_pi_test.go b/internal/vision/client_pi_test.go new file mode 100644 index 00000000..884aed96 --- /dev/null +++ b/internal/vision/client_pi_test.go @@ -0,0 +1,108 @@ +package vision + +import ( + "context" + "encoding/base64" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os/exec" + "strings" + "testing" + + "cyberstrike-ai/internal/agentruntime" + "cyberstrike-ai/internal/config" +) + +const fixturePNG = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAKElEQVR4nO3NsQ0AAAzCMP5/un0CNkuZ41wybXsHAAAAAAAAAAAAxR4yw/wuPL6QkAAAAABJRU5ErkJggg==" + +func TestAnalyzeRoutesImageThroughPi(t *testing.T) { + if _, err := exec.LookPath("node"); err != nil { + t.Skip("Node not installed") + } + if _, err := agentruntime.ResolveWorker(""); err != nil { + t.Skip("build runtime/pi before Pi integration tests") + } + raw, err := base64.StdEncoding.DecodeString(fixturePNG) + if err != nil { + t.Fatal(err) + } + + var userText, imageURL string + var tools json.RawMessage + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body struct { + Messages []struct { + Role string `json:"role"` + Content json.RawMessage `json:"content"` + } `json:"messages"` + Tools json.RawMessage `json:"tools"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + w.WriteHeader(http.StatusBadRequest) + return + } + tools = body.Tools + for _, message := range body.Messages { + if message.Role != "user" { + continue + } + var blocks []struct { + Type string `json:"type"` + Text string `json:"text"` + ImageURL struct { + URL string `json:"url"` + } `json:"image_url"` + } + if json.Unmarshal(message.Content, &blocks) != nil { + continue + } + for _, block := range blocks { + switch block.Type { + case "text": + userText += block.Text + case "image_url": + imageURL = block.ImageURL.URL + } + } + } + w.Header().Set("Content-Type", "text/event-stream") + for _, choice := range []map[string]any{ + {"index": 0, "delta": map[string]any{"role": "assistant", "content": "A7K2"}, "finish_reason": nil}, + {"index": 0, "delta": map[string]any{}, "finish_reason": "stop"}, + } { + b, _ := json.Marshal(map[string]any{"id": "fixture", "object": "chat.completion.chunk", "model": "fixture", "choices": []any{choice}}) + fmt.Fprintf(w, "data: %s\n\n", b) + } + fmt.Fprint(w, "data: [DONE]\n\n") + })) + defer server.Close() + + client := NewClient(config.VisionConfig{Enabled: true, Model: "fixture-vl", APIKey: "fixture-key", BaseURL: server.URL + "/v1"}, + config.OpenAIConfig{}, config.AgentRuntimeConfig{}) + got, err := client.Analyze(context.Background(), ImagePayload{Bytes: raw, MIMEType: "image/png"}, "识别验证码,只输出字符") + if err != nil { + t.Fatal(err) + } + if got != "A7K2" { + t.Fatalf("analysis = %q", got) + } + if want := "data:image/png;base64," + fixturePNG; imageURL != want { + t.Fatalf("image reached the model as %q", imageURL) + } + if !strings.Contains(userText, "识别验证码") || !strings.Contains(userText, "仅输出你辨认出的字符序列") { + t.Fatalf("captcha prompt missing: %q", userText) + } + if len(tools) != 0 { + t.Fatalf("vision call exposed tools: %s", tools) + } +} + +func TestAnalyzeRejectsEmptyPayload(t *testing.T) { + client := NewClient(config.VisionConfig{Enabled: true, Model: "fixture-vl", APIKey: "fixture-key"}, config.OpenAIConfig{}, config.AgentRuntimeConfig{}) + if _, err := client.Analyze(context.Background(), ImagePayload{}, "describe"); err == nil { + t.Fatal("empty payload accepted") + } +} \ No newline at end of file diff --git a/internal/vision/tool.go b/internal/vision/tool.go index 1654323d..fdd6e9bf 100644 --- a/internal/vision/tool.go +++ b/internal/vision/tool.go @@ -40,7 +40,7 @@ func RegisterAnalyzeImageTool(mcpServer *mcp.Server, cfg *config.Config, logger MaxPayloadBytes: cfg.Vision.MaxPayloadBytesEffective(), SkipPreprocessBelowBytes: cfg.Vision.SkipPreprocessBelowBytesEffective(), } - client := NewClient(cfg.Vision, cfg.OpenAI) + client := NewClient(cfg.Vision, cfg.OpenAI, cfg.AgentRuntime) tool := mcp.Tool{ Name: builtin.ToolAnalyzeImage, diff --git a/runtime/pi/src/worker.ts b/runtime/pi/src/worker.ts index 77f18498..c9290ad5 100644 --- a/runtime/pi/src/worker.ts +++ b/runtime/pi/src/worker.ts @@ -39,7 +39,7 @@ interface RunRequest { toolSearch?: boolean; alwaysVisibleTools?: string[]; toolSearchMinTools?: number; } -interface ToolReply { content: string; isError?: boolean; executionId?: string; terminate?: boolean; structuredContent?: Record } +interface ToolReply { content: string; images?: Omit[]; isError?: boolean; executionId?: string; terminate?: boolean; structuredContent?: Record } let session: AgentSession | undefined; let started = false; @@ -62,7 +62,7 @@ function resources(prompt: string): ResourceLoader { }; } -function hostTool(def: RunRequest["tools"][number], recorded?: (name: string, reply: ToolReply) => void, entryFor?: (providerId: string) => string | undefined): ToolDefinition { +function hostTool(def: RunRequest["tools"][number], imageInput: boolean, recorded?: (name: string, reply: ToolReply) => void, entryFor?: (providerId: string) => string | undefined): ToolDefinition { return { name: def.name, label: def.name, description: def.description, parameters: def.parameters as never, outputSchema: def.outputSchema as never, annotations: def.annotations, namespace: def.namespace ? { name: def.namespace } : undefined, @@ -83,7 +83,11 @@ function hostTool(def: RunRequest["tools"][number], recorded?: (name: string, re void send({ type: "tool_call", call: { id, providerId, sessionEntryId: entryFor?.(providerId), name: def.name, arguments: args } }).catch(reject); }); if (!reply.isError) recorded?.(def.name, reply); - return { content: [{ type: "text", text: reply.content + (recorded && !reply.isError ? "\n[Execution receipt: " + (reply.executionId || id) + "]" : "") }], details: { executionId: reply.executionId, ...(reply.structuredContent ? { structuredContent: reply.structuredContent } : {}) }, structuredContent: reply.structuredContent as never, isError: !!reply.isError, terminate: reply.terminate }; + const content: any[] = [{ type: "text", text: reply.content + (recorded && !reply.isError ? "\n[Execution receipt: " + (reply.executionId || id) + "]" : "") }]; + if (imageInput && reply.images?.length) { + for (const image of reply.images) content.push({ type: "image", data: image.data, mimeType: image.mimeType }); + } + return { content, details: { executionId: reply.executionId, ...(reply.structuredContent ? { structuredContent: reply.structuredContent } : {}) }, structuredContent: reply.structuredContent as never, isError: !!reply.isError, terminate: reply.terminate }; }, }; } @@ -125,6 +129,10 @@ function assistantReasoning(message: AssistantMessage | undefined): string { return message?.content.filter(block => block.type === "thinking").map(block => block.thinking).join("") ?? ""; } +function withoutImageBlocks(blocks: any[]): any[] { + return blocks.filter(block => block.type !== "image"); +} + function historyHasAssistantFragment(history: readonly Record[], fragment: string): boolean { const text = fragment ?? ""; if (!text.trim()) return true; @@ -327,8 +335,8 @@ async function run(req: RunRequest): Promise { model = runtime.getModel("cyberstrike-router", "auto")!; } if (!model) throw new Error("Model registration failed"); - const images: ImageContent[] = physical.some(model => model.input.includes("image")) - ? (req.images ?? []).map(image => ({ ...image, type: "image" })) : []; + const imageInput = physical.some(model => model.input.includes("image")); + const images: ImageContent[] = imageInput ? (req.images ?? []).map(image => ({ ...image, type: "image" })) : []; const skillPaths = req.skillPaths?.length ? req.skillPaths : req.nativeWorkflow?.skillPaths; const skills = skillPaths?.length ? loadSkills({ cwd: workingDir, agentDir: scratch, skillPaths, includeDefaults: false }) : undefined; @@ -393,7 +401,7 @@ async function run(req: RunRequest): Promise { ({ session } = await createAgentSession({ cwd: workingDir, agentDir: scratch, modelRuntime: runtime, model, thinkingLevel: (req.model.thinking || "off") as any, sessionManager: manager, settingsManager: SettingsManager.inMemory({ retry: { enabled: true, maxRetries: req.retryMax ?? Math.max(2, configs.length - 1), ...(req.retryMaxDelayMs ? { maxAgentDelayMs: req.retryMaxDelayMs } : {}) }, compaction: { enabled: true, reserveTokens: model.contextWindow - inputBudget, keepRecentTokens: Math.min(20000, Math.floor(inputBudget / 2)) } }), - noTools: "builtin", tools: searchEnabled ? ["+tool_search"] : names, customTools: req.tools.map(def => ({ ...hostTool(def, workflow ? (name, reply) => { + noTools: "builtin", tools: searchEnabled ? ["+tool_search"] : names, customTools: req.tools.map(def => ({ ...hostTool(def, imageInput, workflow ? (name, reply) => { if (name === workflow?.completionTool) submitted = true; if (workflow && (name === workflow.checkpointTool || name === workflow.completionTool)) manager!.appendCustomEntry("assessment-checkpoint", { tool: name, content: reply.content.slice(0,16000), data: reply.structuredContent }); } : undefined, workflow ? providerId => { @@ -463,8 +471,15 @@ async function run(req: RunRequest): Promise { data = { assistantMessageEvent: delta }; } if (e.type === "agent_end") data = {}; - if (e.message?.role === "user" && Array.isArray(e.message.content)) { - data = { ...e, message: { ...e.message, content: e.message.content.filter((block: { type: string }) => block.type !== "image") } }; + // Base64 images belong to the model request, never to the host event stream. + if (e.message && Array.isArray(e.message.content) && (e.message.role === "user" || e.message.role === "toolResult")) { + data = { ...(data as object), message: { ...e.message, content: withoutImageBlocks(e.message.content) } }; + } + if (Array.isArray(e.toolResults)) { + data = { ...(data as object), toolResults: e.toolResults.map((message: any) => Array.isArray(message.content) ? { ...message, content: withoutImageBlocks(message.content) } : message) }; + } + if (e.result && Array.isArray(e.result.content)) { + data = { ...(data as object), result: { ...e.result, content: withoutImageBlocks(e.result.content) } }; } void send({ type: "event", event: { type: e.type, data } }).catch(() => session?.abort()); }); diff --git a/runtime/pi/test/worker.test.mjs b/runtime/pi/test/worker.test.mjs index 84622dfb..650cf959 100644 --- a/runtime/pi/test/worker.test.mjs +++ b/runtime/pi/test/worker.test.mjs @@ -616,3 +616,33 @@ test('ordinary sessions disclose configured skills through native loadSkills', { assert.ok(system.includes('Run specific notes')); assert.ok(system.indexOf('chat-fixture-skill') < system.indexOf('Run specific notes'), system); }); + +test('host tool images reach vision models natively and stay out of host events', { timeout: 30000 }, async t => { + const image = { + mimeType: 'image/png', + data: 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAKElEQVR4nO3NsQ0AAAzCMP5/un0CNkuZ41wybXsHAAAAAAAAAAAAxR4yw/wuPL6QkAAAAABJRU5ErkJggg==', + }; + for (const capability of [true, false]) { + const fixture = await startFixture(t, (body, res, count) => { + if (count === 1) { + sse(res, { role: 'assistant', tool_calls: [{ index: 0, id: 'shot', type: 'function', function: { name: 'echo', arguments: '{"text":"capture"}' } }] }, 'tool_calls'); + return; + } + const wire = JSON.stringify(body.messages); + assert.equal(wire.includes(image.data), capability, wire); + if (capability) { + assert.ok(body.messages.some(m => m.role === 'user' && Array.isArray(m.content) && m.content.some(b => b.type === 'image_url')), wire); + } + sse(res, { role: 'assistant', content: 'image inspected' }, 'stop'); + }); + const req = request(fixture.url); + req.model.imageInput = capability; + const { result, records } = await invoke(t, req, (r, send) => { + if (r.type === 'tool_call') send({ type: 'tool_result', id: r.call.id, result: { content: 'captured', images: [image] } }); + }); + assert.equal(result.status, 'completed', result.error); + assert.equal(result.response, 'image inspected'); + assert.ok(!JSON.stringify(records).includes(image.data), 'host events carried raw image bytes'); + assert.ok(!JSON.stringify(result.history).includes(image.data), 'exported history carried raw image bytes'); + } +});