Skip to content

fix(sandbox): use base64+stdin for edit() to avoid bash -lc escaping … - #3084

Closed
gh-zhaoweifeng wants to merge 11 commits into
agentscope-ai:mainfrom
gh-zhaoweifeng:fix/edit-file-e2b-sandbox
Closed

gh-zhaoweifeng wants to merge 11 commits into
agentscope-ai:mainfrom
gh-zhaoweifeng:fix/edit-file-e2b-sandbox

Conversation

@gh-zhaoweifeng

Copy link
Copy Markdown

…issues

In E2B sandbox environments, the shell is bash -lc, which treats \n inside double quotes as a literal backslash+n (not a newline). This causes the entire multi-line Python script in python3 -c "...\n..." to collapse into a single line, failing with:

SyntaxError: unexpected character after line continuation character

This makes the edit_file tool 100% non-functional in sandbox environments. The model falls back to write_file, which refuses to overwrite existing files, so no file can be modified at all.

This fix base64-encodes the Python script (assembled with real newlines) and pipes it through stdin to python3 -, passing the payload via argv[1]. This avoids all quoting/escaping issues and works correctly in both sandbox and non-sandbox environments.

The command shape changes from:

python3 -c "...\n..." 2>&1 <<'EDIT_EOF'

EDIT_EOF

to:

echo | base64 -d | python3 - 2>&1

AgentScope-Java Version

[The version of AgentScope-Java you are working on, e.g. 1.0.12, check your pom.xml dependency version or run mvn dependency:tree | grep agentscope-parent:pom(only mac/linux)]

Description

[Please describe the background, purpose, changes made, and how to test this PR]

Checklist

Please check the following items before code is ready to be reviewed.

  • Code has been formatted with mvn spotless:apply
  • All tests are passing (mvn test)
  • Javadoc comments are complete and follow project conventions
  • Related documentation has been updated (e.g. links, examples, etc.)
  • Code is ready for review

…issues

In E2B sandbox environments, the shell is `bash -lc`, which treats `\n`
inside double quotes as a literal backslash+n (not a newline). This causes
the entire multi-line Python script in `python3 -c "...\n..."` to collapse
into a single line, failing with:

  SyntaxError: unexpected character after line continuation character

This makes the `edit_file` tool 100% non-functional in sandbox environments.
The model falls back to `write_file`, which refuses to overwrite existing
files, so no file can be modified at all.

This fix base64-encodes the Python script (assembled with real newlines)
and pipes it through stdin to `python3 -`, passing the payload via argv[1].
This avoids all quoting/escaping issues and works correctly in both
sandbox and non-sandbox environments.

The command shape changes from:

  python3 -c "...\n..." 2>&1 <<'__EDIT_EOF__'
  <payload>
  __EDIT_EOF__

to:

  echo <scriptB64> | base64 -d | python3 - <payloadB64> 2>&1
@CLAassistant

CLAassistant commented Sep 10, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@codecov

codecov Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.88889% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...gent/filesystem/sandbox/BaseSandboxFilesystem.java 88.88% 0 Missing and 2 partials ⚠️

📢 Thoughts on this report? Let us know!

Add test to verify that edit() uses 'base64 -d | python3 -' instead of
'python3 -c' inline form, which fails in bash -lc environments.

This improves patch coverage for the fix in commit b00209d.

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Real bug, well diagnosed — under bash -lc the inline python3 -c "...\n..." form does collapse to one line, so edit() was indeed broken in sandbox filesystems. Anchoring the explanation in a "do NOT revert" comment plus a shape regression test is the right call, and I confirmed BaseSandboxFilesystem#edit is the only python3 -c call site left in the codebase, so the fix is complete.

One design concern worth a second look (inline below): the payload moved from stdin to argv[1], which is exactly the channel that was originally chosen for size/visibility reasons. The script itself is constant-size and fine on the command line; the payload is not.

Findings

  • [Warning] BaseSandboxFilesystem.java:292 — payload on argv reintroduces ARG_MAX truncation and /proc/<pid>/cmdline exposure for file content
  • [Info] BaseSandboxFilesystem.java:290 — prefer printf '%s\n' over echo for long base64, and cover a large payload in the regression test

Checklist notes

  • Tests: added edit_usesBase64PipedScript asserts the command shape but never exercises the payload content; a case with a multi-KB new string would have caught the ARG_MAX concern directly.
  • Compatibility: internal command construction only, no public API change. CLA signed, CI green on both OS matrices.

Automated review by github-manager-bot

Comment on lines +268 to +292
String script =
"import sys, os, base64, json\n"
+ "payload = json.loads(base64.b64decode(sys.argv[1]).decode('utf-8'))\n"
+ "path, old, new = payload['path'], payload['old'], payload['new']\n"
+ "replace_all = payload.get('replace_all', False)\n"
+ "if not os.path.isfile(path):\n"
+ " print(json.dumps({'error': 'file_not_found'}))\n"
+ " sys.exit(0)\n"
+ "with open(path, 'rb') as f: text = f.read().decode('utf-8')\n"
+ "count = text.count(old)\n"
+ "if count == 0:\n"
+ " print(json.dumps({'error': 'string_not_found'}))\n"
+ " sys.exit(0)\n"
+ "if count > 1 and not replace_all:\n"
+ " print(json.dumps({'error': 'multiple_occurrences', 'count': count}))\n"
+ " sys.exit(0)\n"
+ "result = text.replace(old, new) if replace_all else text.replace(old, new,"
+ " 1)\\n"
+ "with open(path, 'wb') as f: f.write(result.encode('utf-8'))\\n"
+ "print(json.dumps({'count': count}))\\n"
+ "\" 2>&1 <<'__EDIT_EOF__'\n"
+ payloadB64
+ "\n__EDIT_EOF__\n";
+ " 1)\n"
+ "with open(path, 'wb') as f: f.write(result.encode('utf-8'))\n"
+ "print(json.dumps({'count': count}))\n";
String scriptB64 =
Base64.getEncoder()
.encodeToString(script.getBytes(java.nio.charset.StandardCharsets.UTF_8));

String cmd = "echo " + scriptB64 + " | base64 -d | python3 - " + payloadB64 + " 2>&1";

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Warning] The fix moves the payload from stdin to argv[1], which reintroduces the two limits the original heredoc was protecting against:

  1. ARG_MAX — old/new are arbitrary model-generated strings (whole-file edits are common), so the quoted form was unbounded-safe while python3 - <payloadB64> is not. On executors with a small per-request limit (E2B / Docker sh -c wrappers, Windows CreateProcess 32k) a large edit now fails at the shell instead of at the Python layer.
  2. /proc/<pid>/cmdline — argv is readable through ps for the lifetime of the process, so the file content being edited is briefly visible to anything else running in the sandbox. stdin is not.

Suggested shape that keeps the newline fix and the previous safety properties: keep the base64 script in argv (it is constant-size and contains no user data) and put only the payload back on stdin, e.g.

String cmd = "echo " + scriptB64 + " | base64 -d | python3 - 2>&1 <<'__EDIT_EOF__'\n"
        + payloadB64 + "\n__EDIT_EOF__\n";

(with payload = json.loads(base64.b64decode(sys.stdin.read().strip())) restored in the script), or write both to a temp file via a single quoted heredoc.

+ "print(json.dumps({'count': count}))\n";
String scriptB64 =
Base64.getEncoder()
.encodeToString(script.getBytes(java.nio.charset.StandardCharsets.UTF_8));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Info] echo is only guaranteed to pass a single long argument through verbatim by bash's builtin; some echo implementations/versions wrap very long output, and a wrapped base64 stream decodes to a truncated script (manifesting as a Python SyntaxError, i.e. the same symptom this PR is fixing). This repo already hit the mirror-image problem on the read path — see SandboxBackedFilesystem#L209 ("MIME decoder tolerates wrapped base64 output from GNU base64"). printf '%s\n' avoids the ambiguity, and it would be worth extending edit_usesBase64PipedScript with a large-payload case asserting the emitted command is a single line.

@gh-zhaoweifeng
gh-zhaoweifeng force-pushed the fix/edit-file-e2b-sandbox branch from fac9dea to c9a4e57 Compare September 11, 2026 10:39

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Switches edit() from passing the base64 payload as argv[1] to feeding it through a quoted heredoc on stdin, to avoid ARG_MAX on large edits. The motivation is right — a multi-KB edit really can hit the argument-size limit — but this implementation breaks the call entirely, because the heredoc takes over the same stdin that was carrying the Python script.

Verified locally: printf '<b64>' | base64 -d | python3 - <<EOF … EOF makes Python parse the payload as source code:

$ printf "%s\n" "<b64 script>" | base64 -d | python3 - <<EOF
aGVsbG8td29ybGQ=
EOF
  File "<stdin>", line 1
    aGVsbG8td29ybGQ=
                    ^
SyntaxError: invalid syntax

So edit_file regresses to the same "100% non-functional in sandbox environments" state that the comment block immediately above this code documents as the reason for never using the inline python3 -c form. Requesting changes rather than commenting because it silently disables a core tool path.

Findings

  • [Critical] BaseSandboxFilesystem.java:296 — the heredoc becomes python3 -'s stdin, so the piped script is never read; a concrete fix (write the payload to a temp file, pass its path as argv) is in the inline comment.
  • [Warning] BaseSandboxFilesystem.java:271 — sys.stdin.read() inside the script has no stdin left to read; the payload must arrive over a channel other than stdin.
  • [Warning] BaseSandboxFilesystemTest.java:277 — the new assertions check the command string only, which is why this passes CI; edit_largePayloadUsesHeredocNotArgv would pass under any layout that puts the payload between the markers.

Suggestions

The ARG_MAX problem is worth solving properly rather than reverting: materialise the payload into a file (heredoc into cat > tmp) and hand Python the path, so the script keeps coming from the pipe. Also please add one test that runs the assembled command through a real bash -lc against a temp workspace — the string-shape tests cannot distinguish these two designs, and this is the second time the inline-vs-piped distinction has bit this method.

Cross-PR Note

#3094 (fix(harness): defer self-managed sandbox shutdown until session mirrors flush) and #3039 touch adjacent sandbox lifecycle behaviour; no direct file overlap, so this should not conflict, but the three are worth landing in order if they are related work.


Automated review by github-manager-bot

String cmd =
"printf '%s\n' "
+ scriptB64
+ " | base64 -d | python3 - 2>&1 <<'__EDIT_EOF__'\n"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Critical] This makes edit() non-functional again — the payload heredoc replaces the script on stdin, so python3 - never sees the script.

python3 - reads the program text from stdin. Here stdin is redirected to the heredoc (payloadB64), which overrides the base64 -d | pipe feeding the script. So Python parses the base64 payload as Python source instead of running the decoder script:

$ printf "%s\n" "<b64 script>" | base64 -d | python3 - <<EOF
aGVsbG8td29ybGQ=
EOF
  File "<stdin>", line 1
    aGVsbG8td29ybGQ=
                    ^
SyntaxError: invalid syntax

The previous design was correct in this respect: python3 - <payloadB64> took the script from the pipe and the payload from sys.argv[1], and the only thing wrong with it was that a large payload counts against ARG_MAX. Moving the payload to stdin loses the script; the SyntaxError path is exactly the failure the comment above this block warns about.

The existing tests do not catch this because they assert on the assembled command string (fs.lastCommand.contains(...)) and never execute it through a shell.

Keeping the ARG_MAX win without losing the script — write the payload to a file with the heredoc, then pass its path as argv:

String cmd =
        "cat > /tmp/.agentscope-edit-$$ <<'__EDIT_EOF__'\n"
                + payloadB64
                + "\n__EDIT_EOF__\n"
                + "printf '%s\\n' "
                + scriptB64
                + " | base64 -d | python3 - /tmp/.agentscope-edit-$$ 2>&1\n"
                + "rm -f /tmp/.agentscope-edit-$$";

and read it in the script as base64.b64decode(open(sys.argv[1], "rb").read().strip()). Alternatively pass it as an environment assignment (AGT_PAYLOAD_B64=<b64> python3 -), but that also counts against the env/arg budget, so a temp file is the safer option for the multi-KB case this commit is targeting.

Please add one test that runs the assembled command through a real shell (as the Linux job already does for other sandbox paths) — a string-shape assertion cannot distinguish these two designs.

+ "if count > 1 and not replace_all:\\n"
+ " print(json.dumps({'error': 'multiple_occurrences', 'count': count}))\\n"
+ " sys.exit(0)\\n"
+ " json.loads(base64.b64decode(sys.stdin.read().strip()).decode('utf-8'))\n"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Warning] sys.stdin.read() cannot work here: this script is itself being fed to the interpreter over stdin (python3 -), so there is no second stdin left for the payload. It also shadows the base64 payload onto stdout of the pipe. Whatever shell quoting is chosen, the payload has to arrive over a channel other than stdin — argv or a file path (see the comment at line 296).

// return an error result, but we only care about verifying the command shape.
var result = fs.edit(RT, "/workspace/test.txt", "old", "new", false);

// Verify command uses printf + base64 pipe + heredoc stdin (not echo/argv)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Warning] These assertions lock in the command's textual shape, which is why the breakage above passes CI: edit_largePayloadUsesHeredocNotArgv asserts the heredoc marker is present and the payload is between the markers — it never runs the command, so it would still pass if the payload were placed anywhere that made Python fail.

A test that executes the assembled string via bash -lc against a temp workspace (or runs the base64-decoded script with the same stdin arrangement) would actually pin the behaviour the comment says is required.

…nflicts

- Write payload to temp file via heredoc (avoids ARG_MAX limits)
- Pass temp file path as argv[1] to Python script
- Script reads payload from file instead of stdin
- This fixes the stdin conflict where python3 - reads script from stdin
  but heredoc was redirecting stdin to payload

The command structure:
1. cat > /tmp/.agentscope-edit-$$ <<'EOF' (write payload to temp file)
2. printf '%s\n' <scriptB64> | base64 -d | python3 - /tmp/... (pipe script, pass file as arg)
3. rm -f /tmp/.agentscope-edit-$$ (cleanup)

Python script reads: open(sys.argv[1], 'rb').read()

This solves:
- ARG_MAX limit for large payloads (multi-KB edits)
- stdin conflict (script via pipe, payload via file)
- /proc/<pid>/cmdline exposure (payload in file, not argv)
@gh-zhaoweifeng
gh-zhaoweifeng force-pushed the fix/edit-file-e2b-sandbox branch from c9a4e57 to a051736 Compare September 13, 2026 00:19

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Re-reviewed after the new commits (c9a4e577 → a051736a). The blocker from my previous CHANGES_REQUESTED is resolved: the Python script now arrives through the base64 pipe on stdin, the payload goes to a temp file, and the script reads it from argv[1] instead of stdin. I confirmed locally that the three $$ expansions resolve to the same PID within one shell invocation, so the command runs end to end. ARG_MAX is genuinely avoided and the inline python3 -c form is not reintroduced. Approving — the remaining items are hardening, not correctness.

Findings

  • [Warning] BaseSandboxFilesystem.java:301 — payload written world-readable to a PID-only name in shared /tmp: exposes plaintext edit content in a multi-tenant sandbox, and collides if the backend reuses one shell session across calls.
  • [Info] BaseSandboxFilesystem.java:302 — a raw traceback on the failure path falls through to the generic "unexpected server response" message, which is how the previous breakage surfaced.
  • [Warning] BaseSandboxFilesystemTest.java:280 — string-shape assertions still cannot distinguish the two designs that broke this method twice; one executed shell test would.

Notes

  • The __EDIT_EOF__ sentinel is not an injection vector here, because the heredoc body is base64 output; no extra escaping needed.
  • Non-blocking, but if you want to drop the temp-file dance entirely, write() in this same class already ships content through the sandbox uploadFiles API rather than through a shell heredoc — the same transport would give edit() a payload path with no quoting, no ARG_MAX, and no /tmp exposure.

Automated review by github-manager-bot

+ "printf '%s\\n' "
+ scriptB64
+ " | base64 -d | python3 - /tmp/.agentscope-edit-$$ 2>&1\n"
+ "rm -f /tmp/.agentscope-edit-$$";

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The payload lands in /tmp under a name whose only uniqueness token is $$, i.e. the PID of the shell running this one command line (verified: within a single bash login invocation all three $$ expansions resolve identically, so the command does work). Two residual hazards follow from relying on that. (1) cat > creates the file with the process umask — typically 0644 — so the plain-text payload of an edit (the old text plus the new text, which in practice often include connection strings or API keys copied out of the file being edited) is readable by every other user/process in a shared sandbox or container until the final rm -f runs. (2) If the execution backend ever reuses a persistent shell session, $$ is constant across calls and two edits within one turn overwrite each other's temp file. Suggest deriving one unique name per call in Java (or T=$(mktemp /tmp/.agentscope-edit.XXXXXX) and then writing/reading/removing "$T"), which fixes both the permission and the collision question in one move.

+ scriptB64
+ " | base64 -d | python3 - /tmp/.agentscope-edit-$$ 2>&1\n"
+ "rm -f /tmp/.agentscope-edit-$$";

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The base64 alphabet is newline-free, so the quoted heredoc delimiter can never be terminated early by the payload — that part is safe. What is not safe is the error path: if the temp file ever goes missing or base64 -d fails, the 2>&1 redirect puts a raw Python traceback into output, which matches neither the "error" nor the "count" branch and falls through to the generic "unexpected server response" message. That is exactly how the previous revision's breakage surfaced, so a cheap guard (detect Traceback / No such file or directory in the output and report an execution failure rather than a model-visible edit result) would make the next regression obvious instead of mysterious.

// Verify command uses temp file + printf + base64 pipe (not echo/argv)
assertTrue(
fs.lastCommand.contains("cat > /tmp/.agentscope-edit-$$"),
"edit should write payload to temp file, got: " + fs.lastCommand);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These new assertions still only check the string shape, which is why the previous revision passed CI while being fully broken at runtime — the base64 -d | python3 - /tmp/.agentscope-edit-$$ containment check would also have been satisfied by the heredoc-eats-stdin version. Please add one test that actually runs the assembled command against a temp workspace on a POSIX shell and asserts the edited file content plus the JSON on stdout. I know both tests here were added in the earlier revision rather than this one; the reason I am asking again is that this PR's whole failure mode is shell semantics that no string comparison can distinguish.

…ell edit tests

- edit(): replace predictable /tmp/.agentscope-edit-$$ with mktemp (0600,
  collision-safe) per review feedback
- edit(): detect Traceback/SyntaxError in output and report execution
  failure instead of the opaque "unexpected server response"
- add 5 LocalShell integration tests that run the assembled edit command
  through a real shell and assert file content (multi-line, 50KB payload,
  replaceAll, ambiguous-match) — the shape-only tests could not

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Re-reviewed after the two new commits (a051736a → cd23b853). The hardening lands what the previous review asked for: a unique mktemp file instead of the predictable /tmp/.agentscope-edit-$$ name (which fixed both the world-readable payload and the same-$$ collision inside a reused shell session), an explicit execution-failure branch instead of the opaque unexpected server response, and — most valuable — real end-to-end tests that execute the assembled command through a shell and assert the file content actually changes. CLA is signed. Not approving yet: two items are about the failure path still being able to go silent, one is portability of the new /tmp dependency.

Findings

  • [Warning] BaseSandboxFilesystem.java:318 — the new guard only reads output, but the class already has ExecuteResponse.exitCode() and uses it elsewhere (:461, :475). mktemp failing exits 1 with empty output and falls straight back into the opaque branch this commit was meant to close.
  • [Warning] BaseSandboxFilesystem.java:300 — /tmp is now a hard requirement for every edit() call; a sandbox without a writable /tmp regresses from "works via stdin heredoc" to "always fails".
  • [Info] BaseSandboxFilesystem.java:307 — the payload cleanup does not survive a sandbox timeout killing the shell; a trap-based removal would.
  • [Info] BaseSandboxFilesystemTest.java:302 — assertFalse(contains("echo ")) is over-broad, and the e2e cases run through sh -c under a Linux-only gate, so the bash -lc shape that originally broke is never the one actually executed.

Suggestions

if (!result.isSuccess() || looksLikeExecutionFailure(output)) {
T=$(mktemp "${TMPDIR:-/tmp}/.agentscope-edit.XXXXXX" 2>/dev/null || mktemp) || exit 1

Nice regression coverage on the large-payload (ARG_MAX) case — that is exactly what a command-string assertion could never prove.


Automated review by github-manager-bot

// regression to a broken command shape). Surface that as an execution failure instead of
// letting it fall through to the opaque "unexpected server response" branch below — that
// opacity is exactly how the earlier bash -lc breakage stayed mysterious.
if (looksLikeExecutionFailure(output)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Warning] The new guard is a substring heuristic but ExecuteResponse already carries an exit code, which is what the rest of this class checks (exitCode() != 0 at :461/:475). Two paths still slip through: T=$(mktemp /tmp/.agentscope-edit.XXXXXX) || exit 1 produces empty output with a non-zero code, so it lands on the opaque unexpected server response: branch (empty message) — the exact opacity this commit set out to remove; and sh: 1: python3: not found matches none of the three patterns. Consider if (!result.isSuccess() || looksLikeExecutionFailure(output)) (or treat blank output as a failure), which also removes the need to grow the pattern list. exit 1 also means a cat/heredoc write failure is invisible: only python3's stage has 2>&1.

// clobbering each other when a backend reuses a single shell session (where $$ is
// constant across calls).
String cmd =
"T=$(mktemp /tmp/.agentscope-edit.XXXXXX) || exit 1\n"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Warning] Portability nit on the temp file: the path is hardcoded to /tmp and neither mktemp nor cat failure is distinguished from a real edit failure. Sandboxes where /tmp is absent, read-only, or where TMPDIR points elsewhere (K8s pods without an emptyDir mount on /tmp, non-root images with noexec/full tmpfs) now fail every edit() call even though the previous stdin-heredoc form worked. mktemp "${TMPDIR:-/tmp}/.agentscope-edit.XXXXXX" 2>/dev/null || mktemp 2>/dev/null keeps the ARG_MAX fix while degrading gracefully; a command -v mktemp probe (fall back to the stdin form) would be even safer.

+ "printf '%s\\n' "
+ scriptB64
+ " | base64 -d | python3 - \"$T\" 2>&1\n"
+ "rm -f \"$T\"";

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Info] If the shell is killed by a sandbox timeout between cat > "$T" and rm -f "$T", the payload stays on disk for the sandbox lifetime. The comment correctly identifies the world-readability/PID-collision hazards of the old fixed name, and mktemp fixes both — worth finishing the job with trap 'rm -f "$T"' EXIT INT TERM so the cleanup survives a SIGTERM as well. The payload can contain file content copied out of the workspace, i.e. potentially credentials.

fs.lastCommand.contains("python3 -c"),
"edit should NOT use python3 -c inline form");
assertFalse(
fs.lastCommand.contains("echo "),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Info] assertFalse(fs.lastCommand.contains("echo ")) is brittle in a way that will bite the next unrelated change: the assertion matches any occurrence of echo anywhere in the command, including a heredoc payload or a path. Asserting on the shape you actually care about (assertFalse(cmd.startsWith("echo ") || cmd.contains("| echo ")), or simply that the script travels through base64 -d) keeps the regression locked without blocking future edits. Same for the @EnabledOnOs(OS.LINUX) gate: the bash -lc behaviour that caused the original breakage is not what LocalShellSandboxFilesystem.execute() uses (sh -c), so on macOS/Windows runners these e2e cases silently skip.

…leanup, bash -lc e2e

Address the 09-15 review on agentscope-ai#3084:
- Failure guard keys off ExecuteResponse.isSuccess() (exit code), not just an
  output substring, so a mktemp failure (exit 1, empty output) or a missing
  python3 no longer falls through to the opaque "unexpected server response"
  branch. Report the exit code when output is empty; extend the output heuristic
  with ": not found".
- Temp file uses "${TMPDIR:-/tmp}" with a bare-mktemp fallback so edit() keeps
  working where /tmp is absent, read-only, or relocated instead of failing every
  call.
- trap 'rm -f "$T"' EXIT INT TERM removes the plaintext payload even if the
  shell is killed by a sandbox timeout.
- Tests: tighten the over-broad echo assertion, assert TMPDIR fallback + trap,
  and add bash -lc end-to-end cases (multi-line + large payload) exercising the
  exact shell whose backslash-n handling caused the original breakage (sh -c
  never did).
Add three CannedResponse unit tests for the edit_file failure guard:
- non-zero exit with empty output surfaces the exit code
- a python traceback with exit code 0 is still treated as a failure
- a 'not found' interpreter error with exit code 0 is treated as a failure

These exercise the !isSuccess() empty-output branch and the
looksLikeExecutionFailure() path (including the new ': not found'
pattern), which the existing non-zero-exit tests short-circuited past.

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Re-reviewed the two commits pushed since my last pass (cd23b853 → 66c8b796). The delta lands everything the previous round asked for: the exitCode-based failure branch closes the empty-output hole, mktemp now honours TMPDIR with a fallback, cleanup moved onto a trap, and the new bash -lc end-to-end cases exercise the shell shape that actually broke (the previous ones ran under sh -c). CLA is signed and build (ubuntu-latest) is green. Two things on the new failure path are still worth tightening — a null exit code is now treated as a hard failure, which contradicts how the rest of this class reads ExecuteResponse.

Findings

  • [Warning] BaseSandboxFilesystem.java:325 — isSuccess() is exitCode != null && exitCode == 0, so a backend that reports no exit code now turns a successful edit into edit command failed to execute, inviting the model to retry and double-apply the replacement.
  • [Warning] BaseSandboxFilesystem.java:306 — trapping INT/TERM without exiting suppresses the default termination, so a SIGTERM escalation no longer interrupts a hung python3; it only unlinks the payload the pipeline is still about to read.
  • [Info] BaseSandboxFilesystem.java:304 — the bare-mktemp fallback still resolves $TMPDIR on GNU/BusyBox (and needs a template on BSD/macOS), so it does not actually escape a bad TMPDIR.
  • [Info] BaseSandboxFilesystem.java:328 — the null case renders as exit code null; add a FixedResponseFilesystem case for it.

Inline comments carry the details and suggested replacements. Not blocking on style — the direction is right and the regression coverage here is genuinely good.


Automated review by github-manager-bot

// message would otherwise fall through to the opaque "unexpected server response" branch —
// exactly the opacity this path exists to remove). The output-shape check still catches
// the rare broken shell that exits 0 while emitting a Python traceback / SyntaxError.
if (!result.isSuccess() || looksLikeExecutionFailure(output)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Warning] isSuccess() is exitCode != null && exitCode == 0, so a backend that cannot report an exit code (exitCode == null) now makes edit() return "edit command failed to execute" even though python already rewrote the file and printed {"count": N}. That is a false negative the agent will react to by retrying the edit — double-applying the replacement or reporting string_not_found on a file that was in fact edited.

Every other call site in this class is deliberately null-tolerant about the exit code (:146 and :206 both guard with exitCode() != null), which suggests null means "unknown", not "failed". Suggest matching that pattern here and reserving the hard failure for a known non-zero code:

Integer exit = result.exitCode();
if ((exit != null && exit != 0) || looksLikeExecutionFailure(output)) {

The looksLikeExecutionFailure check still covers the shapes that used to leak through, so nothing is lost.

String cmd =
"T=$(mktemp \"${TMPDIR:-/tmp}/.agentscope-edit.XXXXXX\" 2>/dev/null || mktemp)"
+ " || exit 1\n"
+ "trap 'rm -f \"$T\"' EXIT INT TERM\n"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Warning] The EXIT trap alone gives the cleanup guarantee described in the comment. Adding INT TERM without an exit in the handler actually replaces the default action for those signals: non-interactive bash runs the handler only after the current foreground command returns, then keeps going, so a sandbox that escalates with SIGTERM no longer interrupts the hung python3 — it just deletes the payload file underneath it and the run continues to a confusing No such file or directory. A SIGKILL escalation runs no handler at all, so the comment's "on any shell exit" wording overstates it.

Either keep it simple:

+ "trap 'rm -f \"$T\"' EXIT\n"

or, if the INT/TERM handling is wanted, make the handler terminate the shell (and let EXIT do the removal):

+ "trap 'exit 130' INT\n"
+ "trap 'exit 143' TERM\n"

// payload on any shell exit — including a SIGTERM from a sandbox timeout between the write
// and the read — so the plaintext never lingers on disk.
String cmd =
"T=$(mktemp \"${TMPDIR:-/tmp}/.agentscope-edit.XXXXXX\" 2>/dev/null || mktemp)"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Info] The bare-mktemp fallback does not escape a bad TMPDIR: GNU coreutils and BusyBox mktemp consult $TMPDIR (falling back to /tmp) when no template is given, so when TMPDIR is set to something missing or read-only both attempts fail the same way and edit() still exits 1. Pinning the second attempt explicitly keeps the fallback meaningful:

"T=$(mktemp \"${TMPDIR:-/tmp}/.agentscope-edit.XXXXXX\" 2>/dev/null || mktemp /tmp/.agentscope-edit.XXXXXX) || exit 1\n"

The bare form is also the one BSD/macOS mktemp rejects (a template is mandatory there), so an explicit template is the safer default for both branches.

if (!result.isSuccess() || looksLikeExecutionFailure(output)) {
String detail =
output.isEmpty()
? "exit code " + result.exitCode()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Info] In the exitCode == null case this renders as ... failed to execute: exit code null, which is the exact opacity this branch exists to remove. Something like result.exitCode() == null ? "no exit code reported" : "exit code " + result.exitCode() keeps the message actionable, and would be worth a small FixedResponseFilesystem test (new ExecuteResponse("", null, false)) so the unknown-code path stays covered.

…emp fallback

Address the post-approval review round on edit():
- Treat only a known non-zero exit code as a hard failure (exitCode != null
  && != 0), matching the null-tolerant convention at :146/:206. A null code
  means 'unknown', not 'failed', so a successful edit on a backend that omits
  the exit code is no longer turned into a false 'failed to execute' that would
  make the model retry and double-apply the replacement. Render a null code as
  'no exit code reported' instead of 'exit code null'.
- Split the cleanup trap: 'rm -f $T' on EXIT, and exit 130/143 on INT/TERM so
  a SIGTERM actually interrupts a hung python3 (and triggers EXIT cleanup)
  rather than only unlinking the file the pipeline is about to read.
- Pin an explicit /tmp template in the mktemp fallback; a bare mktemp is
  rejected by BSD/macOS and still consults the same broken TMPDIR on GNU/BusyBox.

Tests: add a null-exit-code case (unknown code must not be a hard failure) and
update the trap-shape assertions. Verified the assembled command end-to-end
under a real bash -lc (multi-line replacement lands, EXIT trap cleans the temp
file, bad TMPDIR degrades to /tmp).

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

The third hardening pass (66c8b796..e5078f61) is an improvement: splitting the traps so INT/TERM actually exit (and therefore run the EXIT cleanup) instead of unlinking mid-pipeline is the right call, the explicit /tmp mktemp template removes the BSD/macOS rejection and the $TMPDIR double-read, and treating a null exit code as "unknown" rather than "failed" matches how the rest of this class reasons about missing codes. Test coverage moved along with the command shape, so the assertions now pin the split traps too. license/cla is signed; build (ubuntu-latest), Check License and Check Module Sync are green with build (windows-latest) still running on the current head.

One consequence of the null-code relaxation is worth a look, plus a test-strengthening suggestion — neither blocks the change, hence a comment rather than a change request:

  • [Warning] BaseSandboxFilesystem:339 — the exitCode == null detail arm is unreachable (output.isEmpty() inside this branch implies a known non-zero code), and the case it names — null code with no output at all — falls through to unexpected server response: with an empty tail, which is the opacity the exit-code guard was introduced to remove.
  • [Info] BaseSandboxFilesystemTest:458 — the new fixture pins the negative direction only; the outcome the change protects (valid {"count": ...} output with a null exit code reported as success) is not asserted anywhere.

Suggestions

Either drop the dead ternary, or make exitCode == null && output.isEmpty() an explicit failure with a message that says the backend reported neither a code nor output. Adding the positive null-code case (new ExecuteResponse("{\"count\": 1}", null, false) → assertTrue(result.isSuccess())) is the assertion that would actually catch a regression if the guard is later re-tightened to !result.isSuccess().


Automated review by github-manager-bot

if ((exitCode != null && exitCode != 0) || looksLikeExecutionFailure(output)) {
String detail =
output.isEmpty()
? (exitCode == null ? "no exit code reported" : "exit code " + exitCode)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Warning] This exitCode == null arm is unreachable. The enclosing branch is entered only when (exitCode != null && exitCode != 0) || looksLikeExecutionFailure(output), and looksLikeExecutionFailure("") is always false — so whenever output.isEmpty() here, exitCode is guaranteed non-null. The case the string describes (null code, no output) never reaches it: it falls through both the execution-failure branch and the "count" parse into the final unexpected server response: branch with an empty detail, i.e. the exact opacity the exit-code guard was added to remove. Either drop the dead ternary, or make the null-code + empty-output case an explicit failure (e.g. exitCode == null && output.isEmpty() → "backend reported neither an exit code nor any output") so it gets a real message instead of a blank one.

// make the model retry and double-apply the replacement on an edit that may have
// succeeded.
FixedResponseFilesystem fs =
new FixedResponseFilesystem(new ExecuteResponse("", null, false));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Info] This fixture (ExecuteResponse("", null, false)) pins the negative direction only: it proves the null exit code is not reported as "edit command failed to execute", and it does discriminate against the previous code (which failed here) — but the edit still comes back failed, just as unexpected server response: . The outcome the change actually protects is the positive one: a backend that omits the exit code while the script printed a valid result. Worth adding new ExecuteResponse("{\"count\": 1}", null, false) → assertTrue(result.isSuccess()), which is the assertion that would regress if someone re-tightened the guard to !result.isSuccess().

gh-zhaoweifeng and others added 2 commits September 16, 2026 14:00
Address final review on agentscope-ai#3084: the exitCode==null arm of the failure
detail was unreachable (whenever output is empty inside that branch the
code is guaranteed non-null), so a null exit code with no output at all
fell through to the opaque "unexpected server response" branch with a
blank tail. Add an explicit noCodeNoOutput guard so that case gets a real
message ("backend reported neither an exit code nor any output"), while
a null code WITH a valid {"count":...} payload is still honored as
success.

Split the old edit_nullExitCode_notTreatedAsHardFailure test into a
positive case (null code + valid payload -> success) and a boundary case
(null code + empty output -> clear, non-opaque failure).

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

The follow-up commit e5078f61..680b3582 lands exactly the two items from the previous round: the exitCode == null detail arm is now reachable because null-code-with-no-output is an explicit failure condition of its own (noCodeNoOutput), with a message that says the backend reported neither a code nor output instead of falling through to the blank-tailed unexpected server response branch, and the previously missing positive assertion now exists (edit_nullExitCode_withResultPayload_treatedAsSuccess — a valid {"count": 1} payload with a null code must be a success, which is the case that would regress if the guard were re-tightened to !result.isSuccess()). The rewritten detail block also keeps the non-empty-output path first, so a real traceback still surfaces verbatim rather than being replaced by a generic string. LGTM.

Findings

None on this delta.

Notes for the record

  • The empty-output-with-null-code path now fails in both directions consistently; a backend that omits the exit code but prints a valid result is still honored, which is the trade-off the earlier rounds settled on.
  • CI is green on the current head (build (ubuntu-latest) / build (windows-latest) / Check License / Check Module Sync / codecov/patch), mergeable is clean, and license/cla is signed.

Automated review by github-manager-bot

// here instead of the blank-tailed opaque branch. The output-shape check still catches the
// rare broken shell that exits 0 while emitting a Python traceback / SyntaxError.
Integer exitCode = result.exitCode();
boolean noCodeNoOutput = exitCode == null && output.isEmpty();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Info] Nice — hoisting this into its own condition instead of a detail-arm ternary is what makes the null-code case observable: exitCode == null && output.isEmpty() now fails with a message that names the missing evidence, while noCodeNoOutput keeps exitCode == null with a real payload on the success path. No action needed.

@gh-zhaoweifeng

Copy link
Copy Markdown
Author

Thanks for the thorough review! No further changes planned — ready to merge from my side

@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict detected

This PR currently conflicts with main and cannot be merged, so a reviewer cannot get a meaningful signal on the current head. Please rebase (or merge main in) and resolve the conflicts:

git fetch origin
git checkout 
git rebase origin/main
# resolve conflicts, then:
git push --force-with-lease

Once the state is back to CLEAN, @mention me for a re-review. This is a one-time reminder.


Automated notification by github-manager-bot

aMetric added a commit to aMetric/agentscope-java that referenced this pull request Sep 29, 2026
… output (agentscope-ai#3262)

On a Windows host the argv -> command-line -> docker.exe re-parse round-trip
drops inner double quotes; a double-quoted span containing a space then
breaks into argv separators and the in-container shell fails with a syntax
error, so write_file always failed there.

- write(): mkdir -p "$(dirname <p>)" -> d=$(dirname <p>); mkdir -p "$d"
  (same quote-free-spread pattern move() already uses); no double-quoted
  span contains a space anymore, no POSIX behavior change
- write(): the pre-check failure branch now appends checkResult.output()
  (exit-code fallback when blank) instead of returning a bare reason-less
  'Failed to file' message, matching the upload branch's convention

edit() deliberately left untouched: its python3 -c rewrite belongs to
in-flight agentscope-ai#3084 / agentscope-ai#3226.

Regression tests: command contains no double-quoted span with a space;
failure message carries the container's error output; exit-code fallback.
Sabotage-verified: restoring the old construction fails the new test.
@gh-zhaoweifeng

Copy link
Copy Markdown
Author

Closing in favor of #3226, which fixes the same bash -lc escaping bug via a Java text block — glad to see it resolved upstream.
One note for future reference: the e2e tests here exercised the command through bash -lc (the exact shell where the bug reproduced), while the current tests on main run through sh -c. If anyone changes the script assembly in edit() again, that bash -lc shape is worth keeping covered — happy to contribute a test-only follow-up if the maintainers think it's useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants