"""Opt-in, one-per-episode recovery for a no-tool output-length cutoff. This is a local Bash-loop extension, inspired by mini-SWE-agent's upstream format feedback. Native Prime interception retains both model generations. """ import ast import hashlib import importlib.metadata import importlib.util import py_compile from pathlib import Path ENVIRONMENT_VARIABLE = "VF_BASH_LENGTH_RECOVERY" RECOVERY_MESSAGE = ( "Your response reached the output limit before issuing a tool call. " "Keep your reasoning brief and take the next concrete action using a tool." ) ORIGINAL_LOOP_SHA256 = "c700239176c6731643eaa3fcb624366b473dddd8f1c5bc98540f1c11173354dd" _INITIALIZE = ''' import os import sys recovery_setting = os.environ.get("VF_BASH_LENGTH_RECOVERY", "0") if recovery_setting not in ("0", "1"): raise ValueError("VF_BASH_LENGTH_RECOVERY must be 0 or 1") recovery_used = False ''' _ORIGINAL_REPLY = ''' message = completion.choices[0].message messages.append(message.model_dump(exclude_none=True)) ''' _RECOVERY_REPLY = f''' message = completion.choices[0].message if ( recovery_setting == "1" and not recovery_used and completion.choices[0].finish_reason == "length" and not message.tool_calls ): recovery_used = True # The interceptor has already recorded this completion. Do not send # the unfinished assistant response back as conversation history. # Prime's native graph records the resulting alternate branch. messages.append({{"role": "user", "content": {RECOVERY_MESSAGE!r}}}) print( "VF_BASH_LENGTH_RECOVERY " + json.dumps({{ "event": "corrective_request", "budget_per_episode": 1, "finish_reason": "length", "tool_calls": 0, }}), file=sys.stderr, flush=True, ) continue messages.append(message.model_dump(exclude_none=True)) ''' def loop_span(source: str) -> tuple[int, int]: function = next(node for node in ast.parse(source).body if isinstance(node, ast.AsyncFunctionDef) and node.name == "run_chat_loop") return function.lineno - 1, function.end_lineno def patch_source(source: str) -> str: lines = source.splitlines(keepends=True) start, end = loop_span(source) current = "".join(lines[start:end]) if "recovery_setting = " in current: original = current.replace(_INITIALIZE, "", 1).replace(_RECOVERY_REPLY, _ORIGINAL_REPLY, 1) if original == current or hashlib.sha256(original.encode()).hexdigest() != ORIGINAL_LOOP_SHA256: raise RuntimeError("Recovery patch changed; refusing an unreviewed patch") return source if hashlib.sha256(current.encode()).hexdigest() != ORIGINAL_LOOP_SHA256: raise RuntimeError("Upstream Bash loop changed; refusing an unreviewed patch") assert current.count(" while True:\n") == current.count(_ORIGINAL_REPLY) == 1 replacement = current.replace(" while True:\n", _INITIALIZE + " while True:\n", 1) replacement = replacement.replace(_ORIGINAL_REPLY, _RECOVERY_REPLY, 1) updated = "".join(lines[:start]) + replacement + "".join(lines[end:]) ast.parse(updated) return updated def verify_runtime(expected_sha256: str) -> dict[str, str]: """Use Python's installed module location in both CPU and GPU checks.""" spec = importlib.util.find_spec("verifiers.v1.harnesses.utils.core") if spec is None or spec.origin is None: raise RuntimeError("Installed Verifiers Bash module was not found") path = Path(spec.origin) source = path.read_text() assert patch_source(source) == source and "recovery_used = False" in source from verifiers.v1.harnesses.utils.launch import CHAT_PROGRAM_SOURCE assert "recovery_used = False" in CHAT_PROGRAM_SOURCE compile(CHAT_PROGRAM_SOURCE, "", "exec") assert hashlib.sha256(Path(__file__).read_bytes()).hexdigest() == expected_sha256 return {"core_path": str(path), "core_sha256": hashlib.sha256(source.encode()).hexdigest(), "bundle_sha256": hashlib.sha256(CHAT_PROGRAM_SOURCE.encode()).hexdigest()} def install() -> None: if importlib.metadata.version("verifiers") != "0.4.1.dev12": raise RuntimeError("Recovery patch requires reviewed Verifiers 0.4.1.dev12") package = importlib.util.find_spec("verifiers") path = Path(package.origin).parent / "v1/harnesses/utils/core.py" source = path.read_text() updated = patch_source(source) if updated != source: path.write_text(updated) for cached in (path.parent / "__pycache__").glob("core.*.pyc"): cached.unlink() py_compile.compile(str(path), doraise=True, invalidation_mode=py_compile.PycInvalidationMode.CHECKED_HASH) print("Bash length recovery installed; disabled unless VF_BASH_LENGTH_RECOVERY=1") if __name__ == "__main__": install()