Skip to content

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

fix(gateway): tolerate non-string "type" values in client history (#6306)

Pujitha Paladugud9db19ab6402
diff --git a/openviking_gateway/capture.py b/openviking_gateway/capture.py
index 73334ffc7..edb908b0e 100644
--- a/openviking_gateway/capture.py
+++ b/openviking_gateway/capture.py
@@ -23,7 +23,7 @@ from .archives import TERMINAL, observe_archive
from .capture_store import Document, LeaseLost
from .models import Policy
from .notices import without_notices
-from .protocols import clean_text, is_user, text_content, unwrap_client
+from .protocols import clean_text, is_user, string_type, text_content, unwrap_client
from .records import RecordKind as K
from .tool_protocols import reply_chain
@@ -453,14 +453,14 @@ def capture_messages(messages, chain):
for message in messages:
if message.get("role") == "tool":
results[message.get("tool_call_id")] = message.get("content", "")
- if message.get("type") in {"function_call_output", "custom_tool_call_output"}:
+ if string_type(message) in {"function_call_output", "custom_tool_call_output"}:
results[message.get("call_id")] = message.get("output", "")
for block in message.get("content", []) if isinstance(message.get("content"), list) else []:
if isinstance(block, dict) and block.get("type") == "tool_result":
results[block.get("tool_use_id")] = block.get("content", "")
output = []
for message, anchor in zip(messages, chain, strict=True):
- if message.get("role") not in {"user", "assistant"} and message.get("type") not in {
+ if message.get("role") not in {"user", "assistant"} and string_type(message) not in {
"function_call",
"custom_tool_call",
}:
@@ -473,7 +473,7 @@ def capture_messages(messages, chain):
text = clean_text(unwrap_client(text))
parts = [{"type": "text", "text": text}] if text else []
calls = list(message.get("tool_calls") or [])
- if message.get("type") in {"function_call", "custom_tool_call"}:
+ if string_type(message) in {"function_call", "custom_tool_call"}:
calls.append(message)
calls.extend(
b
diff --git a/openviking_gateway/protocols.py b/openviking_gateway/protocols.py
index ddccea160..8ca8fbba4 100644
--- a/openviking_gateway/protocols.py
+++ b/openviking_gateway/protocols.py
@@ -124,6 +124,12 @@ def parse_body(raw: bytes) -> dict | None:
return None
+def string_type(value: Any) -> str:
+ """A block's ``type`` when it is a string; malformed histories may carry an object."""
+ kind = value.get("type") if isinstance(value, dict) else None
+ return kind if isinstance(kind, str) else ""
+
+
def text_content(message: dict) -> str:
content = message.get("content", "")
if isinstance(content, str):
@@ -133,7 +139,7 @@ def text_content(message: dict) -> str:
x.get("text", "")
for x in content
if isinstance(x, dict)
- and x.get("type") in {"text", "input_text", "output_text"}
+ and string_type(x) in {"text", "input_text", "output_text"}
and isinstance(x.get("text", ""), str)
)
return ""
@@ -162,10 +168,10 @@ def normalize(value: Any) -> Any:
if not (
isinstance(v, dict)
and (
- v.get("type") in {"thinking", "redacted_thinking"}
+ string_type(v) in {"thinking", "redacted_thinking"}
or (
- v.get("type") in {"text", "input_text", "output_text"}
- and not v.get("text", "").strip()
+ string_type(v) in {"text", "input_text", "output_text"}
+ and not (isinstance(v.get("text", ""), str) and v.get("text", "").strip())
)
)
)
@@ -182,7 +188,7 @@ def normalize(value: Any) -> Any:
content = out["content"]
if isinstance(content, list) and len(content) == 1 and isinstance(content[0], dict):
block = content[0]
- if set(block) == {"type", "text"} and block["type"] in {
+ if set(block) == {"type", "text"} and string_type(block) in {
"text",
"input_text",
"output_text",
@@ -191,7 +197,9 @@ def normalize(value: Any) -> Any:
if isinstance(content, str):
content = unwrap_client(content).strip()
out["content"] = content
- if out.get("type") in {"text", "input_text", "output_text"}:
+ if string_type(out) in {"text", "input_text", "output_text"} and isinstance(
+ out.get("text", ""), str
+ ):
out["text"] = unwrap_client(out.get("text", "")).strip()
# Responses message items may omit type/status/id when resent by a client.
# IDs of opaque items (item_reference, reasoning, calls) remain significant.
@@ -316,7 +324,7 @@ def client_openviking_tools(body: dict, names) -> bool:
continue
# Hosted MCP servers (Responses mcp, Anthropic mcp_servers and mcp_toolset) list
# no tools, so their name is all there is.
- server = definition.get("type") in {"mcp", "mcp_toolset", "url"}
+ server = string_type(definition) in {"mcp", "mcp_toolset", "url"}
named_tool = isinstance(definition.get("name"), str) and not server
# A tool must be one of OpenViking's, so a connector's authenticate tool is not.
if any(
@@ -436,7 +444,7 @@ def strip_thinking(messages: list[dict]) -> list[dict]:
message["content"] = [
b
for b in message["content"]
- if b.get("type") not in {"thinking", "redacted_thinking"}
+ if string_type(b) not in {"thinking", "redacted_thinking"}
]
return result
diff --git a/openviking_gateway/tool_executor.py b/openviking_gateway/tool_executor.py
index 1c7b15949..59823043d 100644
--- a/openviking_gateway/tool_executor.py
+++ b/openviking_gateway/tool_executor.py
@@ -18,6 +18,7 @@ import orjson
from .capture_store import Document
from .client import VikingError
from .config import MOUNT_PATH
+from .protocols import string_type
from .state_store import get_state
from .storage import digest
from .tool_catalog import PREFIX, TOOL_OVERRIDES
@@ -57,7 +58,7 @@ def attachments(body, protocol):
content = message.get("content", [])
if isinstance(content, list):
for part in content:
- if isinstance(part, dict) and part.get("type") in {"file", "input_file"}:
+ if string_type(part) in {"file", "input_file"}:
output.append(part.get("file", part))
elif isinstance(part, dict) and part.get("type") == "document":
source = part.get("source", {})
diff --git a/openviking_gateway/tool_protocols/anthropic.py b/openviking_gateway/tool_protocols/anthropic.py
index 128e896df..6163136ff 100644
--- a/openviking_gateway/tool_protocols/anthropic.py
+++ b/openviking_gateway/tool_protocols/anthropic.py
@@ -6,7 +6,7 @@ import copy
import orjson
-from ..protocols import strip_thinking, text_content
+from ..protocols import string_type, strip_thinking, text_content
from .common import (
SUMMARY_HEADROOM,
SummaryError,
@@ -94,7 +94,7 @@ class AnthropicProtocol(ToolProtocol):
blocks = [
[position, block]
for position, block in enumerate(content if isinstance(content, list) else [])
- if isinstance(block, dict) and block.get("type") in THINKING
+ if string_type(block) in THINKING
]
if blocks:
reasoning[index] = {"blocks": blocks}
@@ -108,7 +108,7 @@ class AnthropicProtocol(ToolProtocol):
if (
message.get("role") != "assistant"
or not isinstance(content, list)
- or any(isinstance(b, dict) and b.get("type") in THINKING for b in content)
+ or any(string_type(b) in THINKING for b in content)
):
return [message]
# Blocks go back where the reply had them, so the client's form must equal it without them.
diff --git a/openviking_gateway/tool_protocols/responses.py b/openviking_gateway/tool_protocols/responses.py
index 9f593ce73..c8f21aa27 100644
--- a/openviking_gateway/tool_protocols/responses.py
+++ b/openviking_gateway/tool_protocols/responses.py
@@ -6,7 +6,7 @@ import copy
import uuid
from ..notices import without_recall_notice
-from ..protocols import text_content
+from ..protocols import string_type, text_content
from .common import (
PREFIX,
SUMMARY_HEADROOM,
@@ -44,18 +44,18 @@ class ResponsesProtocol(ToolProtocol):
@staticmethod
def is_reply(message):
- return message.get("role") == "assistant" or message.get("type") in {
+ return message.get("role") == "assistant" or string_type(message) in {
"reasoning",
*CLIENT_CALLS,
}
@staticmethod
def accepts_context(message):
- return message.get("role") == "user" or message.get("type") in TOOL_OUTPUTS
+ return message.get("role") == "user" or string_type(message) in TOOL_OUTPUTS
@staticmethod
def append_context(message, text):
- if message.get("type") in TOOL_OUTPUTS:
+ if string_type(message) in TOOL_OUTPUTS:
append_text(message, "output", text, "input_text", joins_strings=True)
else:
append_text(message, "content", text, "input_text")
diff --git a/tests/gateway/test_malformed_types.py b/tests/gateway/test_malformed_types.py
new file mode 100644
index 000000000..2ba684144
--- /dev/null
+++ b/tests/gateway/test_malformed_types.py
@@ -0,0 +1,31 @@
+"""Histories whose ``type`` is not a string must not abort request processing."""
+
+from openviking_gateway.capture import capture_messages
+from openviking_gateway.protocols import normalize, prefix_chain, strip_thinking, text_content
+from openviking_gateway.tool_protocols import tool_protocol
+
+ODD = {"type": "string"}
+
+
+def malformed():
+ return {
+ "role": "user",
+ "type": ODD,
+ "content": [{"type": ODD, "text": "hello"}, {"type": "text", "text": ODD}],
+ }
+
+
+def test_protocol_helpers_ignore_object_types():
+ message = malformed()
+ assert normalize([message])[0]["type"] == ODD
+ assert len(prefix_chain([message])) == 1
+ assert text_content(message) == ""
+ assert strip_thinking([message])[0]["content"][0]["type"] == ODD
+
+
+def test_capture_and_responses_ignore_object_types():
+ message = malformed()
+ assert capture_messages([message], ["a"]) == capture_messages([message], ["a"])
+ protocol = tool_protocol("responses")
+ assert protocol.accepts_context(message)
+ assert not protocol.is_reply(message)