Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
fix(compile): accept image sources through existing readers (#6719)
Lusen Dongba344c5e4075
diff --git a/bot/tests/test_compile_sources.py b/bot/tests/test_compile_sources.pynew file mode 100644index 000000000..27537f6d7--- /dev/null+++ b/bot/tests/test_compile_sources.py@@ -0,0 +1,488 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Issue #6713: native images must remain readable, cited evidence in Compile."""++import base64+import json+from dataclasses import asdict+from io import BytesIO+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock++import pytest+from PIL import Image, ImageDraw+from vikingbot.agent.loop import AgentLoop, _inline_media_bytes+from vikingbot.agent.tools.base import MultimodalToolResult, ToolContext+from vikingbot.agent.tools.compile import CompileImageReadTool, CompileSpawnTool+from vikingbot.agent.tools.ov_file import VikingMultiReadTool+from vikingbot.agent.tools.registry import ToolRegistry+from vikingbot.bus.queue import MessageBus+from vikingbot.compile import entry+from vikingbot.compile.hashing import content_hash+from vikingbot.compile.models import CompileFailure, CompileLimits, SanitizedCompileRequest+from vikingbot.compile.ops.common import pack, payload+from vikingbot.compile.pipeline import Pipeline+from vikingbot.compile.pipeline_agent import ChildProvider, complete_tool_result+from vikingbot.compile.results import CombineResponse, FileResponse, RecordResponse+from vikingbot.compile.service import BotCompileService+from vikingbot.compile.skill_resources import EvidenceReader+from vikingbot.compile.sources import read_source, split_source+from vikingbot.config.schema import Config, SessionKey+from vikingbot.providers.base import LLMProvider, LLMResponse, ToolCallRequest+from vikingbot.sandbox.backends.direct import DirectBackend+from vikingbot.session.manager import SessionManager++URI = "viking://resources/cedar/diagram.png"+TEXT = "viking://resources/cedar/notes.md"+++class MemoryFiles:+ def __init__(self):+ self.values = {}++ async def put(self, key, value):+ self.values[key] = value+ return key++ async def get(self, key):+ return self.values.get(key)+++def runtime():+ image = Image.new("RGB", (400, 100), "white")+ ImageDraw.Draw(image).text((10, 30), "RETRY LIMIT: 7", fill="black")+ output = BytesIO()+ image.save(output, format="PNG")+ png = output.getvalue()+ client = SimpleNamespace(+ stat=AsyncMock(return_value={"size": len(png)}),+ download_bytes=AsyncMock(return_value=png),+ read_raw=AsyncMock(return_value="# Cedar\n\n"),+ read_content=AsyncMock(return_value="visible text"),+ )+ provider = SimpleNamespace(supports_tool_result_media=Mock(return_value=True), chat=AsyncMock())+ pipeline = Pipeline(+ client=client,+ provider=provider,+ sandbox=SimpleNamespace(sandbox_cwd="/sandbox"),+ model="vision-test",+ temperature=0,+ limits=CompileLimits(),+ skill="Cite source facts.",+ usage={},+ request=SanitizedCompileRequest(+ **{+ "from": ["viking://resources/cedar"],+ "to": "viking://resources/wiki",+ "skill": "viking://agent/skills/llm-wiki",+ "instruction": "Use image-only facts.",+ }+ ),+ )+ pipeline.files = MemoryFiles()+ pipeline.model.files, pipeline.model.resources = pipeline.files, None+ return pipeline, png+++async def seed(runtime):+ pipeline, _ = runtime+ service = SimpleNamespace(+ limits=pipeline.limits, agent_loop=SimpleNamespace(provider=pipeline.model.provider)+ )+ batches = await BotCompileService._prepare_source_batches(+ service, pipeline.client, [], files=[TEXT, URI]+ )++ async def inputs():+ for batch in batches:+ yield batch++ records = await pipeline.seed(inputs())+ return records[-1]+++async def test_preloaded_image_fact_reaches_output_with_source_identity(runtime):+ pipeline, png = runtime+ image = await seed(runtime)+ stored = await pipeline.files.get(image.payload_ref)+ assert "text" not in stored and stored["hash"] == content_hash(png)+ assert (stored["start_line"], stored["end_line"], stored["start_char"], stored["end_char"]) == (+ 0,+ 0,+ 0,+ 0,+ )+ data = {"inputs": [await payload(pipeline, image)]}+ assert "base64," not in json.dumps(data)+ pipeline.client.read_raw.assert_awaited_once_with(TEXT)++ def respond(**kwargs):+ if pipeline.model.provider.chat.await_count == 1:+ return LLMResponse(+ content="",+ tool_calls=[+ ToolCallRequest(+ "read",+ "read_evidence",+ {"source_range": image.record_id},+ 0,+ )+ ],+ )+ content = kwargs["messages"][-1]["content"]+ attached = next(p for p in content if p["type"] == "image_url")+ assert base64.b64decode(attached["image_url"]["url"].split(",")[1]) == png+ assert "RETRY LIMIT" not in json.dumps(data)+ # Simulated visual response: verifies transport and citation, not real-model OCR.+ return LLMResponse(+ content=json.dumps(+ {+ "files": [+ {+ "path": "cedar.md",+ "content": f"Retry limit: 7. [Source]({URI})",+ "inputs": [image.record_id],+ }+ ]+ }+ )+ )++ pipeline.model.provider.chat.side_effect = respond+ result = await pipeline.model.ask("compile", "Inspect original images.", data, FileResponse)+ assert "Retry limit: 7" in result.files[0].content and URI in result.files[0].content+ assert result.files[0].inputs == [image.record_id]+++async def test_discovered_images_use_existing_multi_read_wrapper(runtime):+ pipeline, png = runtime+ pipeline.files.get = AsyncMock(wraps=pipeline.files.get)+ pipeline.changes = {"diff_dirs": [], "full_dirs": ["viking://resources/cedar"], "head": "test"}+ pipeline.tools = {+ "openviking_multi_read": VikingMultiReadTool(),+ "openviking_diff_paths": SimpleNamespace(name="openviking_diff_paths"),+ }+ pipeline.tool_context = ToolContext()++ async def ask(*args, readers, **kwargs):+ result = await readers["openviking_multi_read"].execute(uris=[URI])+ assert isinstance(result, MultimodalToolResult) and URI in result.text+ assert _inline_media_bytes([{"content": result.content}]) == len(png)+ assert "base64," not in result.text+ return SimpleNamespace(needs_pipeline=True)++ pipeline.model.ask = AsyncMock(side_effect=ask)+ assert await entry.run(pipeline, [], {}) is None+ assert next(iter(pipeline.evidence.values()))["hash"] == content_hash(png)+ assert not any(+ call.args[0].startswith("sources/") for call in pipeline.files.get.await_args_list+ )++[email protected]("combine", [False, True])+async def test_image_payload_and_packing_reuse_registered_metadata(runtime, combine):+ pipeline, _ = runtime+ image = await seed(runtime)+ stored = pipeline.files.values[image.payload_ref]+ pipeline.files.get = AsyncMock(wraps=pipeline.files.get)+ expected = {+ "id": image.record_id,+ "payload": {+ **{key: value for key, value in stored.items() if key != "image"},+ "source_ranges": [image.record_id],+ },+ }+ assert await payload(pipeline, image, combine=combine) == expected+ schema = CombineResponse if combine else RecordResponse+ assert await pack(pipeline, [image], "Read the image.", schema) == [[image]]+ pipeline.files.get.assert_not_awaited()+ assert "source_ranges" not in pipeline.evidence[image.record_id]++ text = next(record for record in pipeline.records.values() if record.routing_text == TEXT)+ result = await payload(pipeline, text, combine=combine)+ pipeline.files.get.assert_awaited_once_with(text.payload_ref)+ if combine:+ assert result["content"]["text"] == pipeline.client.read_raw.return_value+ else:+ assert result["payload"]["text"].startswith("1: # Cedar\n")+ del pipeline.files.values[text.payload_ref]+ with pytest.raises(ValueError, match="Missing evidence/payload"):+ await payload(pipeline, text, combine=combine)+ del pipeline.files.values[image.payload_ref]+ with pytest.raises(ValueError, match="Assigned source range is missing"):+ await EvidenceReader(pipeline.files, {"inputs": [expected]}).execute(+ source_range=image.record_id+ )+++async def test_image_evidence_view_reads_snapshot_once(runtime):+ pipeline, png = runtime+ image = await seed(runtime)+ data = {"inputs": [await payload(pipeline, image)]}+ get = AsyncMock(wraps=pipeline.files.get)+ reader = EvidenceReader(SimpleNamespace(get=get), data)++ result = await reader.execute(source_range=image.record_id)++ get.assert_awaited_once_with(f"sources/{image.record_id}")+ assert isinstance(result, MultimodalToolResult)+ assert _inline_media_bytes([{"content": result.content}]) == len(png)+ attached = next(part for part in result.content if part["type"] == "image_url")+ assert base64.b64decode(attached["image_url"]["url"].split(",", 1)[1]) == png+ assert "base64," not in result.text+ assert "image" not in json.loads(result.text)+ assert (await pipeline.files.get(image.payload_ref))["image"] == attached++ get.reset_mock()+ metadata = await reader.read(image.record_id)+ get.assert_awaited_once_with(f"sources/{image.record_id}")+ assert "image" not in metadata and metadata["complete"] is False+++ "stage,schema",+ [("map", RecordResponse), ("reduce", FileResponse), ("combine", CombineResponse)],+)+async def test_pipeline_stages_can_reread_original_images(runtime, stage, schema):+ pipeline, png = runtime+ image = await seed(runtime)+ data = {"inputs": [await payload(pipeline, image, combine=stage == "combine")]}+ result = {"files": []} if schema is FileResponse else {"records": []}+ if schema is CombineResponse:+ result = {"records": [{"inputs": [image.record_id], "content": "Retry limit: 7."}]}+ pipeline.model.provider.chat.side_effect = [+ LLMResponse(+ content="",+ tool_calls=[+ ToolCallRequest("read", "read_evidence", {"source_range": image.record_id}, 0)+ ],+ ),+ LLMResponse(content=json.dumps(result)),+ ]+ await pipeline.model.ask(stage, "Read the image.", data, schema)+ messages = pipeline.model.provider.chat.call_args.kwargs["messages"]+ assert _inline_media_bytes(messages) == len(png)+ reader = EvidenceReader(pipeline.files, data)+ with pytest.raises(ValueError, match="no text line ranges"):+ await reader.execute(source_range=image.record_id, start_line=1, end_line=1)+ with pytest.raises(ValueError, match="outside this assignment"):+ await reader.execute(source_range="foreign")+ result = await reader.execute(source_range=image.record_id)+ assert ChildProvider(pipeline.model, schema).supports_tool_result_media()+ assert await complete_tool_result(result, "session", preserve_complete=True) is result+++ "problem,code",+ [+ ("provider", "UNSUPPORTED_MEDIA"),+ ("format", "INVALID_ARGUMENT"),+ ("size", "SOURCE_READ_FAILED"),+ ],+)+async def test_image_limitations_never_fall_back_to_binary_text(runtime, problem, code):+ pipeline, _ = runtime+ uri = URI+ if problem == "provider":+ pipeline.model.provider.supports_tool_result_media.return_value = False+ elif problem == "format":+ uri = URI.replace(".png", ".svg")+ else:+ pipeline.client.stat.return_value = {+ "size": VikingMultiReadTool._MAX_INLINE_MEDIA_BYTES + 1+ }+ with pytest.raises(CompileFailure) as caught:+ await read_source(pipeline.client, uri, pipeline.model.provider)+ assert caught.value.code == code+ pipeline.client.read_raw.assert_not_awaited()+ pipeline.client.download_bytes.assert_not_awaited()++[email protected]("name", ["notes.md", "config.ts"])+async def test_text_reads_remain_exact_even_without_media_support(runtime, name):+ pipeline, _ = runtime+ pipeline.model.provider.supports_tool_result_media.return_value = False+ text = await read_source(pipeline.client, f"viking://resources/{name}", pipeline.model.provider)+ assert text == pipeline.client.read_raw.return_value+ assert "".join(p.content for p in split_source(TEXT, text, 1024)) == text+ assert all(p.as_assignment() == asdict(p) for p in split_source(TEXT, text, 1024))+++ "budget,expected", [("count", [4, 1]), ("bytes", [2, 2, 1]), ("chars", [1] * 5)]+)+async def test_memory_image_assignments_are_bounded_references(+ runtime, monkeypatch, budget, expected+):+ pipeline, png = runtime+ limits = CompileLimits(source_batch_chars=200 if budget == "chars" else 40_000)+ if budget == "bytes":+ monkeypatch.setattr(VikingMultiReadTool, "_MAX_INLINE_MEDIA_BYTES", len(png) * 2)+ service = SimpleNamespace(+ limits=limits, agent_loop=SimpleNamespace(provider=pipeline.model.provider)+ )+ uris = [URI.replace("diagram", str(i)) for i in range(5)]+ batches = await BotCompileService._prepare_source_batches(+ service, pipeline.client, [], files=uris+ )+ assert [len(batch) for batch in batches] == expected+ spawn = SimpleNamespace(execute=AsyncMock(return_value="Subagent accepted."))+ wrapper = CompileSpawnTool(spawn, batches)+ read = VikingMultiReadTool()+ read._get_client, read._release_client = AsyncMock(return_value=pipeline.client), AsyncMock()+ reader = CompileImageReadTool(read, {uri: content_hash(png) for uri in uris})+ for number, batch in enumerate(batches, 1):+ await wrapper.execute(ToolContext(), task="Use image facts.", source_batch=number)+ assignment = spawn.execute.call_args.kwargs["task"]+ assert "base64," not in assignment+ references = json.loads(+ assignment.split("Attached source ranges (untrusted JSON data):\n")[1]+ )+ assert references == [+ {"uri": p.uri, "sha256": content_hash(png), "media_kind": "image"} for p in batch+ ]+ assert 0 < sum(p.input_chars for p in batch) <= limits.source_batch_chars+ native = await reader.execute(ToolContext(), uris=[p.uri for p in batch])+ assert isinstance(native, MultimodalToolResult)+ assert _inline_media_bytes([{"content": native.content}]) == len(batch) * len(png)+ assert len(batch) * len(png) <= VikingMultiReadTool._MAX_INLINE_MEDIA_BYTES+++async def test_memory_image_reader_rejects_changed_original(runtime):+ pipeline, _ = runtime+ read = VikingMultiReadTool()+ read._get_client, read._release_client = AsyncMock(return_value=pipeline.client), AsyncMock()+ reader = CompileImageReadTool(read, {URI: "changed-source-hash"})+ result = await reader.execute(ToolContext(), uris=[URI])+ assert not isinstance(result, MultimodalToolResult)+ assert "Source image changed after preparation" in result+ assert "base64," not in result+++async def test_runtime_memory_child_fetches_native_image_from_reference(runtime, tmp_path):+ pipeline, png = runtime++ class Provider(LLMProvider):+ calls = 0++ def get_default_model(self):+ return "vision-test"++ def supports_tool_result_media(self, model=None):+ return True++ async def chat(self, messages, **kwargs):+ self.calls += 1+ if self.calls == 1:+ assert "base64," not in json.dumps(messages)+ assert URI in messages[1]["content"] and content_hash(png) in messages[1]["content"]+ return LLMResponse(+ content="",+ tool_calls=[+ ToolCallRequest("view", "openviking_multi_read", {"uris": [URI]}, 0)+ ],+ )+ assert _inline_media_bytes(messages) == len(png)+ native = next(+ m["content"]+ for m in messages+ if m["role"] == "tool" and isinstance(m["content"], list)+ )+ image = next(p for p in native if p["type"] == "image_url")+ assert base64.b64decode(image["image_url"]["url"].split(",", 1)[1]) == png+ assert content_hash(png) in json.dumps(native)+ # Controlled model response verifies child transport, not visual recognition.+ return LLMResponse(+ content="",+ tool_calls=[+ ToolCallRequest(+ "write",+ "write_file",+ {"path": "cedar.md", "content": f"Retry limit: 7. [Source]({URI})"},+ 0,+ ),+ ToolCallRequest(+ "submit", "submit_compile_draft", {"summary": "Image read and cited."}, 0+ ),+ ],+ )++ config, provider = Config(), Provider()+ key = SessionKey(type="cli", channel_id="default", chat_id="compile-image")+ sandbox = DirectBackend(config.sandbox, key, tmp_path)+ manager = SimpleNamespace(+ get_sandbox=AsyncMock(return_value=sandbox), to_workspace_id=lambda key: "compile-image"+ )+ await sandbox.start()+ loop = AgentLoop(+ bus=MessageBus(),+ provider=provider,+ workspace=tmp_path,+ model="vision-test",+ config=config,+ sandbox_manager=manager,+ session_manager=SessionManager(tmp_path),+ )+ registry = ToolRegistry(config)+ for name in ("spawn", "write_file"):+ registry.register(loop.tools.get(name))+ read = VikingMultiReadTool()+ read._get_client, read._release_client = AsyncMock(return_value=pipeline.client), AsyncMock()+ registry.register(read)+ registry.register(SimpleNamespace(name="submit_wiki_bundle"))+ service = SimpleNamespace(+ limits=CompileLimits(), agent_loop=loop, _build_prompts=BotCompileService._build_prompts+ )+ batches = await BotCompileService._prepare_source_batches(+ service, pipeline.client, [], files=[URI]+ )+ request = pipeline.request.model_copy(+ update={"to": "viking://user/default/memories/cedar", "changes": None}+ )+ try:+ children = BotCompileService._configure_compile_subagents(+ service,+ loop,+ registry,+ request=request,+ connection=None,+ usage={},+ skill_text="Cite original sources.",+ source_batches=batches,+ )+ await registry.get("spawn").execute(+ ToolContext(session_key=key), task="Use the image.", source_batch=1+ )+ outcome = await children.wait()+ assert outcome["results"][0]["status"] == "completed", outcome+ assert provider.calls == 2+ draft = await sandbox.read_file(outcome["results"][0]["files"][0])+ assert "Retry limit: 7" in draft and URI in draft+ finally:+ await loop.subagents.cancel_all()+ await sandbox.stop()+++async def test_multi_read_and_request_budget_still_preserve_native_images(runtime, monkeypatch):+ pipeline, png = runtime+ tool = VikingMultiReadTool()+ tool._get_client, tool._release_client = AsyncMock(return_value=pipeline.client), AsyncMock()+ result = await tool.execute(ToolContext(), [URI])+ assert isinstance(result, MultimodalToolResult)+ assert _inline_media_bytes([{"content": result.content}]) == len(png)+ monkeypatch.setattr("vikingbot.compile.pipeline_io.MAX_INLINE_TOOL_RESULT_MEDIA_BYTES", 1)+ with pytest.raises(CompileFailure, match="media budget"):+ await pipeline.model.call("compile", [{"content": result.content}], [], max_tokens=100)+ pipeline.model.provider.chat.assert_not_awaited()diff --git a/bot/vikingbot/agent/tools/compile.py b/bot/vikingbot/agent/tools/compile.pyindex 862f6cc52..1a58afda2 100644--- a/bot/vikingbot/agent/tools/compile.py+++ b/bot/vikingbot/agent/tools/compile.py@@ -6,7 +6,6 @@ import jsonimport posixpathfrom collections.abc import Awaitable, Callablefrom copy import deepcopy-from dataclasses import asdictfrom typing import Any, Mappingimport yaml@@ -20,6 +19,7 @@ from openviking.utils.path_safety import (validate_safe_viking_uri_path,)from vikingbot.agent.tools.base import TOOL_RESULT_DIRECTORY, Tool, ToolContext+from vikingbot.agent.tools.ov_file import VikingMultiReadToolfrom vikingbot.compile.models import (COMPILE_DRAFT_ROOT,COMPILE_STAGING_ROOT,@@ -47,6 +47,33 @@ def _path_is_within(path: str, root: str) -> bool:return path == root or path.startswith(root + "/")+class CompileImageReadTool(VikingMultiReadTool):+ """Reuse native multi-read while checking the prepared originals' identities."""++ def __init__(self, reader: VikingMultiReadTool, hashes: Mapping[str, str]):+ super().__init__()+ self.reader, self.hashes = reader, hashes++ async def _get_client(self, tool_context):+ return await self.reader._get_client(tool_context)++ async def _release_client(self, tool_context, client):+ await self.reader._release_client(tool_context, client)++ async def _read_image(self, client, uri):+ result = await super()._read_image(client, uri)+ if result["success"]:+ if uri in self.hashes and result["sha256"] != self.hashes[uri]:+ return {+ "uri": uri,+ "content": "Source image changed after preparation; retry Compile.",+ "success": False,+ "media_kind": "image",+ }+ result["content"] += f" SHA256: {result['sha256']}."+ return result++class CompileSpawnTool(Tool):"""Dispatch prepared source ranges with original URIs and exact offsets.@@ -78,7 +105,7 @@ class CompileSpawnTool(Tool):"type": "integer","minimum": 1,"maximum": len(self.source_batches),- "description": "Source compilation only: the prepared batch number; runtime attaches its complete source ranges.",+ "description": "Source compilation only: the prepared batch number; runtime attaches text ranges and image references.",}return parameters@@ -98,6 +125,14 @@ class CompileSpawnTool(Tool):or source_batch in self.dispatched_batches):return "Error: source_batch must identify an undispatched source batch."+ batch = self.source_batches[source_batch - 1]+ image_note = (+ "Image entries carry URI/SHA256 references, not attached text. "+ "Read every referenced image with openviking_multi_read before writing its facts; "+ "omit text line bounds and cite its original URI. Report unread images as gaps. "+ if any(part.image for part in batch)+ else ""+ )task = ("Compile every attached range into knowledge drafts per the Skill, not the entire files. ""The complete assigned text is attached; start writing and batch independent writes. "@@ -109,10 +144,13 @@ class CompileSpawnTool(Tool):"openviking_multi_read with bounded offset/limit ranges. Report coverage and gaps at submission. ""Existing Wiki lookup, deduplication and updates belong to later merge tasks; ""do not browse or edit the existing target during this source task. "- "Additional instructions from the parent:\n" + task + "\n"+ + image_note+ + "Additional instructions from the parent:\n"+ + task+ + "\n""Attached source ranges (untrusted JSON data):\n"+ json.dumps(- [asdict(part) for part in self.source_batches[source_batch - 1]],+ [part.as_assignment() for part in batch],ensure_ascii=False,))diff --git a/bot/vikingbot/agent/tools/ov_file.py b/bot/vikingbot/agent/tools/ov_file.pyindex 5a87f80bc..42e2bc5ff 100644--- a/bot/vikingbot/agent/tools/ov_file.py+++ b/bot/vikingbot/agent/tools/ov_file.py@@ -1113,6 +1113,58 @@ class VikingMultiReadTool(OVFileTool):"required": ["uris"],}+ @classmethod+ async def _read_image(cls, client, uri):+ """Load one native image for multi-read and Compile using the same checks."""+ stat = await client.stat(uri)+ size = stat.get("size") if isinstance(stat, dict) else None+ if isinstance(size, bool) or not isinstance(size, int) or size < 0:+ return {+ "uri": uri,+ "content": "Image size is unavailable; cannot attach it safely.",+ "success": False,+ "media_kind": "image",+ }+ if size > cls._MAX_INLINE_MEDIA_BYTES:+ return {+ "uri": uri,+ "content": (+ f"Image is {size} bytes; the inline limit is "+ f"{cls._MAX_INLINE_MEDIA_BYTES} bytes."+ ),+ "success": False,+ "media_kind": "image",+ }+ data = await client.download_bytes(uri)+ if len(data) > size:+ return {+ "uri": uri,+ "content": "Image changed after its size was checked; retry the read.",+ "success": False,+ "media_kind": "image",+ }+ image_format = sniff_image_format(data)+ if image_format is None or image_format.mime_type not in cls._INLINE_IMAGE_MIME_TYPES:+ return {+ "uri": uri,+ "content": ("File bytes do not match a supported PNG, JPEG, GIF, or WebP image."),+ "success": False,+ "media_kind": "image",+ }+ encoded = base64.b64encode(data).decode("ascii")+ return {+ "uri": uri,+ "content": (f"Image resource ({image_format.mime_type}, {len(data)} bytes)."),+ "image": {+ "type": "image_url",+ "image_url": {"url": f"data:{image_format.mime_type};base64,{encoded}"},+ },+ "media_bytes": len(data),+ "sha256": hashlib.sha256(data).hexdigest(),+ "success": True,+ "media_kind": "image",+ }+async def execute(self,tool_context: ToolContext,@@ -1145,7 +1197,9 @@ class VikingMultiReadTool(OVFileTool):if with_revision and (media_kind or offset < 0 or (limit != -1 and limit < 1)):- raise ValueError("Revision reads require text files and valid line ranges")+ raise ValueError(+ "Revision reads require text files and valid line ranges"+ )if media_kind == "image":if index not in inline_image_indexes:return {@@ -1158,63 +1212,7 @@ class VikingMultiReadTool(OVFileTool):"success": False,"media_kind": media_kind,}- stat = await client.stat(uri)- size = stat.get("size") if isinstance(stat, dict) else None- if isinstance(size, bool) or not isinstance(size, int) or size < 0:- return {- "uri": uri,- "content": "Image size is unavailable; cannot attach it safely.",- "success": False,- "media_kind": media_kind,- }- if size > self._MAX_INLINE_MEDIA_BYTES:- return {- "uri": uri,- "content": (- f"Image is {size} bytes; the inline limit is "- f"{self._MAX_INLINE_MEDIA_BYTES} bytes."- ),- "success": False,- "media_kind": media_kind,- }- data = await client.download_bytes(uri)- if len(data) > size:- return {- "uri": uri,- "content": "Image changed after its size was checked; retry the read.",- "success": False,- "media_kind": media_kind,- }- image_format = sniff_image_format(data)- if (- image_format is None- or image_format.mime_type not in self._INLINE_IMAGE_MIME_TYPES- ):- return {- "uri": uri,- "content": (- "File bytes do not match a supported PNG, JPEG, GIF, "- "or WebP image."- ),- "success": False,- "media_kind": media_kind,- }- encoded = base64.b64encode(data).decode("ascii")- return {- "uri": uri,- "content": (- f"Image resource ({image_format.mime_type}, {len(data)} bytes)."- ),- "image": {- "type": "image_url",- "image_url": {- "url": f"data:{image_format.mime_type};base64,{encoded}"- },- },- "media_bytes": len(data),- "success": True,- "media_kind": media_kind,- }+ return await self._read_image(client, uri)if media_kind in {"audio", "video"}:content = await client.read_content(uri, level="overview")@@ -1259,7 +1257,9 @@ class VikingMultiReadTool(OVFileTool):return {"uri": uri,"content": "".join(- lines[offset:] if limit == -1 else lines[offset : offset + limit]+ lines[offset:]+ if limit == -1+ else lines[offset : offset + limit]),"base_hash": hashlib.sha256(raw).hexdigest(),"success": True,diff --git a/bot/vikingbot/compile/entry.py b/bot/vikingbot/compile/entry.pyindex d4ae9dc70..8853a65b2 100644--- a/bot/vikingbot/compile/entry.py+++ b/bot/vikingbot/compile/entry.py@@ -9,13 +9,15 @@ from pydantic import Fieldfrom openviking.core.namespace import relative_uri_pathfrom openviking.models.model_error import ModelErrorKind, model_error_kind+from vikingbot.agent.tools.base import MultimodalToolResult+from vikingbot.agent.tools.ov_file import VikingMultiReadToolfrom vikingbot.compile import file_opsfrom vikingbot.compile.models import has_directory_planfrom vikingbot.compile.ops.common import payloadfrom vikingbot.compile.pipeline_io import ModelCallError, ModelCallLimitErrorfrom vikingbot.compile.renderer import validate_relative_file_pathfrom vikingbot.compile.results import FileResponse, Group-from vikingbot.compile.sources import split_source+from vikingbot.compile.sources import CompileSourceRange, read_source, split_sourceclass EntryResponse(FileResponse):@@ -133,7 +135,7 @@ async def run(runtime, sources, context):continuevalidate_relative_file_path(relative_uri_path(runtime.target, uri))target_uris.append(uri)- material = {}+ material, images = {}, []if source_uris:offset, limit = arguments.get("offset", 0), arguments.get("limit", -1)if offset < 0 or (limit != -1 and limit < 1):@@ -142,25 +144,39 @@ async def run(runtime, sources, context):manifest.update({uri: manifest.get(uri, "pending") for uri in source_uris})await runtime.files.put("inputs", manifest)selected = set()- for uri in dict.fromkeys(source_uris):- text = await runtime.client.read_raw(uri)- lines = text.splitlines(keepends=True)- excerpt = "".join(- lines[offset:] if limit == -1 else lines[offset : offset + limit]+ if (+ sum(+ VikingMultiReadTool._media_kind(uri) == "image"+ for uri in dict.fromkeys(source_uris))- start = len("".join(lines[:offset]))- parts = [- replace(- part,- start_char=part.start_char + start,- end_char=part.end_char + start,- start_line=part.start_line + offset,- end_line=part.end_line + offset,+ > VikingMultiReadTool._MAX_INLINE_IMAGES+ ):+ raise ValueError("Read at most four images at once")+ for uri in dict.fromkeys(source_uris):+ text = await read_source(runtime.client, uri, runtime.model.provider)+ if isinstance(text, CompileSourceRange):+ parts = [text]+ images.extend(+ [{"type": "text", "text": f"Original image: {uri}"}, text.image])- for part in split_source(- uri, excerpt, runtime.limits.source_batch_chars+ else:+ lines = text.splitlines(keepends=True)+ excerpt = "".join(+ lines[offset:] if limit == -1 else lines[offset : offset + limit])- ]+ start = len("".join(lines[:offset]))+ parts = [+ replace(+ part,+ start_char=part.start_char + start,+ end_char=part.end_char + start,+ start_line=part.start_line + offset,+ end_line=part.end_line + offset,+ )+ for part in split_source(+ uri, excerpt, runtime.limits.source_batch_chars+ )+ ]sources.extend(await runtime.seed(batch(parts)))selected.update((uri, part.start_char, part.end_char) for part in parts)material["inputs"] = [@@ -181,7 +197,12 @@ async def run(runtime, sources, context):if not source_uris:return valuematerial["targets"] = json.loads(value)- return json.dumps(material, ensure_ascii=False)+ result = json.dumps(material, ensure_ascii=False)+ return (+ MultimodalToolResult(result, [{"type": "text", "text": result}, *images])+ if images+ else result+ )readers[read.name] = copy(read)readers[read.name].execute = read_targetdiff --git a/bot/vikingbot/compile/ops/common.py b/bot/vikingbot/compile/ops/common.pyindex 6c49864df..1152918ca 100644--- a/bot/vikingbot/compile/ops/common.py+++ b/bot/vikingbot/compile/ops/common.py@@ -48,9 +48,16 @@ Cover every input. Preserve source paths and applicability in content where releasync def payload(runtime: Pipeline, record: Record, *, combine=False) -> dict:"""Load assigned evidence; Combine receives content and identity, without runtime metadata.- Ready drafts retain their supporting facts and scope because the body alone may- omit relationships. Missing stored evidence fails the assignment.+ Image metadata is registered only after its snapshot write succeeds; load its+ body on viewing. Ready drafts retain their supporting facts and scope because+ the body alone may omit relationships. Missing other payloads fail the assignment."""+ data = runtime.evidence.get(record.record_id, {})+ if data.get("media_kind") == "image":+ return {+ "id": record.record_id,+ "payload": {**data, "source_ranges": [record.record_id]},+ }data = await runtime.files.get(record.payload_ref)if data is None:raise ValueError(f"Missing evidence/payload: {record.payload_ref}")diff --git a/bot/vikingbot/compile/pipeline.py b/bot/vikingbot/compile/pipeline.pyindex a7b1e8ca9..7f9762619 100644--- a/bot/vikingbot/compile/pipeline.py+++ b/bot/vikingbot/compile/pipeline.py@@ -450,6 +450,9 @@ class Pipeline:return {"file_count": count,+ "image_count": sum(+ self.evidence[r.record_id].get("media_kind") == "image" for r in sources+ ),"range_count": len(sources),"total_chars": sum(lengths),"file_chars": {@@ -470,9 +473,10 @@ class Pipeline:async def write_source(item):"""Atomically write one (ID, metadata, range); return its record and evidence."""- record_id, metadata, text, context = item+ record_id, metadata, text, context, image = itemawait self.files.put(- f"sources/{record_id}", {**metadata, "text": text, "context": context}+ f"sources/{record_id}",+ {**metadata, **({"image": image} if image else {"text": text, "context": context})},)return Record(record_id, f"sources/{record_id}", [record_id], metadata["uri"], {}, []@@ -499,7 +503,7 @@ class Pipeline:for part in batch:metadata = {"uri": part.uri,- "hash": content_hash(part.content),+ "hash": part.sha256 or content_hash(part.content),"start_char": part.start_char,"end_char": part.end_char,"start_line": part.start_line,@@ -507,11 +511,13 @@ class Pipeline:"continues_before": part.continues_before,"continues_after": part.continues_after,}+ if part.image:+ metadata["media_kind"] = "image"record_id = digest(metadata)[:24]if record_id in seen:continueseen.add(record_id)- pending.append((record_id, metadata, part.content, part.context))+ pending.append((record_id, metadata, part.content, part.context, part.image))if len(pending) >= self.limits.source_concurrency:await flush()if pending:@@ -543,7 +549,7 @@ class Pipeline:continueseen.add(record_id)manifest.setdefault(uri, "pending")- pending.append((record_id, metadata, text, ""))+ pending.append((record_id, metadata, text, "", None))if len(pending) >= self.limits.source_concurrency:await flush()if pending:diff --git a/bot/vikingbot/compile/pipeline_agent.py b/bot/vikingbot/compile/pipeline_agent.pyindex 5004b633d..aafbc98d4 100644--- a/bot/vikingbot/compile/pipeline_agent.py+++ b/bot/vikingbot/compile/pipeline_agent.py@@ -37,6 +37,9 @@ class ChildProvider(LLMProvider):def get_default_model(self):return self.model.model+ def supports_tool_result_media(self, model=None):+ return self.model.provider.supports_tool_result_media(model or self.model.model)+async def chat(self, messages, tools=None, **kwargs):"""Retry truncated output without executing incomplete tool calls."""while True:diff --git a/bot/vikingbot/compile/pipeline_io.py b/bot/vikingbot/compile/pipeline_io.pyindex d8662afca..64dea4710 100644--- a/bot/vikingbot/compile/pipeline_io.py+++ b/bot/vikingbot/compile/pipeline_io.py@@ -18,9 +18,11 @@ from loguru import loggerfrom pydantic import BaseModel, ValidationErrorfrom openviking.models.model_error import ModelError+from openviking.utils.media_limits import MAX_INLINE_TOOL_RESULT_MEDIA_BYTESfrom openviking_cli.exceptions import NotFoundError+from vikingbot.agent.tools.base import MultimodalToolResultfrom vikingbot.compile.hashing import digest-from vikingbot.compile.models import COMPILE_STAGING_ROOT+from vikingbot.compile.models import COMPILE_STAGING_ROOT, CompileFailurefrom vikingbot.compile.results import FileResponse, RouteBatchResponsefrom vikingbot.compile.schemas import result_schemafrom vikingbot.compile.skill_resources import EvidenceReader@@ -30,7 +32,7 @@ T = TypeVar("T")R = TypeVar("R", bound=BaseModel)ROOT = f"{COMPILE_STAGING_ROOT}/pipeline"# Cache identity for the processing rules used by model calls.-PROCESSING_VERSION = "compile-pipeline-36"+PROCESSING_VERSION = "compile-pipeline-37"# Output-token fallback when the configured VLM provides no value.DEFAULT_MAX_TOKENS = 32_000# Total attempts per operator job or routing record, including the initial execution.@@ -270,6 +272,17 @@ class JsonModel:Diagnostics contain budgets, usage and failure categories, never reasoning.A cancelled or timed-out request cannot be accepted as a partial response."""+ from vikingbot.agent.loop import _inline_media_bytes++ media_bytes = _inline_media_bytes(messages)+ if media_bytes and not self.provider.supports_tool_result_media(self.model):+ raise CompileFailure(+ "UNSUPPORTED_MEDIA", "Compile provider cannot deliver image evidence", stage=stage+ )+ if media_bytes > MAX_INLINE_TOOL_RESULT_MEDIA_BYTES:+ raise CompileFailure(+ "MEDIA_LIMIT", "Compile image request exceeds the inline media budget", stage=stage+ )self.metrics[f"{stage}_calls"] += 1number = self.metrics[f"{stage}_calls"]started = time.monotonic()@@ -439,7 +452,7 @@ class JsonModel:}]readers = dict(readers or {})- if stage not in {"plan", "combine"}:+ if stage != "plan":evidence = EvidenceReader(self.files, data)if evidence.allowed - evidence.delivered:readers["read_evidence"] = evidence@@ -520,6 +533,9 @@ class JsonModel:value = "Error: " + str(exc)[:800]else:retries.pop(f"read:{call.name}", None)+ multimodal = value if isinstance(value, MultimodalToolResult) else None+ if multimodal:+ value = multimodal.texttry:content = json.loads(value, object_hook=lambda v: v.get("text", v.get("excerpts", v))@@ -530,8 +546,15 @@ class JsonModel:progress = progress or fingerprint not in seen_resultsif fingerprint in seen_results:value = "Unchanged: same tool result. Use previous results or submit."+ multimodal = Noneseen_results.add(fingerprint)- messages.append({"role": "tool", "tool_call_id": call.id, "content": value})+ messages.append(+ {+ "role": "tool",+ "tool_call_id": call.id,+ "content": multimodal.content if multimodal else value,+ }+ )stalled_rounds = 0 if progress else stalled_rounds + 1if stalled_rounds >= 3:raise ModelCallLimitError(f"{stage}: tool calls made no progress")diff --git a/bot/vikingbot/compile/review.py b/bot/vikingbot/compile/review.pyindex 09bcecc96..2da764873 100644--- a/bot/vikingbot/compile/review.py+++ b/bot/vikingbot/compile/review.py@@ -98,7 +98,8 @@ class StageOutputReader(Tool):if payload is None:raise ValueError(f"Missing stage payload: {record.record_id}")self.evidence.allowed.update(record.source_refs)- value = {"id": record.record_id, "payload": payload.get("fields", payload)}+ visible = {key: item for key, item in payload.items() if key != "image"}+ value = {"id": record.record_id, "payload": visible.get("fields", visible)}if record.ready_ref:ready = await self.runtime.files.get(record.ready_ref)if ready is None:diff --git a/bot/vikingbot/compile/service.py b/bot/vikingbot/compile/service.pyindex d4e408650..aea79925a 100644--- a/bot/vikingbot/compile/service.py+++ b/bot/vikingbot/compile/service.py@@ -37,6 +37,7 @@ from vikingbot.agent.subagent import SubagentManagerfrom vikingbot.agent.tools.base import ToolContextfrom vikingbot.agent.tools.compile import (CompileChildTool,+ CompileImageReadTool,CompileSpawnTool,SubmitCompileDraftTool,SubmitWikiBundleTool,@@ -71,7 +72,7 @@ from vikingbot.compile.renderer import (validate_declared_okf_markdown,)from vikingbot.compile.sandbox import CompileSandboxManager-from vikingbot.compile.sources import CompileSourceRange, pack_source_batches+from vikingbot.compile.sources import CompileSourceRange, pack_source_batches, read_sourcefrom vikingbot.compile.store import CompileTaskStorefrom vikingbot.config.schema import SandboxBackend, SandboxMode, SessionKeyfrom vikingbot.openviking_mount.ov_server import VikingClient@@ -1144,7 +1145,8 @@ class BotCompileService:for start in range(0, len(ordered), 8):uris = ordered[start : start + 8]contents = await asyncio.gather(- *(client.read_raw(uri) for uri in uris), return_exceptions=True+ *(read_source(client, uri, pipeline.model.provider) for uri in uris),+ return_exceptions=True,)readable = []for uri, content in zip(uris, contents, strict=True):@@ -1152,6 +1154,11 @@ class BotCompileService:manifest = await pipeline.files.get("inputs")manifest[uri] = "failed"await pipeline.files.put("inputs", manifest)+ if (+ isinstance(content, CompileFailure)+ and content.code == "UNSUPPORTED_MEDIA"+ ):+ raise contentpipeline.failures.append(f"Source read failed: {uri}: {str(content)[:400]}")elif isinstance(content, BaseException):raise content@@ -1576,11 +1583,13 @@ class BotCompileService:self, client: VikingClient, roots: list[str], *, files: list[str] | None = None) -> list[list[CompileSourceRange]]:"""Read selected files (or inventory roots) eight at a time; read errors propagate."""- sources: list[tuple[str, str]] = []+ sources: list[tuple[str, str | CompileSourceRange]] = []ordered = files if files is not None else await self._list_source_files(client, roots)for start in range(0, len(ordered), 8):uris = ordered[start : start + 8]- contents = await asyncio.gather(*(client.read_raw(uri) for uri in uris))+ contents = await asyncio.gather(+ *(read_source(client, uri, self.agent_loop.provider) for uri in uris)+ )sources.extend(zip(uris, contents, strict=True))return pack_source_batches(sources, self.limits)@@ -1605,6 +1614,12 @@ class BotCompileService:return Nonemanager = request_loop.subagentsclaimed_roots: set[str] = set()+ image_hashes = {+ part.uri: part.sha256+ for batch in source_batches or []+ for part in batch+ if part.image and part.sha256+ }async def run_child(child_id: str,@@ -1669,6 +1684,8 @@ class BotCompileService:for name in _COMPILE_READ_TOOLS:tool = registry.get(name)if tool is not None:+ if name == "openviking_multi_read" and image_hashes:+ tool = CompileImageReadTool(tool, image_hashes)child_tools.register(tool)async def require_draft_submission(context: _PlainTextContext) -> _PlainTextDelivered:diff --git a/bot/vikingbot/compile/skill_resources.py b/bot/vikingbot/compile/skill_resources.pyindex 796ae05e7..e2f9b1c29 100644--- a/bot/vikingbot/compile/skill_resources.py+++ b/bot/vikingbot/compile/skill_resources.py@@ -9,7 +9,7 @@ import uuidfrom openviking.core.namespace import relative_uri_pathfrom openviking.utils.path_safety import safe_join_viking_uri-from vikingbot.agent.tools.base import Tool+from vikingbot.agent.tools.base import MultimodalToolResult, Toolfrom vikingbot.compile.hashing import content_hashfrom vikingbot.compile.models import COMPILE_STAGING_ROOTfrom vikingbot.compile.renderer import validate_relative_file_path@@ -127,7 +127,8 @@ class EvidenceReader(Tool):name = "read_evidence"description = ("Read assigned original evidence. Optional start_line/end_line are one-based, inclusive "- "lines within the source_range shard; omit both for the complete shard."+ "lines within the source_range shard; omit both for the complete shard. "+ "For image evidence omit line bounds to view the original image.")parameters = {"type": "object",@@ -169,7 +170,7 @@ class EvidenceReader(Tool):for reference in full:self.spans.pop(reference, None)- async def read(self, source_range, spans=()):+ async def read(self, source_range, spans=(), *, include_image=False):"""Return exact original excerpts with shard metadata, or the full shard without bounds.Reject unauthorized IDs and invalid shard-local lines; merge overlapping/adjacent@@ -180,6 +181,13 @@ class EvidenceReader(Tool):value = await self.files.get(f"sources/{source_range}")if value is None:raise ValueError("Assigned source range is missing")+ if value.get("image"):+ if spans:+ raise ValueError("Image evidence has no text line ranges")+ return {+ **{key: item for key, item in value.items() if key != "image" or include_image},+ "complete": False,+ }lines = value["text"].splitlines(keepends=True)merged = []for start, end in sorted(spans):@@ -210,4 +218,9 @@ class EvidenceReader(Tool):if (start_line is None) != (end_line is None):raise ValueError("Supply both start_line and end_line, or neither")spans = [] if start_line is None else [(start_line, end_line)]- return json.dumps(await self.read(source_range, spans), ensure_ascii=False)+ value = await self.read(source_range, spans, include_image=True)+ image = value.pop("image", None)+ text = json.dumps(value, ensure_ascii=False)+ if image:+ return MultimodalToolResult(text, [{"type": "text", "text": text}, image])+ return textdiff --git a/bot/vikingbot/compile/sources.py b/bot/vikingbot/compile/sources.pyindex 493fa4e9a..7db0fe0cd 100644--- a/bot/vikingbot/compile/sources.py+++ b/bot/vikingbot/compile/sources.py@@ -2,12 +2,16 @@from __future__ import annotations+import jsonimport refrom bisect import bisect_right-from dataclasses import dataclass+from dataclasses import asdict, dataclassfrom typing import Iterable+from urllib.parse import urlsplit-from vikingbot.compile.models import CompileLimits+from openviking.parse.parsers.media.utils import get_media_type+from vikingbot.agent.tools.ov_file import VikingMultiReadTool+from vikingbot.compile.models import CompileFailure, CompileLimits_HEADING = re.compile(r"^ {0,3}(#{1,6})[ \t]+\S")_FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})")@@ -25,6 +29,7 @@ class CompileSourceRange:frontmatter, enclosing headings and a table header when they fit the repeat budget.Continuation flags identify cuts inside an oversized line or table row;these fragments require their adjacent ranges for complete interpretation.+ Images keep zero offsets and carry their original bytes and hash instead of text."""uri: str@@ -36,14 +41,46 @@ class CompileSourceRange:context: str = ""continues_before: bool = Falsecontinues_after: bool = False+ image: dict | None = None+ sha256: str | None = None++ def as_assignment(self) -> dict:+ """Attach exact text ranges or bounded references to original images."""+ if self.image:+ return {"uri": self.uri, "sha256": self.sha256, "media_kind": "image"}+ return asdict(self)@propertydef input_chars(self) -> int:"""Count source text and repeated context against the batch character budget."""+ if self.image:+ return len(json.dumps(self.as_assignment(), ensure_ascii=False))return len(self.content) + len(self.context)-def split_source(uri: str, content: str, max_chars: int) -> list[CompileSourceRange]:+async def read_source(client, uri, provider) -> str | CompileSourceRange:+ """Keep text reads intact; consume image sources through multi-read's native reader."""+ if get_media_type(urlsplit(uri).path, None) != "image":+ return await client.read_raw(uri)+ if VikingMultiReadTool._media_kind(uri) != "image":+ raise CompileFailure(+ "INVALID_ARGUMENT", f"Unsupported Compile image format: {uri}", stage="pipeline"+ )+ if not provider.supports_tool_result_media():+ raise CompileFailure(+ "UNSUPPORTED_MEDIA",+ f"Compile provider cannot deliver image evidence: {uri}",+ stage="pipeline",+ )+ result = await VikingMultiReadTool._read_image(client, uri)+ if not result["success"]:+ raise CompileFailure("SOURCE_READ_FAILED", f"{uri}: {result['content']}", stage="pipeline")+ return CompileSourceRange(uri, 0, 0, 0, 0, "", image=result["image"], sha256=result["sha256"])+++def split_source(+ uri: str, content: str | CompileSourceRange, max_chars: int+) -> list[CompileSourceRange]:"""Partition original text by characters, preferring headings, paragraphs and whole lines.Complete table rows fit together with their header whenever the budget permits.@@ -51,6 +88,12 @@ def split_source(uri: str, content: str, max_chars: int) -> list[CompileSourceRafrontmatter/headings/table headers use at most one quarter of the budget; theiroriginal text remains in the source ranges. Empty files retain one empty range."""+ if isinstance(content, CompileSourceRange):+ return [content]+ if get_media_type(urlsplit(uri).path, None) == "image":+ raise CompileFailure(+ "INVALID_ARGUMENT", "Image evidence must not be split as text", stage="pipeline"+ )if max_chars < 1:raise ValueError("Source character budget must be positive")lines = content.splitlines(keepends=True)@@ -136,9 +179,9 @@ def split_source(uri: str, content: str, max_chars: int) -> list[CompileSourceRadef pack_source_batches(- sources: Iterable[tuple[str, str]], limits: CompileLimits+ sources: Iterable[tuple[str, str | CompileSourceRange]], limits: CompileLimits) -> list[list[CompileSourceRange]]:- """Pack exact source ranges in input order, bounded only by characters.+ """Pack exact source ranges and image references within existing text/media budgets.Adjacent ranges may share a batch when they fit. Small files share remainingcapacity; original URIs remain the citation targets for all ranges. Source text@@ -147,13 +190,33 @@ def pack_source_batches(batches: list[list[CompileSourceRange]] = []batch: list[CompileSourceRange] = []size = 0+ image_count = media_bytes = 0for uri, content in sources:for part in split_source(uri, content, limits.source_batch_chars):- if batch and size + part.input_chars > limits.source_batch_chars:+ chars, part_bytes = part.input_chars, 0+ if part.image:+ from vikingbot.agent.loop import _inline_media_bytes++ part_bytes = _inline_media_bytes([{"content": [part.image]}])+ if (+ chars > limits.source_batch_chars+ or part_bytes > VikingMultiReadTool._MAX_INLINE_MEDIA_BYTES+ ):+ raise CompileFailure(+ "MEDIA_LIMIT", "Image exceeds the source batch budget", stage="pipeline"+ )+ if batch and (+ size + chars > limits.source_batch_chars+ or image_count + bool(part.image) > VikingMultiReadTool._MAX_INLINE_IMAGES+ or media_bytes + part_bytes > VikingMultiReadTool._MAX_INLINE_MEDIA_BYTES+ ):batches.append(batch)batch, size = [], 0+ image_count = media_bytes = 0batch.append(part)- size += part.input_chars+ size += chars+ image_count += bool(part.image)+ media_bytes += part_bytesif batch:batches.append(batch)return batchesdiff --git a/openviking/utils/message_format.py b/openviking/utils/message_format.pyindex 53e732b86..505bfb716 100644--- a/openviking/utils/message_format.py+++ b/openviking/utils/message_format.py@@ -80,7 +80,11 @@ def format_messages(messages: List[Dict[str, Any]]) -> str:result_json = json.loads(content)output.append(json.dumps(result_json, indent=2, ensure_ascii=False))except (json.JSONDecodeError, TypeError):- output.append(content)+ output.append(+ content+ if isinstance(content, str)+ else json.dumps(content, ensure_ascii=False, indent=2)+ )else:if content:output.append(f"\n[{role}]")diff --git a/tests/unit/test_message_format.py b/tests/unit/test_message_format.pyindex 767ff9f3a..975b89c81 100644--- a/tests/unit/test_message_format.py+++ b/tests/unit/test_message_format.py@@ -1,6 +1,8 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0+import pytest+from openviking.utils.message_format import format_messages, sanitize_openai_messages@@ -22,11 +24,12 @@ def test_format_messages_renders_roles_and_content():)-def test_format_messages_renders_multimodal_content_as_json():[email protected]("role", ["user", "tool"])+def test_format_messages_renders_multimodal_content_as_json(role):rendered = format_messages([{- "role": "user",+ "role": role,"content": [{"type": "text", "text": "Describe this image."},{"type": "image_url", "image_url": {"url": "[redacted]"}},@@ -35,7 +38,7 @@ def test_format_messages_renders_multimodal_content_as_json():])- assert "[user]" in rendered+ assert f"[{role}]" in renderedassert '"type": "image_url"' in renderedassert '"url": "[redacted]"' in rendered