Skip to content

The agent that grows with you

feat(api-server): opt-in cap on tool outputs in the stored /v1/responses history

teknium1064756ca45c0
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index 899cb9589e3..6b5016460aa 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -1149,6 +1149,9 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
# restored — what next?", so a resumed turn should complete the interrupted work rather than acknowledge
# (#57056).
interactive_resume: bool = False
+ # Opt-in cap (chars) on tool outputs / tool-call arguments in the stored /v1/responses
+ # transcript; 0 = store verbatim (gateway.api_server.history_tool_output_max_chars, #82513).
+ _history_tool_output_max_chars: int = 0
# Admission-gated OpenAI-compatible entry points (bodies live in the mixin).
_handle_chat_completions = _admit_api_agent_request(OpenAICompatRoutesMixin._handle_chat_completions)
@@ -1188,6 +1191,8 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
self._last_resolved_model: Dict[str, str] = {}
self._session_db_lock: Optional[asyncio.Lock] = None # single-flight for lazy init
self._max_concurrent_runs: int = self._resolve_max_concurrent_runs() # 0 disables
+ self._history_tool_output_max_chars = self._resolve_api_server_int(
+ "history_tool_output_max_chars", default=0)
# In-flight _run_agent() turns (/v1/runs tracks its own via _active_run_tasks).
# Concurrency cap shared across all agent-serving endpoints (/v1/chat/completions, /v1/responses,
# /v1/runs, /api/sessions/{id}/chat[/stream]). Read from config.yaml
@@ -1290,12 +1295,14 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
@staticmethod
def _resolve_max_concurrent_runs() -> int:
"""gateway.api_server.max_concurrent_runs (0 disables; default 10; negatives -> 0)."""
- default = 10
+ return APIServerAdapter._resolve_api_server_int("max_concurrent_runs", default=10)
+
+ @staticmethod
+ def _resolve_api_server_int(key: str, *, default: int) -> int:
+ """Integer setting under gateway.api_server (unreadable config -> default; negatives -> 0)."""
try:
from hermes_cli.config import cfg_get, load_config
- raw = cfg_get(
- load_config(), "gateway", "api_server", "max_concurrent_runs", default=default)
- value = int(raw)
+ value = int(cfg_get(load_config(), "gateway", "api_server", key, default=default))
except Exception:
return default
return max(0, value)
diff --git a/gateway/platforms/api_server_openai_routes.py b/gateway/platforms/api_server_openai_routes.py
index f4a3434955a..82c0281fc78 100644
--- a/gateway/platforms/api_server_openai_routes.py
+++ b/gateway/platforms/api_server_openai_routes.py
@@ -110,6 +110,50 @@ def _same_transcript_prefix(agent_messages: List[Any], prefix: List[Any]) -> boo
return True
+def _cap_text(text: str, keep: int) -> str:
+ """Head of ``text`` plus a marker saying how much was cut (the Responses truncation rule)."""
+ return text[:keep] + "...[" + str(len(text) - keep) + " more chars]"
+
+
+def _cap_history_tool_outputs(history: List[Dict[str, Any]], max_chars: int) -> List[Dict[str, Any]]:
+ """Copy of ``history`` with tool outputs and string tool-call arguments longer than
+ ``max_chars`` cut down. Only tool rows and ``tool_calls`` blobs change; user/assistant text
+ is left alone, and the agent's own transcript rows are never mutated (rows are copied).
+ Opt-in via gateway.api_server.history_tool_output_max_chars: a single stored snapshot
+ embeds the full cumulative history, so a few large tool outputs pushed one
+ response_store.db write to ~677 KB (#82513)."""
+ if max_chars <= 0:
+ return history
+ out: List[Dict[str, Any]] = []
+ for msg in history:
+ if not isinstance(msg, dict):
+ out.append(msg)
+ continue
+ content = msg.get("content")
+ if msg.get("role") == "tool" and isinstance(content, str) and len(content) > max_chars:
+ msg = {**msg, "content": _cap_text(content, max_chars)}
+ tool_calls = msg.get("tool_calls")
+ if msg.get("role") == "assistant" and isinstance(tool_calls, list):
+ capped_calls = []
+ for call in tool_calls:
+ fn = call.get("function") if isinstance(call, dict) else None
+ raw = fn.get("arguments") if isinstance(fn, dict) else None
+ if isinstance(raw, str) and len(raw) > max_chars:
+ try:
+ args = json.loads(raw)
+ except ValueError:
+ args = None
+ if isinstance(args, dict):
+ for k, v in args.items():
+ if isinstance(v, str) and len(v) > max_chars:
+ args[k] = _cap_text(v, max_chars)
+ call = {**call, "function": {**fn, "arguments": json.dumps(args)}}
+ capped_calls.append(call)
+ msg = {**msg, "tool_calls": capped_calls}
+ out.append(msg)
+ return out
+
+
def _trim_tool_items(items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Trim large tool payloads in place so response.completed stays under ~100KB (clients
already received the full details via the incremental events)."""
@@ -132,7 +176,7 @@ def _trim_tool_items(items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
if isinstance(first, dict) and first.get("type") == "input_text":
text = first.get("text", "")
if len(text) > 1000:
- first["text"] = text[:500] + "...[" + str(len(text) - 500) + " more chars]"
+ first["text"] = _cap_text(text, 500)
item["output"] = [first]
return items
@@ -380,7 +424,8 @@ class _ResponsesStream:
env = self.terminal_envelope("completed", self._final_items())
result = self.result
full_history = self.adapter._build_response_conversation_history(
- self.conversation_history, self.user_message, result, self.final_response_text)
+ self.conversation_history, self.user_message, result, self.final_response_text,
+ tool_output_max_chars=self.adapter._history_tool_output_max_chars)
# Transcript substitution for result["_compressed"] happens in the history builder; only
# a compression-rotated session_id is propagated so chaining resumes the child session.
sid = result.get("session_id") if isinstance(result, dict) else None
@@ -938,7 +983,8 @@ class OpenAICompatRoutesMixin:
response_id = f"resp_{uuid.uuid4().hex[:28]}"
created_at = int(time.time())
full_history = self._build_response_conversation_history(
- conversation_history, user_message, result, final_response)
+ conversation_history, user_message, result, final_response,
+ tool_output_max_chars=self._history_tool_output_max_chars)
# _run_agent's effective session id carries compression rotations; storing it keeps
# previous_response_id chaining off the pre-rotation session (else compression re-fires).
_result_sid = result.get("session_id") if isinstance(result, dict) else None
@@ -990,12 +1036,15 @@ class OpenAICompatRoutesMixin:
@staticmethod
def _build_response_conversation_history(
conversation_history: List[Dict[str, Any]], user_message: Any, result: Dict[str, Any],
- final_response: Any) -> List[Dict[str, Any]]:
+ final_response: Any, *, tool_output_max_chars: int = 0) -> List[Dict[str, Any]]:
"""Build the stored Responses transcript without duplicating history.
A compressed transcript (``result["_compressed"]``) shares no input-history prefix, so
turn-start detection fails; prepending the uncompressed history would bloat the stored
context and re-trigger compression every request — it is stored as-is instead.
+
+ ``tool_output_max_chars`` > 0 caps tool outputs / tool-call argument blobs in the
+ stored copy (gateway.api_server.history_tool_output_max_chars; 0 = store verbatim).
"""
from gateway.platforms.api_server import APIServerAdapter
prior = list(conversation_history)
@@ -1006,9 +1055,12 @@ class OpenAICompatRoutesMixin:
conversation_history, user_message, result)
# turn_start == 0: compression rewrote the transcript or agent_messages is turn-only.
if turn_start or result.get("_compressed"):
- return list(agent_messages)
- return prior + [current_user] + agent_messages
- return prior + [current_user, {"role": "assistant", "content": final_response}]
+ history = list(agent_messages)
+ else:
+ history = prior + [current_user] + agent_messages
+ else:
+ history = prior + [current_user, {"role": "assistant", "content": final_response}]
+ return _cap_history_tool_outputs(history, tool_output_max_chars)
@staticmethod
def _response_messages_turn_start_index(
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 5f0970c3936..83b17325ffe 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -2099,6 +2099,12 @@ DEFAULT_CONFIG = {
# /v1/runs beyond this get HTTP 429 + Retry-After, bounding CPU/memory/LLM-quota
# exhaustion from a request flood. 0 = no cap.
"max_concurrent_runs": 10,
+ # Cap (chars) on each tool output and tool-call argument string in the stored
+ # /v1/responses conversation history used for previous_response_id chaining. The
+ # stored history is cumulative, so a few large tool outputs can make one
+ # response_store.db write several hundred KB. 0 = store tool outputs verbatim
+ # (default: the capped text is what the model is replayed on the next turn).
+ "history_tool_output_max_chars": 0,
},
},
# Real-time token streaming to messaging platforms (gateway; restart after enabling). Off by
diff --git a/tests/gateway/test_api_server_responses_history_cap.py b/tests/gateway/test_api_server_responses_history_cap.py
new file mode 100644
index 00000000000..ca75472bfb3
--- /dev/null
+++ b/tests/gateway/test_api_server_responses_history_cap.py
@@ -0,0 +1,58 @@
+"""Opt-in byte cap on tool outputs in the stored /v1/responses conversation history.
+
+The persisted snapshot embeds the cumulative transcript with every tool output verbatim, so a
+few large tool outputs made one response_store.db write ~677 KB (#82513). The cap is opt-in
+(``gateway.api_server.history_tool_output_max_chars``, 0 = verbatim) because the stored
+history is what the model is replayed on the next chained turn.
+"""
+
+import json
+from unittest.mock import patch
+
+from gateway.platforms.api_server import APIServerAdapter
+from gateway.platforms.base import PlatformConfig
+
+BIG = "x" * 20_000
+PRIOR = [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "hello"}]
+
+
+def _result():
+ return {"messages": [
+ *PRIOR,
+ {"role": "user", "content": "read it", "timestamp": 1.0},
+ {"role": "assistant", "content": "", "tool_calls": [
+ {"id": "c1", "type": "function",
+ "function": {"name": "write_file", "arguments": json.dumps({"path": "/tmp/f", "content": BIG})}}]},
+ {"role": "tool", "tool_call_id": "c1", "name": "write_file", "content": BIG},
+ {"role": "assistant", "content": "done " + BIG},
+ ]}
+
+
+def test_default_stores_tool_outputs_verbatim():
+ with patch("hermes_cli.config.load_config", return_value={}):
+ adapter = APIServerAdapter(PlatformConfig(enabled=True, extra={"port": 0}))
+ assert adapter._history_tool_output_max_chars == 0
+ result = _result()
+ history = adapter._build_response_conversation_history(
+ PRIOR, "read it", result, "done", tool_output_max_chars=adapter._history_tool_output_max_chars)
+ assert history[4]["content"] == BIG
+ assert json.loads(history[3]["tool_calls"][0]["function"]["arguments"])["content"] == BIG
+
+
+def test_cap_trims_only_tool_rows_and_leaves_agent_transcript_intact():
+ cfg = {"gateway": {"api_server": {"history_tool_output_max_chars": 1000}}}
+ with patch("hermes_cli.config.load_config", return_value=cfg):
+ adapter = APIServerAdapter(PlatformConfig(enabled=True, extra={"port": 0}))
+ assert adapter._history_tool_output_max_chars == 1000
+ result = _result()
+ history = adapter._build_response_conversation_history(
+ PRIOR, "read it", result, "done", tool_output_max_chars=adapter._history_tool_output_max_chars)
+ tool_row = history[4]
+ assert tool_row["content"].startswith("x" * 1000) and tool_row["content"].endswith("...[19000 more chars]")
+ assert len(tool_row["content"]) < 1100
+ args = json.loads(history[3]["tool_calls"][0]["function"]["arguments"])
+ assert args["path"] == "/tmp/f" and args["content"].endswith("...[19000 more chars]")
+ # Non-tool rows are untouched, and the agent's own transcript rows were copied, not mutated.
+ assert history[5]["content"] == "done " + BIG
+ assert result["messages"][4]["content"] == BIG
+ assert [m["role"] for m in history] == ["user", "assistant", "user", "assistant", "tool", "assistant"]
diff --git a/website/docs/user-guide/features/api-server.md b/website/docs/user-guide/features/api-server.md
index 9e8fc513790..939e12ae202 100644
--- a/website/docs/user-guide/features/api-server.md
+++ b/website/docs/user-guide/features/api-server.md
@@ -710,6 +710,7 @@ gateway:
cors_origins: http://localhost:3000
model_name: my-hermes
max_concurrent_runs: 10 # concurrent-run cap; 0 disables the limit
+ history_tool_output_max_chars: 0 # cap tool outputs in stored /v1/responses history; 0 = verbatim
```
`port`, `key`, `host`, `cors_origins`, and `model_name` are automatically bridged into the platform's `extra` settings, so they behave exactly like their `API_SERVER_*` environment-variable counterparts. Environment variables take precedence over `config.yaml` values. The block is also accepted under `gateway.platforms.api_server:` or a top-level `platforms.api_server:` section.
@@ -718,6 +719,10 @@ gateway:
The API server limits how many agent runs may execute at once across the endpoints that start one directly: the OpenAI-compatible endpoints, the Runs endpoints, and the session-chat endpoints (`POST /api/sessions/{id}/chat` and its `/stream` variant, which carry cross-machine agent DMs). Cron-triggered runs (`POST /api/jobs/{id}/run`, `POST /api/cron/fire`) go through the cron scheduler and are governed by cron's own limits, not this cap. The cap is read from `gateway.api_server.max_concurrent_runs` (default **10**; `0` disables the limit, negative values clamp to 0). When the cap is reached, new run-starting requests are rejected with **HTTP 429** `Too many concurrent runs (max N)` — clients should back off and retry.
+### Stored history size for `previous_response_id` chaining
+
+Each stored `/v1/responses` snapshot embeds the full cumulative conversation history (that is what `previous_response_id` and `conversation` chaining replay), including every tool output verbatim. A conversation with a few large tool outputs can therefore make a single `response_store.db` write several hundred KB. Set `gateway.api_server.history_tool_output_max_chars` (default **0** = store verbatim) to cap each tool output and each string tool-call argument in the **stored** history at that many characters; anything longer is cut to the head plus a `...[N more chars]` marker. User and assistant text is never touched, and the `response.completed` payload and incremental SSE events are unaffected. Because the stored history is what the model sees on the next chained turn, enabling the cap also trims what the model is replayed — leave it at 0 if your workflow needs complete tool outputs across turns.
+
## Security Headers
All responses include security headers: