Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

fix(kernel): cap error text, refuse oversized host_request payloads, and pin the kernel fixes (#2500)

Sebastian Müller0e3c900225f8
diff --git a/packages/coding-agent/.changes/kernel-error-text-cap.md b/packages/coding-agent/.changes/kernel-error-text-cap.md
new file mode 100644
index 0000000000..4dbddd950d
--- /dev/null
+++ b/packages/coding-agent/.changes/kernel-error-text-cap.md
@@ -0,0 +1,3 @@
+- Fixed a Python cell raising an exception with a huge message restarting the kernel through protocol repair: error text and traceback entries are now capped at 1 Mi characters with a truncation marker, like result text, so the error is reported in the cell.
+- Fixed an oversized `host_request` payload (for example a huge skill-call argument) tearing the kernel protocol and restarting the kernel: `rlm.host_request()` now raises `ValueError` in the calling cell, like `emit()` does for display payloads.
+- Fixed a stale background `bash()` completion notice waking the model after it had already read the finished handle's result in the same turn ([#2372](https://github.com/PrimeIntellect-ai/prime-agent/pull/2372)).
diff --git a/prime-agent-runtime/src/rlm/repl.md b/prime-agent-runtime/src/rlm/repl.md
index 122bda80fe..7437ad70f0 100644
--- a/prime-agent-runtime/src/rlm/repl.md
+++ b/prime-agent-runtime/src/rlm/repl.md
@@ -65,8 +65,12 @@ runtime keeps serving. Closing stdin is equivalent to `shutdown`.
the cell finishes; user threads emit `null`.
- `{"event":"host_request","id":str,"data":{...}}` — one typed request from
runtime code to the host; the host answers with a `host_reply` request
- carrying the same id.
+ carrying the same id. `data` is subject to the same encoding cap as a
+ `display` payload: `host_request()` raises `ValueError` in the calling cell
+ instead of sending an oversized request.
- `{"event":"error","id":str|null,"ename":str,"evalue":str,"traceback":[str,...]}`
+ — `evalue` and each `traceback` entry are capped like `result` text (same
+ cap, same trailing marker).
- `{"event":"done","id":str,"status":"ok"|"error"}` — exactly one per id'd
request, always after all of that request's other events. A snapshot `done`
adds `saved`, `skipped`, `pruned`, `bytes`; a restore `done` adds `restored`,
diff --git a/prime-agent-runtime/src/rlm/repl.py b/prime-agent-runtime/src/rlm/repl.py
index 6ead01fa71..be0fdf1af4 100644
--- a/prime-agent-runtime/src/rlm/repl.py
+++ b/prime-agent-runtime/src/rlm/repl.py
@@ -39,11 +39,11 @@ DEFAULT_SNAPSHOT_MAX_VARIABLE_BYTES = 16 * 1024 * 1024
# 64 KiB pump chunks.
_STREAM_FRAME_TEXT_CAP = 64 * 1024
# The host truncates results at a smaller per-execution maxChars, so this only
-# bounds a pathological repr in transit.
+# bounds a pathological repr or exception text in transit.
_RESULT_TEXT_CAP = 1_048_576
_RESULT_TRUNCATION_MARKER = f"\n[... result truncated at {_RESULT_TEXT_CAP} characters ...]"
-# Oversized display payloads fail the cell instead of wedging host memory.
-_DISPLAY_PAYLOAD_CAP = 16 * 1024 * 1024
+# Oversized display and host_request payloads fail the cell instead of wedging host memory.
+_PAYLOAD_CAP = 16 * 1024 * 1024
# Names the session bootstrap re-creates on every start; never snapshotted.
_ALWAYS_SKIP = {"rlm", "mcp", "bash", "asyncio", "In", "Out", "get_ipython", "exit", "quit", "open"}
@@ -98,6 +98,19 @@ def _send(event: dict[str, Any]) -> None:
pass
+def _check_payload(event: str, data: dict[str, Any]) -> None:
+ """Fail the calling cell when a `data` payload would not fit one protocol frame.
+
+ Strict-dumps validation: default allow_nan=True would let NaN/Infinity
+ serialize as non-JSON text and tear the host's protocol framing (a
+ non-serializable value raises TypeError here before any bytes are
+ written, so NaN is the only corruption vector). The encoded length
+ enforces the frame cap; _send re-serializes.
+ """
+ if len(json.dumps(data, allow_nan=False)) > _PAYLOAD_CAP:
+ raise ValueError(f"{event} payload exceeds the {_PAYLOAD_CAP}-character frame cap")
+
+
def emit(data: dict[str, Any]) -> None:
"""Ship one display event carrying a dict of MIME type -> JSON payload.
@@ -105,14 +118,7 @@ def emit(data: dict[str, Any]) -> None:
"""
if not isinstance(data, dict) or not data or not all(isinstance(k, str) for k in data):
raise TypeError("emit() requires a non-empty dict keyed by MIME type strings")
- # Strict-dumps validation: default allow_nan=True would let NaN/Infinity
- # serialize as non-JSON text and tear the host's protocol framing (a
- # non-serializable value already raises in _send before any bytes are
- # written, so NaN is the only corruption vector). The encoded length
- # enforces the display frame cap; _send re-serializes.
- encoded = json.dumps(data, allow_nan=False)
- if len(encoded) > _DISPLAY_PAYLOAD_CAP:
- raise ValueError(f"display payload exceeds the {_DISPLAY_PAYLOAD_CAP}-character frame cap")
+ _check_payload("display", data)
_send({"event": "display", "id": _current_cell.get(), "data": data})
@@ -145,6 +151,7 @@ async def host_request(data: dict[str, Any]) -> dict[str, Any]:
raise RuntimeError("repl runtime is not serving")
if _host_closed:
raise RuntimeError("host connection closed; host_request cannot be answered")
+ _check_payload("host_request", data)
rid = uuid.uuid4().hex
future: asyncio.Future[dict[str, Any]] = _loop.create_future()
_pending_host[rid] = future
@@ -503,6 +510,12 @@ def _safe_str(exc: BaseException) -> str:
return "<exception str() failed>"
+def _cap_text(text: str) -> str:
+ if len(text) > _RESULT_TEXT_CAP:
+ return text[:_RESULT_TEXT_CAP] + _RESULT_TRUNCATION_MARKER
+ return text
+
+
def _error_event(cell_id: str, exc: BaseException) -> dict[str, Any]:
# No cell frame (e.g. SyntaxError): exception-only keeps filename, source, and caret.
te = traceback.TracebackException.from_exception(exc)
@@ -516,8 +529,8 @@ def _error_event(cell_id: str, exc: BaseException) -> dict[str, Any]:
"event": "error",
"id": cell_id,
"ename": type(exc).__name__,
- "evalue": _safe_str(exc),
- "traceback": lines,
+ "evalue": _cap_text(_safe_str(exc)),
+ "traceback": [_cap_text(line) for line in lines],
}
@@ -616,8 +629,8 @@ async def _handle_execute(req: dict[str, Any], ns: dict[str, Any]) -> None:
result_text = repr(value)
except BaseException as exc: # noqa: BLE001 - a broken __repr__ is a cell error
status, error = "error", _error_event(cell_id, exc)
- if result_text is not None and len(result_text) > _RESULT_TEXT_CAP:
- result_text = result_text[:_RESULT_TEXT_CAP] + _RESULT_TRUNCATION_MARKER
+ if result_text is not None:
+ result_text = _cap_text(result_text)
_drain_output()
finally:
# Close the interrupt window before the protocol sends so a
diff --git a/prime-agent-runtime/test/test_repl.py b/prime-agent-runtime/test/test_repl.py
index c3ca8ab3a0..396b439071 100644
--- a/prime-agent-runtime/test/test_repl.py
+++ b/prime-agent-runtime/test/test_repl.py
@@ -735,14 +735,19 @@ class ReplTest(unittest.TestCase):
self.assertEqual("".join(frames), "x" * 300_000)
self.assertTrue(all(len(frame) <= 65536 for frame in frames))
- def test_oversized_repr_and_display_payloads_are_capped(self):
+ def test_oversized_text_and_payloads_are_capped(self):
code = "class C:\n def __repr__(self):\n return 'x' * 3_000_000\nC()"
events = self.repl.execute("big-repr", code)
expected = "x" * 1_048_576 + "\n[... result truncated at 1048576 characters ...]"
self.assertEqual(one(events, "result")["text"], expected)
+ error = one(self.repl.execute("big-error", "raise ValueError('x' * 3_000_000)"), "error")
+ self.assertEqual(error["evalue"], expected)
+ self.assertEqual(error["traceback"][-1], "ValueError: " + expected[len("ValueError: ") :])
events = self.repl.execute("emit-big", "from rlm.repl import emit\nemit({'text/plain': 'x' * 17_000_000})")
self.assertEqual(one(events, "error")["ename"], "ValueError")
self.assertEqual(one(events, "done")["status"], "error")
+ code = "from rlm.repl import host_request\nawait host_request({'type': 'demo', 'blob': 'x' * 17_000_000})"
+ self.assertEqual(one(self.repl.execute("hr-big", code), "error")["ename"], "ValueError")
def test_bash_integration(self):
events = self.repl.execute(
@@ -821,13 +826,21 @@ class ReplTest(unittest.TestCase):
self.assertEqual(
request["data"], {"type": "bash.consumed", "pid": pid, "command": command}
)
- # Old host: error reply is absorbed and the withdrawal never repeats.
+ # Old host: the error reply is dropped silently and the withdrawal never repeats.
self.repl.send(
{"type": "host_reply", "id": request["id"], "data": {"status": "error", "error": "unknown"}}
)
if label == "poll":
again = self.repl.execute("withdraw-again", "handle.output()\nhandle.tail(1)")
- self.assertIsNone(one(again, "host_request"))
+ self.assertEqual([e for e in again if e.get("event") in ("error", "host_request")], [])
+
+ def test_result_read_before_notice_acceptance_withdraws_at_acceptance(self):
+ started = self.repl.execute("early", "from rlm import bash\nhandle = bash('printf early')\nhandle.pid")
+ notice = wait_for_host_request(self.repl, started)
+ self.assertIsNone(one(self.repl.execute("early-read", "handle.poll().output"), "host_request"))
+ reply_ok(self.repl, notice)
+ withdrawal = wait_for_host_request(self.repl, [])["data"]
+ self.assertEqual(withdrawal, {"type": "bash.consumed", "pid": notice["data"]["pid"], "command": "printf early"})
def test_detached_read_between_turns_keeps_bash_completion(self):
# A watcher reading the handle with no cell running reaches nobody: the