From 018a8d814d1cdab467e72d477f4acb27c2e96ad3 Mon Sep 17 00:00:00 2001 From: golemon Date: Fri, 20 Nov 2026 06:49:21 +0800 Subject: [PATCH] fix(sandbox): derive bash tool status from process exit codes (#8396) * fix(sandbox): derive bash tool status from process exit codes Carry native exit codes in string-compatible command output and stamp bash tool results before content-based normalization. Preserve redaction, truncation, timeout markers, scoped execution, and legacy provider string returns. Add real subprocess and graph regressions for error-like stdout, JSON data, forged exit markers, redaction, nonzero exits, timeouts, and result copying. Validate sync and async execution with tool progress enabled and disabled. * docs(sandbox): explain local bash execution status Document that native bash status follows the exit code while error-like output remains command data. Clarify that redaction and output limits do not change execution status. * fix(sandbox): include provider exit codes in bash metadata Carry numeric process exit codes in producer-stamped bash tool results. Extend the progress metadata schema and regression coverage so the additional field preserves progress tracking and graph receipts. * fix(subagents): prefer provider exit codes for test evidence Use validated producer exit codes before output markers when harvesting bash execution evidence. Preserve text fallback for legacy results and malformed metadata without weakening test-summary acceptance. Cover real pytest reporter conflicts, checkpoint round trips, failure and unverified summaries, and legacy metadata. Document the exit-code precedence and compatibility behavior. --- .../middlewares/TOOL_OUTPUT_PERSISTENCE.md | 13 +- .../agents/middlewares/tool_result_meta.py | 1 + .../deerflow/sandbox/local/local_sandbox.py | 6 +- .../harness/deerflow/sandbox/sandbox.py | 23 +++- .../harness/deerflow/sandbox/tools.py | 55 ++++++--- .../harness/deerflow/subagents/executor.py | 28 +++-- .../test_local_sandbox_command_timeout.py | 20 ++++ backend/tests/test_subagent_executor.py | 102 ++++++++++++++++ .../tests/test_tool_progress_middleware.py | 17 +++ backend/tests/test_tool_result_meta.py | 112 ++++++++++++++++++ docs/guide/sandbox.md | 5 + docs/guide/subagents.md | 8 ++ 12 files changed, 353 insertions(+), 37 deletions(-) diff --git a/backend/packages/harness/deerflow/agents/middlewares/TOOL_OUTPUT_PERSISTENCE.md b/backend/packages/harness/deerflow/agents/middlewares/TOOL_OUTPUT_PERSISTENCE.md index 23be92661b..11b8b328d9 100644 --- a/backend/packages/harness/deerflow/agents/middlewares/TOOL_OUTPUT_PERSISTENCE.md +++ b/backend/packages/harness/deerflow/agents/middlewares/TOOL_OUTPUT_PERSISTENCE.md @@ -53,11 +53,14 @@ existing pass-through behavior. ## Bash exit marker -The subagent executor reads a bash result's exit status only from its end -(`Exit Code: N`, or a whole-output `Command exited with code N`); with no marker -it falls back to `deerflow_tool_meta`, which reports `success` for a nonzero -exit. A model-visible rewrite of a `bash`/`bash_tool` result must therefore keep -the original trailing marker last: the preview re-appends it after the `Access:` +The subagent executor prefers an integer `deerflow_tool_meta.exit_code` stamped +by the tool producer (`source: tool_return`), so command output that prints an +exit marker cannot override the provider's execution result. Older checkpoints +and plain-string providers retain the fallback: a trailing `Exit Code: N` or a +whole-output `Command exited with code N`, then metadata/native status when no +marker exists. A model-visible rewrite of a `bash`/`bash_tool` result keeps the +original trailing marker last for this compatibility path: the preview +re-appends it after the `Access:` footer, and the storage-unavailable fallback reserves it from `max_chars` like sandbox truncation. The local marker regex mirrors `sandbox.tools._BASH_EXIT_MARKER_TAIL_RE` and a test pins them together. The diff --git a/backend/packages/harness/deerflow/agents/middlewares/tool_result_meta.py b/backend/packages/harness/deerflow/agents/middlewares/tool_result_meta.py index a1f9249314..a94ec353a6 100644 --- a/backend/packages/harness/deerflow/agents/middlewares/tool_result_meta.py +++ b/backend/packages/harness/deerflow/agents/middlewares/tool_result_meta.py @@ -35,6 +35,7 @@ class ToolResultMeta: recoverable_by_model: bool recommended_next_action: RecommendedNextAction source: Literal["exception", "tool_return", "content_analysis", "progress_middleware"] + exit_code: int | None = None _UNKNOWN_ERROR: dict[str, object] = { diff --git a/backend/packages/harness/deerflow/sandbox/local/local_sandbox.py b/backend/packages/harness/deerflow/sandbox/local/local_sandbox.py index 93ae0b1edd..3c3801d4d0 100644 --- a/backend/packages/harness/deerflow/sandbox/local/local_sandbox.py +++ b/backend/packages/harness/deerflow/sandbox/local/local_sandbox.py @@ -24,7 +24,7 @@ from deerflow.sandbox.download import DEFAULT_DOWNLOAD_LIMIT, download_limit from deerflow.sandbox.env_policy import build_sandbox_env from deerflow.sandbox.local.list_dir import list_dir from deerflow.sandbox.path_patterns import PATH_START_BOUNDARY, replace_output_path_matches -from deerflow.sandbox.sandbox import Sandbox, _validate_extra_env +from deerflow.sandbox.sandbox import CommandOutput, Sandbox, _validate_extra_env from deerflow.sandbox.search import GrepMatch, find_glob_matches, find_grep_matches, path_matches from deerflow.utils.atomic_write import publish_bytes_atomically @@ -872,7 +872,7 @@ class LocalSandbox(Sandbox): command: str, env: dict[str, str] | None = None, timeout: float | None = None, - ) -> str: + ) -> CommandOutput: # Validate ``env`` keys against the POSIX env-var rule. Defense in # depth: ``subprocess.run(env=...)`` does not go through a shell so a # metachar in a key here would not actually inject — but the public @@ -987,7 +987,7 @@ class LocalSandbox(Sandbox): final_output = output if output else "(no output)" # Reverse resolve local paths back to container paths in output - return self._reverse_resolve_paths_in_output(final_output) + return CommandOutput(self._reverse_resolve_paths_in_output(final_output), 124 if timed_out else returncode) @staticmethod def _run_windows_command( diff --git a/backend/packages/harness/deerflow/sandbox/sandbox.py b/backend/packages/harness/deerflow/sandbox/sandbox.py index 3fbd2f16c3..4aaa306ec3 100644 --- a/backend/packages/harness/deerflow/sandbox/sandbox.py +++ b/backend/packages/harness/deerflow/sandbox/sandbox.py @@ -42,6 +42,25 @@ def _validate_extra_env(extra_env: dict[str, str] | None) -> None: raise ValueError(f"extra_env key {key!r} is not a valid POSIX environment variable name (must match ^[A-Za-z_][A-Za-z0-9_]*$). This protects shell-using sandbox implementations from command injection via the key.") +class CommandOutput(str): + """String-compatible command output carrying the provider's actual exit code. + + Providers may return this from either command execution hook. Ordinary + strings remain supported for providers without structured exit information. + Consumers must read the exit code before masking or truncating the text. + """ + + exit_code: int + + def __new__(cls, output: str, exit_code: int) -> "CommandOutput": + result = super().__new__(cls, output) + result.exit_code = exit_code + return result + + def __getnewargs__(self) -> tuple[str, int]: + return str(self), self.exit_code + + class Sandbox(ABC): """Abstract base class for sandbox environments""" @@ -130,7 +149,9 @@ class Sandbox(ABC): timeouts. Returns: - The standard or error output of the command. + The standard or error output of the command. Providers that know + the actual exit code can return :class:`CommandOutput` to preserve + execution status independently of the output text. Raises: ValueError: when an ``env`` key is not a valid env-var name. diff --git a/backend/packages/harness/deerflow/sandbox/tools.py b/backend/packages/harness/deerflow/sandbox/tools.py index b586bf342e..8d60d7854c 100644 --- a/backend/packages/harness/deerflow/sandbox/tools.py +++ b/backend/packages/harness/deerflow/sandbox/tools.py @@ -59,7 +59,7 @@ from deerflow.sandbox.read_file_contract import ( READ_FILE_START_LINE_EXCEEDS, READ_FILE_TRUNCATION_PREFIX, ) -from deerflow.sandbox.sandbox import Sandbox +from deerflow.sandbox.sandbox import CommandOutput, Sandbox from deerflow.sandbox.sandbox_provider import SandboxProvider, get_sandbox_provider from deerflow.sandbox.search import GrepMatch from deerflow.sandbox.security import LOCAL_HOST_BASH_DISABLED_MESSAGE, is_host_bash_allowed @@ -2937,7 +2937,7 @@ def _lark_cli_env_from_runtime(runtime: Runtime, command: str, *, sandbox_paths: @tool("bash", parse_docstring=True) -def bash_tool(runtime: Runtime, command: str, description: str = "") -> str: +def bash_tool(runtime: Runtime, command: str, description: str = "") -> str | ToolMessage: """Execute a bash command in the configured execution environment. @@ -3020,10 +3020,11 @@ def bash_tool(runtime: Runtime, command: str, description: str = "") -> str: env=local_env, timeout=command_timeout, ) - return _truncate_bash_output( + content = _truncate_bash_output( mask_secret_values(mask_local_paths_in_output(output, thread_data), redaction_env), max_chars, ) + return _bash_command_result(runtime, output, content) ensure_thread_directories_exist(runtime) command = f"cd {VIRTUAL_PATH_PREFIX}/workspace; {command}" command = user_prefix + (identity_prefix or "") + command @@ -3036,19 +3037,15 @@ def bash_tool(runtime: Runtime, command: str, description: str = "") -> str: except Exception: max_chars = 20000 command_timeout = None - return _truncate_bash_output( - mask_secret_values( - _execute_bash_command( - sandbox, - command, - runtime=runtime, - env=injected_env, - timeout=command_timeout, - ), - injected_env, - ), - max_chars, + output = _execute_bash_command( + sandbox, + command, + runtime=runtime, + env=injected_env, + timeout=command_timeout, ) + content = _truncate_bash_output(mask_secret_values(output, injected_env), max_chars) + return _bash_command_result(runtime, output, content) except SandboxError as e: return mask_secret_values(f"Error: {e}", redaction_env) except PermissionError as e: @@ -3057,7 +3054,33 @@ def bash_tool(runtime: Runtime, command: str, description: str = "") -> str: return mask_secret_values(f"Error: Unexpected error executing command: {_sanitize_error(e, runtime)}", redaction_env) -async def _bash_tool_async(runtime: Runtime, command: str, description: str = "") -> str: +def _bash_command_result(runtime: Runtime, output: str, content: str) -> str | ToolMessage: + """Stamp provider execution state before stdout can be interpreted as an error.""" + call_id = getattr(runtime, "tool_call_id", None) + if not isinstance(output, CommandOutput) or not isinstance(call_id, str) or not call_id: + # Legacy providers retain their existing error envelopes; direct Python + # callers without a tool-call ID retain their string return contract. + return content + status = "error" if output.exit_code != 0 else "success" + return ToolMessage( + content=content, + name="bash", + tool_call_id=call_id, + status=status, + additional_kwargs={ + "deerflow_tool_meta": { + "status": status, + "exit_code": output.exit_code, + "error_type": "unknown" if status == "error" else None, + "recoverable_by_model": True, + "recommended_next_action": "try_alternative" if status == "error" else "continue", + "source": "tool_return", + } + }, + ) + + +async def _bash_tool_async(runtime: Runtime, command: str, description: str = "") -> str | ToolMessage: return await _run_sync_tool_after_async_sandbox_init(bash_tool.func, runtime, command, description) diff --git a/backend/packages/harness/deerflow/subagents/executor.py b/backend/packages/harness/deerflow/subagents/executor.py index a3ab514bbe..e0bce3cd0c 100644 --- a/backend/packages/harness/deerflow/subagents/executor.py +++ b/backend/packages/harness/deerflow/subagents/executor.py @@ -486,15 +486,18 @@ _BASH_EVIDENCE_COMMAND_CHARS = 500 _BASH_EVIDENCE_OUTPUT_TAIL_CHARS = 1000 -def _bash_evidence_status(content: str, meta_status: str) -> tuple[str, str | None]: - """Derive the recorded status from the shell exit marker when present. +def _bash_evidence_status(content: str, meta_status: str, meta: Mapping[str, Any]) -> tuple[str, str | None]: + """Prefer a provider exit code, retaining text markers for legacy results. Returns ``(status, marker)``: the marker text actually seen (e.g. ``Exit - Code: 5``), so consumers can report it instead of asserting a failure the - harness cannot distinguish from the command's own trailing text. The - explicit marker takes precedence over generic metadata in old checkpoints - or provider stamps that report ``success`` for a nonzero shell exit. + Code: 5``) only when text determined the status. A provider's numeric code + takes precedence over stdout, which may itself print an exit marker. + Missing or invalid codes retain the marker-first fallback for older + checkpoints and plain-string providers with generic success metadata. """ + exit_code = meta.get("exit_code") + if meta.get("source") == "tool_return" and type(exit_code) is int: + return ("success" if exit_code == 0 else "error"), None return bash_exit_status(content) or (meta_status, None) @@ -557,11 +560,11 @@ def _harvest_bash_executions( a specific recorded execution — the command text lets the parent match the criterion against the call that actually ran. A bounded summary stamp is computed from the full tool output before retaining the diagnostic tail. - The recorded status is the **actual shell exit status**: a nonzero bash exit comes back as ordinary output text - (local: a trailing ``Exit Code: N``; e2b/opensandbox with empty output: - ``Command exited with code N``), which ``deerflow_tool_meta`` still reports - as success — so an explicit exit marker wins, and the meta status is only - the fallback when no marker exists. Every entry is stamped with + The recorded status prefers the provider's numeric exit code from + ``deerflow_tool_meta``. Older checkpoints and plain-string providers retain + the text-marker fallback (``Exit Code: N`` or a whole-output ``Command + exited with code N``), followed by the metadata/native status when no + marker exists. Every entry is stamped with ``shell_persistent`` — the producing sandbox's ``persistent_shell_sessions`` flag, resolved against the sandbox recorded in THIS state (the subagent's own graph state), so provenance survives @@ -609,9 +612,10 @@ def _harvest_bash_executions( command_truncated = len(command) > _BASH_EVIDENCE_COMMAND_CHARS command = command[:_BASH_EVIDENCE_COMMAND_CHARS] meta = (message.additional_kwargs or {}).get(TOOL_META_KEY) or {} + meta = meta if isinstance(meta, dict) else {} meta_status = str(meta.get("status") or getattr(message, "status", "success") or "success") content = message.content if isinstance(message.content, str) else json.dumps(message.content, sort_keys=True, default=str) - status, status_marker = _bash_evidence_status(content, meta_status) + status, status_marker = _bash_evidence_status(content, meta_status, meta) result_id = message.id if isinstance(message.id, str) and message.id else None cache_key = _bash_evidence_key({"result_id": result_id, "tool_call_id": tool_call_id}) cached = summary_cache.get(cache_key) if summary_cache is not None else None diff --git a/backend/tests/test_local_sandbox_command_timeout.py b/backend/tests/test_local_sandbox_command_timeout.py index 88ed87a516..821cd3ebda 100644 --- a/backend/tests/test_local_sandbox_command_timeout.py +++ b/backend/tests/test_local_sandbox_command_timeout.py @@ -9,7 +9,10 @@ The platform-specific cases exercise real subprocess and process-tree/group semantics, while the shared tests pin the user-facing timeout notice. """ +import copy +import json import os +import pickle import shlex import signal import subprocess @@ -27,6 +30,22 @@ posix_only = pytest.mark.skipif(os.name == "nt", reason="POSIX process-group sem linux_proc_fd_only = pytest.mark.skipif(not Path("/proc/self/fd").exists(), reason="requires Linux /proc fd links") +@posix_only +@pytest.mark.parametrize( + "command,expected,exit_code", + [("printf 'Error: sample\\n'", "Error: sample\n", 0), ("printf 'OK\\n'; exit 7", "OK\n\nExit Code: 7", 7), (":", "(no output)", 0)], +) +def test_command_output_keeps_string_and_copy_contracts(command, expected, exit_code): + output = LocalSandbox("command-result").execute_command(command, timeout=5) + + assert isinstance(output, str) + assert output == expected + assert json.loads(json.dumps({"output": output})) == {"output": expected} + for copied in (copy.copy(output), copy.deepcopy(output), pickle.loads(pickle.dumps(output))): + assert copied == expected + assert copied.exit_code == exit_code + + @posix_only def test_backgrounded_process_returns_promptly(): """A backgrounded long-lived process (e.g. a dev server started with `&`) @@ -101,6 +120,7 @@ def test_timeout_output_carries_authoritative_failure_marker(monkeypatch): assert "timed out" in output.lower() assert output.endswith("Exit Code: 124") + assert output.exit_code == 124 def test_windows_timeout_returns_notice(monkeypatch): diff --git a/backend/tests/test_subagent_executor.py b/backend/tests/test_subagent_executor.py index 572f305649..2dfed26121 100644 --- a/backend/tests/test_subagent_executor.py +++ b/backend/tests/test_subagent_executor.py @@ -18,6 +18,8 @@ import asyncio import importlib import inspect import logging +import os +import shlex import sys import threading import time @@ -170,6 +172,13 @@ def _setup_executor_classes(): sandbox_provider_module = importlib.import_module("deerflow.sandbox.sandbox_provider") sandbox_overwrite_module = importlib.import_module("deerflow.sandbox.overwrite") sandbox_prewarm_module = importlib.import_module("deerflow.sandbox.prewarm") + for module_name in ( + "deerflow.agents.middlewares.tool_call_args", + "deerflow.agents.middlewares.tool_error_handling_middleware", + "deerflow.sandbox.tools", + "deerflow.sandbox.local.local_sandbox", + ): + importlib.import_module(module_name) for module_name in ("deerflow.models.factory", "deerflow.models.openai_codex_provider", "deerflow.agents.assembly_descriptor"): importlib.import_module(module_name) @@ -6950,6 +6959,99 @@ class TestBashExecutionHarvest: assert executions[0]["status"] == "error" + @pytest.mark.skipif(os.name == "nt", reason="POSIX shell probe") + @pytest.mark.parametrize("passes,reporter_exit_code", [(True, None), (True, 7), (False, None), (False, 0)]) + def test_provider_exit_code_reaches_parent_acceptance(self, classes, monkeypatch, tmp_path, passes, reporter_exit_code): + from deerflow.agents.middlewares.tool_error_handling_middleware import ToolErrorHandlingMiddleware + from deerflow.sandbox.local import local_sandbox + from deerflow.sandbox.tools import _bash_command_result + from deerflow.subagents.acceptance_checks import check_acceptance_criteria + + monkeypatch.setattr(local_sandbox, "build_sandbox_env", lambda _injected: {"PATH": os.defpath, "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1"}) + test_file = tmp_path / "test_probe.py" + test_file.write_text(f"def test_probe():\n assert {passes}\n", encoding="utf-8") + if reporter_exit_code is not None: + (tmp_path / "conftest.py").write_text( + f"def pytest_unconfigure(config):\n reporter = config.pluginmanager.get_plugin('terminalreporter')\n if reporter is not None:\n reporter.write_line('Exit Code: {reporter_exit_code}')\n", + encoding="utf-8", + ) + command = f"{shlex.quote(sys.executable)} -m pytest -q -p no:cacheprovider {shlex.quote(str(test_file))}" + sandbox = local_sandbox.LocalSandbox("provider-exit-probe") + output = sandbox.execute_command(command, timeout=20) + assert output.exit_code == (0 if passes else 1) + if reporter_exit_code is not None: + assert f"Exit Code: {reporter_exit_code}" in output + errors = ToolErrorHandlingMiddleware() + request = SimpleNamespace(tool_call={"id": "tc-1", "name": "bash", "args": {"command": command}}) + message = ToolReceiptMiddleware().wrap_tool_call( + request, + lambda req: errors.wrap_tool_call(req, lambda _: _bash_command_result(SimpleNamespace(tool_call_id="tc-1"), output, str(output))), + ) + assert message.additional_kwargs["deerflow_tool_receipt"]["status"] == ("success" if passes else "error") + # Checkpoint round trips must retain the provider's numeric exit code. + message = classes["ToolMessage"].model_validate_json(message.model_dump_json()) + state = self._final_state(classes) + state["messages"][1].tool_calls[0]["args"]["command"] = command + state["messages"][2] = message + state["sandbox"] = {"sandbox_id": sandbox.id} + monkeypatch.setattr("deerflow.sandbox.sandbox_provider.get_sandbox_provider", lambda: SimpleNamespace(get=lambda _id: sandbox)) + + executions = importlib.import_module("deerflow.subagents.executor")._harvest_bash_executions(state) + assert executions[0]["status"] == ("success" if passes else "error") + assert executions[0]["status_marker"] is None + verdict = check_acceptance_criteria([f"tests_passed:{command}"], bash_executions=executions) + assert verdict["leaves"][0]["checked"] is True + assert verdict["all_hold"] is passes + + @pytest.mark.parametrize( + "exit_code,output,checked,holds", + [ + (0, "12 passed\nExit Code: 7", True, True), + (7, "12 passed\nExit Code: 0", True, False), + (-9, "12 passed\nExit Code: 0", True, False), + (124, "12 passed\nExit Code: 0", True, False), + (0, "1 failed\nExit Code: 7", True, False), + (0, "collected 0 items\nExit Code: 7", False, False), + (0, "ordinary output\nExit Code: 7", False, False), + ], + ) + def test_provider_exit_code_precedes_text_without_bypassing_test_summary(self, classes, monkeypatch, exit_code, output, checked, holds): + from deerflow.subagents.acceptance_checks import check_acceptance_criteria + + state = self._final_state(classes) + state["messages"][1].tool_calls[0]["args"]["command"] = "pytest -q" + state["messages"][2].content = output + state["messages"][2].additional_kwargs["deerflow_tool_meta"] = {"source": "tool_return", "status": "success", "exit_code": exit_code} + state["sandbox"] = {"sandbox_id": "provider-exit-probe"} + monkeypatch.setattr("deerflow.sandbox.sandbox_provider.get_sandbox_provider", lambda: SimpleNamespace(get=lambda _id: SimpleNamespace(persistent_shell_sessions=False))) + + executions = importlib.import_module("deerflow.subagents.executor")._harvest_bash_executions(state) + assert executions[0]["status"] == ("success" if exit_code == 0 else "error") + assert executions[0]["status_marker"] is None + verdict = check_acceptance_criteria(["tests_passed:pytest -q"], bash_executions=executions) + leaf = verdict["leaves"][0] + assert (leaf["checked"], leaf["holds"]) == (checked, holds) + + @pytest.mark.parametrize( + "meta", + [ + {"status": "success", "source": "tool_return"}, + *({"status": "success", "source": "tool_return", "exit_code": code} for code in (None, False, True, "0", 0.0, [], {})), + {"status": "success", "source": "content_analysis", "exit_code": 0}, + {"status": "success", "exit_code": 0}, + ["malformed metadata"], + ], + ) + def test_legacy_or_invalid_provider_exit_code_keeps_text_fallback(self, classes, meta): + state = self._final_state(classes) + state["messages"][2].content = "12 passed\nExit Code: 7" + state["messages"][2].additional_kwargs["deerflow_tool_meta"] = meta + + executions = importlib.import_module("deerflow.subagents.executor")._harvest_bash_executions(state) + + assert executions[0]["status"] == "error" + assert executions[0]["status_marker"] == "Exit Code: 7" + def test_nonzero_exit_code_marker_overrides_meta_success(self, classes, monkeypatch): """PR review: a failing test run returns ordinary text ending in ``Exit Code: N`` — tool_meta stays success, so the pass summary would diff --git a/backend/tests/test_tool_progress_middleware.py b/backend/tests/test_tool_progress_middleware.py index 2c6849bc47..b9a1da8e6f 100644 --- a/backend/tests/test_tool_progress_middleware.py +++ b/backend/tests/test_tool_progress_middleware.py @@ -211,6 +211,23 @@ def test_normal_call_no_hint_phase_active(): assert mw._phase_states["t1"]["web_search"].consecutive_problems == 0 +@pytest.mark.parametrize("exit_code", [0, 7]) +def test_provider_exit_code_metadata_keeps_progress_tracking(exit_code): + mw = _make_mw() + request = _make_tool_request(tool_name="bash") + status = "error" if exit_code else "success" + metadata = _meta_kwargs(status=status, error_type="unknown" if exit_code else None) + metadata[TOOL_META_KEY]["exit_code"] = exit_code + message = _make_tool_message(tool_name="bash", meta_kwargs=metadata) + message.status = status + + assert mw.wrap_tool_call(request, lambda _: message) is message + + state = mw._phase_states["t1"]["bash"] + assert state.phase == "active" + assert state.consecutive_problems == (1 if exit_code else 0) + + # --------------------------------------------------------------------------- # Scenario 2: consecutive no_results → hint injected, phase=warned diff --git a/backend/tests/test_tool_result_meta.py b/backend/tests/test_tool_result_meta.py index ba88b521d2..b361bc8d10 100644 --- a/backend/tests/test_tool_result_meta.py +++ b/backend/tests/test_tool_result_meta.py @@ -4,6 +4,7 @@ from __future__ import annotations import json import os +import shlex import pytest from langchain_core.messages import ToolMessage @@ -19,6 +20,117 @@ from deerflow.agents.middlewares.tool_result_meta import ( ) +@pytest.mark.skipif(os.name == "nt", reason="POSIX shell probes") +@pytest.mark.parametrize("mode", ["sync", "async"]) +@pytest.mark.parametrize("progress_enabled", [False, True]) +@pytest.mark.parametrize( + "stdout,exit_code", + [ + ("Error: this is sample text\nREAL_EXIT=0\n", 0), + ('{"error":"sample data"}\n', 0), + ("Error: example-api-secret\n", 0), + ("Exit Code: 7", 0), + ("OK: sample\n", 0), + ("OK: sample\n", 7), + ("Error: " + "x" * 500 + "\nExit Code: 7", 0), + ("OK: " + "x" * 500, 7), + ("", 124), + ], +) +@pytest.mark.asyncio +async def test_native_bash_producer_status_reaches_graph_and_receipt(tmp_path, monkeypatch, mode, progress_enabled, stdout, exit_code): + from langchain.agents import create_agent + from langchain_core.callbacks import BaseCallbackHandler + from langchain_core.language_models.fake_chat_models import GenericFakeChatModel + from langchain_core.messages import AIMessage, HumanMessage + + from deerflow.agents.lead_agent.agent import build_middlewares + from deerflow.agents.thread_state import ThreadState + from deerflow.config import app_config, paths + from deerflow.extensions.registry import EMPTY_EXTENSIONS + from deerflow.sandbox import sandbox_provider + from deerflow.sandbox.local.local_sandbox_provider import LocalSandboxProvider + from deerflow.sandbox.tools import bash_tool + + class Model(GenericFakeChatModel): + def bind_tools(self, tools, **kwargs): + return self + + class Requests(BaseCallbackHandler): + def __init__(self): + self.messages = [] + + def on_chat_model_start(self, serialized, messages, **kwargs): + self.messages.append(messages[0]) + + monkeypatch.setenv("DEER_FLOW_HOME", str(tmp_path / "home")) + monkeypatch.setenv("DEER_FLOW_CONFIG_PATH", str(tmp_path / "config.json")) + extensions_path = tmp_path / "extensions_config.json" + extensions_path.write_text("{}", encoding="utf-8") + monkeypatch.setenv("DEER_FLOW_EXTENSIONS_CONFIG_PATH", str(extensions_path)) + monkeypatch.setattr(paths, "_paths", None) + config = app_config.AppConfig.model_validate( + { + "models": [], + "sandbox": { + "use": "deerflow.sandbox.local:LocalSandboxProvider", + "allow_host_bash": True, + "bash_output_max_chars": 0 if exit_code == 124 else 80, + "bash_command_timeout": 0.1 if exit_code == 124 else 5, + "environment": {"EXAMPLE_API_KEY": "example-api-secret"}, + }, + "memory": {"enabled": False}, + "summarization": {"enabled": False}, + "title": {"enabled": False}, + "tool_progress": {"enabled": progress_enabled}, + } + ) + monkeypatch.setattr(app_config, "_app_config", config) + monkeypatch.setattr(app_config, "_app_config_is_custom", True) + provider = LocalSandboxProvider() + monkeypatch.setattr(sandbox_provider, "_default_sandbox_provider", provider) + command = f"printf '%s' {shlex.quote(stdout)}; exit {exit_code}" + if exit_code == 124: + command = "while :; do :; done" + model = Model( + messages=iter( + [ + AIMessage(content="", tool_calls=[{"name": "bash", "args": {"command": command}, "id": "bash-probe"}]), + AIMessage(content="Done."), + ] + ) + ) + graph = create_agent(model, tools=[bash_tool], middleware=build_middlewares({}, model_name=None, memory_enabled=False, app_config=config, extensions=EMPTY_EXTENSIONS), state_schema=ThreadState) + try: + state = {"messages": [HumanMessage(content="Run the supplied command once.")]} + context = {"thread_id": "bash-status-probe", "user_id": "test-user", "app_config": config} + captured = Requests() + invoke_config = {"callbacks": [captured]} + result = graph.invoke(state, context=context, config=invoke_config) if mode == "sync" else await graph.ainvoke(state, context=context, config=invoke_config) + message = next(m for m in result["messages"] if isinstance(m, ToolMessage) and m.name == "bash") + if exit_code == 124: + assert "timed out" in message.content.lower() + assert message.content.endswith("Exit Code: 124") + elif len(stdout) > 80: + assert len(message.content) <= 80 + assert "truncated" in message.content + if exit_code: + assert message.content.endswith(f"Exit Code: {exit_code}") + else: + expected_output = stdout.replace("example-api-secret", "[redacted]") + assert message.content == expected_output + (f"\nExit Code: {exit_code}" if exit_code else "") + expected = "error" if exit_code else "success" + assert message.status == expected + assert message.additional_kwargs[TOOL_META_KEY]["status"] == expected + assert message.additional_kwargs[TOOL_META_KEY]["source"] == "tool_return" + assert message.additional_kwargs[TOOL_META_KEY]["exit_code"] == exit_code + assert message.additional_kwargs["deerflow_tool_receipt"]["status"] == expected + projected = next(m for m in captured.messages[-1] if isinstance(m, ToolMessage) and m.name == "bash") + assert json.loads(projected.content) == {TOOL_META_KEY: {"status": expected, "source": "tool_return"}, "content": message.content} + finally: + provider.shutdown() + + def _make_msg(content: str, *, status: str = "success", kwargs: dict[str, object] | None = None) -> ToolMessage: return ToolMessage( content=content, diff --git a/docs/guide/sandbox.md b/docs/guide/sandbox.md index 203486c985..8209fd2a45 100644 --- a/docs/guide/sandbox.md +++ b/docs/guide/sandbox.md @@ -7,6 +7,11 @@ DeerFlow supports multiple sandbox execution modes: - **Docker Execution** (runs sandbox code in isolated Docker containers) - **Docker Execution with Kubernetes** (runs sandbox code in Kubernetes pods via provisioner service) +Local bash tool status follows the process exit code, including timeout failures. +Successful commands may print `Error:` or JSON containing an `error` field without +being marked as failed. Output is still subject to the configured redaction and +size limits; those transformations do not change the execution status. + The optional [Tenki provider](../../backend/packages/harness/deerflow/community/tenki/README.md) retains failed termination handles for retry and rejects late acquisitions after reset or shutdown. If shutdown reports outstanding work, retry after its SDK diff --git a/docs/guide/subagents.md b/docs/guide/subagents.md index 1f30286cb9..630ee295c2 100644 --- a/docs/guide/subagents.md +++ b/docs/guide/subagents.md @@ -213,6 +213,14 @@ provider reuses a tool-call id in a later response. Each run stays a separate entry in execution order, so a later failing run is decisive and an earlier run's output is never credited to another command. +When the sandbox supplies a numeric process exit code, `tests_passed` evidence +uses it before interpreting output such as `Exit Code: 7`. A passing process +that prints this text therefore retains its successful execution status. Older +checkpoints and providers that return plain strings keep the existing trailing +exit-marker fallback. A zero exit code still requires a passing test summary; +failed summaries are rejected, and missing or zero-test summaries remain +`UNVERIFIED`. + For Maven and Gradle test acceptance, a `BUILD SUCCESS` / `BUILD SUCCESSFUL` banner alone remains `UNVERIFIED`: builds can succeed without running tests. Complete `Tests run: N, Failures: F, Errors: E, Skipped: S` or `N tests completed`