Skip to content

[Bug]: Hermes and Deep Agents return the whole conversation in output.messages on every invoke, so multi-turn runtimes hit max_response_bytes #717

Backlog

Description

@kaofelix

Affected area

  • Harness adapter
  • Adapter contract
  • Rust core or runtime

NeMo Fabric version

0.7.0 (76bde16c), and main: nightly 0.8.0a20261125 (bd3d9b9a). The adapter code involved is identical in both.

Installation method

PyPI package

Current behavior

On a runtime that takes several ordered invocations (start_runtime, then invoke repeatedly), the Hermes and Deep
Agents adapters put the whole conversation so far into RunResult.output.messages (and message_count) on every
invoke, not only the messages the invocation produced. Each result grows with the conversation.

Once a result is larger than runtime.response_limits.max_response_bytes, the invoke fails with
response_limit_exceeded, and every later invoke on that runtime fails too, because the next result is larger
still. The limit is 4 MiB by default and always applies under the OpenShell environment provider. Locally it applies
when response_limits is set. The agent still ran the rejected turn (with any side effects), but output is cleared,
so the caller loses the answer.

Deep Agents already reports usage for the invocation only (it aggregates the turn's messages), while it returns the
replayed graph state in messages.

Expected behavior

output.messages holds only the messages this invocation produced, as usage is invocation-local
(results contract). A result is then bounded by the
turn, not by the session, and a long runtime keeps working.

For Hermes, "this invocation's messages" should be what run_conversation appended, not a slice by the previous
length, because context compression can rewrite the earlier history. Deep Agents already collects turn_messages.

If some consumers rely on the full list, an opt-in such as a harness setting output_history: full could keep it,
with per-invocation messages as the default. A cursor (a stable message_offset or the last message's ID, or
messages_since on the request) would also work. For a consumer that de-duplicates messages by ID, all three options
are compatible.

Steps to reproduce

No model key is needed: a deterministic fake OpenAI-compatible server answers every request with the same text, so each
turn adds exactly two messages (user, assistant).

  1. Install Hermes Agent at the commit Fabric pins (b200f5bc), as just install-hermes-agent does, then the packages:

    git init -q hermes-agent && git -C hermes-agent remote add origin https://github.com/NousResearch/hermes-agent.git
    git -C hermes-agent fetch -q --depth 1 origin b200f5bc60e31588ba2cb60e288029c4a54ba5fa
    git -C hermes-agent checkout -q --detach b200f5bc60e31588ba2cb60e288029c4a54ba5fa
    uv venv -q --python 3.14 .venv
    UV_PROJECT_ENVIRONMENT=$PWD/.venv uv sync -q --project hermes-agent --frozen --no-default-groups \
      --no-install-package discord-py --no-install-package python-telegram-bot --no-install-package slack-bolt \
      --no-install-package slack-sdk --no-install-package qrcode --no-install-package brotlicffi
    uv pip install --python .venv/bin/python nemo-fabric==0.7.0 nemo-fabric-adapters-hermes==0.7.0
    # Deep Agents, in its own venv: uv pip install "nemo-fabric[deepagents]==0.7.0"
  2. Save the two files below, then start the fake server:

    .venv/bin/python fake_openai.py &
  3. Run a runtime with many turns, first without a limit, then with a low one:

    .venv/bin/python repro.py --adapter hermes --turns 12
    .venv/bin/python repro.py --adapter hermes --turns 60 --limit 32768 --keep-going 2
  4. Observe that messages grows by 2 every turn and result_bytes by about 0.9 KB, until turn 30 fails with
    response_limit_exceeded and the following invokes fail too (output below).

fake_openai.py (72 lines)
"""A tiny deterministic OpenAI-compatible server: no model key, no network.

Answers every chat completion with the same short text (streamed or not), so
a harness's conversation grows by exactly its own messages each turn.
Usage: python fake_openai.py [port]   (default 18731)
"""

import json
import sys
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

REPLY = "Noted. " + "This is a deterministic reply from a fake model. " * 8
MODEL = "fake-model"


class Handler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def log_message(self, fmt, *args):
        sys.stderr.write("fake_openai: " + (fmt % args) + "\n")

    def _json(self, code, body):
        data = json.dumps(body).encode()
        self.send_response(code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        model = {"id": MODEL, "object": "model", "owned_by": "fake", "context_length": 128000}
        if self.path.rstrip("/").endswith("/models"):
            return self._json(200, {"object": "list", "data": [model]})
        if self.path.rstrip("/").endswith(f"/models/{MODEL}"):
            return self._json(200, model)
        self._json(404, {"error": {"message": "not found"}})

    def do_POST(self):
        body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
        if not self.path.rstrip("/").endswith("/chat/completions"):
            return self._json(404, {"error": {"message": "not found"}})
        created = int(time.time())
        usage = {"prompt_tokens": 10, "completion_tokens": 10, "total_tokens": 20}
        if not body.get("stream"):
            return self._json(200, {
                "id": "chatcmpl-fake", "object": "chat.completion", "created": created, "model": MODEL,
                "choices": [{"index": 0, "finish_reason": "stop",
                             "message": {"role": "assistant", "content": REPLY}}],
                "usage": usage})
        self.send_response(200)
        self.send_header("Content-Type", "text/event-stream")
        self.send_header("Cache-Control", "no-cache")
        self.send_header("Connection", "close")
        self.end_headers()
        base = {"id": "chatcmpl-fake", "object": "chat.completion.chunk", "created": created, "model": MODEL}
        chunks = [
            {**base, "choices": [{"index": 0, "delta": {"role": "assistant", "content": REPLY}, "finish_reason": None}]},
            {**base, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]},
            {**base, "choices": [], "usage": usage},
        ]
        for chunk in chunks:
            self.wfile.write(f"data: {json.dumps(chunk)}\n\n".encode())
        self.wfile.write(b"data: [DONE]\n\n")
        self.wfile.flush()
        self.close_connection = True


if __name__ == "__main__":
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 18731
    ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever()
repro.py (114 lines)
"""Repro: a Fabric adapter's RunResult grows every turn because output.messages
holds the whole conversation, until runtime.response_limits.max_response_bytes
rejects it with response_limit_exceeded.

No model key needed: start fake_openai.py first (it answers deterministically).

    python repro.py --adapter hermes --turns 12 --limit 32768
    python repro.py --adapter deepagents --turns 12 --limit 32768

Prints, per turn: len(output.messages), the RunResult's compact JSON size
(what Fabric's limit counts), and how many messages are new this turn, and RunResult.usage.total_tokens (which
the contract requires to be invocation-local).
"""

import argparse
import asyncio
import json
import os
import sys
import tempfile
from importlib.metadata import version
from pathlib import Path

from nemo_fabric import Fabric, FabricConfig, ResponseLimits


ADAPTER_IDS = {
    "hermes": "nvidia.fabric.hermes",
    "deepagents": "nvidia.fabric.langchain.deepagents",
}


def config(adapter: str, base_url: str, work: Path, limit: int | None) -> FabricConfig:
    data = {
        "schema_version": "fabric.agent/v1alpha1",
        "metadata": {"name": f"s9-{adapter}"},
        "harness": {"adapter_id": ADAPTER_IDS[adapter]},
        "models": {"default": {
            "provider": "openai",
            "model": "fake-model",
            "base_url": base_url,
            "api_key_env": "FAKE_OPENAI_API_KEY",
            "max_tokens": 256,
        }},
        "instructions": {"system": {"mode": "replace", "content": "Be brief."}},
        "runtime": {
            "artifacts": str(work / "artifacts"),
            "max_turns": 10,
            "timeout_seconds": 60,
        },
        "environment": {"provider": "local", "workspace": str(work)},
    }
    if adapter == "hermes":
        data["harness"]["settings"] = {
            "auxiliary": {"title_generation": {"enabled": False},
                          "background_review": {"enabled": False}},
            "tools": {"tool_search": {"enabled": "off"}},
        }
        data["tools"] = {"enabled": []}
    cfg = FabricConfig.model_validate(data)
    if limit is not None:
        cfg.runtime.response_limits = ResponseLimits(max_response_bytes=limit)
    return cfg


async def main() -> None:
    p = argparse.ArgumentParser()
    p.add_argument("--adapter", default="hermes", choices=["hermes", "deepagents"])
    p.add_argument("--turns", type=int, default=12)
    p.add_argument("--limit", type=int, default=None, help="max_response_bytes")
    p.add_argument("--keep-going", type=int, default=0,
                   help="invokes to send after the first failure")
    p.add_argument("--base-url", default="http://127.0.0.1:18731/v1")
    args = p.parse_args()
    os.environ.setdefault("FAKE_OPENAI_API_KEY", "not-a-real-key")
    # Fabric starts the adapter host with ADAPTER_PYTHON; use this venv.
    os.environ.setdefault("ADAPTER_PYTHON", sys.executable)
    pkg = f"nemo-fabric-adapters-{args.adapter}"
    print(f"nemo-fabric-runtime {version('nemo-fabric-runtime')}, {pkg} {version(pkg)}, "
          f"max_response_bytes={args.limit}")
    work = Path(tempfile.mkdtemp(prefix=f"s9-{args.adapter}-"))
    runtime = await Fabric().start_runtime(config(args.adapter, args.base_url, work, args.limit))
    print(f"{'turn':>4} {'status':>9} {'messages':>8} {'new':>4} {'result_bytes':>12} {'usage_tokens':>12}  error")
    previous = 0
    try:
        for turn in range(1, args.turns + 1):
            result = await runtime.invoke(input=f"Turn {turn}: say something short.")
            mapping = result.to_mapping()
            size = len(json.dumps(mapping, separators=(",", ":"), ensure_ascii=False).encode())
            output = mapping.get("output")
            messages = output.get("messages") if isinstance(output, dict) else None
            count = len(messages) if isinstance(messages, list) else None
            new = count - previous if count is not None else None
            usage = mapping.get("usage") or {}
            tokens = usage.get("total_tokens")
            error = ""
            if result.error is not None:
                meta = result.error.metadata or {}
                error = f"{result.error.code} (configured={meta.get('configured')}, observed={meta.get('observed')})"
            print(f"{turn:>4} {result.status:>9} {count if count is not None else '-':>8} "
                  f"{new if new is not None else '-':>4} {size:>12} {tokens if tokens is not None else '-':>12}  {error}", flush=True)
            if result.status != "succeeded":
                if args.keep_going <= 0:
                    break
                args.keep_going -= 1
                continue
            previous = count or 0
    finally:
        await runtime.stop()


if __name__ == "__main__":
    asyncio.run(main())

Environment

  • OS and architecture: macOS 26.7.1, arm64 (Apple silicon)
  • Python version: 3.14.10 (Hermes runs); 3.13.18 (Deep Agents run)
  • Rust version: N/A (PyPI wheels)
  • Harness and version: Hermes Agent b200f5bc (from its lockfile); deepagents 0.7.41
  • Adapter and version: nemo-fabric-adapters-hermes 0.7.0 and 0.8.0a20261125; nemo-fabric-adapters-deepagents 0.7.0
  • Install or build command: in Steps to reproduce (uv). The environment provider is local, and the model endpoint is the fake server above

Relevant logs or artifacts

Hermes, 0.7.0, no limit:

turn    status messages  new result_bytes usage_tokens  error
   1 succeeded        2    2         8357            -
   2 succeeded        4    2         9228            -
   3 succeeded        6    2        10087            -
  ...
  11 succeeded       22    2        16988            -
  12 succeeded       24    2        17852            -

Hermes, 0.7.0, max_response_bytes=32768:

  28 succeeded       56    2        31706            -
  29 succeeded       58    2        32594            -
  30    failed        -    -         4795            -  response_limit_exceeded (configured=32768, observed=33404)
  31    failed        -    -         4791            -  response_limit_exceeded (configured=32768, observed=34264)
  32    failed        -    -         4791            -  response_limit_exceeded (configured=32768, observed=35130)

Hermes on main (0.8.0a20261125): the same, turn 30 fails (observed 33450).

Deep Agents, 0.7.0, max_response_bytes=32768 (--adapter deepagents): usage stays per invocation while messages
grows.

turn    status messages  new result_bytes usage_tokens  error
   1 succeeded        2    2         8764           20
   2 succeeded        4    2         9797           20
  ...
  24 succeeded       48    2        32488           20
  25    failed        -    -         5367           20  response_limit_exceeded (configured=32768, observed=33462)

The fake model's messages are short. With a real model and file tools, a multi-turn consumer measured about 1.3 KB of
growth per turn (11.7 KB at turn 1, 24.4 KB at turn 11). Tool-heavy turns grow faster.

Code (permalinks at 0.7.0, with main in brackets):

The output shape comes from the original single-shot Hermes SDK adapter, where a run's messages were the conversation.
An early, closed proposal for a stateless multi-turn Session API (#5) replayed the transcript from the caller on each
turn, so returning the whole transcript in output.messages was the point there; it also noted the messages output
field contract still needed coordinating. With persistent local hosting (#87) the adapter keeps the history itself, so
the caller no longer needs it back, but the output kept the whole list. That makes it look incidental, and not tied to
cold resume (#605).

Other adapters already return per-invocation messages, or none:

Adapter Messages in output
hermes whole conversation (messages, message_count)
deepagents whole conversation (messages, message_count); usage per invocation
nooa this invocation (messages captured during the invoke)
claude this invocation (events from this query)
codex this invocation (events, this turn's items)
openclaw, openhands, remote-agent, mini-swe-agent none (response only)
TypeScript adapters (cline, droid, kilo, kiro, opencode, pi, qwen, strands) none (response only)

Impact and workaround

Affects any multi-turn consumer of the Hermes or Deep Agents adapters: a long enough runtime fails every invoke, and
resuming with a SessionRef doesn't help, because (by reading the code) the resumed runtime loads the saved history
and returns all of it in its first result. Under the OpenShell provider the 4 MiB default always applies. Consumers also
receive the history again on every turn and must de-duplicate it, which costs O(n) per turn and O(n²) over a session,
across the OpenShell transport.

Workaround: raise runtime.response_limits.max_response_bytes. This only postpones the failure. Alternatively, start a
fresh runtime without the SessionRef, which loses the conversation.

Duplicate check

  • I searched the existing issues and did not find a duplicate. (Searched open and closed issues and PRs for
    output.messages, message_count, response_limit_exceeded, max_response_bytes, and cumulative on
    2026-11-25.)

Activity

  1. added
    triage
    on Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    triage

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions