A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(runtime): ordered bash output completion sentinel (#1838)
Sebastian Müller809027134a1f
diff --git a/packages/coding-agent/.changes/bash-output-sentinel.md b/packages/coding-agent/.changes/bash-output-sentinel.mdnew file mode 100644index 0000000000..36e43eb31b--- /dev/null+++ b/packages/coding-agent/.changes/bash-output-sentinel.md@@ -0,0 +1 @@+- Fixed `bash()` to capture all foreground command output before finalizing results by using an ordered per-command completion marker; output written after the marker (e.g. by `EXIT` traps or background jobs) is not in the awaited result but stays visible via `handle.output()`/`tail()`.diff --git a/prime-agent-runtime/src/rlm/bash.py b/prime-agent-runtime/src/rlm/bash.pyindex 4de0b49938..5795b6ae72 100644--- a/prime-agent-runtime/src/rlm/bash.py+++ b/prime-agent-runtime/src/rlm/bash.py@@ -6,6 +6,7 @@ import asyncioimport atexitimport jsonimport os+import secretsimport selectorsimport shutilimport signal@@ -35,6 +36,9 @@ _READ_CHUNK = 65536# Fixed child-side fd for the status channel; POSIX shells (notably dash) only# guarantee single-digit fds in redirection syntax._STATUS_FD = 9+_OUTPUT_FD = 8+_COMPLETION_PREFIX = b"\x1eprime-agent-complete:"+_COMPLETION_SUFFIX = b"\x1f"# Cancelled one-shot awaits: TERM grace before the group KILL, then the bounded# wait for a confirmed group exit before CancelledError propagates._CANCEL_TERM_GRACE = 0.5@@ -116,6 +120,10 @@ class BashHandle:self._buffer = _BoundedBuffer()self._done = threading.Event()self._eof = threading.Event()+ self._completion_terminal = threading.Event()+ self._completion_output: str | None = None+ self._completion_lock = threading.Lock()+ self._completion_pending = b""self._status: int | None = Noneself._status_known = threading.Event()self._reaped = False@@ -133,6 +141,7 @@ class BashHandle:# True only while the pump moves a chunk from the pipe into the buffer.self._pump_transfer = Falseself._job: int | None = None+ self._completion_marker: bytes | None = Nonestatus_write = -1if _IS_POSIX:# Full-duplex status channel: the child end rides in as stdin (fd 0)@@ -150,9 +159,19 @@ class BashHandle:os.close(self._status_read)os.close(status_write)raise- script = _status_script(_with_prefix(command))+ completion_token = secrets.token_hex(32)+ # Halves stop passive echoes; a deliberate forgery freezes only this call while later bytes stay live.+ token_midpoint = len(completion_token) // 2+ self._completion_marker = (+ _COMPLETION_PREFIX + completion_token.encode("ascii") + _COMPLETION_SUFFIX+ )+ script = _status_script(+ _with_prefix(command),+ completion_token[:token_midpoint],+ completion_token[token_midpoint:],+ )else:- # Windows: the child is created suspended, atomically inside the kill-on-close job.+ # Windows lacks a foreground-status channel, so its exit drain stays best-effort.script = _with_prefix(command)self._job = _winjob.create_job()if self._job is None:@@ -274,8 +293,6 @@ class BashHandle:stdout = self._proc.stdoutassert stdout is not Noneif not _IS_POSIX:- # Windows: no FIONREAD fence; the drain keeps its quiescence- # heuristic (best-effort parity).try:while chunk := stdout.read1(_READ_CHUNK):self._buffer.write(chunk)@@ -284,9 +301,6 @@ class BashHandle:stdout.close()self._eof.set()return- # POSIX: select-gate the read and flag the read->commit window, so the- # drain fence never sees "pipe empty + buffer quiescent" while a chunk- # is in flight between the pipe read and the buffer commit.fd = stdout.fileno()try:with selectors.DefaultSelector() as sel:@@ -298,17 +312,54 @@ class BashHandle:chunk = os.read(fd, _READ_CHUNK)if not chunk:break- self._buffer.write(chunk)+ self._consume_output(chunk)finally:self._pump_transfer = Falseexcept (OSError, ValueError):pass+ self._abandon_completion()try:stdout.close()except OSError:passself._eof.set()+ def _consume_output(self, chunk: bytes) -> None:+ marker = self._completion_marker+ assert marker is not None+ with self._completion_lock:+ if self._completion_terminal.is_set():+ self._buffer.write(chunk)+ return+ data = self._completion_pending + chunk+ marker_at = data.find(marker)+ if marker_at >= 0:+ self._buffer.write(data[:marker_at])+ self._completion_pending = b""+ self._completion_output = self._buffer.text()+ self._completion_terminal.set()+ self._buffer.write(data[marker_at + len(marker) :])+ return+ retained = 0+ for size in range(min(len(data), len(marker) - 1), 0, -1):+ if data.endswith(marker[:size]):+ retained = size+ break+ self._buffer.write(data[:-retained] if retained else data)+ self._completion_pending = data[-retained:] if retained else b""++ def _abandon_completion(self) -> None:+ with self._completion_lock:+ if self._completion_terminal.is_set():+ return+ self._buffer.write(self._completion_pending)+ self._completion_pending = b""+ self._completion_terminal.set()++ def _wait_for_completion(self) -> str | None:+ self._completion_terminal.wait()+ return self._completion_output+def _report(self) -> None:# Finalize at foreground completion (status channel), not EOF, so# `cmd &` does not hang the await; the shell then `wait`s for its@@ -325,8 +376,10 @@ class BashHandle:# (parsed status, EOF, garbage, exception) must set it.self._status_known.set()if status is not None:- self._drain_grace()- self._finalize(status)+ output = self._wait_for_completion()+ if output is None:+ self._drain_grace()+ self._finalize(status, output)def _watch(self) -> None:# Observe shell death independently of the status socket: an early@@ -347,6 +400,7 @@ class BashHandle:with self._callback_lock:delivered = self._statusif delivered is None and not self._done.is_set():+ self._abandon_completion()self._drain_grace()self._finalize(exit_code)with self._kill_lock:@@ -409,10 +463,7 @@ class BashHandle:os.close(self._wake_read)def _drain_grace(self) -> None:- # Bounded wait so the result includes foreground output still in the pipe:- # EOF arrives immediately without background jobs, otherwise stop once the- # buffer is quiescent for one tick AND the pipe holds no unread bytes (a- # slow pump must not lose output the shell wrote before its status).+ # Best-effort fallback when process exit/EOF arrives without a sentinel.deadline = time.monotonic() + 0.5size = self._buffer.size()while time.monotonic() < deadline:@@ -442,13 +493,13 @@ class BashHandle:return Falsereturn pending > 0- def _finalize(self, exit_code: int) -> None:+ def _finalize(self, exit_code: int, output: str | None = None) -> None:with self._callback_lock:if self._done.is_set():returnself._result = BashResult(exit_code=exit_code,- output=self._buffer.text(),+ output=self._buffer.text() if output is None else output,duration=time.monotonic() - self._started,)self._done.set()@@ -609,6 +660,9 @@ def bash(command: str) -> BashHandle:POSIX; a kill-on-close job object on Windows entered while the child isstill suspended, so no descendant can escape it and kill()/crash cleanupare unconditional -- bash() raises if containment cannot be established.+ Output written after the completion fence (e.g. by an EXIT trap or a+ background job) is not in BashResult.output but stays visible via+ handle.output()/tail()."""if not isinstance(command, str) or not command:raise TypeError("command must be a non-empty str")@@ -642,24 +696,33 @@ def _with_prefix(command: str) -> str:return f"{prefix}\n{command}" if prefix else command-def _status_script(command: str) -> str:- # The status socket arrives as stdin (fd 0); the prologue dups it to the- # single-digit _STATUS_FD (dash rejects multi-digit fds in redirections at- # parse time) and points stdin at /dev/null, so no other copy remains. The- # gate read blocks until the parent has journaled the pid; EOF (parent died- # first) exits without running the command. The brace group runs the command- # with the status fd closed so `&` children do not inherit it; the trailing- # `wait` keeps the shell alive as group leader until its own jobs exit- # (double-forked daemons stay out of scope).+def _fence_printf() -> str:+ # `\command -p printf` defeats alias expansion but not a user-defined shell+ # function named `command`, which would swallow both fence frames and leave+ # the await hanging until the shell dies (wedged behind background jobs). A+ # slash-qualified command name bypasses function and alias lookup for+ # ordinary command names, so resolve printf on the system default utility PATH.+ path = shutil.which("printf", path=os.confstr("CS_PATH") or os.defpath)+ if path and "'" not in path:+ return f"'{path}'"+ return "\\command -p printf"+++def _status_script(command: str, completion_a: str, completion_b: str) -> str:+ # Closed control fds preserve background behavior; supported shells atomically write the frame.+ emit = _fence_printf()return (- f"exec {_STATUS_FD}>&0 0</dev/null\n"+ f"exec {_STATUS_FD}>&0 {_OUTPUT_FD}>&1 0</dev/null\n"f"read -r _prime_agent_gate <&{_STATUS_FD} || exit 127\n""{\n"f"{command}\n"- f"}} {_STATUS_FD}>&-\n"+ f"}} {_OUTPUT_FD}>&- {_STATUS_FD}>&-\n""__prime_status=$?\n"- f"printf '%s\\n' \"$__prime_status\" >&{_STATUS_FD}\n"- f"exec {_STATUS_FD}>&-\n"+ "\\set +x\n"+ f"{emit} '\\036prime-agent-complete:%s%s\\037' "+ f"'{completion_a}' '{completion_b}' >&{_OUTPUT_FD} || exit \"$__prime_status\"\n"+ f"{emit} '%s\\n' \"$__prime_status\" >&{_STATUS_FD}\n"+ f"exec {_OUTPUT_FD}>&- {_STATUS_FD}>&-\n""wait\n"'exit "$__prime_status"\n')diff --git a/prime-agent-runtime/test/test_bash.py b/prime-agent-runtime/test/test_bash.pyindex 6fc4233247..f7202cf68d 100644--- a/prime-agent-runtime/test/test_bash.py+++ b/prime-agent-runtime/test/test_bash.py@@ -176,20 +176,20 @@ class BashTest(unittest.IsolatedAsyncioTestCase):self.assertFalse(records[-1]["active"])await _poll_group_dead(handle.pid)- async def test_delivered_status_wins_when_shell_dies_during_drain(self):+ async def test_delivered_status_wins_when_shell_dies_during_completion(self):entered = threading.Event()release = threading.Event()- original = bash_module.BashHandle._drain_grace+ original = bash_module.BashHandle._wait_for_completion- def held_drain(handle_self):- # Hold only the first caller (the reporter, which drains right after- # reading status 0); any later caller must proceed normally.- if not entered.is_set():- entered.set()- release.wait(10)- original(handle_self)+ def held_completion(handle_self):+ output = original(handle_self)+ entered.set()+ release.wait(10)+ return output- with mock.patch.object(bash_module.BashHandle, "_drain_grace", held_drain):+ with mock.patch.object(+ bash_module.BashHandle, "_wait_for_completion", held_completion+ ):# Background job keeps the shell alive in `wait` after status 0 is delivered.handle = bash("sleep 30 & true")try:@@ -337,7 +337,7 @@ class BashTest(unittest.IsolatedAsyncioTestCase):self.skipTest("POSIX-only gate")with tempfile.TemporaryDirectory() as tmp:marker = os.path.join(tmp, "ran")- script = bash_module._status_script(f"touch {marker}")+ script = bash_module._status_script(f"touch {marker}", "a" * 32, "b" * 32)parent, child = socket.socketpair()proc = subprocess.Popen([bash_module._shell(), "-c", script],@@ -539,26 +539,29 @@ class BashTest(unittest.IsolatedAsyncioTestCase):bash_module._shell()which.assert_not_called()- async def test_pump_paused_between_read_and_commit_does_not_lose_output(self):- # Reviewer repro: the chunk is out of the pipe (FIONREAD 0) but not yet- # in the buffer; the drain fence must wait for the commit.+ async def test_pump_delayed_past_old_quiescence_bound_captures_all_output(self):+ # The ordered sentinel must wait through a pump delay beyond the old 500 ms bound.original_write = bash_module._BoundedBuffer.writedelayed_once = threading.Event()def delayed_write(buffer_self, chunk):if not delayed_once.is_set():delayed_once.set()- time.sleep(0.3)+ time.sleep(0.7)original_write(buffer_self, chunk)with mock.patch.object(bash_module._BoundedBuffer, "write", delayed_write):- result = await asyncio.wait_for(bash("printf between-read-and-write"), timeout=5)+ result = await asyncio.wait_for(bash("printf delayed-output-complete"), timeout=5)self.assertEqual(result.exit_code, 0)- self.assertIn("between-read-and-write", result.output)+ self.assertEqual(result.output, "delayed-output-complete")++ async def test_completion_marker_split_across_reads_is_removed(self):+ with mock.patch.object(bash_module, "_READ_CHUNK", 7):+ result = await asyncio.wait_for(bash("printf exact-pre-fence-output"), timeout=5)+ self.assertEqual(result.output, "exact-pre-fence-output")async def test_slow_pump_does_not_lose_foreground_output(self):- # A descheduled pump must not let _drain_grace conclude quiescence- # while the shell's output still sits unread in the pipe.+ # Finalization waits for the pump to parse the ordered sentinel.original_pump = bash_module.BashHandle._pumpdef slow_pump(handle_self):@@ -570,6 +573,58 @@ class BashTest(unittest.IsolatedAsyncioTestCase):self.assertEqual(result.exit_code, 0)self.assertIn("slow-pump-x", result.output)+ async def test_sentinel_like_output_and_echoed_wrapper_do_not_truncate(self):+ token = "0123456789abcdef" * 4+ raw_lookalike = "\x1eprime-agent-complete:not-this-invocation\x1f"+ command = (+ "set -x\n"+ "printf '\\036prime-agent-complete:not-this-invocation\\037'\n"+ "if [ -r /proc/$$/cmdline ]; then cat /proc/$$/cmdline; fi\n"+ "printf '\\nafter-sentinel-lookalike\\n'"+ )+ with mock.patch.object(bash_module.secrets, "token_hex", return_value=token):+ result = await asyncio.wait_for(bash(command), timeout=5)+ actual_marker = (+ bash_module._COMPLETION_PREFIX + token.encode() + bash_module._COMPLETION_SUFFIX+ )+ self.assertIn(raw_lookalike, result.output)+ self.assertIn("after-sentinel-lookalike", result.output)+ self.assertNotIn(actual_marker.decode(), result.output)++ async def test_user_alias_cannot_replace_completion_emitter(self):+ if os.path.basename(bash_module._shell()) != "bash":+ self.skipTest("bash alias expansion semantics")+ handle = bash(+ "shopt -s expand_aliases; alias command='printf alias-expanded'; sleep 30 &"+ )+ try:+ result = await asyncio.wait_for(handle, timeout=5)+ self.assertEqual(result.exit_code, 0)+ self.assertNotIn("alias-expanded", result.output)+ finally:+ handle.kill(signal.SIGKILL)+ await _poll_group_dead(handle.pid)++ async def test_user_function_cannot_replace_completion_emitter(self):+ # The backslash in `\command` defeats alias expansion only: a shell+ # function named `command` would otherwise swallow both fence frames+ # and wedge the await behind the background job until shell death.+ handle = bash("command() { printf function-expanded; }; sleep 30 &")+ try:+ result = await asyncio.wait_for(handle, timeout=5)+ self.assertEqual(result.exit_code, 0)+ self.assertNotIn("function-expanded", result.output)+ finally:+ handle.kill(signal.SIGKILL)+ await _poll_group_dead(handle.pid)++ async def test_shell_killed_before_sentinel_finalizes_from_exit(self):+ result = await asyncio.wait_for(+ bash("printf output-before-shell-kill; kill -KILL $$"), timeout=5+ )+ self.assertEqual(result.exit_code, -signal.SIGKILL)+ self.assertIn("output-before-shell-kill", result.output)+async def test_relative_bash_shell_override_rejected(self):with mock.patch.dict(os.environ, {"PRIME_AGENT_BASH_SHELL": "bash"}):with self.assertRaises(ValueError):