From 94643281f4650adcc574e95588543789960e314f Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 29 Jul 2026 14:59:57 +0700 Subject: [PATCH 1/5] feat(dcode): add managed non-interactive JSON envelope Signed-off-by: San Dang --- .../patch-managed-deepagents-code.py | 279 ++++++++++++++++++ .../quickstart-langchain-deepagents-code.mdx | 38 +++ docs/reference/commands.mdx | 8 + test/dcode-non-interactive-json.test.ts | 268 +++++++++++++++++ .../07-deepagents-code-headless-inference.sh | 84 ++++-- ...langchain-deepagents-code-patch-fixture.ts | 45 ++- ...n-deepagents-code-headless-runtime.test.ts | 44 ++- test/langchain-deepagents-code-image.test.ts | 10 +- 8 files changed, 735 insertions(+), 41 deletions(-) create mode 100644 test/dcode-non-interactive-json.test.ts diff --git a/agents/langchain-deepagents-code/patch-managed-deepagents-code.py b/agents/langchain-deepagents-code/patch-managed-deepagents-code.py index 692f86e4f37..ee094313131 100644 --- a/agents/langchain-deepagents-code/patch-managed-deepagents-code.py +++ b/agents/langchain-deepagents-code/patch-managed-deepagents-code.py @@ -35,6 +35,16 @@ MANAGED_RUNTIME_SOURCE_PATH = Path(__file__).with_name("managed-dcode-runtime.py") MAIN_MARKER = " args = parser.parse_args()\n" +NON_INTERACTIVE_CALL_MARKER = ''' message=args.non_interactive_message, +''' +NON_INTERACTIVE_CALL_PATCH = ''' message=args.non_interactive_message, + output_format=output_format, + timeout_seconds=timeout, +''' +NON_INTERACTIVE_TIMEOUT_MARKER = ''' timeout=timeout, +''' +NON_INTERACTIVE_TIMEOUT_PATCH = ''' timeout=(None if output_format == "json" else timeout), +''' ENTRYPOINT_MARKER = "from deepagents_code.main import cli_main\n" ENTRYPOINT_PATCH = '''# NemoClaw-managed Deep Agents Code hardening v2. import os @@ -763,10 +773,17 @@ def _run_single_hook(command, event, payload_bytes) -> None: ''' NON_INTERACTIVE_PATCH = r''' +import asyncio as _nemoclaw_asyncio +import contextlib as _nemoclaw_contextlib +import contextvars as _nemoclaw_contextvars +import io as _nemoclaw_io +import json as _nemoclaw_json import logging as _nemoclaw_logging import os as _nemoclaw_os import re as _nemoclaw_re import sqlite3 as _nemoclaw_sqlite3 +import sys as _nemoclaw_sys +import time as _nemoclaw_time # NemoClaw-managed Deep Agents Code hardening v2. _NEMOCLAW_PROVIDER_CAPACITY_ERROR = _nemoclaw_re.compile( @@ -777,6 +794,232 @@ def _run_single_hook(command, event, payload_bytes) -> None: ) _NEMOCLAW_MANAGED_STATE_DB = "/sandbox/.deepagents/.state/sessions.db" +_NEMOCLAW_JSON_SCHEMA_VERSION = 1 +_NEMOCLAW_JSON_MAX_BYTES = 1_048_576 +_NEMOCLAW_JSON_ENVELOPE_RESERVE_BYTES = 4_096 + + +class _NemoClawOutputLimitError(RuntimeError): + """Stop a managed JSON run before its response can exceed the envelope.""" + + +class _NemoClawJsonRun: + """Collect one bounded non-interactive result without exposing partial text.""" + + def __init__(self, stdout): + self.stdout = stdout + self.started = _nemoclaw_time.monotonic() + self.phase = "process" + self.thread_id = None + self.response_parts = [] + self.response_bytes = 0 + self.encoded_response_bytes = 0 + self.output_limit = False + self.unexpected_stdout = False + + def append_response(self, text): + encoded = text.encode("utf-8") + encoded_json = _nemoclaw_json.dumps(text, ensure_ascii=True)[1:-1].encode("ascii") + next_encoded_size = self.encoded_response_bytes + len(encoded_json) + if next_encoded_size > ( + _NEMOCLAW_JSON_MAX_BYTES - _NEMOCLAW_JSON_ENVELOPE_RESERVE_BYTES + ): + self.output_limit = True + raise _NemoClawOutputLimitError( + "managed non-interactive JSON response exceeded its output limit" + ) + self.response_parts.append(text) + self.response_bytes += len(encoded) + self.encoded_response_bytes = next_encoded_size + + def completion(self, *, include_response_bytes): + return { + "thread_id": self.thread_id, + "duration_ms": max( + 0, + int((_nemoclaw_time.monotonic() - self.started) * 1000), + ), + "response_bytes": self.response_bytes if include_response_bytes else 0, + } + + +class _NemoClawUnexpectedStdout(_nemoclaw_io.TextIOBase): + """Suppress Python stdout that bypasses the managed assistant-text writer.""" + + def __init__(self, run): + self._run = run + + @property + def encoding(self): + return "utf-8" + + def write(self, text): + if text: + self._run.unexpected_stdout = True + return len(text) + + def flush(self): + return None + + def isatty(self): + return False + + +_nemoclaw_json_run = _nemoclaw_contextvars.ContextVar( + "nemoclaw_managed_json_run", + default=None, +) +_nemoclaw_original_write_text = _write_text +_nemoclaw_original_write_newline = _write_newline +_nemoclaw_original_generate_thread_id = generate_thread_id +_nemoclaw_original_run_agent_loop = _run_agent_loop + + +def _write_text(text): + """Capture assistant text only while the managed JSON boundary is active.""" + run = _nemoclaw_json_run.get() + if run is None: + return _nemoclaw_original_write_text(text) + run.append_response(text) + + +def _write_newline(): + """Keep the text-mode presentation newline out of the JSON response.""" + if _nemoclaw_json_run.get() is None: + return _nemoclaw_original_write_newline() + return None + + +def generate_thread_id(): + """Record the upstream thread identifier as completion metadata.""" + thread_id = _nemoclaw_original_generate_thread_id() + run = _nemoclaw_json_run.get() + if run is not None: + run.thread_id = thread_id + return thread_id + + +async def _run_agent_loop(*args, **kwargs): + """Mark failures after this boundary as agent failures.""" + run = _nemoclaw_json_run.get() + if run is not None: + run.phase = "agent" + return await _nemoclaw_original_run_agent_loop(*args, **kwargs) + + +def _nemoclaw_json_status(exit_code, run): + if run.output_limit: + return "output_limit", 1 + if exit_code == 0: + return "success", 0 + if exit_code == 124: + return "turn_limit", 124 + if exit_code == 130: + return "cancelled", 130 + if run.phase == "agent": + return "agent_failure", exit_code + return "process_failure", exit_code + + +def _nemoclaw_write_json_envelope(run, status, exit_code): + success = status == "success" + data = { + "status": status, + "exit_code": exit_code, + "response": "".join(run.response_parts) if success else None, + "completion": run.completion(include_response_bytes=success), + } + envelope = { + "schema_version": _NEMOCLAW_JSON_SCHEMA_VERSION, + "command": "non-interactive", + "data": data, + } + payload = _nemoclaw_json.dumps( + envelope, + ensure_ascii=True, + separators=(",", ":"), + ) + if len(payload.encode("utf-8")) + 1 > _NEMOCLAW_JSON_MAX_BYTES: + status = "output_limit" + exit_code = 1 + envelope["data"] = { + "status": status, + "exit_code": exit_code, + "response": None, + "completion": run.completion(include_response_bytes=False), + } + payload = _nemoclaw_json.dumps( + envelope, + ensure_ascii=True, + separators=(",", ":"), + ) + if len(payload.encode("utf-8")) + 1 > _NEMOCLAW_JSON_MAX_BYTES: + print( + "dcode: failed to produce a bounded non-interactive JSON envelope.", + file=_nemoclaw_sys.stderr, + ) + return 1 + try: + run.stdout.write(f"{payload}\n") + run.stdout.flush() + except Exception: + print( + "dcode: failed to write the managed non-interactive JSON envelope.", + file=_nemoclaw_sys.stderr, + ) + return 1 + return exit_code + + +async def _nemoclaw_run_json_non_interactive(timeout_seconds, *args, **kwargs): + run = _NemoClawJsonRun(_nemoclaw_sys.stdout) + token = _nemoclaw_json_run.set(run) + guard = _NemoClawUnexpectedStdout(run) + try: + with _nemoclaw_contextlib.redirect_stdout(guard): + try: + operation = _nemoclaw_original_run_non_interactive( + *args, + **kwargs, + ) + if timeout_seconds is None: + exit_code = await operation + else: + exit_code = await _nemoclaw_asyncio.wait_for( + operation, + timeout=timeout_seconds, + ) + except TimeoutError: + print( + f"dcode: agent timed out after {timeout_seconds}s.", + file=_nemoclaw_sys.stderr, + ) + status, exit_code = "timeout", 124 + except _nemoclaw_asyncio.CancelledError: + print( + "dcode: managed non-interactive run was cancelled.", + file=_nemoclaw_sys.stderr, + ) + status, exit_code = "cancelled", 130 + except Exception: + print( + "dcode: managed non-interactive execution failed.", + file=_nemoclaw_sys.stderr, + ) + status = ( + "agent_failure" if run.phase == "agent" else "process_failure" + ) + exit_code = 1 + else: + status, exit_code = _nemoclaw_json_status(exit_code, run) + finally: + _nemoclaw_json_run.reset(token) + if run.unexpected_stdout: + print( + "dcode: managed JSON mode suppressed unexpected stdout.", + file=_nemoclaw_sys.stderr, + ) + return _nemoclaw_write_json_envelope(run, status, exit_code) def _nemoclaw_classify_persisted_error(thread_id): @@ -849,6 +1092,8 @@ def _nemoclaw_report_non_interactive_error(thread_id, console): async def run_non_interactive(*args, **kwargs): """Enforce the managed headless boundary at the final Python call site.""" + output_format = kwargs.pop("output_format", "text") + timeout_seconds = kwargs.pop("timeout_seconds", None) settings.shell_allow_list = None kwargs["startup_cmd"] = None from deepagents_code.config import CLI_MAX_RETRIES_KEY @@ -871,6 +1116,14 @@ async def run_non_interactive(*args, **kwargs): kwargs["enable_interpreter"] = False kwargs["interpreter_ptc"] = None kwargs["rubric_model"] = None + if output_format == "json": + kwargs["quiet"] = True + kwargs["stream"] = True + return await _nemoclaw_run_json_non_interactive( + timeout_seconds, + *args, + **kwargs, + ) return await _nemoclaw_original_run_non_interactive(*args, **kwargs) @@ -1484,6 +1737,14 @@ def main() -> None: "Managed package non-interactive error patch is incomplete in " f"{paths['non_interactive']}" ) + if texts["main"].count(NON_INTERACTIVE_CALL_PATCH) != 1: + raise RuntimeError( + f"Managed package JSON call patch is incomplete in {paths['main']}" + ) + if texts["main"].count(NON_INTERACTIVE_TIMEOUT_PATCH) != 1: + raise RuntimeError( + f"Managed package JSON timeout patch is incomplete in {paths['main']}" + ) return if marker_states != {False} or helper_path.exists(): raise RuntimeError("Managed package patch is partial; refusing mixed source state") @@ -1660,6 +1921,14 @@ def main() -> None: "Expected one Deep Agents Code non-interactive error marker in " f"{paths['non_interactive']}" ) + if texts["main"].count(NON_INTERACTIVE_CALL_MARKER) != 1: + raise RuntimeError( + f"Expected one Deep Agents Code non-interactive call marker in {paths['main']}" + ) + if texts["main"].count(NON_INTERACTIVE_TIMEOUT_MARKER) != 1: + raise RuntimeError( + f"Expected one Deep Agents Code non-interactive timeout marker in {paths['main']}" + ) transformed = dict(texts) transformed["entrypoint"] = texts["entrypoint"].replace( ENTRYPOINT_MARKER, ENTRYPOINT_PATCH, 1 @@ -1667,6 +1936,16 @@ def main() -> None: transformed["main"] = texts["main"].replace( MAIN_MARKER, f"{MAIN_MARKER}{MAIN_PATCH}", 1 ) + transformed["main"] = transformed["main"].replace( + NON_INTERACTIVE_CALL_MARKER, + NON_INTERACTIVE_CALL_PATCH, + 1, + ) + transformed["main"] = transformed["main"].replace( + NON_INTERACTIVE_TIMEOUT_MARKER, + NON_INTERACTIVE_TIMEOUT_PATCH, + 1, + ) transformed["app"] = _append_patch(paths["app"], texts["app"], APP_PATCH) transformed["auth_store"] = _append_patch( paths["auth_store"], texts["auth_store"], AUTH_STORE_PATCH diff --git a/docs/get-started/quickstart-langchain-deepagents-code.mdx b/docs/get-started/quickstart-langchain-deepagents-code.mdx index 843b5f5f817..a4fe4fc06db 100644 --- a/docs/get-started/quickstart-langchain-deepagents-code.mdx +++ b/docs/get-started/quickstart-langchain-deepagents-code.mdx @@ -158,6 +158,44 @@ For a single headless task, run: dcode -n "Summarize this repository" ``` +For automation, add `--json`. +The managed runtime writes exactly one UTF-8 JSON object to stdout and suppresses other stdout text. +Progress is suppressed. +Warnings and diagnostics go to stderr. + +```bash +dcode -n "Summarize this repository" --json +``` + +A successful run has this version 1 envelope: + +```json +{ + "schema_version": 1, + "command": "non-interactive", + "data": { + "status": "success", + "exit_code": 0, + "response": "The repository contains...", + "completion": { + "thread_id": "thread-id", + "duration_ms": 842, + "response_bytes": 26 + } + } +} +``` + +`response` contains the exact final assistant text on success and is `null` on failure. +`response_bytes` is its UTF-8 byte length on success and is `0` on failure. +The process exit code matches `data.exit_code`. +The terminal statuses are `success`, `agent_failure`, `process_failure`, `timeout`, `turn_limit`, `cancelled`, and `output_limit`. +A timeout exits `124`, cancellation exits `130`, and other failures exit nonzero. + +The complete serialized envelope is limited to 1 MiB. +If the response cannot fit, the runtime discards it and emits a bounded `output_limit` failure envelope. +If it cannot write the envelope, the command exits nonzero and reports the write failure on stderr; callers must reject empty, malformed, additional, or unsupported-version stdout. + The managed `dcode`, `dcode.real`, and `deepagents-code` launchers use `/opt/venv/bin/python3 -I` to run the pinned package with an isolated import path and `HOME=/sandbox`. For interactive and headless sessions, each launcher supervises its own process descendants so completion, terminal exit, or disconnect terminates the associated LangGraph server tree without affecting another session. After a disconnect, the supervisor uses bounded grace periods before it kills unresponsive processes from that session. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 28d9c8f78fa..99ae19efed7 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -100,13 +100,17 @@ The in-sandbox Hermes integration installs the NemoClaw Hermes plugin, which exp Deep Agents does not use the OpenClaw chat slash command. Use the host-side `nemo-deepagents` commands for lifecycle, status, policy, and inference operations. Inside the sandbox, use `dcode` for the interactive TUI and `dcode -n` for explicit headless automation. +Add `--json` when automation needs the managed, versioned result envelope. ```bash dcode dcode -n "Summarize this repository" +dcode -n "Summarize this repository" --json dcode status ``` +For the JSON schema, status and exit behavior, and 1 MiB output limit, refer to [Quickstart with LangChain Deep Agents Code](/user-guide/deepagents/get-started/quickstart#use-the-harness). + ## Standalone Host Commands @@ -1003,6 +1007,7 @@ $$nemoclaw my-assistant agent --session-id review-42 -m "Any new findings?" $$nemoclaw my-assistant agent --session-key intake-42 --json -m 'ping' $$nemoclaw dcode-sandbox agent --help $$nemoclaw dcode-sandbox agent -n "Summarize this repository" +$$nemoclaw dcode-sandbox agent -n "Summarize this repository" --json ``` When post-command permission cleanup succeeds, the wrapper inherits the remote command's exit code so host-side pipelines can branch on it. @@ -1047,6 +1052,9 @@ curl -sN http://127.0.0.1:8642/v1/chat/completions \ For Deep Agents sandboxes, `agent` forwards to the manifest-declared terminal command. Bare invocations run `dcode`, and `--help` runs `dcode --help`. Use `dcode -n` for explicit headless automation when you are already connected to the sandbox, or use `$$nemoclaw agent -n ""` from the host. +Add `--json` to either form for one managed, versioned JSON envelope on stdout. +The host wrapper forwards the flag to `dcode`. +For the schema, status and exit behavior, and 1 MiB output limit, refer to [Quickstart with LangChain Deep Agents Code](/user-guide/deepagents/get-started/quickstart#use-the-harness). The host wrapper keeps `HOME=/sandbox`, the managed proxy environment, and the manifest-declared Deep Agents config path aligned with `connect`. Interactive `$$nemoclaw agent` launches the same terminal TUI as `dcode`. Headless `$$nemoclaw agent -n ""` uses the managed headless boundary, where non-shell tools can auto-run without the interactive approval UI. diff --git a/test/dcode-non-interactive-json.test.ts b/test/dcode-non-interactive-json.test.ts new file mode 100644 index 00000000000..514d9b4a1ca --- /dev/null +++ b/test/dcode-non-interactive-json.test.ts @@ -0,0 +1,268 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import { afterEach, describe, expect, it } from "vitest"; +import { + cleanupPackageFixtures, + createPackageFixture, + patchFixture, +} from "./helpers/langchain-deepagents-code-patch-fixture"; + +afterEach(cleanupPackageFixtures); + +type JsonEnvelope = { + schema_version: number; + command: string; + data: { + status: string; + exit_code: number; + response: string | null; + completion: { + thread_id: string | null; + duration_ms: number; + response_bytes: number; + }; + }; +}; + +function runDriver(driver: string) { + const tempDir = createPackageFixture(); + patchFixture(tempDir); + return spawnSync("python3", ["-c", driver], { + encoding: "utf8", + env: { + PATH: process.env.PATH, + PYTHONPATH: tempDir, + }, + timeout: 10_000, + }); +} + +function parseEnvelope(stdout: string): JsonEnvelope { + return JSON.parse(stdout) as JsonEnvelope; +} + +const preamble = ` +import asyncio +from deepagents_code.client import non_interactive as target +`; + +describe("managed DCode non-interactive JSON output", () => { + it("forwards the public --json flag through the non-interactive CLI (#7773)", () => { + const tempDir = createPackageFixture(); + patchFixture(tempDir); + const result = spawnSync( + "python3", + ["-m", "deepagents_code", "-n", "fixture-json-task", "--json"], + { + encoding: "utf8", + env: { + PATH: process.env.PATH, + PYTHONPATH: tempDir, + }, + timeout: 10_000, + }, + ); + + expect(result.status).toBe(0); + expect(parseEnvelope(result.stdout).data).toMatchObject({ + status: "success", + exit_code: 0, + response: "", + }); + }); + + it("emits one versioned success envelope with exact assistant text (#7773)", () => { + const result = runDriver(` +${preamble} +async def succeed(*args, **kwargs): + del args, kwargs + target._write_text('hello "') + target._write_text("雪\\n") + return 0 + +target._run_non_interactive_impl = succeed +exit_code = asyncio.run( + target.run_non_interactive( + "task", + output_format="json", + timeout_seconds=None, + ) +) +assert exit_code == 0 +`); + + expect(result.status).toBe(0); + const envelope = parseEnvelope(result.stdout); + expect(envelope).toEqual({ + schema_version: 1, + command: "non-interactive", + data: { + status: "success", + exit_code: 0, + response: 'hello "雪\n', + completion: { + thread_id: "thread-1", + duration_ms: expect.any(Number), + response_bytes: Buffer.byteLength('hello "雪\n'), + }, + }, + }); + expect(result.stdout.trim().split("\n")).toHaveLength(1); + }); + + it("suppresses progress output without corrupting the success envelope (#7773)", () => { + const result = runDriver(` +${preamble} +async def succeed(*args, **kwargs): + del args, kwargs + print("progress that must not reach stdout") + target._write_text("PONG") + return 0 + +target._run_non_interactive_impl = succeed +exit_code = asyncio.run(target.run_non_interactive("task", output_format="json")) +assert exit_code == 0 +`); + + expect(result.status).toBe(0); + expect(parseEnvelope(result.stdout).data).toMatchObject({ + status: "success", + exit_code: 0, + response: "PONG", + }); + expect(result.stdout).not.toContain("progress"); + expect(result.stderr).toContain("suppressed unexpected stdout"); + }); + + it.each([ + ["agent_failure", "target._run_non_interactive_impl = fail_agent", 1], + ["process_failure", "target._nemoclaw_original_run_non_interactive = fail_process", 1], + ["turn_limit", "target._run_non_interactive_impl = finish_at_limit", 124], + ])("emits a null response for %s (#7773)", (expectedStatus, setup, expectedExit) => { + const result = runDriver(` +${preamble} +async def fail_agent(*args, **kwargs): + del args, kwargs + raise RuntimeError("private failure detail") + +async def fail_process(*args, **kwargs): + del args, kwargs + raise RuntimeError("private process detail") + +async def finish_at_limit(*args, **kwargs): + del args, kwargs + return 124 + +${setup} +exit_code = asyncio.run(target.run_non_interactive("task", output_format="json")) +assert exit_code == ${expectedExit} +`); + + expect(result.status).toBe(0); + expect(parseEnvelope(result.stdout).data).toMatchObject({ + status: expectedStatus, + exit_code: expectedExit, + response: null, + completion: { + response_bytes: 0, + }, + }); + expect(`${result.stdout}\n${result.stderr}`).not.toContain("private"); + }); + + it("classifies cancellation and timeout independently (#7773)", () => { + const cancelled = runDriver(` +${preamble} +async def wait_forever(*args, **kwargs): + del args, kwargs + await asyncio.sleep(60) + +async def main(): + target._run_non_interactive_impl = wait_forever + task = asyncio.create_task( + target.run_non_interactive("task", output_format="json") + ) + await asyncio.sleep(0) + task.cancel() + assert await task == 130 + +asyncio.run(main()) +`); + const timedOut = runDriver(` +${preamble} +async def wait_forever(*args, **kwargs): + del args, kwargs + await asyncio.sleep(60) + +target._run_non_interactive_impl = wait_forever +exit_code = asyncio.run( + target.run_non_interactive( + "task", + output_format="json", + timeout_seconds=0.01, + ) +) +assert exit_code == 124 +`); + + expect(cancelled.status).toBe(0); + expect(parseEnvelope(cancelled.stdout).data).toMatchObject({ + status: "cancelled", + exit_code: 130, + response: null, + }); + expect(timedOut.status).toBe(0); + expect(parseEnvelope(timedOut.stdout).data).toMatchObject({ + status: "timeout", + exit_code: 124, + response: null, + }); + }); + + it("returns a bounded output-limit envelope instead of partial text (#7773)", () => { + const result = runDriver(` +${preamble} +async def overflow(*args, **kwargs): + del args, kwargs + target._write_text("x" * 300) + return 0 + +target._NEMOCLAW_JSON_MAX_BYTES = 512 +target._NEMOCLAW_JSON_ENVELOPE_RESERVE_BYTES = 256 +target._run_non_interactive_impl = overflow +exit_code = asyncio.run(target.run_non_interactive("task", output_format="json")) +assert exit_code == 1 +`); + + expect(result.status).toBe(0); + expect(Buffer.byteLength(result.stdout)).toBeLessThanOrEqual(512); + expect(parseEnvelope(result.stdout).data).toMatchObject({ + status: "output_limit", + exit_code: 1, + response: null, + completion: { + response_bytes: 0, + }, + }); + expect(result.stdout).not.toContain("x".repeat(100)); + }); + + it("preserves the existing text-mode stdout contract (#7773)", () => { + const result = runDriver(` +${preamble} +async def succeed(*args, **kwargs): + del args, kwargs + target._write_text("PONG") + return 0 + +target._run_non_interactive_impl = succeed +exit_code = asyncio.run(target.run_non_interactive("task")) +assert exit_code == 0 +`); + + expect(result.status).toBe(0); + expect(result.stdout).toBe("PONG"); + }); +}); diff --git a/test/e2e/e2e-cloud-experimental/checks/07-deepagents-code-headless-inference.sh b/test/e2e/e2e-cloud-experimental/checks/07-deepagents-code-headless-inference.sh index 4fa55ab96e6..5bee2cfc912 100755 --- a/test/e2e/e2e-cloud-experimental/checks/07-deepagents-code-headless-inference.sh +++ b/test/e2e/e2e-cloud-experimental/checks/07-deepagents-code-headless-inference.sh @@ -7,9 +7,10 @@ # Headless `dcode -n ""`, run inside a built Deep Agents Code sandbox, # must route through the managed https://inference.local/v1 endpoint using the # placeholder OpenAI-compatible key NemoClaw writes into config.toml. The login -# shell path must reject an empty prompt with exit 2, then return PONG with exit -# 0 for a real prompt; provider, connection, DNS, timeout, and ambiguous failures -# are not acceptable. No real provider/proxy credentials may appear in +# shell path must reject an empty prompt with exit 2, then return a versioned +# JSON success envelope containing PONG with exit 0 for a real prompt; provider, +# connection, DNS, timeout, and ambiguous failures are not acceptable. No real +# provider/proxy credentials may appear in # config.toml, .env, .mcp.json, /tmp/nemoclaw-proxy-env.sh, or output. # The sandbox entrypoint, direct managed launcher, and both login/interactive # shell paths must keep the documented nproc=512 and nofile=65536 contract. @@ -359,9 +360,9 @@ is_empty_prompt_rejection() { } # Route reachability is proved separately with /v1/models. This classifier has -# the stronger #6191 acceptance contract: dcode itself must be usable and return -# exit-zero PONG, so authentication, quota, provider, and model errors are -# intentionally failures rather than route-only success signals. +# the stronger #6191 and #7773 acceptance contract: dcode itself must be usable +# and return an exit-zero, versioned JSON envelope containing PONG. Authentication, +# quota, provider, model, and malformed-envelope errors are intentionally failures. classify_headless_output() { local dcode_exit="$1" local headless_output="$2" @@ -403,12 +404,57 @@ classify_headless_output() { return 1 fi - if printf '%s\n' "$payload" | tr -d '\r' | grep -Eiq '^[[:space:]]*PONG[[:space:]]*$'; then - printf '%s\n' "pong" + if printf '%s' "$payload" | python3 -c ' +import json +import sys + +objects = [] +for line in sys.stdin: + try: + value = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(value, dict): + objects.append(value) + +if len(objects) != 1: + raise SystemExit(1) +envelope = objects[0] +if set(envelope) != {"schema_version", "command", "data"}: + raise SystemExit(1) +if envelope["schema_version"] != 1 or envelope["command"] != "non-interactive": + raise SystemExit(1) +data = envelope["data"] +if not isinstance(data, dict) or set(data) != { + "status", + "exit_code", + "response", + "completion", +}: + raise SystemExit(1) +if data["status"] != "success" or data["exit_code"] != 0: + raise SystemExit(1) +if not isinstance(data["response"], str) or data["response"].strip() != "PONG": + raise SystemExit(1) +completion = data["completion"] +if not isinstance(completion, dict) or set(completion) != { + "thread_id", + "duration_ms", + "response_bytes", +}: + raise SystemExit(1) +if not isinstance(completion["thread_id"], str) or not completion["thread_id"]: + raise SystemExit(1) +if not isinstance(completion["duration_ms"], int) or completion["duration_ms"] < 0: + raise SystemExit(1) +if completion["response_bytes"] != len(data["response"].encode("utf-8")): + raise SystemExit(1) +'; then + printf '%s\n' "json-pong" return 0 fi - printf '%s\n' "ambiguous-output" + printf '%s\n' "invalid-json-envelope" return 1 } @@ -500,7 +546,6 @@ main() { fail_test "config.toml does not use the managed placeholder API key env reference (captured config redacted from log)" fi if printf '%s\n' "$config_output" | uses_native_openrouter_config; then - native_openrouter=1 openrouter_identity_output="$(sandbox_direct_dcode identity || true)" if printf '%s\n' "$openrouter_identity_output" | grep -Fxq "Provider: openrouter" \ && printf '%s\n' "$openrouter_identity_output" | grep -Eq '^Model:[[:space:]]+openrouter:' \ @@ -510,7 +555,6 @@ main() { fail_test "installed dcode identity does not report native OpenRouter consistently" fi else - native_openrouter=0 openrouter_identity_output="" fi @@ -553,25 +597,17 @@ main() { fail_test "login-shell proxy did not receive HTTP 200 from https://inference.local/v1/models (HTTP ${route_code:-000})" fi - # 5. The same login-shell path runs dcode and returns PONG. - headless_output="$(sandbox_login_exec "cd /sandbox && timeout ${HEADLESS_TIMEOUT} dcode -n 'Reply with exactly one word: PONG'; echo \"DCODE_EXIT:\$?\"" || true)" + # 5. The same login-shell path runs dcode and returns a JSON PONG envelope. + headless_output="$(sandbox_login_exec "cd /sandbox && timeout ${HEADLESS_TIMEOUT} dcode -n 'Reply with exactly one word: PONG' --json; echo \"DCODE_EXIT:\$?\"" || true)" dcode_exit="$(printf '%s' "$headless_output" | sed -n 's/.*DCODE_EXIT:\([0-9]\+\).*/\1/p' | tail -n1)" if classification="$(classify_headless_output "${dcode_exit:-unknown}" "$headless_output")"; then pass "login-shell dcode -n reached managed inference with ${classification} (exit ${dcode_exit:-unknown}; direct DNS/hosts ${direct_dns_state})" - if [ "$native_openrouter" -eq 1 ]; then - if printf '%s\n' "$headless_output" | grep -Fq "Usage Stats" \ - && printf '%s\n' "$headless_output" | grep -Eiq '(^|[[:space:]])openrouter([[:space:]]|$)'; then - pass "headless usage output reports the native OpenRouter provider" - else - fail_test "headless usage output does not report the native OpenRouter provider" - fi - fi else - fail_test "login-shell dcode -n did not exit 0 with PONG (${classification}, exit ${dcode_exit:-unknown})" + fail_test "login-shell dcode -n --json did not return a success envelope with PONG (${classification}, exit ${dcode_exit:-unknown})" fi # 6. The public direct-exec path reaches inference without shell startup files. - if direct_output="$(sandbox_direct_dcode -n "Reply with exactly one word: PONG")"; then + if direct_output="$(sandbox_direct_dcode -n "Reply with exactly one word: PONG" --json)"; then direct_exit=0 else direct_exit=$? @@ -581,7 +617,7 @@ DCODE_EXIT:${direct_exit}" if direct_classification="$(classify_headless_output "$direct_exit" "$direct_headless_output")"; then pass "direct-exec dcode -n reached managed inference with ${direct_classification} (exit ${direct_exit}; direct DNS/hosts ${direct_dns_state})" else - fail_test "direct-exec dcode -n did not exit 0 with PONG (${direct_classification}, exit ${direct_exit})" + fail_test "direct-exec dcode -n --json did not return a success envelope with PONG (${direct_classification}, exit ${direct_exit})" fi # 7. The user-facing bare-connect readiness path must route every observed diff --git a/test/helpers/langchain-deepagents-code-patch-fixture.ts b/test/helpers/langchain-deepagents-code-patch-fixture.ts index b4b3c1bbaa0..f3d82486349 100644 --- a/test/helpers/langchain-deepagents-code-patch-fixture.ts +++ b/test/helpers/langchain-deepagents-code-patch-fixture.ts @@ -55,6 +55,7 @@ from __future__ import annotations import os import sys +import asyncio from types import SimpleNamespace @@ -62,6 +63,12 @@ class Parser: def parse_args(self): argv = sys.argv[1:] command = next((arg for arg in argv if not arg.startswith("-") and arg != "none"), None) + non_interactive_message = None + for index, arg in enumerate(argv): + if arg in {"-n", "--non-interactive"} and index + 1 < len(argv): + non_interactive_message = argv[index + 1] + elif arg.startswith("--non-interactive="): + non_interactive_message = arg.split("=", 1)[1] tools_command = None if command == "tools": index = argv.index("tools") @@ -89,6 +96,11 @@ class Parser: no_mcp=False, trust_project_mcp=True, shell_allow_list=["bash"], + non_interactive_message=non_interactive_message, + output_format=("json" if "--json" in argv else "text"), + quiet=("-q" in argv or "--quiet" in argv), + no_stream=("--no-stream" in argv), + timeout=None, ) def error(self, message): @@ -119,6 +131,22 @@ def cli_main(): assert all(os.environ.get(name) == "false" for name in tracing_flags) assert os.environ["LANGGRAPH_CLI_NO_ANALYTICS"] == "1" assert os.environ["HOME"] == "/sandbox" + output_format = getattr(args, "output_format", "text") + if args.non_interactive_message: + from deepagents_code.client.non_interactive import run_non_interactive + + timeout = getattr(args, "timeout", None) + exit_code = asyncio.run( + asyncio.wait_for( + run_non_interactive( + message=args.non_interactive_message, + quiet=args.quiet, + stream=not args.no_stream, + ), + timeout=timeout, + ) + ) + raise SystemExit(exit_code) print(f"managed-posture-ok auto_approve={args.auto_approve}") `, ); @@ -450,16 +478,31 @@ def generate_thread_id(): return "thread-1" +def _write_text(text): + print(text, end="", flush=True) + + +def _write_newline(): + print() + + async def _run_non_interactive_impl(*args, **kwargs): del args + if kwargs.get("message") == "fixture-json-task": + return 0 return kwargs +async def _run_agent_loop(*args, **kwargs): + return await _run_non_interactive_impl(*args, **kwargs) + + async def run_non_interactive(*args, **kwargs): console = _Console() thread_id = generate_thread_id() try: - return await _run_non_interactive_impl(*args, **kwargs) + result = await _run_agent_loop(*args, **kwargs) + return result except Exception as e: logger.exception("Unexpected error during non-interactive execution") console.print( diff --git a/test/langchain-deepagents-code-headless-runtime.test.ts b/test/langchain-deepagents-code-headless-runtime.test.ts index 5f4d05e4277..dc59067c543 100644 --- a/test/langchain-deepagents-code-headless-runtime.test.ts +++ b/test/langchain-deepagents-code-headless-runtime.test.ts @@ -145,18 +145,33 @@ describe("LangChain Deep Agents Code headless runtime contracts", () => { } }); - it("requires exit zero and PONG from Deep Agents Code headless inference (#6191)", () => { + it("requires an exit-zero JSON success envelope containing PONG (#6191, #7773)", () => { const classify = (exitCode: string, output: string) => runHeadlessCheckHelper("classify-output", { DCODE_EXIT: exitCode, HEADLESS_OUTPUT: output, }); + const envelope = (response = "PONG") => + JSON.stringify({ + schema_version: 1, + command: "non-interactive", + data: { + status: "success", + exit_code: 0, + response, + completion: { + thread_id: "thread-1", + duration_ms: 12, + response_bytes: Buffer.byteLength(response), + }, + }, + }); - expect(classify("0", "startup log\n PONG \nDCODE_EXIT:0")).toBe("pass:pong"); + expect(classify("0", `startup log\n${envelope()}\nDCODE_EXIT:0`)).toBe("pass:json-pong"); expect( classify("1", "OpenAI provider returned HTTP 401 for inference.local\nDCODE_EXIT:1"), ).toBe("fail:actionable-inference-error"); - expect(classify("1", "PONG\nDCODE_EXIT:1")).toBe("fail:nonzero-exit"); + expect(classify("1", `${envelope()}\nDCODE_EXIT:1`)).toBe("fail:nonzero-exit"); expect(classify("1", "openai.APIConnectionError\nDCODE_EXIT:1")).toBe( "fail:inference-connection-failure", ); @@ -180,20 +195,19 @@ describe("LangChain Deep Agents Code headless runtime contracts", () => { expect(classify("1", "No module named deepagents_code\nDCODE_EXIT:1")).toBe( "fail:wrapper-missing", ); - // The word 'dcode' appearing in a non-error context (e.g. a version - // banner) must not be misclassified as a wrapper-missing failure. The - // is_dcode_wrapper_failure regex requires a specific error indicator - // ("command not found", "No such file or directory", "Permission denied", - // or "No module named deepagents_code") after the dcode path segment. - // See PR #6206 / advisor PRA-2. - expect(classify("0", " PONG \nDCODE_EXIT:0")).toBe("pass:pong"); - expect(classify("0", "dcode version 0.1.12\nPONG\nDCODE_EXIT:0")).toBe("pass:pong"); - expect(classify("0", "something happened\nDCODE_EXIT:0")).toBe("fail:ambiguous-output"); + expect(classify("0", `${envelope()}\nDCODE_EXIT:0`)).toBe("pass:json-pong"); + expect(classify("0", `dcode version 0.1.12\n${envelope()}\nDCODE_EXIT:0`)).toBe( + "pass:json-pong", + ); + expect(classify("0", "something happened\nDCODE_EXIT:0")).toBe("fail:invalid-json-envelope"); expect(classify("0", "Reply with exactly one word: PONG\nDCODE_EXIT:0")).toBe( - "fail:ambiguous-output", + "fail:invalid-json-envelope", + ); + expect(classify("0", `${envelope("PONG because the route works")}\nDCODE_EXIT:0`)).toBe( + "fail:invalid-json-envelope", ); - expect(classify("0", "PONG because the route works\nDCODE_EXIT:0")).toBe( - "fail:ambiguous-output", + expect(classify("0", `${envelope()}\n${envelope()}\nDCODE_EXIT:0`)).toBe( + "fail:invalid-json-envelope", ); expect(classify("1", "something happened\nDCODE_EXIT:1")).toBe("fail:nonzero-exit"); }); diff --git a/test/langchain-deepagents-code-image.test.ts b/test/langchain-deepagents-code-image.test.ts index 0302b6496dc..8652deb64a2 100644 --- a/test/langchain-deepagents-code-image.test.ts +++ b/test/langchain-deepagents-code-image.test.ts @@ -763,7 +763,7 @@ describe("LangChain Deep Agents Code image contracts", () => { for (const expected of [ 'sandbox_exec "test -d /sandbox/.deepagents"', "command -v dcode", - "dcode -n 'Reply with exactly one word: PONG'", + "dcode -n 'Reply with exactly one word: PONG' --json", "sandbox_login_exec", "sandbox_login_proxy_contract", "-u HTTP_PROXY -u HTTPS_PROXY -u NO_PROXY", @@ -822,6 +822,14 @@ describe("LangChain Deep Agents Code image contracts", () => { "references_managed_placeholder_key", 'api_key_env[[:space:]]*=[[:space:]]*"DEEPAGENTS_CODE_OPENAI_API_KEY"', "classify_headless_output", + '"schema_version", "command", "data"', + '"status"', + '"exit_code"', + '"response"', + '"completion"', + '"thread_id"', + '"duration_ms"', + '"response_bytes"', "NEMOCLAW_DCODE_DNS_PROBE_MISSING_GETENT", "required DNS diagnostic tool getent is unavailable", "NEMOCLAW_DCODE_DNS_PROBE_MISSING_TIMEOUT", From 84c325df7c8b9049bde3db52f56975efa6a0a58c Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 29 Jul 2026 15:42:35 +0700 Subject: [PATCH 2/5] test(dcode): align disclosure fixture with JSON patch Signed-off-by: San Dang --- ...ts-code-progressive-tool-disclosure.test.ts | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/test/langchain-deepagents-code-progressive-tool-disclosure.test.ts b/test/langchain-deepagents-code-progressive-tool-disclosure.test.ts index b0ee00d2b9b..7065a6ce333 100644 --- a/test/langchain-deepagents-code-progressive-tool-disclosure.test.ts +++ b/test/langchain-deepagents-code-progressive-tool-disclosure.test.ts @@ -35,6 +35,7 @@ if __name__ == "__main__": "main.py": `from __future__ import annotations import os +import asyncio from types import SimpleNamespace class Parser: @@ -51,7 +52,22 @@ def parse_args(): return args def cli_main(): - return parse_args() + args = parse_args() + output_format = getattr(args, "output_format", "text") + if getattr(args, "non_interactive_message", None): + from deepagents_code.client.non_interactive import run_non_interactive + + timeout = getattr(args, "timeout", None) + exit_code = asyncio.run( + asyncio.wait_for( + run_non_interactive( + message=args.non_interactive_message, + ), + timeout=timeout, + ) + ) + raise SystemExit(exit_code) + return args `, "app.py": fs .readFileSync( From a2bf82560bd3d15c153f155b050958564cc8201e Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Wed, 29 Jul 2026 08:01:29 -0400 Subject: [PATCH 3/5] fix(dcode): reject unframed smoke output Signed-off-by: Julie Yaunches --- .../07-deepagents-code-headless-inference.sh | 21 ++++++++----------- ...n-deepagents-code-headless-runtime.test.ts | 9 ++++++-- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/test/e2e/e2e-cloud-experimental/checks/07-deepagents-code-headless-inference.sh b/test/e2e/e2e-cloud-experimental/checks/07-deepagents-code-headless-inference.sh index 5bee2cfc912..5912f8f157e 100755 --- a/test/e2e/e2e-cloud-experimental/checks/07-deepagents-code-headless-inference.sh +++ b/test/e2e/e2e-cloud-experimental/checks/07-deepagents-code-headless-inference.sh @@ -367,7 +367,10 @@ classify_headless_output() { local dcode_exit="$1" local headless_output="$2" local payload - payload="$(printf '%s' "$headless_output" | sed 's/DCODE_EXIT:[0-9]*//g')" + payload="$( + printf '%s' "$headless_output" \ + | sed '$ { /^DCODE_EXIT:[0-9][0-9]*$/d; }' + )" if [ "$dcode_exit" = "124" ]; then printf '%s\n' "timeout" @@ -408,18 +411,12 @@ classify_headless_output() { import json import sys -objects = [] -for line in sys.stdin: - try: - value = json.loads(line) - except json.JSONDecodeError: - continue - if isinstance(value, dict): - objects.append(value) - -if len(objects) != 1: +try: + envelope = json.load(sys.stdin) +except json.JSONDecodeError: + raise SystemExit(1) +if not isinstance(envelope, dict): raise SystemExit(1) -envelope = objects[0] if set(envelope) != {"schema_version", "command", "data"}: raise SystemExit(1) if envelope["schema_version"] != 1 or envelope["command"] != "non-interactive": diff --git a/test/langchain-deepagents-code-headless-runtime.test.ts b/test/langchain-deepagents-code-headless-runtime.test.ts index dc59067c543..c6801a4c1c8 100644 --- a/test/langchain-deepagents-code-headless-runtime.test.ts +++ b/test/langchain-deepagents-code-headless-runtime.test.ts @@ -167,7 +167,9 @@ describe("LangChain Deep Agents Code headless runtime contracts", () => { }, }); - expect(classify("0", `startup log\n${envelope()}\nDCODE_EXIT:0`)).toBe("pass:json-pong"); + expect(classify("0", `startup log\n${envelope()}\nDCODE_EXIT:0`)).toBe( + "fail:invalid-json-envelope", + ); expect( classify("1", "OpenAI provider returned HTTP 401 for inference.local\nDCODE_EXIT:1"), ).toBe("fail:actionable-inference-error"); @@ -197,7 +199,10 @@ describe("LangChain Deep Agents Code headless runtime contracts", () => { ); expect(classify("0", `${envelope()}\nDCODE_EXIT:0`)).toBe("pass:json-pong"); expect(classify("0", `dcode version 0.1.12\n${envelope()}\nDCODE_EXIT:0`)).toBe( - "pass:json-pong", + "fail:invalid-json-envelope", + ); + expect(classify("0", `${envelope()}\ntrailing banner\nDCODE_EXIT:0`)).toBe( + "fail:invalid-json-envelope", ); expect(classify("0", "something happened\nDCODE_EXIT:0")).toBe("fail:invalid-json-envelope"); expect(classify("0", "Reply with exactly one word: PONG\nDCODE_EXIT:0")).toBe( From d69dc28ac0a5cf1708bf3a61cfa84325e4b16f61 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Wed, 29 Jul 2026 08:19:08 -0400 Subject: [PATCH 4/5] fix(dcode): protect JSON stdout descriptor Signed-off-by: Julie Yaunches --- .../patch-managed-deepagents-code.py | 97 ++++++++++++------- test/dcode-non-interactive-json.test.ts | 33 +++++++ 2 files changed, 95 insertions(+), 35 deletions(-) diff --git a/agents/langchain-deepagents-code/patch-managed-deepagents-code.py b/agents/langchain-deepagents-code/patch-managed-deepagents-code.py index ee094313131..756d25de7a3 100644 --- a/agents/langchain-deepagents-code/patch-managed-deepagents-code.py +++ b/agents/langchain-deepagents-code/patch-managed-deepagents-code.py @@ -783,6 +783,7 @@ def _run_single_hook(command, event, payload_bytes) -> None: import re as _nemoclaw_re import sqlite3 as _nemoclaw_sqlite3 import sys as _nemoclaw_sys +import tempfile as _nemoclaw_tempfile import time as _nemoclaw_time # NemoClaw-managed Deep Agents Code hardening v2. @@ -865,6 +866,29 @@ def isatty(self): return False +@_nemoclaw_contextlib.contextmanager +def _nemoclaw_capture_process_stdout(run): + """Suppress direct and child-process writes to the stdout descriptor.""" + run.stdout.flush() + with _nemoclaw_tempfile.TemporaryFile() as capture: + saved_stdout_fd = _nemoclaw_os.dup(1) + redirected = False + try: + _nemoclaw_os.dup2(capture.fileno(), 1) + redirected = True + yield + finally: + if redirected: + try: + run.stdout.flush() + finally: + _nemoclaw_os.dup2(saved_stdout_fd, 1) + capture.seek(0, _nemoclaw_os.SEEK_END) + if capture.tell() > 0: + run.unexpected_stdout = True + _nemoclaw_os.close(saved_stdout_fd) + + _nemoclaw_json_run = _nemoclaw_contextvars.ContextVar( "nemoclaw_managed_json_run", default=None, @@ -976,42 +1000,45 @@ async def _nemoclaw_run_json_non_interactive(timeout_seconds, *args, **kwargs): token = _nemoclaw_json_run.set(run) guard = _NemoClawUnexpectedStdout(run) try: - with _nemoclaw_contextlib.redirect_stdout(guard): - try: - operation = _nemoclaw_original_run_non_interactive( - *args, - **kwargs, - ) - if timeout_seconds is None: - exit_code = await operation - else: - exit_code = await _nemoclaw_asyncio.wait_for( - operation, - timeout=timeout_seconds, + with _nemoclaw_capture_process_stdout(run): + with _nemoclaw_contextlib.redirect_stdout(guard): + try: + operation = _nemoclaw_original_run_non_interactive( + *args, + **kwargs, ) - except TimeoutError: - print( - f"dcode: agent timed out after {timeout_seconds}s.", - file=_nemoclaw_sys.stderr, - ) - status, exit_code = "timeout", 124 - except _nemoclaw_asyncio.CancelledError: - print( - "dcode: managed non-interactive run was cancelled.", - file=_nemoclaw_sys.stderr, - ) - status, exit_code = "cancelled", 130 - except Exception: - print( - "dcode: managed non-interactive execution failed.", - file=_nemoclaw_sys.stderr, - ) - status = ( - "agent_failure" if run.phase == "agent" else "process_failure" - ) - exit_code = 1 - else: - status, exit_code = _nemoclaw_json_status(exit_code, run) + if timeout_seconds is None: + exit_code = await operation + else: + exit_code = await _nemoclaw_asyncio.wait_for( + operation, + timeout=timeout_seconds, + ) + except TimeoutError: + print( + f"dcode: agent timed out after {timeout_seconds}s.", + file=_nemoclaw_sys.stderr, + ) + status, exit_code = "timeout", 124 + except _nemoclaw_asyncio.CancelledError: + print( + "dcode: managed non-interactive run was cancelled.", + file=_nemoclaw_sys.stderr, + ) + status, exit_code = "cancelled", 130 + except _NemoClawOutputLimitError: + status, exit_code = "output_limit", 1 + except Exception: + print( + "dcode: managed non-interactive execution failed.", + file=_nemoclaw_sys.stderr, + ) + status = ( + "agent_failure" if run.phase == "agent" else "process_failure" + ) + exit_code = 1 + else: + status, exit_code = _nemoclaw_json_status(exit_code, run) finally: _nemoclaw_json_run.reset(token) if run.unexpected_stdout: diff --git a/test/dcode-non-interactive-json.test.ts b/test/dcode-non-interactive-json.test.ts index 514d9b4a1ca..f533fda0f8a 100644 --- a/test/dcode-non-interactive-json.test.ts +++ b/test/dcode-non-interactive-json.test.ts @@ -136,6 +136,39 @@ assert exit_code == 0 expect(result.stderr).toContain("suppressed unexpected stdout"); }); + it("suppresses direct and child-process writes to stdout (#7773)", () => { + const result = runDriver(` +${preamble} +import os +import subprocess +import sys + +async def succeed(*args, **kwargs): + del args, kwargs + os.write(1, b"direct descriptor output") + subprocess.run( + [sys.executable, "-c", "import os; os.write(1, b'child output')"], + check=True, + ) + target._write_text("PONG") + return 0 + +target._run_non_interactive_impl = succeed +exit_code = asyncio.run(target.run_non_interactive("task", output_format="json")) +assert exit_code == 0 +`); + + expect(result.status).toBe(0); + expect(parseEnvelope(result.stdout).data).toMatchObject({ + status: "success", + exit_code: 0, + response: "PONG", + }); + expect(result.stdout).not.toContain("descriptor output"); + expect(result.stdout).not.toContain("child output"); + expect(result.stderr).toContain("suppressed unexpected stdout"); + }); + it.each([ ["agent_failure", "target._run_non_interactive_impl = fail_agent", 1], ["process_failure", "target._nemoclaw_original_run_non_interactive = fail_process", 1], From 6d36977fd5a1eb003336a8d52752ec7f85fe3472 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Wed, 29 Jul 2026 08:30:02 -0400 Subject: [PATCH 5/5] fix(dcode): bound suppressed stdout Signed-off-by: Julie Yaunches --- .../patch-managed-deepagents-code.py | 64 ++++++++++++++----- test/dcode-non-interactive-json.test.ts | 6 +- 2 files changed, 54 insertions(+), 16 deletions(-) diff --git a/agents/langchain-deepagents-code/patch-managed-deepagents-code.py b/agents/langchain-deepagents-code/patch-managed-deepagents-code.py index 756d25de7a3..c646b80cfeb 100644 --- a/agents/langchain-deepagents-code/patch-managed-deepagents-code.py +++ b/agents/langchain-deepagents-code/patch-managed-deepagents-code.py @@ -783,7 +783,7 @@ def _run_single_hook(command, event, payload_bytes) -> None: import re as _nemoclaw_re import sqlite3 as _nemoclaw_sqlite3 import sys as _nemoclaw_sys -import tempfile as _nemoclaw_tempfile +import threading as _nemoclaw_threading import time as _nemoclaw_time # NemoClaw-managed Deep Agents Code hardening v2. @@ -870,23 +870,57 @@ def isatty(self): def _nemoclaw_capture_process_stdout(run): """Suppress direct and child-process writes to the stdout descriptor.""" run.stdout.flush() - with _nemoclaw_tempfile.TemporaryFile() as capture: - saved_stdout_fd = _nemoclaw_os.dup(1) - redirected = False + read_fd, write_fd = _nemoclaw_os.pipe() + _nemoclaw_os.set_blocking(read_fd, False) + stop_drain = _nemoclaw_threading.Event() + + def drain_stdout(): try: - _nemoclaw_os.dup2(capture.fileno(), 1) - redirected = True - yield - finally: - if redirected: + while not stop_drain.is_set(): try: - run.stdout.flush() - finally: - _nemoclaw_os.dup2(saved_stdout_fd, 1) - capture.seek(0, _nemoclaw_os.SEEK_END) - if capture.tell() > 0: + chunk = _nemoclaw_os.read(read_fd, 65_536) + except BlockingIOError: + stop_drain.wait(0.01) + continue + if not chunk: + return + run.unexpected_stdout = True + try: + if _nemoclaw_os.read(read_fd, 65_536): run.unexpected_stdout = True - _nemoclaw_os.close(saved_stdout_fd) + except BlockingIOError: + pass + finally: + _nemoclaw_os.close(read_fd) + + drain_thread = _nemoclaw_threading.Thread( + target=drain_stdout, + name="nemoclaw-json-stdout-drain", + daemon=True, + ) + saved_stdout_fd = _nemoclaw_os.dup(1) + redirected = False + try: + _nemoclaw_os.dup2(write_fd, 1) + redirected = True + _nemoclaw_os.close(write_fd) + write_fd = None + drain_thread.start() + yield + finally: + if redirected: + try: + run.stdout.flush() + finally: + _nemoclaw_os.dup2(saved_stdout_fd, 1) + _nemoclaw_os.close(saved_stdout_fd) + if write_fd is not None: + _nemoclaw_os.close(write_fd) + stop_drain.set() + if drain_thread.ident is not None: + drain_thread.join(timeout=1) + else: + _nemoclaw_os.close(read_fd) _nemoclaw_json_run = _nemoclaw_contextvars.ContextVar( diff --git a/test/dcode-non-interactive-json.test.ts b/test/dcode-non-interactive-json.test.ts index f533fda0f8a..d1665e4e1ba 100644 --- a/test/dcode-non-interactive-json.test.ts +++ b/test/dcode-non-interactive-json.test.ts @@ -147,7 +147,11 @@ async def succeed(*args, **kwargs): del args, kwargs os.write(1, b"direct descriptor output") subprocess.run( - [sys.executable, "-c", "import os; os.write(1, b'child output')"], + [ + sys.executable, + "-c", + "import sys; sys.stdout.buffer.write(b'child output' * 200000)", + ], check=True, ) target._write_text("PONG")