Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(memory): redact inline image bytes from extraction (#4456)

jasonzhang78962c32add9
diff --git a/openviking/session/session.py b/openviking/session/session.py
index e1c7a3de2..7e88a1c48 100644
--- a/openviking/session/session.py
+++ b/openviking/session/session.py
@@ -78,6 +78,39 @@ _AGENT_TRAINING_REQUIRED_MEMORY_TYPES = frozenset({"experiences"})
_SESSION_PHASE1_LOCK_TIMEOUT_SECONDS = 30.0
_MEMORY_STEP_NAMES = ("long_term",)
_CUMULATIVE_CHECKPOINT_VERSION = 2
+# Match inline image transports emitted inside coding-agent tool output.
+_INLINE_IMAGE_DATA_URL_RE = re.compile(
+ r"data:(image/[a-z0-9.+-]+)(?:;[^;,\s\"'\\]+)*;base64,([a-z0-9+/_=-]+)",
+ re.IGNORECASE,
+)
+_B64_JSON_RE = re.compile(
+ r"(([\"'])b64_json\2\s*:\s*)([\"'])([a-z0-9+/_=-]+)\3",
+ re.IGNORECASE,
+)
+
+
+def _inline_image_placeholder(mime: str, base64_chars: int) -> str:
+ return f"[OpenViking inline image omitted: mime={mime}, base64_chars={base64_chars}]"
+
+
+def _redact_inline_images(text: str) -> str:
+ def replace_data_url(match: re.Match[str]) -> str:
+ return _inline_image_placeholder(match.group(1), len(match.group(2)))
+
+ def replace_b64_json(match: re.Match[str]) -> str:
+ quote = match.group(3)
+ placeholder = _inline_image_placeholder("image/*", len(match.group(4)))
+ return f"{match.group(1)}{quote}{placeholder}{quote}"
+
+ return _B64_JSON_RE.sub(replace_b64_json, _INLINE_IMAGE_DATA_URL_RE.sub(replace_data_url, text))
+
+
+def _redact_inline_images_from_tool_outputs(messages: List[Message]) -> List[Message]:
+ for message in messages:
+ for part in message.parts:
+ if isinstance(part, ToolPart):
+ part.tool_output = _redact_inline_images(part.tool_output or "")
+ return messages
def _publish_telemetry_summary_best_effort(snapshot: Any) -> None:
@@ -922,11 +955,11 @@ class Session:
self,
messages: List[Message],
) -> List[Message]:
- """Return a memory-only copy with externalized tool outputs restored."""
+ """Return a sanitized memory-only copy with externalized tool outputs restored."""
hydrated = [Message.from_dict(m.to_dict()) for m in messages]
store = self._tool_result_store()
if not store:
- return hydrated
+ return _redact_inline_images_from_tool_outputs(hydrated)
for msg in hydrated:
for part in msg.parts:
@@ -967,7 +1000,7 @@ class Session:
continue
part.tool_output = result.get("content", "")
- return hydrated
+ return _redact_inline_images_from_tool_outputs(hydrated)
def _effective_tool_preview_chars(
self,
@@ -4088,7 +4121,7 @@ class Session:
lines.append(p.text)
elif isinstance(p, ToolPart) and p.tool_name:
status = p.tool_status or "completed"
- output = p.tool_output or ""
+ output = _redact_inline_images(p.tool_output or "")
lines.append(f"[tool:{p.tool_name} ({status})] {output}")
elif isinstance(p, ContextPart) and p.abstract:
lines.append(f"[context] {p.abstract}")
diff --git a/tests/unit/session/test_wm_v2_guards.py b/tests/unit/session/test_wm_v2_guards.py
index 067f69ba6..5fb1a782d 100644
--- a/tests/unit/session/test_wm_v2_guards.py
+++ b/tests/unit/session/test_wm_v2_guards.py
@@ -7,6 +7,8 @@ These tests target pure/static methods on Session and related helpers,
so they don't need a running OpenViking server.
"""
+import pytest
+
from openviking.message.message import Message
from openviking.message.part import ContextPart, TextPart, ToolPart
from openviking.session.session import WM_SEVEN_SECTIONS, Session
@@ -636,6 +638,40 @@ class TestFormatMessageForWm:
assert "found 3 results" in result
assert result.startswith("[assistant]:")
+ def test_tool_inline_image_base64_redacted(self):
+ image_data = "A" * 50_000
+ output = (
+ 'before {"image_url":{"url":"data:image/png;base64,'
+ + image_data
+ + '"},"b64_json":"'
+ + image_data
+ + '"} after'
+ )
+ m = _msg(
+ "assistant",
+ [ToolPart(tool_name="view_image", tool_status="completed", tool_output=output)],
+ )
+
+ result = Session._format_message_for_wm(m)
+
+ assert "before" in result
+ assert "after" in result
+ assert "mime=image/png" in result
+ assert result.count("base64_chars=50000") == 2
+ assert image_data not in result
+
+ def test_malformed_inline_image_data_url_is_not_redacted(self):
+ malformed = "data:image/png" + ";param" * 1_024 + ";notbase64,"
+ m = _msg(
+ "assistant",
+ [ToolPart(tool_name="view_image", tool_status="completed", tool_output=malformed)],
+ )
+
+ result = Session._format_message_for_wm(m)
+
+ assert malformed in result
+ assert "inline image omitted" not in result
+
def test_context_part_included(self):
m = _msg(
"assistant",
@@ -694,3 +730,32 @@ class TestFormatMessageForWm:
)
result = Session._format_message_for_wm(m)
assert "(pending)" in result
+
+
+async def test_hydrated_extraction_output_redacts_inline_images():
+ image_data = "A" * 50_000
+ original = _msg(
+ "assistant",
+ [
+ ToolPart(
+ tool_name="view_image",
+ tool_output="externalized preview",
+ tool_output_ref="viking://user/test/sessions/test/tool-results/result-1",
+ tool_output_truncated=True,
+ )
+ ],
+ )
+
+ class Store:
+ async def read(self, _tool_result_id, **_kwargs):
+ return {"content": f"before data:image/png;base64,{image_data} after"}
+
+ session = Session.__new__(Session)
+ session._tool_result_store = lambda: Store()
+
+ hydrated = await session._hydrate_tool_outputs_for_extraction([original])
+
+ assert original.parts[0].tool_output == "externalized preview"
+ assert image_data not in hydrated[0].parts[0].tool_output
+ assert "base64_chars=50000" in hydrated[0].parts[0].tool_output